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) diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 0d591f6d..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()`, `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 d7bb927d..8fd2916b 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 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/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/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() { 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_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 f3ffb04f..2466458c 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_termination.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_termination.rs @@ -73,9 +73,31 @@ 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` + /// 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. diff --git a/crates/solverforge-solver/src/scope/tests.rs b/crates/solverforge-solver/src/scope/tests.rs index a82c31f6..c7e1ccbb 100644 --- a/crates/solverforge-solver/src/scope/tests.rs +++ b/crates/solverforge-solver/src/scope/tests.rs @@ -473,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..bb14c13f --- /dev/null +++ b/crates/solverforge-solver/src/scope/tests/remaining_time.rs @@ -0,0 +1,78 @@ +// 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); + + 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); } 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`. 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.