diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 596534d0..466393d2 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -977,8 +977,8 @@ carry a `reason` attribute naming the model declaration that selected them `required_assignments_remain`, `only_optional_assignments_remain`, `scalar_slot_outside_assignment_groups`, `route_hooks_declared_and_route_non_empty`, `element_groups_declared`, `list_elements_remain_unassigned`). The optional -assignment step of a time-limited solve also carries `time_budget_seconds`, -the share of the time limit it was allowed. +assignment step of a time-limited solve also carries `time_budget_ms`, +the share of the time limit it was allowed, in milliseconds. The default local-search node carries acceptor, forager, `forager_accepted_count_limit`, `selection_order`, `weighting` (`equal`, or `fixed:[...]` with one cost weight per selector) and diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_entity.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_entity.rs index 66eaa7d8..08b1b9d5 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_entity.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_entity.rs @@ -6,7 +6,7 @@ use super::assignment_candidate::{ use super::assignment_path::{ assignment_move_for_entity_value, move_from_edits, AssignmentRequest, }; -use super::assignment_scarcity::sort_values_by_required_scarcity; +use super::assignment_scarcity::{required_value_degrees, sort_values_by_required_scarcity}; use super::assignment_state::{CapacityConflict, ScalarAssignmentState}; use crate::builder::ScalarAssignmentBinding; use crate::heuristic::r#move::CompoundScalarMove; @@ -21,9 +21,14 @@ pub(super) struct EntityValueCursor { pub(super) value_degrees: FastMap, pub(super) options: ScalarAssignmentMoveOptions, pub(super) kind: AssignmentMoveKind, - /* Required rows try every value directly (search depth 0) before any - value with augmenting rematches, so a row with a free value never pays - for a rematch search. False during the direct pass. */ + /* Required rows are placed in two passes over the scarcity order. The + direct pass gives each row its first value that is free (search depth + 0), with the value degrees of every row the pass started with; the + augmenting pass then places the rows left over with rematches, its + degrees counting only the rows that still need a value. A row with a + free value never pays for a rematch search, and one row's rematch never + takes the value a later row would have had free. False during the direct + pass. */ pub(super) augmenting: bool, } @@ -41,7 +46,13 @@ impl EntityValueCursor { ShouldStop: FnMut() -> bool, { let intent = self.kind.intent(); - while self.entity_pos < self.entities.len() { + loop { + if self.entity_pos == self.entities.len() { + if !self.begin_augmenting_pass(group, solution, state, should_stop)? { + return None; + } + continue; + } if should_stop() { return None; } @@ -52,7 +63,6 @@ impl EntityValueCursor { self.entity_pos += 1; self.values.clear(); self.value_pos = 0; - self.augmenting = false; continue; } if self.values.is_empty() { @@ -102,20 +112,52 @@ impl EntityValueCursor { return Some(mov); } } - if self.kind == AssignmentMoveKind::Required - && !self.augmenting - && self.options.max_depth > 0 - { - self.augmenting = true; - self.value_pos = 0; - continue; - } self.entity_pos += 1; self.values.clear(); self.value_pos = 0; - self.augmenting = false; } - None + } + + /* Ends the direct pass of a required cursor: generation restarts at the + first row with rematches allowed, and the value degrees are recounted + over the rows still unassigned. `Some(false)` when there is no + augmenting pass to run, `None` when stopped while recounting. */ + fn begin_augmenting_pass( + &mut self, + group: &ScalarAssignmentBinding, + solution: &S, + state: &ScalarAssignmentState, + should_stop: &mut ShouldStop, + ) -> Option + where + S: PlanningSolution, + ShouldStop: FnMut() -> bool, + { + if self.kind != AssignmentMoveKind::Required + || self.augmenting + || self.options.max_depth == 0 + { + return Some(false); + } + self.entities + .retain(|entity_index| state.current_value(*entity_index).is_none()); + if self.entities.is_empty() { + return Some(false); + } + if self.options.required_scarcity_ordering { + self.value_degrees = required_value_degrees( + group, + solution, + &self.entities, + self.options.value_candidate_limit, + should_stop, + )?; + } + self.augmenting = true; + self.entity_pos = 0; + self.values.clear(); + self.value_pos = 0; + Some(true) } fn request_depth(&self) -> usize { @@ -135,11 +177,11 @@ impl EntityValueCursor { } self.values.clear(); self.value_pos = 0; - self.augmenting = false; } - /* Drops a newly assigned required row from the value degrees, so the - degrees keep counting only the rows that still need a value. */ + /* Drops a required row the augmenting pass assigned from the value + degrees, so they keep counting only the rows that still need a value. + The direct pass keeps the degrees it started with. */ pub(super) fn retire_required_row( &mut self, group: &ScalarAssignmentBinding, @@ -147,7 +189,7 @@ impl EntityValueCursor { entity_index: usize, values: &mut Vec, ) { - if self.value_degrees.is_empty() { + if !self.augmenting || self.value_degrees.is_empty() { return; } group.candidate_values_into( diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/construction_resume.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/construction_resume.rs index a4f44299..7f9ea96e 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/construction_resume.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/construction_resume.rs @@ -2,8 +2,9 @@ The placement cursor keeps its assignment state and row order from one placement to the next, so a construction reads each row's domain a bounded -number of times instead of once per placement, and a required row takes a -free value before any value that needs an augmenting rematch. */ +number of times instead of once per placement. Required rows take free +values in a direct pass, with the value degrees that pass started with, +before an augmenting pass rematches rows for the rest. */ use std::cell::Cell; @@ -80,3 +81,22 @@ fn required_rows_take_a_free_value_before_a_rematch() { ); assert_eq!(solved.assignments, vec![Some(0), Some(1)]); } + +#[test] +fn direct_pass_orders_values_by_the_degrees_it_started_with() { + let group = assignment_group(&descriptor(), ScalarGroupLimits::new()); + let solved = construct( + group, + AssignmentPlan { + score: None, + // Values 0 and 1 are listed once, value 2 three times and values + // 3 and 4 twice. Rows 0 and 1 take their scarcer value, so row 2 + // ranks value 3 (two rows) before value 2 (three rows) and row 3 + // then takes value 4. Recounting value 2 once rows 0 and 1 hold + // values would hand row 2 value 2 and row 3 value 3. + assignments: vec![None; 4], + candidates: vec![vec![0, 2], vec![1, 2], vec![2, 3], vec![3, 4]], + }, + ); + assert_eq!(solved.assignments, vec![Some(0), Some(1), Some(3), Some(4)]); +} 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 d0653c7c..1978b201 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/default_construction.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/default_construction.rs @@ -4,6 +4,7 @@ //! and run through the same prepared dispatcher as explicit construction. use std::fmt; +use std::time::Duration; use solverforge_core::domain::PlanningSolution; use solverforge_core::score::{ParseableScore, Score}; @@ -142,14 +143,13 @@ 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 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( +/// The optional pass's remaining share of the scope's time span, 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_budget( solver_scope: &SolverScope<'_, S, D, ProgressCb>, -) -> Option +) -> Option where S: PlanningSolution, D: Director, @@ -158,11 +158,7 @@ where 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() - }) + Some(share.saturating_sub(elapsed)) } fn execute_resolved_default_construction_plan( @@ -182,22 +178,17 @@ where { let mut steps = Vec::with_capacity(resolved.steps.len()); for step in &resolved.steps { - let mut construction = + let construction = execution.prepare_resolved_construction(default.phase_index, &step.construction)?; - let mut time_budget_seconds = None; - if step.kind == DefaultConstructionStepKind::AssignmentOptional { - if let PreparedConstruction::GroupedScalar { config, .. } = &mut construction { - config.termination = optional_construction_termination(solver_scope); - time_budget_seconds = config - .termination - .as_ref() - .and_then(|termination| termination.seconds_spent_limit); - } - } + let time_budget = (step.kind == DefaultConstructionStepKind::AssignmentOptional + && matches!(construction, PreparedConstruction::GroupedScalar { .. })) + .then(|| optional_construction_budget(solver_scope)) + .flatten(); let execution = execute_prepared_construction( execution, &construction, step.required_only, + time_budget, solver_scope, )?; steps.push(ResolvedConstructionExecutionStep { @@ -206,7 +197,7 @@ where required_only: step.required_only, target: step.target.clone(), list_policies: step.list_policies.clone(), - time_budget_seconds, + time_budget_ms: time_budget.map(|budget| budget.as_millis() as u64), outcome: execution.outcome, }); } diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs b/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs index feac7ad9..73eb01ec 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs @@ -7,6 +7,7 @@ //! savings/merge/completion path. use std::fmt; +use std::time::Duration; use solverforge_config::ConstructionHeuristicConfig; use solverforge_core::domain::PlanningSolution; @@ -48,6 +49,7 @@ pub(crate) fn execute_prepared_construction, construction: &PreparedConstruction, required_only: bool, + time_budget: Option, solver_scope: &mut SolverScope<'_, S, D, ProgressCb>, ) -> Result where @@ -70,6 +72,7 @@ where } => execute_with_construction_termination( config, control_policy, + time_budget, solver_scope, |solver_scope| { if control_policy.should_terminate_construction(solver_scope) { @@ -128,6 +131,7 @@ where execute_with_construction_termination( config, control_policy, + time_budget, solver_scope, |solver_scope| { execute_list_slots( @@ -144,6 +148,7 @@ where execute_with_construction_termination( config, control_policy, + time_budget, solver_scope, |solver_scope| { execute_list_slots( @@ -169,6 +174,7 @@ where execute_with_construction_termination( config, control_policy, + time_budget, solver_scope, |solver_scope| { execute_list_slots( @@ -194,6 +200,7 @@ where execute_with_construction_termination( config, control_policy, + time_budget, solver_scope, |solver_scope| { execute_list_slots( @@ -220,6 +227,7 @@ where PreparedConstruction::KOpt { config, slots } => execute_with_construction_termination( config, control_policy, + time_budget, solver_scope, |solver_scope| { for slot in slots { @@ -239,6 +247,7 @@ where } => execute_with_construction_termination( config, control_policy, + time_budget, solver_scope, |solver_scope| { if control_policy.should_terminate_construction(solver_scope) { @@ -270,6 +279,7 @@ where fn execute_with_construction_termination( config: &ConstructionHeuristicConfig, control_policy: StepControlPolicy, + time_budget: Option, solver_scope: &mut SolverScope<'_, S, D, ProgressCb>, work: impl FnOnce(&mut SolverScope<'_, S, D, ProgressCb>) -> Result, ) -> Result @@ -279,7 +289,7 @@ where D: Director, ProgressCb: ProgressCallback, { - solver_scope.with_phase_termination(config.termination.as_ref(), |solver_scope| { + solver_scope.with_phase_termination(config.termination.as_ref(), time_budget, |solver_scope| { if control_policy.should_terminate_construction(solver_scope) { return Ok(ConstructionExecution::skipped_terminated()); } diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/execution_record.rs b/crates/solverforge-solver/src/runtime/compiler/executor/execution_record.rs index fd0806f2..750c611c 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/execution_record.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/execution_record.rs @@ -70,9 +70,9 @@ pub(crate) struct ResolvedConstructionExecutionStep { pub(crate) required_only: bool, pub(crate) target: Option, pub(crate) list_policies: Option, - /// Whole seconds of the solve's time limit this step was allowed, when + /// Milliseconds of the solve's time limit this step was allowed, when /// the default policy bounded it. - pub(crate) time_budget_seconds: Option, + pub(crate) time_budget_ms: Option, pub(crate) outcome: ResolvedConstructionExecutionOutcome, } diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests.rs b/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests.rs index c511a554..0ac973fe 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests.rs @@ -261,7 +261,7 @@ fn registration_is_structural_and_reuses_one_reached_source_binding() { let mut scope = SolverScope::new(director); assert!( - execute_prepared_construction(&mut prepared, &first, false, &mut scope) + execute_prepared_construction(&mut prepared, &first, false, None, &mut scope) .expect("first reached construction binds its source") .ran() ); @@ -270,7 +270,7 @@ fn registration_is_structural_and_reuses_one_reached_source_binding() { scope.mutate(|director| director.working_solution_mut().routes = vec![Vec::new()]); assert!( - execute_prepared_construction(&mut prepared, &second, false, &mut scope) + execute_prepared_construction(&mut prepared, &second, false, None, &mut scope) .expect("second construction reuses its solve-owned binding") .ran() ); @@ -303,7 +303,7 @@ fn reached_construction_binds_the_current_source_once() { assert_eq!(SOURCE_KEY_CALLS.load(Ordering::SeqCst), 0); assert!( - execute_prepared_construction(&mut prepared, &construction, false, &mut scope) + execute_prepared_construction(&mut prepared, &construction, false, None, &mut scope) .expect("reached source should bind and execute") .ran() ); @@ -341,7 +341,7 @@ fn prepared_construction_dispatches_the_canonical_clarke_wright_kernel() { assert_eq!(SOURCE_KEY_CALLS.load(Ordering::SeqCst), 0); assert!( - execute_prepared_construction(&mut prepared, &construction, false, &mut scope) + execute_prepared_construction(&mut prepared, &construction, false, None, &mut scope) .expect("CW source binds only at its reached construction boundary") .ran() ); @@ -407,7 +407,7 @@ fn phase_terminated_construction_does_not_bind_a_source() { let mut scope = SolverScope::new(director); assert!( - !execute_prepared_construction(&mut prepared, &construction, false, &mut scope) + !execute_prepared_construction(&mut prepared, &construction, false, None, &mut scope) .expect("an expired phase boundary should skip construction") .ran() ); 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 48c1f9fa..1a4c1e6a 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 @@ -215,8 +215,9 @@ fn eager_extension_preparation_precedes_lazy_source_binding() { let input = plan(vec![9, 9], vec![Vec::new()]); let director = ScoreDirector::simple(input, descriptor(), |plan, _| entity_count(plan)); let mut scope = SolverScope::new(director); - let error = execute_prepared_construction(&mut prepared, &construction, false, &mut scope) - .expect_err("the reached malformed source must fail at its own boundary"); + let error = + execute_prepared_construction(&mut prepared, &construction, false, None, &mut scope) + .expect_err("the reached malformed source must fail at its own boundary"); assert!(matches!( error.kind, @@ -227,32 +228,32 @@ fn eager_extension_preparation_precedes_lazy_source_binding() { #[test] fn optional_construction_keeps_its_share_of_a_time_limited_solve() { - use crate::runtime::compiler::executor::default_construction::optional_construction_termination; + use crate::runtime::compiler::executor::default_construction::optional_construction_budget; let input = plan(vec![7], vec![Vec::new()]); let director = ScoreDirector::simple(input, descriptor(), |plan, _| entity_count(plan)); let mut scope = SolverScope::new(director); assert!( - optional_construction_termination(&scope).is_none(), + optional_construction_budget(&scope).is_none(), "a solve without a time limit leaves the optional pass unbounded" ); scope.set_time_limit(std::time::Duration::from_secs(60)); assert_eq!( - optional_construction_termination(&scope).and_then(|config| config.seconds_spent_limit), - Some(12), + optional_construction_budget(&scope), + Some(std::time::Duration::from_secs(12)), "a fifth of a 60 s solve" ); scope.set_time_limit(std::time::Duration::from_secs(4)); assert_eq!( - optional_construction_termination(&scope).and_then(|config| config.seconds_spent_limit), - Some(1), - "the 0.8 s share rounds up to whole seconds" + optional_construction_budget(&scope), + Some(std::time::Duration::from_millis(800)), + "a fifth of a 4 s solve, not rounded to whole seconds" ); } #[test] fn optional_construction_in_a_partition_shares_the_inherited_deadline() { - use crate::runtime::compiler::executor::default_construction::optional_construction_termination; + use crate::runtime::compiler::executor::default_construction::optional_construction_budget; let director = ScoreDirector::simple(plan(vec![7], vec![Vec::new()]), descriptor(), |plan, _| { @@ -270,9 +271,10 @@ fn optional_construction_in_a_partition_shares_the_inherited_deadline() { .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" + let share = optional_construction_budget(&child).expect("the partition inherits a deadline"); + assert!( + share > std::time::Duration::from_millis(11_900) + && share <= std::time::Duration::from_secs(12), + "a fifth of the 60 s the partition inherits, less the time already spent: {share:?}" ); } diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests/publication.rs b/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests/publication.rs index f33384be..b5f64a2c 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests/publication.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests/publication.rs @@ -33,11 +33,15 @@ fn explicit_list_construction_stops_at_a_limit_reached_inside_the_kernel() { let director = ScoreDirector::simple(input, descriptor(), |plan, _| entity_count(plan)); let mut scope = SolverScope::new(director); - assert!( - execute_prepared_construction(&mut prepared, &construction, false, &mut scope) - .expect("explicit list construction executes until its phase limit") - .ran() - ); + assert!(execute_prepared_construction( + &mut prepared, + &construction, + false, + None, + &mut scope + ) + .expect("explicit list construction executes until its phase limit") + .ran()); assert_eq!( scope.working_solution().routes.iter().flatten().count(), 1, @@ -74,8 +78,9 @@ fn required_construction_stops_at_an_ordinary_phase_limit() { let director = ScoreDirector::simple(input, descriptor(), |plan, _| entity_count(plan)); let mut scope = SolverScope::new(director); - let execution = execute_prepared_construction(&mut prepared, &construction, true, &mut scope) - .expect("required construction observes ordinary phase limits"); + let execution = + execute_prepared_construction(&mut prepared, &construction, true, None, &mut scope) + .expect("required construction observes ordinary phase limits"); assert!(!execution.ran()); assert_eq!(scope.working_solution().routes.iter().flatten().count(), 0); } diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs index e6395ace..73262585 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs @@ -245,6 +245,7 @@ where execution, construction, false, + None, solver_scope, ) .unwrap_or_else(|error| panic_execution_error(error)); diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner/local_search.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner/local_search.rs index 88d9838f..18b37a34 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner/local_search.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner/local_search.rs @@ -93,17 +93,21 @@ where ); let evaluation_policy = resolve_evaluation_policy(move_thread_count); let mut source = selector.borrowed_source(); - solver_scope.with_phase_termination(phase_termination.as_ref(), |solver_scope| { - solve_local_search_with_resources( - &mut source, - resources, - &mut acceptor, - &mut forager, - None, - evaluation_policy, - solver_scope, - ); - }); + solver_scope.with_phase_termination( + phase_termination.as_ref(), + None, + |solver_scope| { + solve_local_search_with_resources( + &mut source, + resources, + &mut acceptor, + &mut forager, + None, + evaluation_policy, + solver_scope, + ); + }, + ); } Self::VariableNeighborhoodDescent { phase_termination, @@ -114,15 +118,19 @@ where .iter_mut() .map(RuntimeNeighborhoodState::borrowed_source) .collect::>(); - solver_scope.with_phase_termination(phase_termination.as_ref(), |solver_scope| { - solve_vnd_with_resources( - &mut sources, - resources, - None, - *score_tie_break, - solver_scope, - ); - }); + solver_scope.with_phase_termination( + phase_termination.as_ref(), + None, + |solver_scope| { + solve_vnd_with_resources( + &mut sources, + resources, + None, + *score_tie_break, + solver_scope, + ); + }, + ); } } } diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/trace.rs b/crates/solverforge-solver/src/runtime/compiler/executor/trace.rs index 686eeea7..2edea5b1 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/trace.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/trace.rs @@ -148,8 +148,8 @@ fn default_step_plan(step: &ResolvedConstructionExecutionStep) -> CandidateTrace .map_or_else(|| "none".to_string(), slot_signature), ), ]; - if let Some(seconds) = step.time_budget_seconds { - attributes.push(("time_budget_seconds".to_string(), seconds.to_string())); + if let Some(milliseconds) = step.time_budget_ms { + attributes.push(("time_budget_ms".to_string(), milliseconds.to_string())); } if let Some(policies) = &step.list_policies { match step.kind { diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/trace_tests.rs b/crates/solverforge-solver/src/runtime/compiler/executor/trace_tests.rs index 1ebb1d63..d92508a8 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/trace_tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/trace_tests.rs @@ -24,7 +24,7 @@ fn executed_stage( required_only: false, target: None, list_policies: None, - time_budget_seconds: None, + time_budget_ms: None, outcome: ResolvedConstructionExecutionOutcome::Executed, }], } @@ -98,7 +98,7 @@ fn default_trace_reports_the_optional_pass_time_budget() { DefaultConstructionStepKind::AssignmentOptional, DefaultConstructionReason::OnlyOptionalAssignmentsRemain, ); - stage.steps[0].time_budget_seconds = Some(2); + stage.steps[0].time_budget_ms = Some(2000); let execution = DefaultRuntimeConstructionExecution { ran_child_phase: true, stages: vec![stage], @@ -112,9 +112,9 @@ fn default_trace_reports_the_optional_pass_time_budget() { .filter_map(|step| { step.attributes .iter() - .find(|attribute| attribute.key == "time_budget_seconds") + .find(|attribute| attribute.key == "time_budget_ms") .map(|attribute| attribute.value.as_str()) }) .collect::>(); - assert_eq!(budget, ["2"]); + assert_eq!(budget, ["2000"]); } diff --git a/crates/solverforge-solver/src/scope/solver/phase_budget.rs b/crates/solverforge-solver/src/scope/solver/phase_budget.rs index d75c5c42..857fa71f 100644 --- a/crates/solverforge-solver/src/scope/solver/phase_budget.rs +++ b/crates/solverforge-solver/src/scope/solver/phase_budget.rs @@ -91,18 +91,24 @@ where { fn from_config( scope: &SolverScope<'_, S, D, ProgressCb>, - config: &TerminationConfig, + config: Option<&TerminationConfig>, + time_budget: Option, ) -> Option where D: Director, ProgressCb: ProgressCallback, S::Score: ParseableScore, { - let best_score_limit = crate::run::configured_best_score_limit::(config); - let time_limit = config.time_limit(); - let step_count_limit = config.step_count_limit; - let unimproved_step_count_limit = config.unimproved_step_count_limit; - let unimproved_time_limit = config.unimproved_time_limit(); + let best_score_limit = + config.and_then(crate::run::configured_best_score_limit::); + let time_limit = match (config.and_then(TerminationConfig::time_limit), time_budget) { + (Some(limit), Some(budget)) => Some(limit.min(budget)), + (limit, budget) => limit.or(budget), + }; + let step_count_limit = config.and_then(|config| config.step_count_limit); + let unimproved_step_count_limit = + config.and_then(|config| config.unimproved_step_count_limit); + let unimproved_time_limit = config.and_then(TerminationConfig::unimproved_time_limit); if time_limit.is_none() && step_count_limit.is_none() && best_score_limit.is_none() diff --git a/crates/solverforge-solver/src/scope/solver/scope_core.rs b/crates/solverforge-solver/src/scope/solver/scope_core.rs index 88f736a0..e42a637e 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_core.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_core.rs @@ -202,20 +202,22 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> /// The overlay is intentionally independent from solver-wide termination: /// it starts at this phase boundary, applies every supported /// `TerminationConfig` limit, and is restored before the next phase runs. + /// `time_budget` caps the phase's time below any configured limit at + /// full `Duration` precision. /// Mandatory default construction deliberately does not install this /// overlay, so its required-completion pass remains interruptible only by /// lifecycle control. pub(crate) fn with_phase_termination( &mut self, config: Option<&TerminationConfig>, + time_budget: Option, work: impl FnOnce(&mut Self) -> T, ) -> T where S::Score: ParseableScore, { let previous = self.phase_termination.take(); - self.phase_termination = - config.and_then(|config| ScopedPhaseTermination::from_config(self, config)); + self.phase_termination = ScopedPhaseTermination::from_config(self, config, time_budget); let result = work(self); self.phase_termination = previous; result diff --git a/crates/solverforge-solver/src/scope/tests.rs b/crates/solverforge-solver/src/scope/tests.rs index c7e1ccbb..29eeeb00 100644 --- a/crates/solverforge-solver/src/scope/tests.rs +++ b/crates/solverforge-solver/src/scope/tests.rs @@ -131,7 +131,7 @@ fn scoped_phase_termination_is_relative_complete_and_restored() { ..TerminationConfig::default() }, ] { - scope.with_phase_termination(Some(&termination), |scope| { + scope.with_phase_termination(Some(&termination), None, |scope| { assert!(scope.config_control_polling_required()); assert_eq!( scope.pending_control(), @@ -146,10 +146,21 @@ fn scoped_phase_termination_is_relative_complete_and_restored() { seconds_spent_limit: Some(1), ..TerminationConfig::default() }; - scope.with_phase_termination(Some(&time_limited), |scope| { + scope.with_phase_termination(Some(&time_limited), None, |scope| { assert!(scope.config_control_polling_required()); assert_eq!(scope.pending_control(), PendingControl::Continue); }); + let spent = std::time::Duration::ZERO; + for config in [None, Some(&time_limited)] { + scope.with_phase_termination(config, Some(spent), |scope| { + assert_eq!( + scope.pending_control(), + PendingControl::ConfigTerminationRequested, + "a sub-second time budget binds below any configured limit" + ); + }); + assert_eq!(scope.pending_control(), PendingControl::Continue); + } assert_eq!(scope.terminal_reason(), SolverTerminalReason::Completed); } diff --git a/docs/configuration.md b/docs/configuration.md index 6cc608fe..cdc1ae50 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -139,21 +139,22 @@ fixed fleet. After list construction, a slot with route hooks and a non-empty route runs `ListKOpt` (`route_hooks_declared_and_route_non_empty`). -Required assignment rows are placed one move at a time by the required cursor, -which tries a direct assignment and then bounded augmenting rematches. Keeping an -optional assignment unassigned completes that decision without ending the -optional pass. Completed optional roots are skipped before candidate-domain -reads or move generation, so the candidate budget stays available for later -rows. +Required assignment rows are placed one move at a time by the required cursor +in two passes over the rows, scarcest first: a direct pass gives each row its +first free value, then an augmenting pass places the rows left over with +bounded augmenting rematches. Keeping an optional assignment unassigned +completes that decision without ending the optional pass. Completed optional +roots are skipped before candidate-domain reads or move generation, so the +candidate budget stays available for later rows. Construction and local search share a time-limited budget. Required work is not capped: every list element, required assignment and non-optional scalar must be placed before local search starts, and a solve whose limits end first fails rather than publish a partial plan. The optional assignment pass is the one construction step that can run long without being needed, so it stops once -a fifth of the solve's time limit has passed (rounded up to whole seconds) and -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 +a fifth of the solve's time limit has passed and leaves the rest to local +search, whose optional-assignment moves keep filling optional rows. The step +reports the share it got, in milliseconds, as `time_budget_ms`. 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 partition's construction takes a fifth of the time its