diff --git a/README.md b/README.md index 52712598..e4b7d3ef 100644 --- a/README.md +++ b/README.md @@ -692,6 +692,23 @@ scalar variable is assigned. If a limit is reached first, the solve ends as `Failed`; an incomplete construction state is never emitted as a best or completed solution. +A solution can declare further constraint sets next to `constraints` with +`constraint_provider = "path"` (repeatable), and a configuration picks one by +the path as written in the attribute: + +```toml +[score_director] +constraint_provider = "relaxed_constraints" +constraint_match_enabled = true +``` + +Without `[score_director]` the solve scores with `constraints`. A name that +matches no declared provider fails the solve before it starts with +`RuntimeBuildError::UnknownConstraintProvider`. `SolverManager::analyze_snapshot` +analyzes a job's snapshots with the provider the job selected; +`constraint_match_enabled = false` turns snapshot analysis off for the job, +which then fails with `SolverManagerError::SnapshotAnalysisDisabled`. + ## SolverManager API The `SolverManager` owns the retained runtime lifecycle for each job. The public contract uses neutral `job`, `snapshot`, and `checkpoint` terminology throughout the API. `pause()` settles at a runtime-owned safe boundary and `resume()` continues from the exact in-process state rather than restarting from the best solution. Before mandatory construction completes, that state remains an internal resumable pause and is not exposed as a solution snapshot. Built-in search phases poll retained-runtime control during large neighborhood generation and evaluation, so config time limits, `pause()`, and `cancel()` unwind promptly without app-side watchdogs. Declare a `static` instance so it satisfies the `'static` lifetime requirement: diff --git a/crates/solverforge-bridge/WIREFRAME.md b/crates/solverforge-bridge/WIREFRAME.md index 8dec0ecd..88f28d14 100644 --- a/crates/solverforge-bridge/WIREFRAME.md +++ b/crates/solverforge-bridge/WIREFRAME.md @@ -42,7 +42,7 @@ pub use backend::{ DynamicScalarAssignmentMetadata, DynamicScalarAssignmentMetadataCapabilities, }; pub use ids::{EntityClassId, ProblemFactClassId, VariableId}; -pub use runner::try_run_dynamic_solver_with_config_parts; +pub use runner::{try_run_dynamic_solver_with_config_parts, DynamicConstraintProvider}; pub use score::{ active_dynamic_score_family, scoped_dynamic_score_family, DynamicScore, DynamicScoreFamily, }; @@ -206,7 +206,7 @@ threads need no scope. ```rust pub fn try_run_dynamic_solver_with_config_parts( solution: S, - constraints: fn(&S) -> C, + constraint_providers: &[DynamicConstraintProvider<'_, S, C>], descriptor: SolutionDescriptor, entity_count_by_descriptor: fn(&S, usize) -> usize, runtime: SolverRuntime, @@ -228,7 +228,14 @@ where This is the binding-oriented entrypoint. It consumes frozen dynamic model parts into the same compiled graph and phase runner used by native models. It accepts no phase builder, selector registration, or alternate construction path. -`constraints` builds a constraint set for a given solution; the runtime calls it +`constraint_providers` lists the constraint sets the solve can score with; +`score_director.constraint_provider` selects one by `name`, the first is used +when it is omitted, and an unknown name fails with +`RuntimeBuildError::UnknownConstraintProvider` before solving starts. The +selected provider's `analyze` serves `SolverManager::analyze_snapshot` unless +`score_director.constraint_match_enabled` is `false`, which disables snapshot +analysis for the job. The selected provider's `constraints` builds a constraint +set for a given solution; the runtime calls it for the working solution and for every evaluator replica, so `move_thread_count` evaluates dynamic models in parallel. Bindings rebuild their host constraint set from the solution they receive. Replicas score on @@ -237,6 +244,16 @@ release it on the calling thread for the duration of the solve. The optional qualified provenance changes only the candidate-trace header; it does not select another runner. +### `DynamicConstraintProvider<'a, S, C>` + +One named constraint set a dynamic solve can score with. `Clone + Copy`. + +| Field | Type | Note | +|-------|------|------| +| `name` | `&'a str` | The name `score_director.constraint_provider` selects it by | +| `constraints` | `fn(&S) -> C` | Builds the constraint set for a solution | +| `analyze` | `fn(&S) -> ScoreAnalysis` | Snapshot analysis with this provider's constraint set | + ## Scope - Stable logical IDs for dynamic entity, fact, and variable classes. diff --git a/crates/solverforge-bridge/src/lib.rs b/crates/solverforge-bridge/src/lib.rs index 467875bf..ad0383cd 100644 --- a/crates/solverforge-bridge/src/lib.rs +++ b/crates/solverforge-bridge/src/lib.rs @@ -20,7 +20,7 @@ pub use backend::{ DynamicScalarAssignmentMetadata, DynamicScalarAssignmentMetadataCapabilities, }; pub use ids::{EntityClassId, ProblemFactClassId, VariableId}; -pub use runner::try_run_dynamic_solver_with_config_parts; +pub use runner::{try_run_dynamic_solver_with_config_parts, DynamicConstraintProvider}; pub use score::{ active_dynamic_score_family, scoped_dynamic_score_family, DynamicScore, DynamicScoreFamily, }; diff --git a/crates/solverforge-bridge/src/runner.rs b/crates/solverforge-bridge/src/runner.rs index 86a06f85..cefbcb3e 100644 --- a/crates/solverforge-bridge/src/runner.rs +++ b/crates/solverforge-bridge/src/runner.rs @@ -13,8 +13,8 @@ use solverforge_scoring::ConstraintSet; use solverforge_solver::__private::NoDynamicExtensions; use solverforge_solver::QualifiedCandidateTraceRunProvenance; use solverforge_solver::{ - try_run_solver_with_config_and_search, CrossEntityDistanceMeter, RuntimeBuildResult, - RuntimeModel, SolverRuntime, + try_run_solver_with_config_and_search, CrossEntityDistanceMeter, RuntimeBuildError, + RuntimeBuildResult, RuntimeModel, ScoreAnalysis, SolverRuntime, }; use solverforge_solver::{Search, SearchContext}; @@ -60,18 +60,72 @@ where }) } +/// One named constraint set a dynamic solve can score with. +/// +/// `score_director.constraint_provider` selects a provider by [`Self::name`]; +/// when it is omitted the first provider passed to +/// [`try_run_dynamic_solver_with_config_parts`] is used. +pub struct DynamicConstraintProvider<'a, S: PlanningSolution, C> { + /// The name `score_director.constraint_provider` selects this provider by. + pub name: &'a str, + /// Builds the constraint set for a solution. + pub constraints: fn(&S) -> C, + /// Analyzes a solution with this provider's constraint set; used by + /// `SolverManager::analyze_snapshot` for solves that select it. + pub analyze: fn(&S) -> ScoreAnalysis, +} + +impl Clone for DynamicConstraintProvider<'_, S, C> { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for DynamicConstraintProvider<'_, S, C> {} + +/// The provider `config` selects: the named one, or the first when +/// `score_director.constraint_provider` is omitted. +fn selected_provider<'p, 'n, S: PlanningSolution, C>( + config: &SolverConfig, + providers: &'p [DynamicConstraintProvider<'n, S, C>], +) -> RuntimeBuildResult<&'p DynamicConstraintProvider<'n, S, C>> { + let Some(default) = providers.first() else { + return Err(RuntimeBuildError::declaration( + "a dynamic solve needs at least one constraint provider", + )); + }; + let Some(requested) = config.constraint_provider() else { + return Ok(default); + }; + providers + .iter() + .find(|provider| provider.name == requested) + .ok_or_else(|| RuntimeBuildError::UnknownConstraintProvider { + requested: requested.to_string(), + declared: providers + .iter() + .map(|provider| provider.name.to_string()) + .collect(), + }) +} + /// Runs a dynamic model through the one compiled runtime path. /// /// The one model value is consumed by the canonical compiled runner. There is /// no host-language construction branch or deferred alternate execution path. /// -/// `constraints` builds a constraint set for a given solution. The runtime -/// calls it for the working solution and for every evaluator replica, so -/// `move_thread_count` evaluates dynamic models in parallel. +/// `constraint_providers` lists the constraint sets the solve can score with; +/// `score_director.constraint_provider` selects one by name, and the first is +/// used when it is omitted. A name that matches no provider fails with +/// [`RuntimeBuildError::UnknownConstraintProvider`] before solving starts. The +/// selected provider builds the constraint set for the working solution and +/// for every evaluator replica, so `move_thread_count` evaluates dynamic +/// models in parallel, and its `analyze` serves snapshot analysis unless +/// `score_director.constraint_match_enabled` is `false`. #[allow(clippy::too_many_arguments)] pub fn try_run_dynamic_solver_with_config_parts( solution: S, - constraints: fn(&S) -> C, + constraint_providers: &[DynamicConstraintProvider<'_, S, C>], descriptor: SolutionDescriptor, entity_count_by_descriptor: fn(&S, usize) -> usize, runtime: SolverRuntime, @@ -89,9 +143,15 @@ where DM: CrossEntityDistanceMeter + Clone + Debug + Send + Sync + 'static, IDM: CrossEntityDistanceMeter + Clone + Debug + Send + Sync + 'static, { + let provider = *selected_provider(&config, constraint_providers)?; + runtime.bind_snapshot_analysis( + config + .constraint_match_enabled() + .then_some(provider.analyze), + ); try_run_solver_with_config_and_search( solution, - constraints, + provider.constraints, descriptor, entity_count_by_descriptor, runtime, diff --git a/crates/solverforge-config/WIREFRAME.md b/crates/solverforge-config/WIREFRAME.md index 3c29baf8..52850945 100644 --- a/crates/solverforge-config/WIREFRAME.md +++ b/crates/solverforge-config/WIREFRAME.md @@ -62,7 +62,7 @@ Top-level solver configuration. Derives: `Debug, Clone, Default, Deserialize, Se | `random_seed` | `Option` | `None` | | | `move_thread_count` | `MoveThreadCount` | `Auto` | `#[serde(default)]` | | `termination` | `Option` | `None` | | -| `score_director` | `Option` | `None` | | +| `score_director` | `Option` | `None` | Omitted: the `constraints` provider, snapshot analysis enabled | | `phases` | `Vec` | `[]` | `#[serde(default)]` | | `candidate_trace` | `Option` | `None` | Opt-in bounded candidate-pull diagnostics | @@ -71,6 +71,8 @@ Top-level solver configuration. Derives: `Debug, Clone, Default, Deserialize, Se | Method | Signature | Note | |--------|-----------|------| | `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 | | `load` | `fn(path: impl AsRef) -> Result` | Delegates to `from_toml_file` | | `from_toml_file` | `fn(path: impl AsRef) -> Result` | Reads file, parses TOML | | `from_toml_str` | `fn(s: &str) -> Result` | Parses TOML string | @@ -114,12 +116,12 @@ Derives: `Debug, Clone, Default, Deserialize, Serialize`. ### `DirectorConfig` -Derives: `Debug, Clone, Default, Deserialize, Serialize`. +Derives: `Debug, Clone, Deserialize, Serialize`; `Default` is implemented by hand (`constraint_match_enabled = true`). | Field | Type | Note | |-------|------|------| -| `constraint_provider` | `Option` | Fully qualified constraint provider name | -| `constraint_match_enabled` | `bool` | Default: `false` | +| `constraint_provider` | `Option` | Constraint provider the solve scores with: a `constraints` or `constraint_provider` path as written in `#[planning_solution]`. Omitted: `constraints`. Unknown: the solve fails before it starts | +| `constraint_match_enabled` | `bool` | Default: `true`. `false` makes `SolverManager::analyze_snapshot` fail for the job | ### `ConstructionHeuristicConfig` diff --git a/crates/solverforge-config/src/director.rs b/crates/solverforge-config/src/director.rs index 4724ca70..091e3c95 100644 --- a/crates/solverforge-config/src/director.rs +++ b/crates/solverforge-config/src/director.rs @@ -1,15 +1,35 @@ use serde::{Deserialize, Serialize}; -/// Score director configuration. -#[derive(Debug, Clone, Default, Deserialize, Serialize)] +/// Score director configuration: which constraint set a solve scores with and +/// whether its snapshots can be analyzed. +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case", deny_unknown_fields)] pub struct DirectorConfig { - /// Fully qualified name of the constraint provider type. Not read by the - /// current solver runtime. + /// Name of the constraint provider the solve scores with: the Rust path + /// of the solution's `constraints` function or of one of its + /// `constraint_provider` functions, exactly as written in the + /// `#[planning_solution]` attribute. Omitted: the `constraints` function. + /// A name that matches no declared provider fails the solve before it + /// starts. pub constraint_provider: Option, - /// Whether to enable constraint matching assertions. Default: `false`. - /// Not read by the current solver runtime. - #[serde(default)] + /// Whether the solve's snapshots can be analyzed with + /// `SolverManager::analyze_snapshot`. Default: `true`. When `false`, + /// snapshot analysis of the job fails with + /// `SolverManagerError::SnapshotAnalysisDisabled`. + #[serde(default = "constraint_match_enabled_default")] pub constraint_match_enabled: bool, } + +const fn constraint_match_enabled_default() -> bool { + true +} + +impl Default for DirectorConfig { + fn default() -> Self { + Self { + constraint_provider: None, + constraint_match_enabled: constraint_match_enabled_default(), + } + } +} diff --git a/crates/solverforge-config/src/solver_config.rs b/crates/solverforge-config/src/solver_config.rs index 38361c1f..3e2ce148 100644 --- a/crates/solverforge-config/src/solver_config.rs +++ b/crates/solverforge-config/src/solver_config.rs @@ -31,8 +31,9 @@ pub struct SolverConfig { #[serde(default)] pub termination: Option, - /// Score director settings. Parsed and serialized, but not read by the - /// current solver runtime. + /// Score director settings: the constraint provider and whether snapshot + /// analysis is enabled. Omitted: the solution's `constraints` function, + /// with snapshot analysis enabled. #[serde(default)] pub score_director: Option, @@ -56,6 +57,22 @@ impl SolverConfig { Self::default() } + /// The configured `score_director.constraint_provider` name, or `None` + /// for the solution's `constraints` function. + pub fn constraint_provider(&self) -> Option<&str> { + self.score_director + .as_ref() + .and_then(|director| director.constraint_provider.as_deref()) + } + + /// The configured `score_director.constraint_match_enabled`; `true` when + /// the section is omitted. + pub fn constraint_match_enabled(&self) -> bool { + self.score_director + .as_ref() + .is_none_or(|director| director.constraint_match_enabled) + } + /// Loads configuration from a TOML file. /// /// # Errors diff --git a/crates/solverforge-config/src/tests/parsing.rs b/crates/solverforge-config/src/tests/parsing.rs index a51d5abc..381addb3 100644 --- a/crates/solverforge-config/src/tests/parsing.rs +++ b/crates/solverforge-config/src/tests/parsing.rs @@ -244,3 +244,24 @@ fn move_thread_count_parses_every_documented_form() { MoveThreadCount::Auto ); } + +#[test] +fn score_director_defaults_to_the_constraints_function_with_analysis_enabled() { + let omitted = SolverConfig::from_toml_str("").unwrap(); + assert_eq!(omitted.constraint_provider(), None); + assert!(omitted.constraint_match_enabled()); + + let empty = SolverConfig::from_toml_str("[score_director]\n").unwrap(); + assert_eq!(empty.constraint_provider(), None); + assert!(empty.constraint_match_enabled()); + + let set = SolverConfig::from_toml_str( + "[score_director]\nconstraint_provider = \"crate::constraints::relaxed\"\nconstraint_match_enabled = false\n", + ) + .unwrap(); + assert_eq!( + set.constraint_provider(), + Some("crate::constraints::relaxed") + ); + assert!(!set.constraint_match_enabled()); +} diff --git a/crates/solverforge-macros/WIREFRAME.md b/crates/solverforge-macros/WIREFRAME.md index 0ae32e69..0070e90f 100644 --- a/crates/solverforge-macros/WIREFRAME.md +++ b/crates/solverforge-macros/WIREFRAME.md @@ -84,9 +84,20 @@ Applies to structs. Adds ordinary Rust derives plus hidden SolverForge support d Applies to structs. Adds ordinary Rust derives plus hidden SolverForge support derive output. Accepted arguments are `serde`, `constraints = "path"`, -`config = "path"`, `solver_toml = "path"`, `search = "path"`, +`constraint_provider = "path"` (repeatable), `config = "path"`, `solver_toml = "path"`, `search = "path"`, `conflict_repairs = "path"`, and `scalar_groups = "path"`. Unknown or malformed arguments are compile errors. +Each `constraint_provider` names a further constraint function next to +`constraints`, the default; the name `score_director.constraint_provider` +selects a provider by is its path as written in the attribute, without +whitespace. `constraint_provider` without `constraints`, and a provider name +declared twice (including the `constraints` path), are compile errors. The +generated solve selects the configured provider, binds that provider's +analysis as the job's snapshot analysis (or disables it when +`score_director.constraint_match_enabled` is `false`), and fails with +`RuntimeBuildError::UnknownConstraintProvider` for an undeclared name. Each +provider is its own monomorphized solve; `Analyzable::analyze` uses the +`constraints` function. The `constraints` flag embeds a `#[solverforge_constraints_path = "path"]` attribute for the derive to consume. The `config` flag embeds a `#[solverforge_config_path = "path"]` attribute for the derive to consume; the @@ -210,6 +221,7 @@ arguments are compile errors. **Consumed attributes on struct:** - `#[shadow_variable_updates(...)]` — configures descriptor-aware shadow updates for the canonical solver path - `#[solverforge_constraints_path = "path"]` — path to constraint factory function +- `#[solverforge_constraint_provider_path = "path"]` — generated bridge attribute, one per `constraint_provider` - `#[solverforge_config_path = "path"]` — path to a config callback with signature `fn(&Solution, SolverConfig) -> SolverConfig`; called with the embedded `solver_toml` config, or `SolverConfig::default()` when the solution has no `solver_toml` - `#[solverforge_solver_toml_path = "path"]` — generated bridge attribute for an explicit solver TOML source - `#[solverforge_search_path = "path"]` — generated bridge attribute for a typed custom-search function consumed by runtime phase support @@ -287,6 +299,7 @@ semantics should omit `domain = "cvrp"` and declare explicit hook paths instead. | Function | Signature | Note | |----------|-----------|------| | `parse_constraints_path` | `fn(&[Attribute]) -> syn::Result>` | Extracts and parses `#[solverforge_constraints_path = "..."]`; an unparsable path is a spanned error | +| `parse_constraint_providers` | `fn(&[Attribute], &Option) -> syn::Result>` | The `constraints` provider followed by every `#[solverforge_constraint_provider_path = "..."]`, each with its selection name | | `parse_config_path` | `fn(&[Attribute]) -> syn::Result>` | Extracts and parses `#[solverforge_config_path = "..."]`; an unparsable path is a spanned error | | `parse_solver_toml_path` | `fn(&[Attribute]) -> Option` | Extracts `#[solverforge_solver_toml_path = "..."]` | | `parse_search_path` | `fn(&[Attribute]) -> syn::Result>` | Extracts and parses `#[solverforge_search_path = "..."]`; an unparsable path is a spanned error | diff --git a/crates/solverforge-macros/src/attr_validation.rs b/crates/solverforge-macros/src/attr_validation.rs index 630307d3..9f29c0e0 100644 --- a/crates/solverforge-macros/src/attr_validation.rs +++ b/crates/solverforge-macros/src/attr_validation.rs @@ -60,6 +60,7 @@ const SERDE_FLAG_ARGS: &[AttributeArgSpec] = &[AttributeArgSpec::flag("serde")]; const SOLUTION_ARGS: &[AttributeArgSpec] = &[ AttributeArgSpec::flag("serde"), AttributeArgSpec::string("constraints"), + AttributeArgSpec::repeated_string("constraint_provider"), AttributeArgSpec::string("config"), AttributeArgSpec::string("solver_toml"), AttributeArgSpec::string("search"), @@ -126,12 +127,13 @@ pub(crate) fn parse_serde_flag(attr: TokenStream, macro_name: &str) -> Result, + pub(crate) constraint_provider_paths: Vec, pub(crate) config_path: Option, pub(crate) solver_toml_path: Option, pub(crate) search_path: Option, @@ -148,6 +150,7 @@ pub(crate) fn parse_solution_flags(attr: TokenStream) -> Result = Vec::new(); for meta in nested { match meta { Meta::Path(path) if path_matches_ident(&path, "serde") => { @@ -156,6 +159,12 @@ pub(crate) fn parse_solution_flags(attr: TokenStream) -> Result { flags.constraints_path = rust_path_argument("constraints", &nv)?; } + Meta::NameValue(nv) if path_matches_ident(&nv.path, "constraint_provider") => { + if let Some(path) = rust_path_argument("constraint_provider", &nv)? { + provider_values.push((constraint_provider_name(&path), nv.value.clone())); + flags.constraint_provider_paths.push(path); + } + } Meta::NameValue(nv) if path_matches_ident(&nv.path, "config") => { flags.config_path = rust_path_argument("config", &nv)?; } @@ -175,9 +184,47 @@ pub(crate) fn parse_solution_flags(attr: TokenStream) -> Result Result<(), Error> { + let Some(constraints_path) = &flags.constraints_path else { + return match provider_values.first() { + Some((_, value)) => Err(Error::new_spanned( + value, + "`constraint_provider` requires `constraints`, the default constraint provider", + )), + None => Ok(()), + }; + }; + let mut declared = vec![constraint_provider_name(constraints_path)]; + for (name, value) in provider_values { + if declared.contains(name) { + return Err(Error::new_spanned( + value, + format!("constraint provider `{name}` is declared more than once"), + )); + } + declared.push(name.clone()); + } + Ok(()) +} + +/// The name `score_director.constraint_provider` selects a provider by: its +/// path as written, without whitespace. +pub(crate) fn constraint_provider_name(path: &syn::Path) -> String { + quote::ToTokens::to_token_stream(path) + .to_string() + .split_whitespace() + .collect() +} + /// Parses a Rust-path argument once, when the attribute is read, so a bad /// value is a spanned diagnostic on that argument rather than a derive panic. fn rust_path_argument( diff --git a/crates/solverforge-macros/src/entrypoints.rs b/crates/solverforge-macros/src/entrypoints.rs index ef53c2ae..c163748e 100644 --- a/crates/solverforge-macros/src/entrypoints.rs +++ b/crates/solverforge-macros/src/entrypoints.rs @@ -32,6 +32,10 @@ pub(crate) fn planning_solution_attr(attr: TokenStream, item: TokenStream) -> To let p = hidden_path_literal(&p); parse_quote! { #[solverforge_constraints_path = #p] } })); + leading.extend(flags.constraint_provider_paths.iter().map(|p| { + let p = hidden_path_literal(p); + parse_quote! { #[solverforge_constraint_provider_path = #p] } + })); leading.extend(flags.config_path.map(|p| { let p = hidden_path_literal(&p); parse_quote! { #[solverforge_config_path = #p] } diff --git a/crates/solverforge-macros/src/lib.rs b/crates/solverforge-macros/src/lib.rs index 3cb52883..b7e7d4e0 100644 --- a/crates/solverforge-macros/src/lib.rs +++ b/crates/solverforge-macros/src/lib.rs @@ -83,6 +83,7 @@ pub fn derive_planning_entity(input: TokenStream) -> TokenStream { value_range_provider, shadow_variable_updates, solverforge_constraints_path, + solverforge_constraint_provider_path, solverforge_config_path, solverforge_solver_toml_path, solverforge_search_path, diff --git a/crates/solverforge-macros/src/planning_solution/config.rs b/crates/solverforge-macros/src/planning_solution/config.rs index e6a2fb22..e57cc368 100644 --- a/crates/solverforge-macros/src/planning_solution/config.rs +++ b/crates/solverforge-macros/src/planning_solution/config.rs @@ -1,6 +1,7 @@ use syn::{Error, Lit, LitStr, Meta, Result}; use crate::attr_parse::{get_attribute, parse_attribute_list, parse_attribute_string}; +use crate::attr_validation::constraint_provider_name; #[derive(Default)] pub(super) struct ShadowConfig { @@ -49,6 +50,55 @@ pub(super) fn parse_constraints_path(attrs: &[syn::Attribute]) -> Result, +) -> Result> { + let Some(constraints_path) = constraints_path else { + return Ok(Vec::new()); + }; + let mut providers = vec![ConstraintProvider { + name: constraint_provider_name(constraints_path), + path: constraints_path.clone(), + }]; + for attr in attrs + .iter() + .filter(|attr| attr.path().is_ident("solverforge_constraint_provider_path")) + { + let Meta::NameValue(nv) = &attr.meta else { + continue; + }; + let syn::Expr::Lit(syn::ExprLit { + lit: Lit::Str(lit), .. + }) = &nv.value + else { + continue; + }; + let path = lit.parse::().map_err(|_| { + Error::new_spanned( + lit, + "`constraint_provider` must be a valid Rust path string", + ) + })?; + providers.push(ConstraintProvider { + name: constraint_provider_name(&path), + path, + }); + } + Ok(providers) +} + pub(super) fn parse_config_path(attrs: &[syn::Attribute]) -> Result> { hidden_rust_path_attr(attrs, "solverforge_config_path") } diff --git a/crates/solverforge-macros/src/planning_solution/expand.rs b/crates/solverforge-macros/src/planning_solution/expand.rs index 60032f04..22555c42 100644 --- a/crates/solverforge-macros/src/planning_solution/expand.rs +++ b/crates/solverforge-macros/src/planning_solution/expand.rs @@ -9,8 +9,9 @@ use crate::attr_validation::{ }; use super::config::{ - parse_config_path, parse_conflict_repairs_path, parse_constraints_path, - parse_scalar_groups_path, parse_search_path, parse_shadow_config, parse_solver_toml_path, + parse_config_path, parse_conflict_repairs_path, parse_constraint_providers, + parse_constraints_path, parse_scalar_groups_path, parse_search_path, parse_shadow_config, + parse_solver_toml_path, }; use super::list_operations::generate_list_operations; use super::runtime::{ @@ -119,6 +120,7 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result { let shadow_config = parse_shadow_config(&input.attrs); let shadow_support_impl = generate_shadow_support(&shadow_config, fields, name)?; let constraints_path = parse_constraints_path(&input.attrs)?; + let constraint_providers = parse_constraint_providers(&input.attrs, &constraints_path)?; let config_path = parse_config_path(&input.attrs)?; let solver_toml_path = parse_solver_toml_path(&input.attrs); let search_path = parse_search_path(&input.attrs)?; @@ -178,13 +180,13 @@ pub(crate) fn expand_derive(input: DeriveInput) -> Result { ); let has_constraint_weights = !constraint_weights_accessor.is_empty(); let runtime_solve_internal = generate_runtime_solve_internal( - &constraints_path, + &constraint_providers, &config_path, &solver_toml_path, has_constraint_weights, ); let solvable_solution_impl = - generate_solvable_solution(name, &constraints_path, has_constraint_weights); + generate_solvable_solution(name, &constraint_providers, has_constraint_weights); let collection_source_methods = generate_collection_source_methods(fields); let constraint_stream_extensions = generate_constraint_stream_extensions(fields, name); diff --git a/crates/solverforge-macros/src/planning_solution/runtime/helpers/solvable.rs b/crates/solverforge-macros/src/planning_solution/runtime/helpers/solvable.rs index 42e48772..3d87db81 100644 --- a/crates/solverforge-macros/src/planning_solution/runtime/helpers/solvable.rs +++ b/crates/solverforge-macros/src/planning_solution/runtime/helpers/solvable.rs @@ -1,6 +1,6 @@ pub(super) fn generate_solvable_solution( solution_name: &Ident, - constraints_path: &Option, + providers: &[super::config::ConstraintProvider], has_constraint_weights: bool, ) -> TokenStream { let solvable_solution_impl = quote! { @@ -15,13 +15,66 @@ pub(super) fn generate_solvable_solution( } }; - let solvable_impl = constraints_path.as_ref().map(|constraints_fn| { + let solvable_impl = providers.first().map(|default_provider| { + let constraints_fn = &default_provider.path; // Analysis of a weighted solution type always reports bound weights. let director_ctor = if has_constraint_weights { quote! { ScoreDirector::with_descriptor_weighted } } else { quote! { ScoreDirector::with_descriptor } }; + let analyze_fns = providers.iter().enumerate().map(|(index, provider)| { + let analyze_fn = constraint_provider_analyze_ident(index); + let provider_fn = &provider.path; + quote! { + #[doc(hidden)] + #[allow(dead_code)] + pub fn #analyze_fn( + solution: &Self, + ) -> ::solverforge::ScoreAnalysis<::Score> { + use ::solverforge::__internal::{ + Director, ScoreDirector, + }; + + let constraints = #provider_fn(); + let mut director = #director_ctor( + solution.clone(), + constraints, + Self::descriptor(), + Self::entity_count, + ); + + if let ::core::option::Option::Some(weights) = + ::solverforge::__internal::PlanningSolution::constraint_weights(solution) + { + let metadata = director.constraint_metadata(); + if let ::core::result::Result::Err(error) = + weights.validate(metadata.iter().map(|entry| entry.constraint_ref)) + { + panic!("{error}"); + } + } + + let score = director.calculate_score(); + let constraint_scores = director.constraint_match_totals(); + + let constraints = constraint_scores + .into_iter() + .map(|(name, weight_multiplier, contribution, match_count)| { + ::solverforge::ConstraintAnalysis { + name, + weight_multiplier, + score: contribution, + match_count, + } + }) + .collect(); + + ::solverforge::ScoreAnalysis { score, constraints } + } + } + }); + let default_analyze = constraint_provider_analyze_ident(0); quote! { impl ::solverforge::Solvable for #solution_name { @@ -42,7 +95,8 @@ pub(super) fn generate_solvable_solution( } impl #solution_name { - /// Checks constraint weights against this model's constraints without solving. + /// Checks constraint weights against the constraints of this + /// model's `constraints` function without solving. /// /// Fails on a name that matches no constraint (with close-match /// suggestions) and on a multiplier above @@ -57,49 +111,13 @@ pub(super) fn generate_solvable_solution( ::solverforge::__internal::ConstraintSet::constraint_metadata(&constraints); weights.validate(metadata.iter().map(|entry| entry.constraint_ref)) } + + #(#analyze_fns)* } impl ::solverforge::Analyzable for #solution_name { fn analyze(&self) -> ::solverforge::ScoreAnalysis<::Score> { - use ::solverforge::__internal::{ - Director, ScoreDirector, - }; - - let constraints = #constraints_fn(); - let mut director = #director_ctor( - self.clone(), - constraints, - Self::descriptor(), - Self::entity_count, - ); - - if let ::core::option::Option::Some(weights) = - ::solverforge::__internal::PlanningSolution::constraint_weights(self) - { - let metadata = director.constraint_metadata(); - if let ::core::result::Result::Err(error) = - weights.validate(metadata.iter().map(|entry| entry.constraint_ref)) - { - panic!("{error}"); - } - } - - let score = director.calculate_score(); - let constraint_scores = director.constraint_match_totals(); - - let constraints = constraint_scores - .into_iter() - .map(|(name, weight_multiplier, contribution, match_count)| { - ::solverforge::ConstraintAnalysis { - name, - weight_multiplier, - score: contribution, - match_count, - } - }) - .collect(); - - ::solverforge::ScoreAnalysis { score, constraints } + Self::#default_analyze(self) } } } @@ -110,3 +128,9 @@ pub(super) fn generate_solvable_solution( #solvable_impl } } + +/// The generated analysis function of the solution's `index`-th constraint +/// provider (`0` is the `constraints` function). +fn constraint_provider_analyze_ident(index: usize) -> Ident { + format_ident!("__solverforge_analyze_constraint_provider_{}", index) +} diff --git a/crates/solverforge-macros/src/planning_solution/runtime/solve.rs b/crates/solverforge-macros/src/planning_solution/runtime/solve.rs index c227d193..a679b1c8 100644 --- a/crates/solverforge-macros/src/planning_solution/runtime/solve.rs +++ b/crates/solverforge-macros/src/planning_solution/runtime/solve.rs @@ -1,12 +1,12 @@ pub(super) fn generate_runtime_solve_internal( - constraints_path: &Option, + providers: &[super::config::ConstraintProvider], config_path: &Option, solver_toml_path: &Option, has_constraint_weights: bool, ) -> TokenStream { - let Some(constraints_fn) = constraints_path.as_ref() else { + if providers.is_empty() { return TokenStream::new(); - }; + } /* The base configuration is the embedded `solver_toml` file or the defaults; nothing is read from the working directory. A file that does not parse fails the solve through the returned error. */ @@ -45,27 +45,67 @@ pub(super) fn generate_runtime_solve_internal( } else { quote! { ::solverforge::__internal::try_run_solver_with_config_and_search } }; - let run = |runtime: TokenStream, provenance: TokenStream| { + /* `score_director.constraint_provider` selects the constraint set; each + provider is its own monomorphized solve, and binds its own analysis for + the job's snapshots unless `constraint_match_enabled` is false. */ + let declared: Vec = providers.iter().map(|provider| provider.name.clone()).collect(); + let dispatch = |provenance: TokenStream| { + let arms = providers.iter().enumerate().map(|(index, provider)| { + let constraints_fn = &provider.path; + let name = &provider.name; + let analyze_fn = constraint_provider_analyze_ident(index); + let pattern = if index == 0 { + quote! { ::core::option::Option::None | ::core::option::Option::Some(#name) } + } else { + quote! { ::core::option::Option::Some(#name) } + }; + quote! { + #pattern => { + runtime.bind_snapshot_analysis( + snapshot_analysis_enabled.then_some( + Self::#analyze_fn + as fn(&Self) -> ::solverforge::ScoreAnalysis< + ::Score, + >, + ), + ); + #run_solver( + self, + (|_: &Self| #constraints_fn()) as fn(&Self) -> _, + Self::descriptor(), + Self::entity_count, + runtime, + config, + Self::__solverforge_default_time_limit_secs(), + Self::__solverforge_log_scale, + #provenance, + Self::__solverforge_search_declaration, + ) + } + } + }); quote! { - #run_solver( - self, - (|_: &Self| #constraints_fn()) as fn(&Self) -> _, - Self::descriptor(), - Self::entity_count, - #runtime, - config, - Self::__solverforge_default_time_limit_secs(), - Self::__solverforge_log_scale, - #provenance, - Self::__solverforge_search_declaration, - ) + let snapshot_analysis_enabled = config.constraint_match_enabled(); + let requested_provider = config + .constraint_provider() + .map(::std::string::ToString::to_string); + match requested_provider.as_deref() { + #(#arms)* + ::core::option::Option::Some(requested) => { + ::core::result::Result::Err( + ::solverforge::RuntimeBuildError::UnknownConstraintProvider { + requested: ::std::string::ToString::to_string(requested), + declared: ::std::vec![ + #(::std::string::ToString::to_string(#declared)),* + ], + }, + ) + } + } } }; - let retained_run = run(quote! { runtime }, quote! { qualified_candidate_trace_provenance }); - let detached_run = run( - quote! { ::solverforge::SolverRuntime::detached() }, - quote! { ::core::option::Option::None }, - ); + let retained_run = dispatch(quote! { qualified_candidate_trace_provenance }); + let detached_run = dispatch(quote! { ::core::option::Option::None }); quote! { fn solve_internal( self, @@ -90,6 +130,7 @@ pub(super) fn generate_runtime_solve_internal( config: ::solverforge::SolverConfig, ) -> ::solverforge::RuntimeBuildResult { ::solverforge::__internal::init_console(); + let runtime = ::solverforge::SolverRuntime::detached(); #detached_run } } diff --git a/crates/solverforge-macros/tests/ui/fail/planning_solution_constraint_provider_without_constraints.rs b/crates/solverforge-macros/tests/ui/fail/planning_solution_constraint_provider_without_constraints.rs new file mode 100644 index 00000000..532dfcba --- /dev/null +++ b/crates/solverforge-macros/tests/ui/fail/planning_solution_constraint_provider_without_constraints.rs @@ -0,0 +1,18 @@ +use solverforge::prelude::*; + +#[planning_entity] +struct Task { + #[planning_id] + id: usize, +} + +#[planning_solution(constraint_provider = "relaxed_constraints")] +struct Plan { + #[planning_entity_collection] + tasks: Vec, + + #[planning_score] + score: Option, +} + +fn main() {} diff --git a/crates/solverforge-macros/tests/ui/fail/planning_solution_constraint_provider_without_constraints.stderr b/crates/solverforge-macros/tests/ui/fail/planning_solution_constraint_provider_without_constraints.stderr new file mode 100644 index 00000000..0c96d665 --- /dev/null +++ b/crates/solverforge-macros/tests/ui/fail/planning_solution_constraint_provider_without_constraints.stderr @@ -0,0 +1,5 @@ +error: `constraint_provider` requires `constraints`, the default constraint provider + --> tests/ui/fail/planning_solution_constraint_provider_without_constraints.rs:9:43 + | +9 | #[planning_solution(constraint_provider = "relaxed_constraints")] + | ^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/solverforge-macros/tests/ui/fail/planning_solution_duplicate_constraint_provider.rs b/crates/solverforge-macros/tests/ui/fail/planning_solution_duplicate_constraint_provider.rs new file mode 100644 index 00000000..89d9c977 --- /dev/null +++ b/crates/solverforge-macros/tests/ui/fail/planning_solution_duplicate_constraint_provider.rs @@ -0,0 +1,31 @@ +use solverforge::prelude::*; + +#[planning_entity] +struct Task { + #[planning_id] + id: usize, +} + +#[planning_solution( + constraints = "define_constraints", + constraint_provider = "relaxed_constraints", + constraint_provider = "relaxed_constraints" +)] +struct Plan { + #[planning_entity_collection] + tasks: Vec, + + #[planning_score] + score: Option, +} + +#[planning_solution(constraints = "define_constraints", constraint_provider = "define_constraints")] +struct DefaultTwice { + #[planning_entity_collection] + tasks: Vec, + + #[planning_score] + score: Option, +} + +fn main() {} diff --git a/crates/solverforge-macros/tests/ui/fail/planning_solution_duplicate_constraint_provider.stderr b/crates/solverforge-macros/tests/ui/fail/planning_solution_duplicate_constraint_provider.stderr new file mode 100644 index 00000000..3fdffadd --- /dev/null +++ b/crates/solverforge-macros/tests/ui/fail/planning_solution_duplicate_constraint_provider.stderr @@ -0,0 +1,11 @@ +error: constraint provider `relaxed_constraints` is declared more than once + --> tests/ui/fail/planning_solution_duplicate_constraint_provider.rs:12:27 + | +12 | constraint_provider = "relaxed_constraints" + | ^^^^^^^^^^^^^^^^^^^^^ + +error: constraint provider `define_constraints` is declared more than once + --> tests/ui/fail/planning_solution_duplicate_constraint_provider.rs:22:79 + | +22 | #[planning_solution(constraints = "define_constraints", constraint_provider = "define_constraints")] + | ^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/solverforge-macros/tests/ui/fail/planning_solution_unknown_argument.stderr b/crates/solverforge-macros/tests/ui/fail/planning_solution_unknown_argument.stderr index 144b5e0d..55fba51a 100644 --- a/crates/solverforge-macros/tests/ui/fail/planning_solution_unknown_argument.stderr +++ b/crates/solverforge-macros/tests/ui/fail/planning_solution_unknown_argument.stderr @@ -1,4 +1,4 @@ -error: unsupported planning_solution argument `conflict_repair_providers`; supported arguments are serde, constraints, config, solver_toml, search, conflict_repairs, scalar_groups +error: unsupported planning_solution argument `conflict_repair_providers`; supported arguments are serde, constraints, constraint_provider, config, solver_toml, search, conflict_repairs, scalar_groups --> tests/ui/fail/planning_solution_unknown_argument.rs:3:21 | 3 | #[planning_solution(conflict_repair_providers = "repairs")] diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 2b5da884..92252232 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -645,6 +645,7 @@ Retained-job runtime context passed into `Solvable::solve()`. This is the public | Method | Signature | |--------|-----------| | `detached` | `fn detached() -> Self` | +| `bind_snapshot_analysis` | `fn(&self, analysis: Option ScoreAnalysis>)` | | `job_id` | `fn(&self) -> usize` | | `is_cancel_requested` | `fn(&self) -> bool` | | `emit_progress` | `fn(&self, current_score: Option, best_score: Option, telemetry: SolverTelemetry)` | @@ -654,6 +655,13 @@ Retained-job runtime context passed into `Solvable::solve()`. This is the public | `emit_cancelled` | `fn(&self, current_score: Option, best_score: Option, telemetry: SolverTelemetry)` | | `emit_failed` | `fn(&self, error: String)` | +`bind_snapshot_analysis` sets how `SolverManager::analyze_snapshot` analyzes +the job's snapshots: `Some(analyze)` runs the analysis of the constraint set +the solve scores with, `None` disables snapshot analysis +(`SnapshotAnalysisDisabled`), and a solve that never binds is analyzed with +`Analyzable::analyze`. Generated and bridge solves bind it from +`score_director` before solving starts. + `SolverRuntime::detached()` is for synchronous configured solves that are not retained by a `SolverManager`; it owns an internal lifecycle slot and no event receiver. The slot is cached and reused per solution type per thread; each @@ -757,7 +765,8 @@ Static lifetime retained-job manager: `solve()` returns while installing an externally validated trace attestation. Other methods are `get_status()`, `get_telemetry_detail()`, `pause()`, `resume()`, `cancel()`, `delete()`, `get_snapshot()`, `analyze_snapshot()`, `add_problem_change()`, and -`active_job_count()`. +`active_job_count()`. `analyze_snapshot()` uses the analysis the job's solve +bound through `SolverRuntime::bind_snapshot_analysis`. The retained lifecycle contract is expressed in neutral `job`, `snapshot`, and `checkpoint` terminology. `pause()` settles at a runtime-owned safe boundary and `resume()` continues from the exact in-process checkpoint. `delete()` hides @@ -814,7 +823,7 @@ Snapshots are renderable and analyzable job states with monotonic `snapshot_revi ### `SolverManagerError` -Lifecycle error surface for invalid transitions and missing retained state: `NoFreeJobSlots`, `JobNotFound`, `InvalidStateTransition`, `NoSnapshotAvailable`, `SnapshotNotFound`. +Lifecycle error surface for invalid transitions and missing retained state: `NoFreeJobSlots`, `JobNotFound`, `InvalidStateTransition`, `NoSnapshotAvailable`, `SnapshotNotFound`, and `SnapshotAnalysisDisabled` (the job ran with `score_director.constraint_match_enabled = false`). ### `analyze(solution: &S) -> ScoreAnalysis` @@ -1063,6 +1072,8 @@ public graph or alternate phase-builder fallback. that does not parse; displayed as `solver configuration invalid: ...`), `Declaration { message }`, `Compilation { path, message }`, `ConstraintWeights { message }`, +`UnknownConstraintProvider { requested, declared }` (a +`score_director.constraint_provider` that names no declared provider), `Preparation { phase_index, message }`, or `Execution { phase_index, message }`; `RuntimeBuildResult` is its result alias. This is the public error surface propagated by generated and host diff --git a/crates/solverforge-solver/public-api.txt b/crates/solverforge-solver/public-api.txt index 055ac863..b2b0465b 100644 --- a/crates/solverforge-solver/public-api.txt +++ b/crates/solverforge-solver/public-api.txt @@ -377,6 +377,7 @@ struct SolverProgressRef: pub struct SolverProgressRef<'a, S: PlanningSolution> struct SolverRuntime: pub struct SolverRuntime { /* private fields */ } SolverRuntime: pub fn pause_with_snapshot( &self, solution: S, current_score: Option, best_score: Option, telemetry: SolverTelemetry, ) -> bool SolverRuntime: pub fn detached() -> Self + SolverRuntime: pub fn bind_snapshot_analysis( &self, analysis: Option ScoreAnalysis>, ) SolverRuntime: pub fn job_id(&self) -> usize SolverRuntime: pub fn is_cancel_requested(&self) -> bool SolverRuntime: pub fn emit_progress( &self, current_score: Option, best_score: Option, telemetry: SolverTelemetry, ) @@ -550,14 +551,14 @@ enum ExplorationType: pub enum ExplorationType { DepthFirst, BreadthFirst, Score enum ForagerDecision: pub enum ForagerDecision { Keep, Release, Replace(CandidateId), } enum MoveCandidateRef: pub enum MoveCandidateRef<'a, S, M> where S: PlanningSolution, M: Move,{ Borrowed(&'a M), Sequential(SequentialCompositeMoveRef<'a, S, M>), } enum MoveCandidateUndo: pub enum MoveCandidateUndo { Borrowed(U), Sequential { first: U, second: U, }, } -enum RuntimeBuildError: pub enum RuntimeBuildError { Configuration { message: String, }, Declaration { message: String, }, Compilation { path: String, message: String, }, Preparation { phase_index: usize, message: String, }, ConstraintWeights { message: String, }, Execution { phase_index: usize, message: String, }, } +enum RuntimeBuildError: pub enum RuntimeBuildError { Configuration { message: String, }, Declaration { message: String, }, Compilation { path: String, message: String, }, Preparation { phase_index: usize, message: String, }, ConstraintWeights { message: String, }, UnknownConstraintProvider { requested: String, declared: Vec, }, Execution { phase_index: usize, message: String, }, } RuntimeBuildError: pub fn declaration(message: impl Into) -> Self enum SolverEvent: pub enum SolverEvent { Progress { metadata: SolverEventMetadata, }, BestSolution { metadata: SolverEventMetadata, solution: S, }, PauseRequested { metadata: SolverEventMetadata, }, Paused { metadata: SolverEventMetadata, }, Resumed { metadata: SolverEventMetadata, }, Completed { metadata: SolverEventMetadata, solution: S, }, Cancelled { metadata: SolverEventMetadata, }, Failed { metadata: SolverEventMetadata, error: String, }, } SolverEvent: pub fn metadata(&self) -> &SolverEventMetadata enum SolverEventTryRecvError: pub enum SolverEventTryRecvError { Empty, Disconnected, } enum SolverLifecycleState: pub enum SolverLifecycleState { Solving, PauseRequested, Paused, Completed, Cancelled, Failed, } SolverLifecycleState: pub fn is_terminal(self) -> bool -enum SolverManagerError: pub enum SolverManagerError { NoFreeJobSlots, JobNotFound { job_id: usize, }, InvalidStateTransition { job_id: usize, action: &'static str, state: SolverLifecycleState, }, NoSnapshotAvailable { job_id: usize, }, SnapshotNotFound { job_id: usize, snapshot_revision: u64, }, } +enum SolverManagerError: pub enum SolverManagerError { NoFreeJobSlots, JobNotFound { job_id: usize, }, InvalidStateTransition { job_id: usize, action: &'static str, state: SolverLifecycleState, }, NoSnapshotAvailable { job_id: usize, }, SnapshotNotFound { job_id: usize, snapshot_revision: u64, }, SnapshotAnalysisDisabled { job_id: usize, }, } enum SolverProgressKind: pub enum SolverProgressKind { Progress, BestSolution, } enum SolverTerminalReason: pub enum SolverTerminalReason { Completed, TerminatedByConfig, Cancelled, Failed, } enum ThreadCount: pub enum ThreadCount { Auto, Unlimited, Specific(usize), } diff --git a/crates/solverforge-solver/src/manager/solver_manager/manager.rs b/crates/solverforge-solver/src/manager/solver_manager/manager.rs index 310908e9..aca26ad9 100644 --- a/crates/solverforge-solver/src/manager/solver_manager/manager.rs +++ b/crates/solverforge-solver/src/manager/solver_manager/manager.rs @@ -14,7 +14,7 @@ use super::receiver::SolverEventReceiver; use super::runtime::{panic_payload_to_string, SolverRuntime}; #[cfg(test)] use super::slot::SLOT_FREE; -use super::slot::{JobSlot, SLOT_SOLVING}; +use super::slot::{JobRecord, JobSlot, SnapshotAnalysisBinding, SLOT_SOLVING}; use super::types::{ SolverEvent, SolverLifecycleState, SolverManagerError, SolverSnapshot, SolverSnapshotAnalysis, SolverStatus, SolverTelemetryDetail, @@ -354,36 +354,21 @@ where if slot.public_state().is_none() { return Err(SolverManagerError::JobNotFound { job_id }); } - - if record.snapshots.is_empty() { - return Err(SolverManagerError::NoSnapshotAvailable { job_id }); - } - - match snapshot_revision { - Some(revision) => record - .snapshots - .iter() - .find(|snapshot| snapshot.snapshot_revision == revision) - .cloned() - .ok_or(SolverManagerError::SnapshotNotFound { - job_id, - snapshot_revision: revision, - }), - None => Ok(record - .snapshots - .last() - .expect("checked non-empty snapshots") - .clone()), - } + retained_snapshot(record, job_id, snapshot_revision) }) } - /// Runs [`Analyzable::analyze`] on a retained snapshot (the latest when - /// `snapshot_revision` is `None`). + /// Analyzes a retained snapshot (the latest when `snapshot_revision` is + /// `None`) with the constraint provider the job's solve selected through + /// `score_director.constraint_provider`. A job whose solve bound no + /// analysis (see [`SolverRuntime::bind_snapshot_analysis`]) is analyzed + /// with [`Analyzable::analyze`]. /// /// # Errors /// - /// The same errors as [`Self::get_snapshot`]. + /// [`SolverManagerError::SnapshotAnalysisDisabled`] when the job's solve + /// ran with `score_director.constraint_match_enabled = false`, and + /// otherwise the same errors as [`Self::get_snapshot`]. pub fn analyze_snapshot( &self, job_id: usize, @@ -392,13 +377,30 @@ where where S: Analyzable, { - let snapshot = self.get_snapshot(job_id, snapshot_revision)?; + let slot = self.slot(job_id)?; + let (bound, snapshot) = slot.with_publication(|_, record| { + if slot.public_state().is_none() { + return Err(SolverManagerError::JobNotFound { job_id }); + } + let bound = match record.snapshot_analysis { + SnapshotAnalysisBinding::Disabled => { + return Err(SolverManagerError::SnapshotAnalysisDisabled { job_id }); + } + SnapshotAnalysisBinding::Analyzable => None, + SnapshotAnalysisBinding::Bound(analyze) => Some(analyze), + }; + Ok((bound, retained_snapshot(record, job_id, snapshot_revision)?)) + })?; + let analysis = match bound { + Some(analyze) => analyze(&snapshot.solution), + None => snapshot.solution.analyze(), + }; Ok(SolverSnapshotAnalysis { job_id, lifecycle_state: snapshot.lifecycle_state, terminal_reason: snapshot.terminal_reason, snapshot_revision: snapshot.snapshot_revision, - analysis: snapshot.solution.analyze(), + analysis, }) } @@ -424,3 +426,30 @@ where .ok_or(SolverManagerError::JobNotFound { job_id }) } } + +/// The retained snapshot with `snapshot_revision`, or the latest when `None`. +fn retained_snapshot( + record: &JobRecord, + job_id: usize, + snapshot_revision: Option, +) -> Result, SolverManagerError> { + if record.snapshots.is_empty() { + return Err(SolverManagerError::NoSnapshotAvailable { job_id }); + } + match snapshot_revision { + Some(revision) => record + .snapshots + .iter() + .find(|snapshot| snapshot.snapshot_revision == revision) + .cloned() + .ok_or(SolverManagerError::SnapshotNotFound { + job_id, + snapshot_revision: revision, + }), + None => Ok(record + .snapshots + .last() + .expect("checked non-empty snapshots") + .clone()), + } +} diff --git a/crates/solverforge-solver/src/manager/solver_manager/runtime.rs b/crates/solverforge-solver/src/manager/solver_manager/runtime.rs index f7233044..6c050c3c 100644 --- a/crates/solverforge-solver/src/manager/solver_manager/runtime.rs +++ b/crates/solverforge-solver/src/manager/solver_manager/runtime.rs @@ -5,9 +5,11 @@ use std::sync::atomic::{AtomicBool, Ordering}; use solverforge_core::domain::PlanningSolution; use super::slot::{ - JobSlot, CONTROL_PAUSE, SLOT_CANCELLED, SLOT_COMPLETED, SLOT_FAILED, SLOT_SOLVING, + JobSlot, SnapshotAnalysisBinding, CONTROL_PAUSE, SLOT_CANCELLED, SLOT_COMPLETED, SLOT_FAILED, + SLOT_SOLVING, }; use super::types::{SolverEvent, SolverLifecycleState, SolverTerminalReason}; +use crate::manager::solution_manager::ScoreAnalysis; use crate::stats::SolverTelemetry; mod pause; @@ -129,6 +131,26 @@ impl SolverRuntime { } } + /// Sets how [`SolverManager::analyze_snapshot`](crate::SolverManager::analyze_snapshot) + /// analyzes this job's snapshots: `Some(analyze)` runs `analyze`, the + /// analysis of the constraint set the solve scores with; `None` disables + /// snapshot analysis, so it fails with + /// [`SolverManagerError::SnapshotAnalysisDisabled`](crate::SolverManagerError::SnapshotAnalysisDisabled). + /// A solve that never calls this is analyzed with + /// [`Analyzable::analyze`](crate::Analyzable::analyze). + /// + /// `#[planning_solution]` solves bind it from + /// `score_director.constraint_provider` and + /// `score_director.constraint_match_enabled` before solving starts. + pub fn bind_snapshot_analysis(&self, analysis: Option ScoreAnalysis>) { + self.slot.with_publication(|_, record| { + record.snapshot_analysis = match analysis { + Some(analyze) => SnapshotAnalysisBinding::Bound(analyze), + None => SnapshotAnalysisBinding::Disabled, + }; + }); + } + /// The job's slot index; `usize::MAX` for a detached runtime. pub fn job_id(&self) -> usize { self.job_id diff --git a/crates/solverforge-solver/src/manager/solver_manager/slot.rs b/crates/solverforge-solver/src/manager/solver_manager/slot.rs index fdf0098a..b3c70a3d 100644 --- a/crates/solverforge-solver/src/manager/solver_manager/slot.rs +++ b/crates/solverforge-solver/src/manager/solver_manager/slot.rs @@ -9,6 +9,7 @@ use super::types::{ SolverEvent, SolverEventMetadata, SolverLifecycleState, SolverSnapshot, SolverStatus, SolverTerminalReason, }; +use crate::manager::solution_manager::ScoreAnalysis; use crate::stats::{CandidateTraceTelemetry, SolverTelemetry}; pub(super) const SLOT_FREE: u8 = 0; @@ -23,6 +24,26 @@ const SLOT_VISIBLE: u8 = 0; const SLOT_DELETED: u8 = 1; const SLOT_DELETING: u8 = 2; +/// How `SolverManager::analyze_snapshot` analyzes a job's snapshots. The +/// solve binds it once its configuration is resolved; a solve that binds +/// nothing leaves [`Self::Analyzable`]. +pub(super) enum SnapshotAnalysisBinding { + /// The solution type's `Analyzable::analyze`. + Analyzable, + /// The analysis of the constraint provider the solve selected. + Bound(fn(&S) -> ScoreAnalysis), + /// The solve ran with `score_director.constraint_match_enabled = false`. + Disabled, +} + +impl Clone for SnapshotAnalysisBinding { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for SnapshotAnalysisBinding {} + pub(super) struct JobRecord { pub(super) terminal_reason: Option, pub(super) event_sequence: u64, @@ -39,6 +60,7 @@ pub(super) struct JobRecord { pub(super) snapshots: Vec>, pub(super) failure_message: Option, pub(super) problem_changes: ProblemChangeQueue, + pub(super) snapshot_analysis: SnapshotAnalysisBinding, } impl JobRecord { @@ -55,6 +77,7 @@ impl JobRecord { snapshots: Vec::new(), failure_message: None, problem_changes: ProblemChangeQueue::new(), + snapshot_analysis: SnapshotAnalysisBinding::Analyzable, } } @@ -70,6 +93,7 @@ impl JobRecord { self.snapshots.clear(); self.failure_message = None; self.problem_changes.reset(); + self.snapshot_analysis = SnapshotAnalysisBinding::Analyzable; } pub(super) fn push_snapshot(&mut self, mut snapshot: SolverSnapshot) -> u64 { diff --git a/crates/solverforge-solver/src/manager/solver_manager/types.rs b/crates/solverforge-solver/src/manager/solver_manager/types.rs index e27d1e57..1dc98cf9 100644 --- a/crates/solverforge-solver/src/manager/solver_manager/types.rs +++ b/crates/solverforge-solver/src/manager/solver_manager/types.rs @@ -258,6 +258,12 @@ pub enum SolverManagerError { /// The requested revision. snapshot_revision: u64, }, + /// The job's solve ran with `score_director.constraint_match_enabled = + /// false`, so its snapshots cannot be analyzed. + SnapshotAnalysisDisabled { + /// The job id. + job_id: usize, + }, } impl Display for SolverManagerError { @@ -283,6 +289,10 @@ impl Display for SolverManagerError { f, "job {job_id} has no retained snapshot revision {snapshot_revision}" ), + Self::SnapshotAnalysisDisabled { job_id } => write!( + f, + "job {job_id} was solved with score_director.constraint_match_enabled = false" + ), } } } diff --git a/crates/solverforge-solver/src/runtime_build_error.rs b/crates/solverforge-solver/src/runtime_build_error.rs index f46f0600..b22e584a 100644 --- a/crates/solverforge-solver/src/runtime_build_error.rs +++ b/crates/solverforge-solver/src/runtime_build_error.rs @@ -42,6 +42,14 @@ pub enum RuntimeBuildError { /// Actionable explanation, including close-match suggestions. message: String, }, + /// `score_director.constraint_provider` names no constraint provider the + /// solution declares. + UnknownConstraintProvider { + /// The configured provider name. + requested: String, + /// The provider names the solution declares, `constraints` first. + declared: Vec, + }, /// A reached runtime phase could not bind or execute its declared work. Execution { /// Configured phase index that reached the failure boundary. @@ -75,6 +83,16 @@ impl fmt::Display for RuntimeBuildError { Self::ConstraintWeights { message } => { write!(formatter, "invalid constraint weights: {message}") } + Self::UnknownConstraintProvider { + requested, + declared, + } => { + write!( + formatter, + "unknown constraint provider `{requested}`; declared providers: {}", + declared.join(", ") + ) + } Self::Preparation { phase_index, message, @@ -136,6 +154,18 @@ mod tests { .to_string(), "runtime execution failed at phase 3: source callback failed" ); + assert_eq!( + RuntimeBuildError::UnknownConstraintProvider { + requested: "crate::constraints::missing".to_string(), + declared: vec![ + "crate::constraints::define".to_string(), + "crate::constraints::relaxed".to_string(), + ], + } + .to_string(), + "unknown constraint provider `crate::constraints::missing`; declared providers: \ + crate::constraints::define, crate::constraints::relaxed" + ); assert_eq!( RuntimeBuildError::ConstraintWeights { message: "unknown \"Travle\"".to_string(), diff --git a/crates/solverforge/tests/constraint_providers.rs b/crates/solverforge/tests/constraint_providers.rs new file mode 100644 index 00000000..aee5a06b --- /dev/null +++ b/crates/solverforge/tests/constraint_providers.rs @@ -0,0 +1,122 @@ +//! `[score_director]`: `constraint_provider` selects the constraint set a +//! solve scores with, and `constraint_match_enabled` gates snapshot analysis. + +use solverforge::prelude::*; +use solverforge::{ + RuntimeBuildError, SolverConfig, SolverEvent, SolverManager, SolverManagerError, +}; + +#[path = "constraint_providers/domain/mod.rs"] +mod domain; + +use domain::{Plan, CONSTRUCTION_TOML}; + +fn config(score_director: &str) -> SolverConfig { + SolverConfig::from_toml_str(&format!("{CONSTRUCTION_TOML}\n{score_director}")) + .expect("the test config parses") +} + +const RELAXED: &str = "[score_director]\nconstraint_provider = \"relaxed_constraints\"\n"; +const DEFAULT_BY_NAME: &str = "[score_director]\nconstraint_provider = \"define_constraints\"\n"; +const DISABLED: &str = "[score_director]\nconstraint_match_enabled = false\n"; + +#[test] +fn the_selected_provider_scores_the_solve() { + // First fit puts every task on resource 0, which costs 1 per task under + // the default constraints and nothing under the relaxed ones. + let default = Plan::new("").solve_with_config(config("")).expect("solves"); + assert_eq!(default.score, Some(HardSoftScore::of(0, -4))); + + let by_name = Plan::new("") + .solve_with_config(config(DEFAULT_BY_NAME)) + .expect("solves"); + assert_eq!(by_name.score, Some(HardSoftScore::of(0, -4))); + + let relaxed = Plan::new("") + .solve_with_config(config(RELAXED)) + .expect("solves"); + assert_eq!(relaxed.score, Some(HardSoftScore::of(0, 0))); +} + +#[test] +fn an_unknown_provider_fails_before_solving() { + let error = Plan::new("") + .solve_with_config(config( + "[score_director]\nconstraint_provider = \"crate::missing\"\n", + )) + .expect_err("an unknown provider is rejected"); + assert_eq!( + error, + RuntimeBuildError::UnknownConstraintProvider { + requested: "crate::missing".to_string(), + declared: vec![ + "define_constraints".to_string(), + "relaxed_constraints".to_string(), + ], + } + ); +} + +/// Solves `plan` to completion and returns its job id. +fn solve_to_completion(manager: &'static SolverManager, plan: Plan) -> usize { + let (job_id, mut receiver) = manager.solve(plan).expect("job starts"); + loop { + match receiver.blocking_recv().expect("event stream stays open") { + SolverEvent::Completed { .. } => return job_id, + SolverEvent::Failed { error, .. } => panic!("solve failed: {error}"), + _ => {} + } + } +} + +fn analyzed_constraint_names(manager: &SolverManager, job_id: usize) -> Vec { + manager + .analyze_snapshot(job_id, None) + .expect("analysis is enabled") + .analysis + .constraints + .into_iter() + .map(|constraint| constraint.name) + .collect() +} + +#[test] +fn snapshot_analysis_uses_the_selected_provider() { + static MANAGER: SolverManager = SolverManager::new(); + + let default_job = solve_to_completion(&MANAGER, Plan::new("")); + assert_eq!( + analyzed_constraint_names(&MANAGER, default_job), + ["unassigned task", "placement cost"] + ); + + let relaxed_job = solve_to_completion(&MANAGER, Plan::new(RELAXED)); + assert_eq!( + analyzed_constraint_names(&MANAGER, relaxed_job), + ["unassigned task (relaxed)"] + ); + let analysis = MANAGER.analyze_snapshot(relaxed_job, None).unwrap(); + assert_eq!(analysis.analysis.score, HardSoftScore::of(0, 0)); +} + +#[test] +fn disabled_constraint_matching_rejects_snapshot_analysis() { + static MANAGER: SolverManager = SolverManager::new(); + + let job_id = solve_to_completion(&MANAGER, Plan::new(DISABLED)); + assert!(MANAGER.get_snapshot(job_id, None).is_ok()); + assert_eq!( + MANAGER.analyze_snapshot(job_id, None).unwrap_err(), + SolverManagerError::SnapshotAnalysisDisabled { job_id } + ); + + // The slot's next job binds its own analysis. + MANAGER + .delete(job_id) + .expect("a completed job can be deleted"); + let next = solve_to_completion(&MANAGER, Plan::new("")); + assert_eq!( + analyzed_constraint_names(&MANAGER, next), + ["unassigned task", "placement cost"] + ); +} diff --git a/crates/solverforge/tests/constraint_providers/domain/mod.rs b/crates/solverforge/tests/constraint_providers/domain/mod.rs new file mode 100644 index 00000000..129aabe3 --- /dev/null +++ b/crates/solverforge/tests/constraint_providers/domain/mod.rs @@ -0,0 +1,11 @@ +solverforge::planning_model! { + root = "crates/solverforge/tests/constraint_providers/domain"; + + mod plan; + mod resource; + mod task; + + pub use plan::{Plan, CONSTRUCTION_TOML}; + pub use resource::Resource; + pub use task::Task; +} diff --git a/crates/solverforge/tests/constraint_providers/domain/plan.rs b/crates/solverforge/tests/constraint_providers/domain/plan.rs new file mode 100644 index 00000000..6b022df6 --- /dev/null +++ b/crates/solverforge/tests/constraint_providers/domain/plan.rs @@ -0,0 +1,80 @@ +use solverforge::prelude::*; +use solverforge::stream::ConstraintFactory; +use solverforge::SolverConfig; + +use super::{Resource, Task}; + +#[planning_solution( + constraints = "define_constraints", + constraint_provider = "relaxed_constraints", + config = "director_config" +)] +pub struct Plan { + #[problem_fact_collection] + pub resources: Vec, + + #[planning_entity_collection] + pub tasks: Vec, + + #[planning_score] + pub score: Option, + + /// The `[score_director]` table a retained solve of this plan runs with. + pub score_director_toml: &'static str, +} + +impl Plan { + pub fn new(score_director_toml: &'static str) -> Self { + Self { + resources: (0..3).map(|id| Resource { id }).collect(), + tasks: (0..4) + .map(|id| Task { + id, + resource_idx: None, + }) + .collect(), + score: None, + score_director_toml, + } + } +} + +/// Every assigned task costs its resource index plus one. +fn define_constraints() -> impl ConstraintSet { + ( + ConstraintFactory::::new() + .for_each(Plan::tasks()) + .filter(|task: &Task| task.resource_idx.is_none()) + .penalize(HardSoftScore::ONE_HARD) + .named("unassigned task"), + ConstraintFactory::::new() + .for_each(Plan::tasks()) + .filter(|task: &Task| task.resource_idx.is_some()) + .penalize(|task: &Task| { + HardSoftScore::of(0, task.resource_idx.unwrap_or_default() as i64 + 1) + }) + .named("placement cost"), + ) +} + +/// Only assignment counts; placements are free. +fn relaxed_constraints() -> impl ConstraintSet { + (ConstraintFactory::::new() + .for_each(Plan::tasks()) + .filter(|task: &Task| task.resource_idx.is_none()) + .penalize(HardSoftScore::ONE_HARD) + .named("unassigned task (relaxed)"),) +} + +pub const CONSTRUCTION_TOML: &str = r#" +random_seed = 7 + +[[phases]] +type = "construction_heuristic" +construction_heuristic_type = "first_fit" +"#; + +fn director_config(solution: &Plan, _base: SolverConfig) -> SolverConfig { + let toml = format!("{CONSTRUCTION_TOML}\n{}", solution.score_director_toml); + SolverConfig::from_toml_str(&toml).expect("the fixture config parses") +} diff --git a/crates/solverforge/tests/constraint_providers/domain/resource.rs b/crates/solverforge/tests/constraint_providers/domain/resource.rs new file mode 100644 index 00000000..4a1467d6 --- /dev/null +++ b/crates/solverforge/tests/constraint_providers/domain/resource.rs @@ -0,0 +1,7 @@ +use solverforge::prelude::*; + +#[problem_fact] +pub struct Resource { + #[planning_id] + pub id: usize, +} diff --git a/crates/solverforge/tests/constraint_providers/domain/task.rs b/crates/solverforge/tests/constraint_providers/domain/task.rs new file mode 100644 index 00000000..c46507ea --- /dev/null +++ b/crates/solverforge/tests/constraint_providers/domain/task.rs @@ -0,0 +1,10 @@ +use solverforge::prelude::*; + +#[planning_entity] +pub struct Task { + #[planning_id] + pub id: usize, + + #[planning_variable(value_range_provider = "resources")] + pub resource_idx: Option, +}