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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions crates/solverforge-config/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -692,11 +692,11 @@ Derives: `Debug, Clone, Default, Deserialize, Serialize`.

| Field | Type | Default |
|-------|------|---------|
| `partitioner` | `Option<String>` | `None` |
| `partitioner` | `Option<String>` | `None`; required: the name registered with `SearchBuilder::partitioner` |
| `thread_count` | `MoveThreadCount` | `Auto` |
| `log_progress` | `bool` | `false` |
| `child_phases` | `Vec<PhaseConfig>` | `[]` |
| `termination` | `Option<TerminationConfig>` | `None` |
| `log_progress` | `bool` | `false`; logs the phase's start and end |
| `child_phases` | `Vec<PhaseConfig>` | `[]`; the phases each partition is solved with, compiled like `phases`; empty runs the default phases |
| `termination` | `Option<TerminationConfig>` | `None`; the time limit, from the phase's start, bounds all partitions and the step count limit each partition's solve; reaching one ends the phase with the partitions merged. `best_score_limit` and the unimproved limits are rejected |

### `CustomPhaseConfig`

Expand Down
11 changes: 8 additions & 3 deletions crates/solverforge-config/src/phase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,8 @@ pub struct LocalSearchConfig {
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub struct PartitionedSearchConfig {
/// Compile-time registered partitioner name.
/// Name of the partitioner the search declaration registered with
/// `SearchBuilder::partitioner`.
pub partitioner: Option<String>,

/// Threads solving the partitions: `auto` runs one per partition up to the
Expand All @@ -205,11 +206,15 @@ pub struct PartitionedSearchConfig {
#[serde(default)]
pub log_progress: bool,

/// Optional child phase list to run inside each partition.
/// The phases each partition is solved with, compiled like the solver's
/// `phases`; empty runs the default phases.
#[serde(default)]
pub child_phases: Vec<PhaseConfig>,

/// Phase termination configuration.
/// The phase's termination: the time limit, counted from the phase's
/// start, bounds all partitions and the step count limit each
/// partition's solve. Limits on the merged solution's score are
/// rejected.
pub termination: Option<TerminationConfig>,
}

Expand Down
2 changes: 2 additions & 0 deletions crates/solverforge-scoring/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ pub use stream::{
| `restore_score_state` | `fn restore_score_state(&mut self, state: DirectorScoreState<S::Score>)` | Restore a previously snapshotted committed score state |
| `reset` | `fn reset(&mut self)` | Discard incremental state after an external working-solution rewrite; default: no-op |
| `fork_replica` | `fn fork_replica(&self) -> Option<Self> where Self: Sized` | Independent evaluator replica with initialized incremental state, sharing the director's borrowed descriptor; default: `None` |
| `fork_for_solution` | `fn fork_for_solution(&self, solution: S) -> Option<Self> where Self: Sized` | Independent director of the same kind over another solution, incremental state uninitialized; default: `None` |

### `DirectorScoreState<Sc>`

Expand Down Expand Up @@ -611,6 +612,7 @@ Stock collectors include `count()`, `sum()`, `load_balance()`,
- `simple_zero(solution)` — creates `ScoreDirector<S, ()>` with empty descriptor and zero entity counter
- `with_descriptor(solution, constraints, descriptor: Desc, entity_counter)` — `Desc` is an owned `SolutionDescriptor` or a `ReplicaDescriptor`; `new()`, `simple()` and `simple_zero()` build owned-descriptor directors.
- `Director::fork_replica` forks only directors holding a `ReplicaDescriptor`, in the same weight mode: the replica clones the working solution, builds its constraint set from that clone with the recorded constructor, initializes it, and shares the same borrowed descriptor. Owned-descriptor directors return `None`.
- `Director::fork_for_solution` forks the same way over a given solution instead of a clone of the working solution, and leaves the incremental state uninitialized so the first score calculation, on the thread that solves it, initializes it. Owned-descriptor directors return `None`.
- `reset()` discards incremental state after an external rewrite of the working solution. Directors holding a `ReplicaDescriptor` rebuild their constraint set from the current working solution with the recorded constructor, so solution-derived constraint plans follow fact and entity changes; owned-descriptor directors reset their existing set.
- Implements `Director<S>`

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 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 { ... } }
trait director::Director: pub trait Director<S: PlanningSolution>: Send { Show 19 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 { ... } fn fork_for_solution(&self, _solution: S) -> 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 @@ -496,6 +496,7 @@ trait director::Director: pub trait Director<S: PlanningSolution>: Send { Show 1
director::Director: fn restore_score_state(&mut self, state: DirectorScoreState<S::Score>)
director::Director: fn reset(&mut self)
director::Director: fn fork_replica(&self) -> Option<Self> where Self: Sized,
director::Director: fn fork_for_solution(&self, _solution: S) -> Option<Self> where Self: Sized,
trait director::score_director::DirectorDescriptor: pub trait DirectorDescriptor<S, C> { // Required methods fn solution_descriptor(&self) -> &SolutionDescriptor; fn replica(&self) -> Option<(Self, fn(&S) -> C)> where Self: Sized; }
director::score_director::DirectorDescriptor: fn solution_descriptor(&self) -> &SolutionDescriptor
director::score_director::DirectorDescriptor: fn replica(&self) -> Option<(Self, fn(&S) -> C)> where Self: Sized,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,8 @@ where
fn fork_replica(&self) -> Option<Self> {
self.fork_replica_impl()
}

fn fork_for_solution(&self, solution: S) -> Option<Self> {
self.fork_for_solution_impl(solution)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -127,18 +127,26 @@ where
/// The working-solution clone is the evaluator replica clone boundary: it
/// happens when replicas are created, never per candidate or per step.
pub(crate) fn fork_replica_impl(&self) -> Option<Self> {
let mut replica = self.fork_for_solution_impl(self.working_solution.clone())?;
replica.calculate_score_impl();
Some(replica)
}

/// Builds an independent director over `solution`: a constraint set built
/// for it, the same borrowed descriptor, weight mode, entity counter and
/// score assertion. Its incremental state is uninitialized; the first
/// score calculation initializes it, on whichever thread runs it.
pub(crate) fn fork_for_solution_impl(&self, solution: S) -> Option<Self> {
let (descriptor, constraints) = self.solution_descriptor.replica()?;
let solution = self.working_solution.clone();
let replica_constraints = constraints(&solution);
let mut replica = Self::with_descriptor_in_mode(
let mut director = Self::with_descriptor_in_mode(
solution,
replica_constraints,
descriptor,
self.entity_counter,
);
replica.score_assertion = self.score_assertion;
replica.calculate_score_impl();
Some(replica)
director.score_assertion = self.score_assertion;
Some(director)
}

/* =========================================================================
Expand Down
47 changes: 47 additions & 0 deletions crates/solverforge-scoring/src/director/tests/score_director.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,53 @@ fn fork_replica_matches_score_and_stays_independent() {
assert_eq!(director.working_solution().values[1], None);
}

#[test]
fn fork_for_solution_scores_its_own_solution_independently() {
let solution = TestSolution {
values: vec![Some(1), None, None],
score: None,
};
let descriptor = test_descriptor();
let mut director = ScoreDirector::with_descriptor(
solution.clone(),
unassigned_constraints(&solution),
ReplicaDescriptor::new(&descriptor, unassigned_constraints),
|_, _| 0,
);
let main_score = director.calculate_score();

let partition = TestSolution {
values: vec![None, None, None, None, Some(2)],
score: None,
};
let mut fork = director
.fork_for_solution(partition)
.expect("director with a constraint constructor must fork");
assert!(!fork.is_initialized());
assert!(std::ptr::eq(
Director::solution_descriptor(&fork),
Director::solution_descriptor(&director)
));
assert_eq!(fork.calculate_score(), SoftScore::of(-4));

fork.before_variable_changed(0, 0);
fork.working_solution_mut().values[0] = Some(5);
fork.after_variable_changed(0, 0);
assert_eq!(fork.get_score(), SoftScore::of(-3));
assert_eq!(director.get_score(), main_score);
assert_eq!(director.working_solution().values.len(), 3);
}

#[test]
fn fork_for_solution_requires_a_replica_descriptor() {
let solution = TestSolution {
values: vec![Some(1)],
score: None,
};
let director = ScoreDirector::new(solution.clone(), (make_unassigned_constraint(),));
assert!(director.fork_for_solution(solution).is_none());
}

#[test]
fn fork_of_uninitialized_director_initializes_the_replica() {
let solution = TestSolution {
Expand Down
12 changes: 12 additions & 0 deletions crates/solverforge-scoring/src/director/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,16 @@ pub trait Director<S: PlanningSolution>: Send {
{
None
}

/// Builds an independent director of the same kind over `solution`, for
/// solving a sub-problem such as one partition of partitioned search. Its
/// incremental state is uninitialized until its first score calculation.
///
/// Returns `None` when this director cannot construct one.
fn fork_for_solution(&self, _solution: S) -> Option<Self>
where
Self: Sized,
{
None
}
}
10 changes: 8 additions & 2 deletions crates/solverforge-solver/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,11 @@ src/
├── runtime.rs — List-variable metadata plus the sole immutable compiled runtime-graph entrypoint
├── runtime/compiler/ — Immutable runtime-graph compiler, prepared runner, default policy, and executor kernels; every reached source-backed construction boundary validates stable element keys against the frozen declared stream before deciding whether work remains
├── runtime/compiler/executor/completion.rs — Structural mandatory-work gate and deferred best-solution publication
├── runtime/compiler/executor/partitioned.rs — The configured `partitioned_search` phase: registered partitioner, one child runner per partition
├── runtime/compiler/partitioned.rs — The solver configuration a partition is solved with
├── runtime/compiler/executor/runner/bench.rs — Moves a prepared runner's first lowered local search or scalar construction out for the `__bench` handles
├── runtime/compiler/executor/runner/failure.rs — Cold propagation of configured-runtime execution failures to the public run boundary
├── runtime/compiler/executor/runner/phase_plan.rs — A runner phase's index and its candidate-trace plan with the reached outcome
├── runtime/compiler/executor/runner/problem_change.rs — Problem-change pass loop and per-pass runner state reset
├── runtime/provider_cursor.rs — One lazy compound-provider cursor; static Rust providers retain typed candidates/function pointers, while host callbacks alone use raw named edits and object-safe dispatch
├── model_support.rs — Hidden `PlanningModelSupport` bridge implemented by `planning_model!` for model-owned scalar hook attachment, scalar group attachment, model/solution validation, and shadow updates
Expand Down Expand Up @@ -72,7 +75,7 @@ src/
│ ├── context/scalar/*.rs — Scalar value-source, variable, and group binding definitions
│ ├── context/scalar/group/*.rs — Assignment and member binding chunks
│ ├── search.rs — Typed custom-search surface: SearchContext, Search, CustomSearchPhase, local_search(), and typed custom phase registration
│ ├── search/*.rs — Recursive typed custom-extension registry
│ ├── search/*.rs — Recursive typed extension registry: custom phases (`custom.rs`) and partitioners (`partitioner.rs`)
│ ├── selector.rs — Internal grouped-scalar leaf and indexed compiled-selector composition root
│ ├── selector/grouped_scalar.rs — GroupedScalarSelector used as one compiled runtime leaf
│ ├── selector/types/composite.rs — Indexed Limited/union/cartesian declaration arena with stable node IDs
Expand Down Expand Up @@ -303,6 +306,7 @@ src/
│ │ ├── mod.rs — Partitioned module declarations and re-exports
│ │ ├── child_phases.rs — ChildPhases trait and tuple impls
│ │ ├── config.rs — PartitionedSearchConfig
│ │ ├── execution.rs — One partition/solve/merge pass shared by PartitionedSearchPhase and the configured runtime
│ │ ├── partitioner.rs — SolutionPartitioner trait, FunctionalPartitioner, ThreadCount
│ │ ├── partitioner_tests.rs — Tests
│ │ ├── phase.rs — PartitionedSearchPhase<P, Part>
Expand Down Expand Up @@ -711,12 +715,14 @@ working solution without cloning.

### Partitioned Search

**`PartitionedSearchPhase<S, PD, Part, SDF, PF, CP>`** — Generic over partitioner, score director factory, phase factory, child phases. Child scopes inherit runtime control, environment mode, remaining time limit, in-phase limits, and deterministic child seeds, but retained-job publication stays on the parent scope. The runtime phase-relative termination overlay is not propagated into a child scope. Pause checkpoints are emitted only from the parent full-solution boundary; child pause/cancel/config termination outcomes prevent partition merge.
**`PartitionedSearchPhase<S, PD, Part, SDF, PF, CP>`** — Generic over partitioner, score director factory, phase factory, child phases. The score director factory runs on the solving thread for each partition before the partitions are dispatched; each partition initializes its score on the thread that solves it. Child scopes inherit runtime control, environment mode, remaining time limit, in-phase limits, and deterministic child seeds, but retained-job publication stays on the parent scope. The runtime phase-relative termination overlay is not propagated into a child scope. Pause checkpoints are emitted only from the parent full-solution boundary; child pause/cancel/config termination outcomes prevent partition merge.

**`FunctionalPartitioner<S, PF, MF>`** — Closure-based partitioner.

**`ThreadCount`** — `Auto` (one thread per partition, at most one per available core), `Unlimited` (one per available core), `Specific(NonZeroUsize)` (at most that many, at most one per partition). `PartitionedSearchPhase` solves child partitions sequentially when the resolved count is `1`, otherwise it installs a dedicated Rayon pool whose worker count matches the resolved value.

**Configured `partitioned_search`** — The framework runs it; a search declaration only registers the partitioner, with `SearchBuilder::partitioner(name, |context| partitioner)`, in a namespace separate from custom phase names. `partitioner = "name"` selects it. Each partition gets a director from `Director::fork_for_solution` over the partition and a `CompiledRuntimePhaseRunner` compiled from `partition_child_config`: the parent configuration with `child_phases` as its phases (empty means the default phases) and, as termination, the earliest of the solve's and the phase's time and step count limits, the bounds that reach a partition. The graph compiler compiles that child configuration once up front, so a child phase error fails the solve with a `phases[i].partitioned_search.child_phases[j]` path. The phase's `termination` becomes a `PartitionBound`: its time limit, counted from the phase's start, is shared by every partition, and its step count limit applies to each partition's solve (each partition counts its own steps; a bound inside a partition chains to the enclosing one, which also counts the inner steps). A partition that reaches the bound ends like a phase — `should_terminate` is true without a terminal reason and `solve_limit_reached` stays false — so its best solution is merged and the solve goes on to the next phase; a partition that starts after the deadline is merged as it was. Termination keys that need the merged solution's score (`best_score_limit`, `unimproved_step_count_limit`, `unimproved_seconds_spent_limit`) are rejected at compile time with their `phases[i].partitioned_search.termination.<key>` path. `thread_count` and `log_progress` apply as for `PartitionedSearchPhase` (`log_progress` logs `phase_start` with `partition_count` and `thread_count`, and `phase_end`). A child runner borrows its parent's `RuntimeGraphInput`, so nested partitioned phases compile to the same runner type. The `RuntimeExtensionRegistry` is `Send + Sync` for that reason: partition runners compile on the threads that solve them.

## Scope Hierarchy

### `ProgressCallback<S>` — `scope/solver.rs`
Expand Down
Loading
Loading