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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
23 changes: 20 additions & 3 deletions crates/solverforge-bridge/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -206,7 +206,7 @@ threads need no scope.
```rust
pub fn try_run_dynamic_solver_with_config_parts<S, C, V, DM, IDM>(
solution: S,
constraints: fn(&S) -> C,
constraint_providers: &[DynamicConstraintProvider<'_, S, C>],
descriptor: SolutionDescriptor,
entity_count_by_descriptor: fn(&S, usize) -> usize,
runtime: SolverRuntime<S>,
Expand All @@ -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
Expand All @@ -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<S::Score>` | Snapshot analysis with this provider's constraint set |

## Scope

- Stable logical IDs for dynamic entity, fact, and variable classes.
Expand Down
2 changes: 1 addition & 1 deletion crates/solverforge-bridge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down
74 changes: 67 additions & 7 deletions crates/solverforge-bridge/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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<S::Score>,
}

impl<S: PlanningSolution, C> Clone for DynamicConstraintProvider<'_, S, C> {
fn clone(&self) -> Self {
*self
}
}

impl<S: PlanningSolution, C> 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<S, C, V, DM, IDM>(
solution: S,
constraints: fn(&S) -> C,
constraint_providers: &[DynamicConstraintProvider<'_, S, C>],
descriptor: SolutionDescriptor,
entity_count_by_descriptor: fn(&S, usize) -> usize,
runtime: SolverRuntime<S>,
Expand All @@ -89,9 +143,15 @@ where
DM: CrossEntityDistanceMeter<S> + Clone + Debug + Send + Sync + 'static,
IDM: CrossEntityDistanceMeter<S> + 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,
Expand Down
10 changes: 6 additions & 4 deletions crates/solverforge-config/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Top-level solver configuration. Derives: `Debug, Clone, Default, Deserialize, Se
| `random_seed` | `Option<u64>` | `None` | |
| `move_thread_count` | `MoveThreadCount` | `Auto` | `#[serde(default)]` |
| `termination` | `Option<TerminationConfig>` | `None` | |
| `score_director` | `Option<DirectorConfig>` | `None` | |
| `score_director` | `Option<DirectorConfig>` | `None` | Omitted: the `constraints` provider, snapshot analysis enabled |
| `phases` | `Vec<PhaseConfig>` | `[]` | `#[serde(default)]` |
| `candidate_trace` | `Option<CandidateTraceConfig>` | `None` | Opt-in bounded candidate-pull diagnostics |

Expand All @@ -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<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 @@ -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<String>` | Fully qualified constraint provider name |
| `constraint_match_enabled` | `bool` | Default: `false` |
| `constraint_provider` | `Option<String>` | 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`

Expand Down
34 changes: 27 additions & 7 deletions crates/solverforge-config/src/director.rs
Original file line number Diff line number Diff line change
@@ -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<String>,

/// 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(),
}
}
}
21 changes: 19 additions & 2 deletions crates/solverforge-config/src/solver_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ pub struct SolverConfig {
#[serde(default)]
pub termination: Option<TerminationConfig>,

/// 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<DirectorConfig>,

Expand All @@ -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
Expand Down
21 changes: 21 additions & 0 deletions crates/solverforge-config/src/tests/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
15 changes: 14 additions & 1 deletion crates/solverforge-macros/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<Option<syn::Path>>` | Extracts and parses `#[solverforge_constraints_path = "..."]`; an unparsable path is a spanned error |
| `parse_constraint_providers` | `fn(&[Attribute], &Option<syn::Path>) -> syn::Result<Vec<ConstraintProvider>>` | The `constraints` provider followed by every `#[solverforge_constraint_provider_path = "..."]`, each with its selection name |
| `parse_config_path` | `fn(&[Attribute]) -> syn::Result<Option<syn::Path>>` | Extracts and parses `#[solverforge_config_path = "..."]`; an unparsable path is a spanned error |
| `parse_solver_toml_path` | `fn(&[Attribute]) -> Option<String>` | Extracts `#[solverforge_solver_toml_path = "..."]` |
| `parse_search_path` | `fn(&[Attribute]) -> syn::Result<Option<syn::Path>>` | Extracts and parses `#[solverforge_search_path = "..."]`; an unparsable path is a spanned error |
Expand Down
Loading
Loading