From c3e6bfb36faffb74e38c6fafd83c23fd0ca92603 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 27 Nov 2026 19:47:25 +0100 Subject: [PATCH 1/6] test(solver): drop the ?Sized bounds the clone guard cannot use Clone requires Sized, so the ?Sized bound on the guard's Clone impl was ignored and clippy's needless_maybe_sized lint rejects it under -D warnings, which failed CI's all-targets clippy on main. Every carrier the guard checks is Sized, so both impls drop the bound; the guard still fails to compile when a carrier gains Clone. --- .../compiler/executor/list_leaf/tests/carriers_not_clone.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/list_leaf/tests/carriers_not_clone.rs b/crates/solverforge-solver/src/runtime/compiler/executor/list_leaf/tests/carriers_not_clone.rs index d1cb49b7..4aec05d5 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/list_leaf/tests/carriers_not_clone.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/list_leaf/tests/carriers_not_clone.rs @@ -16,11 +16,11 @@ trait AmbiguousIfClone { fn check() {} } -impl AmbiguousIfClone<()> for T {} +impl AmbiguousIfClone<()> for T {} struct IsClone; -impl AmbiguousIfClone for T {} +impl AmbiguousIfClone for T {} #[test] fn move_carriers_and_borrowed_access_are_not_clone() { From 9d4ebf356649cce20202decd3b4ba57361ed0bcf Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 27 Nov 2026 19:47:25 +0100 Subject: [PATCH 2/6] build: run make's clippy, build and test with CI's targets and features make clippy linted only library code without features, so a lint in test code passed locally and failed CI's cargo clippy --workspace --all-targets --all-features. make build and make test also left out --all-features. The three targets now run the same commands as the CI Rust job, so make lint and make test catch what CI catches. --- Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 683ffbe4..4ab63740 100644 --- a/Makefile +++ b/Makefile @@ -47,7 +47,7 @@ build: banner @printf "$(CYAN)$(BOLD)║ Building Workspace ║$(RESET)\n" @printf "$(CYAN)$(BOLD)╚══════════════════════════════════════╝$(RESET)\n\n" @printf "$(ARROW) $(BOLD)Building all crates...$(RESET)\n" - @cargo build --workspace && \ + @cargo build --workspace --all-features && \ printf "$(GREEN)$(CHECK) Build successful$(RESET)\n\n" || \ (printf "$(RED)$(CROSS) Build failed$(RESET)\n\n" && exit 1) @@ -79,7 +79,7 @@ test: banner @printf "$(CYAN)$(BOLD)║ Full Test Suite ║$(RESET)\n" @printf "$(CYAN)$(BOLD)╚══════════════════════════════════════╝$(RESET)\n\n" @printf "$(ARROW) $(BOLD)Running all tests...$(RESET)\n" - @cargo test --workspace && \ + @cargo test --workspace --all-features && \ printf "\n$(GREEN)$(CHECK) All tests passed$(RESET)\n\n" || \ (printf "\n$(RED)$(CROSS) Tests failed$(RESET)\n\n" && exit 1) @@ -162,7 +162,7 @@ file-length: clippy: @printf "$(PROGRESS) Running clippy...\n" - @cargo clippy --workspace -- -D warnings && \ + @cargo clippy --workspace --all-targets --all-features -- -D warnings && \ printf "$(GREEN)$(CHECK) Clippy passed$(RESET)\n" || \ (printf "$(RED)$(CROSS) Clippy warnings found$(RESET)\n" && exit 1) From 0dff3ef1ce216b9593063b95719f9c47dc9178a4 Mon Sep 17 00:00:00 2001 From: Stefan Lapers Date: Fri, 27 Nov 2026 16:38:42 +0100 Subject: [PATCH 3/6] feat(solver): read the solve's time limit from SolverScope SolverScope::set_time_limit is public but time_limit is crate-private, so a custom phase can set the limit but not read it. The built-in construction takes a share of the limit; a custom phase that needs the same (a time-based annealing temperature, a phase that runs for the first part of the solve) has to carry the limit beside the solver config. Make time_limit public. --- crates/solverforge-solver/WIREFRAME.md | 2 +- crates/solverforge-solver/public-api.txt | 1 + .../src/scope/solver/scope_termination.rs | 2 +- crates/solverforge-solver/src/scope/tests.rs | 11 +++++++++++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 0d591f6d..6e154139 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -755,7 +755,7 @@ Top-level scope for a retained solve. Holds score director, current score, best Custom phases draw randomness through `random_below(upper: usize) -> usize` (panics for `upper == 0`) and `random_u64() -> u64`, both from the solve's seeded generator; the generator itself is crate-private, so a `rand` upgrade is not a public API change. -Key methods: `new(score_director)`, `new_with_callback(score_director, callback, terminate, runtime)`, `with_progress_callback(F) -> SolverScope<.., F>`, `with_runtime(runtime)`, `start_solving()`, `initialize_working_solution_as_best()`, `replace_working_solution_and_reinitialize(solution)`, `score_director()`, `working_solution()`, `mutate(...)`, `current_score()`, `best_score()`, `calculate_score()`, `update_best_solution()`, `report_progress()`, `report_best_solution()`, `pause_if_requested()`, `pause_timers()`, `resume_timers()`, `mark_cancelled()`, `mark_terminated_by_config()`, `is_terminate_early()`, `set_time_limit()`. The current implementation also owns the one-second phase progress pulse and tracks a working-solution revision for built-in descriptor-driven construction completion; committed mutation goes through `mutate(...)` (or the equivalent crate-private step boundary), which clears `current_score` and advances that revision exactly once. The committed-writer contract behind that sentence: every committed change (accepted construction/local-search/VND moves, configuration-list commits, partition merges, apply-closures) funnels through one committed-mutation path, speculation never advances the revision, and model callbacks (candidate values, order keys, value legality, ownership policies) may read the whole solution — placement and enumeration therefore re-read committed global state rather than trusting a cached snapshot. `replace_working_solution_and_reinitialize(solution)` is the wholesale writer: fresh director reset, revision back to 1, frontier completion markers invalidated. Speculative phase evaluation uses `Move::do_move`, the returned typed undo value, `Move::undo_move`, and `DirectorScoreState` snapshots to restore both solution values and committed score state after scoring a candidate, and sequential composite doability checks run `Move::is_doable_with_working_preview` on the caller's live director instead of an immutable preview clone. An internal phase-relative termination overlay records the best and last-improving committed scores only while an explicit runtime construction or local-search phase executes; it is neither a public `SolverScope` setting nor child-scope state. Internal prompt-control plumbing also exposes immutable `pending_control()` so built-in phases can abandon partial steps and unwind to runtime-owned boundaries before settling pause/cancel/config termination or a queued real-time problem change. +Key methods: `new(score_director)`, `new_with_callback(score_director, callback, terminate, runtime)`, `with_progress_callback(F) -> SolverScope<.., F>`, `with_runtime(runtime)`, `start_solving()`, `initialize_working_solution_as_best()`, `replace_working_solution_and_reinitialize(solution)`, `score_director()`, `working_solution()`, `mutate(...)`, `current_score()`, `best_score()`, `calculate_score()`, `update_best_solution()`, `report_progress()`, `report_best_solution()`, `pause_if_requested()`, `pause_timers()`, `resume_timers()`, `mark_cancelled()`, `mark_terminated_by_config()`, `is_terminate_early()`, `time_limit()`, `set_time_limit()`. The current implementation also owns the one-second phase progress pulse and tracks a working-solution revision for built-in descriptor-driven construction completion; committed mutation goes through `mutate(...)` (or the equivalent crate-private step boundary), which clears `current_score` and advances that revision exactly once. The committed-writer contract behind that sentence: every committed change (accepted construction/local-search/VND moves, configuration-list commits, partition merges, apply-closures) funnels through one committed-mutation path, speculation never advances the revision, and model callbacks (candidate values, order keys, value legality, ownership policies) may read the whole solution — placement and enumeration therefore re-read committed global state rather than trusting a cached snapshot. `replace_working_solution_and_reinitialize(solution)` is the wholesale writer: fresh director reset, revision back to 1, frontier completion markers invalidated. Speculative phase evaluation uses `Move::do_move`, the returned typed undo value, `Move::undo_move`, and `DirectorScoreState` snapshots to restore both solution values and committed score state after scoring a candidate, and sequential composite doability checks run `Move::is_doable_with_working_preview` on the caller's live director instead of an immutable preview clone. An internal phase-relative termination overlay records the best and last-improving committed scores only while an explicit runtime construction or local-search phase executes; it is neither a public `SolverScope` setting nor child-scope state. Internal prompt-control plumbing also exposes immutable `pending_control()` so built-in phases can abandon partial steps and unwind to runtime-owned boundaries before settling pause/cancel/config termination or a queued real-time problem change. Public fields: `inphase_step_count_limit`, `inphase_move_count_limit`, `inphase_score_calc_count_limit`. diff --git a/crates/solverforge-solver/public-api.txt b/crates/solverforge-solver/public-api.txt index d7bb927d..1715d884 100644 --- a/crates/solverforge-solver/public-api.txt +++ b/crates/solverforge-solver/public-api.txt @@ -427,6 +427,7 @@ struct SolverScope: pub struct SolverScope<'t, S: PlanningSolution, D: Director< SolverScope: pub fn take_best_or_working_solution(self) -> S SolverScope: pub fn take_solution_and_stats( self, ) -> (S, Option, S::Score, SolverStats, SolverTerminalReason) SolverScope: pub fn is_terminate_early(&self) -> bool + SolverScope: pub fn time_limit(&self) -> Option SolverScope: pub fn set_time_limit(&mut self, limit: Duration) SolverScope: pub fn pause_if_requested(&mut self) SolverScope: pub fn pause_timers(&mut self) diff --git a/crates/solverforge-solver/src/scope/solver/scope_termination.rs b/crates/solverforge-solver/src/scope/solver/scope_termination.rs index f3ffb04f..122de431 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_termination.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_termination.rs @@ -74,7 +74,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> } /// The solve's time limit, when it has one. - pub(crate) fn time_limit(&self) -> Option { + pub fn time_limit(&self) -> Option { self.time_limit } diff --git a/crates/solverforge-solver/src/scope/tests.rs b/crates/solverforge-solver/src/scope/tests.rs index a82c31f6..5ce541f0 100644 --- a/crates/solverforge-solver/src/scope/tests.rs +++ b/crates/solverforge-solver/src/scope/tests.rs @@ -24,6 +24,17 @@ fn test_solver_scope_creation() { assert_eq!(scope.total_step_count(), 0); } +#[test] +fn time_limit_reads_back_what_was_set() { + let director = create_simple_nqueens_director(2); + let mut scope = SolverScope::new(director); + assert_eq!(scope.time_limit(), None); + + scope.set_time_limit(std::time::Duration::from_secs(30)); + + assert_eq!(scope.time_limit(), Some(std::time::Duration::from_secs(30))); +} + #[test] fn test_solver_scope_update_best() { let director = create_simple_nqueens_director(2); From abd313f20efe3da1e67a8fde2702cdb9b88e7ef6 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 27 Nov 2026 19:37:46 +0100 Subject: [PATCH 4/6] refactor(solver): expose remaining time instead of the raw time limit A custom phase that plans its own schedule needs to know how much time is left before a time limit ends it. The raw time_limit() field answers that only for a top-level solve. A custom phase running as a partition's child phase sees None, because its scope carries the enclosing solve's deadline and any partition bound instead of a limit, so a schedule built on it silently loses its time bound there. Using the raw limit also invites a phase to shorten the solve's limit and restore it, which cannot put back "no limit" when there was none. SolverScope::remaining_time() returns the solve's time limit minus solver-active time, or the earliest inherited deadline (enclosing solve or partition bound chain), whichever ends first. It returns None when no time limit applies and zero once one is reached. time_limit() goes back to crate-private; built-in construction still reads it for its share of the solve. Tests cover the top-level limit, the inherited deadline in a child scope and the nested partition bound, and the facade test calls the method from outside the crate. --- crates/solverforge-solver/WIREFRAME.md | 2 +- crates/solverforge-solver/public-api.txt | 2 +- .../src/scope/solver/scope_child.rs | 8 ++ .../src/scope/solver/scope_termination.rs | 29 ++++++- crates/solverforge-solver/src/scope/tests.rs | 12 +-- .../src/scope/tests/remaining_time.rs | 83 +++++++++++++++++++ .../tests/facade_reachability/domain/plan.rs | 2 + 7 files changed, 124 insertions(+), 14 deletions(-) create mode 100644 crates/solverforge-solver/src/scope/tests/remaining_time.rs diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 6e154139..d481a46e 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -755,7 +755,7 @@ Top-level scope for a retained solve. Holds score director, current score, best Custom phases draw randomness through `random_below(upper: usize) -> usize` (panics for `upper == 0`) and `random_u64() -> u64`, both from the solve's seeded generator; the generator itself is crate-private, so a `rand` upgrade is not a public API change. -Key methods: `new(score_director)`, `new_with_callback(score_director, callback, terminate, runtime)`, `with_progress_callback(F) -> SolverScope<.., F>`, `with_runtime(runtime)`, `start_solving()`, `initialize_working_solution_as_best()`, `replace_working_solution_and_reinitialize(solution)`, `score_director()`, `working_solution()`, `mutate(...)`, `current_score()`, `best_score()`, `calculate_score()`, `update_best_solution()`, `report_progress()`, `report_best_solution()`, `pause_if_requested()`, `pause_timers()`, `resume_timers()`, `mark_cancelled()`, `mark_terminated_by_config()`, `is_terminate_early()`, `time_limit()`, `set_time_limit()`. The current implementation also owns the one-second phase progress pulse and tracks a working-solution revision for built-in descriptor-driven construction completion; committed mutation goes through `mutate(...)` (or the equivalent crate-private step boundary), which clears `current_score` and advances that revision exactly once. The committed-writer contract behind that sentence: every committed change (accepted construction/local-search/VND moves, configuration-list commits, partition merges, apply-closures) funnels through one committed-mutation path, speculation never advances the revision, and model callbacks (candidate values, order keys, value legality, ownership policies) may read the whole solution — placement and enumeration therefore re-read committed global state rather than trusting a cached snapshot. `replace_working_solution_and_reinitialize(solution)` is the wholesale writer: fresh director reset, revision back to 1, frontier completion markers invalidated. Speculative phase evaluation uses `Move::do_move`, the returned typed undo value, `Move::undo_move`, and `DirectorScoreState` snapshots to restore both solution values and committed score state after scoring a candidate, and sequential composite doability checks run `Move::is_doable_with_working_preview` on the caller's live director instead of an immutable preview clone. An internal phase-relative termination overlay records the best and last-improving committed scores only while an explicit runtime construction or local-search phase executes; it is neither a public `SolverScope` setting nor child-scope state. Internal prompt-control plumbing also exposes immutable `pending_control()` so built-in phases can abandon partial steps and unwind to runtime-owned boundaries before settling pause/cancel/config termination or a queued real-time problem change. +Key methods: `new(score_director)`, `new_with_callback(score_director, callback, terminate, runtime)`, `with_progress_callback(F) -> SolverScope<.., F>`, `with_runtime(runtime)`, `start_solving()`, `initialize_working_solution_as_best()`, `replace_working_solution_and_reinitialize(solution)`, `score_director()`, `working_solution()`, `mutate(...)`, `current_score()`, `best_score()`, `calculate_score()`, `update_best_solution()`, `report_progress()`, `report_best_solution()`, `pause_if_requested()`, `pause_timers()`, `resume_timers()`, `mark_cancelled()`, `mark_terminated_by_config()`, `is_terminate_early()`, `remaining_time()`, `set_time_limit()`. `remaining_time()` is the time left before a time limit ends the scope: the solve's limit minus solver-active time, or a deadline inherited from an enclosing solve or partition, whichever ends first; `None` without a time limit. The current implementation also owns the one-second phase progress pulse and tracks a working-solution revision for built-in descriptor-driven construction completion; committed mutation goes through `mutate(...)` (or the equivalent crate-private step boundary), which clears `current_score` and advances that revision exactly once. The committed-writer contract behind that sentence: every committed change (accepted construction/local-search/VND moves, configuration-list commits, partition merges, apply-closures) funnels through one committed-mutation path, speculation never advances the revision, and model callbacks (candidate values, order keys, value legality, ownership policies) may read the whole solution — placement and enumeration therefore re-read committed global state rather than trusting a cached snapshot. `replace_working_solution_and_reinitialize(solution)` is the wholesale writer: fresh director reset, revision back to 1, frontier completion markers invalidated. Speculative phase evaluation uses `Move::do_move`, the returned typed undo value, `Move::undo_move`, and `DirectorScoreState` snapshots to restore both solution values and committed score state after scoring a candidate, and sequential composite doability checks run `Move::is_doable_with_working_preview` on the caller's live director instead of an immutable preview clone. An internal phase-relative termination overlay records the best and last-improving committed scores only while an explicit runtime construction or local-search phase executes; it is neither a public `SolverScope` setting nor child-scope state. Internal prompt-control plumbing also exposes immutable `pending_control()` so built-in phases can abandon partial steps and unwind to runtime-owned boundaries before settling pause/cancel/config termination or a queued real-time problem change. Public fields: `inphase_step_count_limit`, `inphase_move_count_limit`, `inphase_score_calc_count_limit`. diff --git a/crates/solverforge-solver/public-api.txt b/crates/solverforge-solver/public-api.txt index 1715d884..8fd2916b 100644 --- a/crates/solverforge-solver/public-api.txt +++ b/crates/solverforge-solver/public-api.txt @@ -427,7 +427,7 @@ struct SolverScope: pub struct SolverScope<'t, S: PlanningSolution, D: Director< SolverScope: pub fn take_best_or_working_solution(self) -> S SolverScope: pub fn take_solution_and_stats( self, ) -> (S, Option, S::Score, SolverStats, SolverTerminalReason) SolverScope: pub fn is_terminate_early(&self) -> bool - SolverScope: pub fn time_limit(&self) -> Option + SolverScope: pub fn remaining_time(&self) -> Option SolverScope: pub fn set_time_limit(&mut self, limit: Duration) SolverScope: pub fn pause_if_requested(&mut self) SolverScope: pub fn pause_timers(&mut self) diff --git a/crates/solverforge-solver/src/scope/solver/scope_child.rs b/crates/solverforge-solver/src/scope/solver/scope_child.rs index 9acaba61..a675d583 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_child.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_child.rs @@ -105,6 +105,14 @@ impl<'p> PartitionBound<'p> { } } + /// The earliest deadline of this bound and the bounds enclosing it. + fn deadline(&self) -> Option { + match (self.deadline, self.parent.and_then(PartitionBound::deadline)) { + (Some(own), Some(parent)) => Some(own.min(parent)), + (own, parent) => own.or(parent), + } + } + /// Whether a limit of this bound or an enclosing one is reached. pub(crate) fn reached(&self) -> bool { self.deadline diff --git a/crates/solverforge-solver/src/scope/solver/scope_termination.rs b/crates/solverforge-solver/src/scope/solver/scope_termination.rs index 122de431..346776a6 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_termination.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_termination.rs @@ -74,10 +74,37 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> } /// The solve's time limit, when it has one. - pub fn time_limit(&self) -> Option { + pub(crate) fn time_limit(&self) -> Option { self.time_limit } + /// How much longer this scope may run before a time limit ends it: the + /// solve's time limit minus solver-active time, or a deadline inherited + /// from an enclosing solve or partition, whichever ends first. `None` + /// when no time limit applies; zero once one is reached. + /// + /// A custom phase reads it to fit its own schedule to the time that is + /// left, for example a temperature that falls with the remaining time or + /// a phase that takes a share of it and then returns. It never needs to + /// change the solve's limit to do so. + pub fn remaining_time(&self) -> Option { + let from_limit = self + .time_limit + .map(|limit| limit.saturating_sub(self.elapsed().unwrap_or_default())); + let deadline = match ( + self.time_deadline, + self.partition_bound.and_then(PartitionBound::deadline), + ) { + (Some(own), Some(partition)) => Some(own.min(partition)), + (own, partition) => own.or(partition), + }; + let from_deadline = deadline.map(|deadline| deadline.saturating_duration_since(Instant::now())); + match (from_limit, from_deadline) { + (Some(limit), Some(deadline)) => Some(limit.min(deadline)), + (limit, deadline) => limit.or(deadline), + } + } + /// Stops the solve once this much solver-active time has elapsed. pub fn set_time_limit(&mut self, limit: Duration) { self.time_limit = Some(limit); diff --git a/crates/solverforge-solver/src/scope/tests.rs b/crates/solverforge-solver/src/scope/tests.rs index 5ce541f0..c7e1ccbb 100644 --- a/crates/solverforge-solver/src/scope/tests.rs +++ b/crates/solverforge-solver/src/scope/tests.rs @@ -24,17 +24,6 @@ fn test_solver_scope_creation() { assert_eq!(scope.total_step_count(), 0); } -#[test] -fn time_limit_reads_back_what_was_set() { - let director = create_simple_nqueens_director(2); - let mut scope = SolverScope::new(director); - assert_eq!(scope.time_limit(), None); - - scope.set_time_limit(std::time::Duration::from_secs(30)); - - assert_eq!(scope.time_limit(), Some(std::time::Duration::from_secs(30))); -} - #[test] fn test_solver_scope_update_best() { let director = create_simple_nqueens_director(2); @@ -484,4 +473,5 @@ fn working_solution_generation_is_monotonic_across_commits_and_replacement() { mod environment_mode; mod partition_bound; mod problem_change; +mod remaining_time; mod weight_mode; diff --git a/crates/solverforge-solver/src/scope/tests/remaining_time.rs b/crates/solverforge-solver/src/scope/tests/remaining_time.rs new file mode 100644 index 00000000..295c1241 --- /dev/null +++ b/crates/solverforge-solver/src/scope/tests/remaining_time.rs @@ -0,0 +1,83 @@ +// Remaining time of a solver scope: the solve's time limit, an inherited +// deadline, and partition bounds. + +use std::time::Duration; + +use solverforge_config::TerminationConfig; + +use crate::scope::{PartitionBound, SolverScope}; +use crate::test_utils::create_simple_nqueens_director; + +#[test] +fn remaining_time_follows_the_solve_time_limit() { + let mut scope = SolverScope::new(create_simple_nqueens_director(2)); + assert_eq!( + scope.remaining_time(), + None, + "no time limit, no remaining time" + ); + + scope.set_time_limit(Duration::from_secs(30)); + assert_eq!( + scope.remaining_time(), + Some(Duration::from_secs(30)), + "before the solve starts the whole limit remains" + ); + + scope.start_solving(); + let remaining = scope.remaining_time().expect("a time limit applies"); + assert!(remaining <= Duration::from_secs(30)); + assert!(remaining > Duration::from_secs(29)); + + scope.set_time_limit(Duration::ZERO); + assert_eq!(scope.remaining_time(), Some(Duration::ZERO)); +} + +#[test] +fn remaining_time_in_a_partition_counts_the_inherited_deadline() { + let mut parent = SolverScope::new(create_simple_nqueens_director(4)); + parent.set_time_limit(Duration::from_secs(30)); + parent.start_solving(); + let budget = parent.child_phase_budget(); + let child = parent + .child_config(Some(&budget)) + .build_scope(create_simple_nqueens_director(4), 7); + + assert_eq!( + child.time_limit(), + None, + "a partition carries a deadline, not a limit" + ); + let remaining = child + .remaining_time() + .expect("the solve's deadline applies"); + assert!(remaining <= Duration::from_secs(30)); + assert!(remaining > Duration::from_secs(29)); +} + +#[test] +fn remaining_time_counts_the_partition_bound_and_its_parents() { + let outer_config = TerminationConfig { + seconds_spent_limit: Some(5), + ..TerminationConfig::default() + }; + let inner_config = TerminationConfig { + seconds_spent_limit: Some(60), + ..TerminationConfig::default() + }; + let outer = PartitionBound::new(None, Some(&outer_config)).expect("a time bound"); + let inner = PartitionBound::new(Some(&outer), Some(&inner_config)).expect("a time bound"); + let parent = SolverScope::new(create_simple_nqueens_director(4)); + let budget = parent.child_phase_budget(); + let child = parent + .child_config(Some(&budget)) + .with_partition_bound(Some(&inner)) + .build_scope(create_simple_nqueens_director(4), 7); + + let remaining = child.remaining_time().expect("the enclosing bound applies"); + assert!( + remaining <= Duration::from_secs(5), + "the outer 5 s bound ends first" + ); + assert!(remaining > Duration::from_secs(4)); +} diff --git a/crates/solverforge/tests/facade_reachability/domain/plan.rs b/crates/solverforge/tests/facade_reachability/domain/plan.rs index fb1e9991..4c976d8c 100644 --- a/crates/solverforge/tests/facade_reachability/domain/plan.rs +++ b/crates/solverforge/tests/facade_reachability/domain/plan.rs @@ -61,6 +61,8 @@ impl CustomSearchPhase for ProbePhase { assert!(task < task_count); let _ = solver_scope.random_u64(); let _: &solverforge::stats::SolverStats = solver_scope.stats(); + // The probe solve sets a step limit only, so no time remains to count. + assert_eq!(solver_scope.remaining_time(), None); PROBE_PHASE_DRAWS.fetch_add(1, Ordering::SeqCst); } From 6f69330b3292480887a144e5aca7309601e07301 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 27 Nov 2026 19:47:25 +0100 Subject: [PATCH 5/6] fix(solver): budget a partition's optional construction from its deadline The optional assignment pass takes a fifth of the solve's time limit. It read the raw time limit, which a partition's child scope does not carry: the partition inherits the solve's deadline instead. Default phases run inside partitions, so there the optional pass had no time cap and could spend the whole partition deadline before local search started. The share is now a fifth of the scope's span, its solver-active time plus remaining_time(), which equals the time limit for a top-level solve and the inherited deadline for a partition. The crate-private time_limit() accessor has no reader left and is removed. --- .../compiler/executor/default_construction.rs | 13 ++++++--- .../executor/prepared/tests/defaults.rs | 27 +++++++++++++++++++ .../src/scope/solver/scope_termination.rs | 5 ---- .../src/scope/tests/remaining_time.rs | 5 ---- docs/configuration.md | 4 ++- 5 files changed, 39 insertions(+), 15 deletions(-) diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/default_construction.rs b/crates/solverforge-solver/src/runtime/compiler/executor/default_construction.rs index 8b9a3be6..d0653c7c 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/default_construction.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/default_construction.rs @@ -142,8 +142,11 @@ where /// Optional rows stay reachable to local search's optional-assignment moves. const OPTIONAL_CONSTRUCTION_BUDGET_PERCENT: u32 = 20; -/// The optional pass's remaining share of the solve's time limit, rounded up -/// to whole seconds, or `None` when the solve has no time limit. +/// The optional pass's remaining share of the scope's time span, rounded up +/// to whole seconds, or `None` when no time limit applies. The span is the +/// solver-active time so far plus the remaining time, so a top-level solve +/// shares its time limit and a partition shares the time its inherited +/// deadline leaves it. pub(super) fn optional_construction_termination( solver_scope: &SolverScope<'_, S, D, ProgressCb>, ) -> Option @@ -152,8 +155,10 @@ where D: Director, ProgressCb: ProgressCallback, { - let share = solver_scope.time_limit()? * OPTIONAL_CONSTRUCTION_BUDGET_PERCENT / 100; - let remaining = share.saturating_sub(solver_scope.elapsed().unwrap_or_default()); + let elapsed = solver_scope.elapsed().unwrap_or_default(); + let span = elapsed + solver_scope.remaining_time()?; + let share = span * OPTIONAL_CONSTRUCTION_BUDGET_PERCENT / 100; + let remaining = share.saturating_sub(elapsed); Some(solverforge_config::TerminationConfig { seconds_spent_limit: Some(remaining.as_millis().div_ceil(1000) as u64), ..solverforge_config::TerminationConfig::default() diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests/defaults.rs b/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests/defaults.rs index 5ff2ff87..48c1f9fa 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests/defaults.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests/defaults.rs @@ -249,3 +249,30 @@ fn optional_construction_keeps_its_share_of_a_time_limited_solve() { "the 0.8 s share rounds up to whole seconds" ); } + +#[test] +fn optional_construction_in_a_partition_shares_the_inherited_deadline() { + use crate::runtime::compiler::executor::default_construction::optional_construction_termination; + + let director = + ScoreDirector::simple(plan(vec![7], vec![Vec::new()]), descriptor(), |plan, _| { + entity_count(plan) + }); + let mut parent = SolverScope::new(director); + parent.set_time_limit(std::time::Duration::from_secs(60)); + parent.start_solving(); + let budget = parent.child_phase_budget(); + let child_director = + ScoreDirector::simple(plan(vec![7], vec![Vec::new()]), descriptor(), |plan, _| { + entity_count(plan) + }); + let mut child = parent + .child_config(Some(&budget)) + .build_scope(child_director, 7); + child.start_solving(); + assert_eq!( + optional_construction_termination(&child).and_then(|config| config.seconds_spent_limit), + Some(12), + "a fifth of the 60 s the partition inherits" + ); +} diff --git a/crates/solverforge-solver/src/scope/solver/scope_termination.rs b/crates/solverforge-solver/src/scope/solver/scope_termination.rs index 346776a6..2466458c 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_termination.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_termination.rs @@ -73,11 +73,6 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> || self.inphase_score_calc_count_limit_reached() } - /// The solve's time limit, when it has one. - pub(crate) fn time_limit(&self) -> Option { - self.time_limit - } - /// How much longer this scope may run before a time limit ends it: the /// solve's time limit minus solver-active time, or a deadline inherited /// from an enclosing solve or partition, whichever ends first. `None` diff --git a/crates/solverforge-solver/src/scope/tests/remaining_time.rs b/crates/solverforge-solver/src/scope/tests/remaining_time.rs index 295c1241..bb14c13f 100644 --- a/crates/solverforge-solver/src/scope/tests/remaining_time.rs +++ b/crates/solverforge-solver/src/scope/tests/remaining_time.rs @@ -43,11 +43,6 @@ fn remaining_time_in_a_partition_counts_the_inherited_deadline() { .child_config(Some(&budget)) .build_scope(create_simple_nqueens_director(4), 7); - assert_eq!( - child.time_limit(), - None, - "a partition carries a deadline, not a limit" - ); let remaining = child .remaining_time() .expect("the solve's deadline applies"); diff --git a/docs/configuration.md b/docs/configuration.md index 07fba5e3..dedf29f8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -157,7 +157,9 @@ leaves the rest to local search, whose optional-assignment moves keep filling optional rows. The step reports the share it got as `time_budget_seconds`. On the rostering bench the pass needs about 7 s: uncapped it leaves a 10 s solve 2 s of search, and capped at a tenth it costs a 60 s solve quality; a fifth -does neither. A solve without a time limit runs the pass to completion. +does neither. A partition's construction takes a fifth of the time its +inherited deadline leaves it. A solve without a time limit runs the pass to +completion. An explicit scalar construction target that names an assignment-owned variable must use the owning `group_name`. From 6421406e58c85b10b5c29b8d92c19ebb6e87df78 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 27 Nov 2026 19:47:25 +0100 Subject: [PATCH 6/6] docs(solver): describe remaining_time for custom phases The custom-phase guide now names SolverScope::remaining_time as the way a phase reads its time, including the deadline it inherits as a partition's child phase, and says a phase that takes a share of the time returns when the share is spent instead of changing the solve's limit. --- docs/extend-solver.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/extend-solver.md b/docs/extend-solver.md index b75c3446..c7d3487b 100644 --- a/docs/extend-solver.md +++ b/docs/extend-solver.md @@ -175,7 +175,11 @@ custom phase that owns its concrete decider and register it through the typed search function. A custom phase implements `CustomSearchPhase` against `solverforge::{SolverScope, ProgressCallback}`; it draws randomness with `SolverScope::random_below` and `random_u64`, which use the solve's seeded -generator. Assignment-backed scalar variables still belong to their +generator. It reads the time it has left with `SolverScope::remaining_time`, +which counts the solve's time limit and any deadline it inherits as a +partition's child phase; a phase that takes a share of that time returns once +the share is spent instead of changing the solve's limit. Assignment-backed +scalar variables still belong to their `ScalarGroup`; exact scalar assignment should not be configured as a second path beside grouped assignment.