From 82e0e0439443464cdc4782e799537d2ac6ae47f1 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Fri, 13 Nov 2026 15:08:00 +0100 Subject: [PATCH] feat(solver): report the resolved solver policy in final telemetry The compiled runtime already resolved an exact phase plan at the end of every solve, but published it only into an enabled candidate trace. It now also lands in SolverTelemetry::resolved_phase_plan for every compiled solve, so the policy a solve actually ran is visible without tracing. The plan gains what #253 asks diagnostics to explain: - default construction steps carry the model declaration that selected them (reason = savings_hooks_declared, required_assignments_remain, ...); - the default local-search node carries its family weighting and the families each slot did not receive with the capabilities they lacked (excluded_families = family@slot:missing=...); - every local-search node carries its effective accepted-count horizon, which separates an omitted forager (the default policy's 256 on list models) from an explicit accepted_count without a limit (1); tabu without a forager and variable neighborhood descent report none. An explicit phase's horizon is resolved from the lowered phase when the plan is published, not while compiling the runner: an extra attribute built at compile time grew one cold allocation by 48 bytes, which moved the heap layout of the hot neighborhood loops (gate: scalar_change simulated D1 misses +10.8%, list_swap LL +5.9%, with equal instructions and allocation counts). Compiling a runner allocates exactly as before. docs/configuration.md documents the default construction choice, the acceptor and forager per model shape, and the omitted-versus-explicit component contract; tests pin each of them. Solver behaviour is unchanged. Refs #253 --- crates/solverforge-solver/WIREFRAME.md | 16 ++ crates/solverforge-solver/public-api.txt | 2 +- .../src/builder/local_search_policy.rs | 5 + .../runtime/compiler/default_local_search.rs | 12 ++ .../compiler/default_local_search/policy.rs | 5 + .../default_local_search/policy/exclusions.rs | 118 +++++++++++++ .../compiler/default_local_search/trace.rs | 21 +++ .../src/runtime/compiler/defaults.rs | 4 +- .../src/runtime/compiler/defaults/stages.rs | 71 +++++++- .../src/runtime/compiler/defaults_tests.rs | 23 ++- .../compiler/defaults_tests/selection.rs | 72 ++++++++ .../src/runtime/compiler/executor/execute.rs | 1 + .../compiler/executor/execution_record.rs | 4 +- .../src/runtime/compiler/executor/runner.rs | 2 +- .../compiler/executor/runner/phase_plan.rs | 62 ++++++- .../src/runtime/compiler/executor/trace.rs | 30 ++++ .../runtime/compiler/executor/trace_tests.rs | 25 ++- .../src/runtime/compiler/mod.rs | 6 +- .../src/scope/solver/scope_trace.rs | 11 +- crates/solverforge-solver/src/scope/tests.rs | 2 +- crates/solverforge-solver/src/solver_tests.rs | 2 +- crates/solverforge-solver/src/stats/solver.rs | 8 +- .../src/stats/solver/candidate_trace.rs | 17 +- .../src/stats/solver/snapshot.rs | 1 + .../solverforge-solver/src/stats/telemetry.rs | 9 +- crates/solverforge-solver/src/stats/tests.rs | 2 +- .../tests/resolved_policy_telemetry.rs | 167 ++++++++++++++++++ docs/configuration.md | 51 +++++- docs/running-solves.md | 10 ++ 29 files changed, 718 insertions(+), 41 deletions(-) create mode 100644 crates/solverforge-solver/src/runtime/compiler/default_local_search/policy/exclusions.rs create mode 100644 crates/solverforge/tests/resolved_policy_telemetry.rs diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index d452ad89b..70c6264f6 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -962,6 +962,22 @@ record: step/candidate indexes, per-step generated/evaluated/accepted/ignored counts, before/after/delta scores, and hard-feasibility transition. They appear as `SolverTelemetry::move_telemetry` and `applied_move_trace`. +`SolverTelemetry::resolved_phase_plan` is the `CandidateTracePhasePlan` the +compiled runtime actually ran, set when the solve ends whether or not +candidate tracing is enabled and `None` before that. Default construction steps +carry a `reason` attribute naming the model declaration that selected them +(`savings_hooks_declared`, `precedence_construction_order_and_ownership_declared`, +`precedence_and_construction_order_declared`, `no_specialized_list_policy_declared`, +`required_assignments_remain`, `only_optional_assignments_remain`, +`scalar_slot_outside_assignment_groups`, `route_hooks_declared_and_route_non_empty`). +The default local-search node carries acceptor, forager, +`forager_accepted_count_limit`, `selection_order`, `weighting` and +`excluded_families` (`family@slot:missing=capability+...`, or `none`); an +explicit local-search node carries the configured or inherited acceptor and +forager plus the effective `forager_accepted_count_limit` (`none` for variable +neighborhood descent). The explicit node's limit is resolved from the lowered +phase when the plan is published, so compiling a runner allocates nothing for it. + ### Candidate Trace Diagnostics — `stats` Candidate tracing is opt-in through `SolverConfig::candidate_trace` and is diff --git a/crates/solverforge-solver/public-api.txt b/crates/solverforge-solver/public-api.txt index e4e96a985..21779074c 100644 --- a/crates/solverforge-solver/public-api.txt +++ b/crates/solverforge-solver/public-api.txt @@ -526,7 +526,7 @@ struct SolverStats: pub struct SolverStats { /* private fields */ } SolverStats: pub fn moves_applied_improving(&self) -> u64 struct SolverStatus: pub struct SolverStatus { pub job_id: usize, pub lifecycle_state: SolverLifecycleState, pub terminal_reason: Option, pub checkpoint_available: bool, pub event_sequence: u64, pub latest_snapshot_revision: Option, pub current_score: Option, pub best_score: Option, pub telemetry: SolverTelemetry, } SolverStatus: pub fn is_terminal(&self) -> bool -struct SolverTelemetry: pub struct SolverTelemetry {Show 34 fields pub elapsed: Duration, pub step_count: u64, pub moves_generated: u64, pub moves_evaluated: u64, pub moves_speculative: u64, pub moves_accepted: u64, pub moves_applied: u64, pub moves_score_improving: u64, pub moves_applied_improving: u64, pub moves_not_doable: u64, pub moves_acceptor_rejected: u64, pub moves_forager_ignored: u64, pub moves_hard_improving: u64, pub moves_hard_neutral: u64, pub moves_hard_worse: u64, pub conflict_repair_provider_generated: u64, pub conflict_repair_duplicate_filtered: u64, pub conflict_repair_illegal_filtered: u64, pub conflict_repair_not_doable_filtered: u64, pub conflict_repair_hard_improving: u64, pub conflict_repair_exposed: u64, pub score_calculations: u64, pub construction_slots_assigned: u64, pub construction_slots_kept: u64, pub construction_slots_no_doable: u64, pub scalar_assignment_required_remaining: u64, pub problem_changes_applied: u64, pub generation_time: Duration, pub evaluation_time: Duration, pub phases: Vec, pub selector_telemetry: Vec, pub move_telemetry: Vec, pub applied_move_trace: Vec, pub candidate_trace: Option, } +struct SolverTelemetry: pub struct SolverTelemetry {Show 35 fields pub elapsed: Duration, pub step_count: u64, pub moves_generated: u64, pub moves_evaluated: u64, pub moves_speculative: u64, pub moves_accepted: u64, pub moves_applied: u64, pub moves_score_improving: u64, pub moves_applied_improving: u64, pub moves_not_doable: u64, pub moves_acceptor_rejected: u64, pub moves_forager_ignored: u64, pub moves_hard_improving: u64, pub moves_hard_neutral: u64, pub moves_hard_worse: u64, pub conflict_repair_provider_generated: u64, pub conflict_repair_duplicate_filtered: u64, pub conflict_repair_illegal_filtered: u64, pub conflict_repair_not_doable_filtered: u64, pub conflict_repair_hard_improving: u64, pub conflict_repair_exposed: u64, pub score_calculations: u64, pub construction_slots_assigned: u64, pub construction_slots_kept: u64, pub construction_slots_no_doable: u64, pub scalar_assignment_required_remaining: u64, pub problem_changes_applied: u64, pub generation_time: Duration, pub evaluation_time: Duration, pub phases: Vec, pub selector_telemetry: Vec, pub move_telemetry: Vec, pub applied_move_trace: Vec, pub candidate_trace: Option, pub resolved_phase_plan: Option, } SolverTelemetry: pub const fn new_const() -> Self struct SolverTelemetryDetail: pub struct SolverTelemetryDetail { pub status: SolverStatus, pub candidate_trace: Option, } struct StepScope: pub struct StepScope<'t, 'a, 'b, S: PlanningSolution, D: Director, BestCb = ()> { /* private fields */ } diff --git a/crates/solverforge-solver/src/builder/local_search_policy.rs b/crates/solverforge-solver/src/builder/local_search_policy.rs index 4ff07693a..f6f332e99 100644 --- a/crates/solverforge-solver/src/builder/local_search_policy.rs +++ b/crates/solverforge-solver/src/builder/local_search_policy.rs @@ -117,6 +117,11 @@ impl CompiledForager { }) } + /// The validated configuration this forager builds from. + pub(crate) fn config(&self) -> &ForagerConfig { + &self.config + } + pub(crate) fn build(&self, score_tie_break: ScoreTieBreak) -> AnyForager where S: PlanningSolution, diff --git a/crates/solverforge-solver/src/runtime/compiler/default_local_search.rs b/crates/solverforge-solver/src/runtime/compiler/default_local_search.rs index 311684146..5d9f74345 100644 --- a/crates/solverforge-solver/src/runtime/compiler/default_local_search.rs +++ b/crates/solverforge-solver/src/runtime/compiler/default_local_search.rs @@ -150,6 +150,16 @@ pub(crate) struct DefaultLocalSearchSelectorDeclaration { pub slots: Vec, } +/// One default move family withheld from one slot. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct DefaultExcludedFamily { + pub family: &'static str, + pub slot: RuntimeScalarSlotId, + /// `missing=[+...]`, or why the slot is not + /// eligible at all. + pub reason: String, +} + /// The immutable omitted-local-search policy. The executor will instantiate /// its leaves from the exact declaration-order runtime bindings; this type /// intentionally owns no cloned slot carriers. @@ -158,6 +168,8 @@ pub(crate) struct DefaultLocalSearchPlan { pub components: DefaultLocalSearchComponents, pub selection_order: UnionSelectionOrder, pub selectors: Vec, + /// Default families a slot does not receive, with the reason. + pub excluded: Vec, } pub(super) fn target_for(slot: &RuntimeScalarSlotId) -> VariableTargetConfig { diff --git a/crates/solverforge-solver/src/runtime/compiler/default_local_search/policy.rs b/crates/solverforge-solver/src/runtime/compiler/default_local_search/policy.rs index 9c5665fef..0fca0e771 100644 --- a/crates/solverforge-solver/src/runtime/compiler/default_local_search/policy.rs +++ b/crates/solverforge-solver/src/runtime/compiler/default_local_search/policy.rs @@ -12,6 +12,7 @@ use super::{ DefaultLocalSearchForagerPolicy, DefaultLocalSearchPlan, }; +mod exclusions; mod list; mod scalar; @@ -101,6 +102,9 @@ where IDM: Clone, { let mut declarations = Vec::new(); + let mut excluded = Vec::new(); + exclusions::list_exclusions(list_slots, &mut excluded); + exclusions::scalar_exclusions(scalar_slots, &mut excluded); list::append_list_policy(list_slots, &mut declarations); scalar::append_nearby_scalar_policy(scalar_slots, &mut declarations); @@ -134,6 +138,7 @@ where components, selection_order, selectors: declarations, + excluded, }, nodes, ))) diff --git a/crates/solverforge-solver/src/runtime/compiler/default_local_search/policy/exclusions.rs b/crates/solverforge-solver/src/runtime/compiler/default_local_search/policy/exclusions.rs new file mode 100644 index 000000000..d02694e81 --- /dev/null +++ b/crates/solverforge-solver/src/runtime/compiler/default_local_search/policy/exclusions.rs @@ -0,0 +1,118 @@ +//! Default move families a slot does not receive, and why. +//! +//! These records describe the selector table in `list.rs` and `scalar.rs` +//! from the same capability checks; they never feed selector construction. + +use crate::builder::context::list_access::ListAccessCapability; +use crate::builder::ScalarAccessCapability; + +use super::super::super::defaults::DefaultScalarBinding; +use super::super::super::types::CompiledListSlot; +use super::super::DefaultExcludedFamily; + +const PRECEDENCE_BUNDLE: [ListAccessCapability; 4] = [ + ListAccessCapability::Precedence, + ListAccessCapability::Set, + ListAccessCapability::Reverse, + ListAccessCapability::Sublist, +]; + +pub(super) fn list_exclusions( + list_slots: &[CompiledListSlot], + excluded: &mut Vec, +) { + for slot in list_slots { + let mut exclude = |family: &'static str, required: &[ListAccessCapability]| { + let missing = required + .iter() + .copied() + .filter(|capability| !slot.supports(*capability)) + .map(list_capability_label) + .collect::>(); + if !missing.is_empty() { + excluded.push(DefaultExcludedFamily { + family, + slot: slot.identity(), + reason: format!("missing={}", missing.join("+")), + }); + } + }; + exclude("list_precedence_and_permute", &PRECEDENCE_BUNDLE); + exclude( + "nearby_list_change", + &[ListAccessCapability::CrossPositionDistance], + ); + if slot.supports(ListAccessCapability::Set) { + exclude( + "nearby_list_swap", + &[ListAccessCapability::CrossPositionDistance], + ); + } else { + exclude("list_swap", &[ListAccessCapability::Set]); + } + exclude("sublist_change_and_swap", &[ListAccessCapability::Sublist]); + exclude("list_reverse", &[ListAccessCapability::Reverse]); + if slot.supports(ListAccessCapability::Sublist) { + exclude( + "nearby_k_opt", + &[ListAccessCapability::IntraPositionDistance], + ); + } else { + exclude("k_opt", &[ListAccessCapability::Sublist]); + } + } +} + +pub(super) fn scalar_exclusions( + scalar_slots: &[DefaultScalarBinding], + excluded: &mut Vec, +) { + for binding in scalar_slots { + let slot = binding.slot.id(); + if binding.assignment_owned { + excluded.push(DefaultExcludedFamily { + family: "scalar_change_and_swap", + slot, + reason: "owned_by_assignment_group".to_string(), + }); + continue; + } + for (family, capability, label) in [ + ( + "nearby_scalar_change", + ScalarAccessCapability::NearbyValue, + "nearby_value", + ), + ( + "nearby_scalar_swap", + ScalarAccessCapability::NearbyEntity, + "nearby_entity", + ), + ] { + if !binding.slot.has_capability(capability) { + excluded.push(DefaultExcludedFamily { + family, + slot: slot.clone(), + reason: format!("missing={label}"), + }); + } + } + } +} + +fn list_capability_label(capability: ListAccessCapability) -> &'static str { + match capability { + ListAccessCapability::Set => "set", + ListAccessCapability::Replace => "replace", + ListAccessCapability::Reverse => "reverse", + ListAccessCapability::Sublist => "sublist", + ListAccessCapability::ElementOwner => "element_owner", + ListAccessCapability::ConstructionOrderKey => "construction_order_key", + ListAccessCapability::Precedence => "precedence", + ListAccessCapability::CrossPositionDistance => "cross_position_distance", + ListAccessCapability::IntraPositionDistance => "intra_position_distance", + ListAccessCapability::Route => "route", + ListAccessCapability::Savings => "savings", + ListAccessCapability::SavingsNeighbors => "savings_neighbors", + } +} diff --git a/crates/solverforge-solver/src/runtime/compiler/default_local_search/trace.rs b/crates/solverforge-solver/src/runtime/compiler/default_local_search/trace.rs index ce2a2dea6..5b791bc39 100644 --- a/crates/solverforge-solver/src/runtime/compiler/default_local_search/trace.rs +++ b/crates/solverforge-solver/src/runtime/compiler/default_local_search/trace.rs @@ -21,6 +21,9 @@ impl DefaultLocalSearchPlan { selection_order_label(self.selection_order).to_string(), ), ("selector_count", self.selectors.len().to_string()), + // Every default union weighs its families equally. + ("weighting", "equal".to_string()), + ("excluded_families", self.excluded_families_signature()), ]; match self.components.acceptor { super::DefaultLocalSearchAcceptorPolicy::LateAcceptance { history_size } @@ -65,6 +68,24 @@ impl DefaultLocalSearchPlan { ) } + fn excluded_families_signature(&self) -> String { + if self.excluded.is_empty() { + return "none".to_string(); + } + self.excluded + .iter() + .map(|excluded| { + format!( + "{}@{}:{}", + excluded.family, + slot_signature(&excluded.slot), + excluded.reason + ) + }) + .collect::>() + .join(";") + } + /// Returns only the selector subtree for an explicit local-search phase /// that omitted its selector. Acceptor, forager, and termination /// provenance remain owned by that explicit phase. diff --git a/crates/solverforge-solver/src/runtime/compiler/defaults.rs b/crates/solverforge-solver/src/runtime/compiler/defaults.rs index 93479b67d..f68da0a94 100644 --- a/crates/solverforge-solver/src/runtime/compiler/defaults.rs +++ b/crates/solverforge-solver/src/runtime/compiler/defaults.rs @@ -25,8 +25,8 @@ pub(crate) use stages::{ resolve_default_postconstruction_kopt, resolve_default_preconstruction_stage, }; pub(crate) use stages::{ - DefaultConstructionStage, DefaultConstructionStepKind, DefaultListPolicyProvenance, - DefaultPreconstructionStage, ResolvedDefaultConstructionPlan, + DefaultConstructionReason, DefaultConstructionStage, DefaultConstructionStepKind, + DefaultListPolicyProvenance, DefaultPreconstructionStage, ResolvedDefaultConstructionPlan, }; /// One scalar slot frozen for default construction/local-search expansion. diff --git a/crates/solverforge-solver/src/runtime/compiler/defaults/stages.rs b/crates/solverforge-solver/src/runtime/compiler/defaults/stages.rs index 78e0ce518..4119b950b 100644 --- a/crates/solverforge-solver/src/runtime/compiler/defaults/stages.rs +++ b/crates/solverforge-solver/src/runtime/compiler/defaults/stages.rs @@ -63,6 +63,44 @@ pub(crate) enum DefaultConstructionStepKind { ListKOpt, } +/// The model fact that selected a default construction step. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DefaultConstructionReason { + /// The list slot declares savings hooks. + SavingsDeclared, + /// Precedence, construction order and ownership are all declared. + PrecedenceOrderAndOwnership, + /// Precedence and construction order are declared, ownership is not. + PrecedenceAndOrder, + /// The list slot declares none of the specialized construction policies. + NoSpecializedListPolicy, + /// The assignment group still has required rows unassigned. + RequiredAssignmentsRemain, + /// Every required row is assigned; optional rows remain. + OnlyOptionalAssignmentsRemain, + /// The scalar slot is not owned by an assignment group. + UngroupedScalarSlot, + /// The list slot declares route hooks and some route is non-empty. + RouteWithContent, +} + +impl DefaultConstructionReason { + pub(crate) fn trace_label(self) -> &'static str { + match self { + Self::SavingsDeclared => "savings_hooks_declared", + Self::PrecedenceOrderAndOwnership => { + "precedence_construction_order_and_ownership_declared" + } + Self::PrecedenceAndOrder => "precedence_and_construction_order_declared", + Self::NoSpecializedListPolicy => "no_specialized_list_policy_declared", + Self::RequiredAssignmentsRemain => "required_assignments_remain", + Self::OnlyOptionalAssignmentsRemain => "only_optional_assignments_remain", + Self::UngroupedScalarSlot => "scalar_slot_outside_assignment_groups", + Self::RouteWithContent => "route_hooks_declared_and_route_non_empty", + } + } +} + /// Frozen list policy labels attached to one resolved default step. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct DefaultListPolicyProvenance { @@ -79,6 +117,7 @@ pub(crate) struct DefaultListPolicyProvenance { #[derive(Clone, Debug)] pub(crate) struct ResolvedDefaultConstructionStep { pub kind: DefaultConstructionStepKind, + pub reason: DefaultConstructionReason, pub construction: CompiledConstruction, /// Required-only selection changes which assignment rows are considered; /// it never changes the configured termination policy. @@ -182,10 +221,11 @@ where DM: Clone + Send + Sync + fmt::Debug + CrossEntityDistanceMeter, IDM: Clone + Send + Sync + fmt::Debug + CrossEntityDistanceMeter, { - let heuristic = default_list_construction_heuristic(slot); + let (heuristic, reason) = default_list_construction_heuristic(slot); let target = slot.identity(); ResolvedDefaultConstructionStep { kind: DefaultConstructionStepKind::ListConstruction(heuristic), + reason, construction: CompiledConstruction::List { kind: ListConstructionKind::from_heuristic(heuristic) .expect("default list construction must map to a compiled list kind"), @@ -207,6 +247,7 @@ where let target = binding.slot.id(); ResolvedDefaultConstructionStep { kind: DefaultConstructionStepKind::ScalarFirstFit, + reason: DefaultConstructionReason::UngroupedScalarSlot, construction: CompiledConstruction::ScalarOrMixed { config: scalar_first_fit_config(&target), schedule: binding.schedule, @@ -235,6 +276,7 @@ where let target = slot.identity(); ResolvedDefaultConstructionStep { kind: DefaultConstructionStepKind::ListKOpt, + reason: DefaultConstructionReason::RouteWithContent, construction: CompiledConstruction::List { kind: ListConstructionKind::KOpt, config: list_config(ConstructionHeuristicType::ListKOpt, &target), @@ -258,22 +300,34 @@ where fn default_list_construction_heuristic( slot: &CompiledListSlot, -) -> ConstructionHeuristicType { +) -> (ConstructionHeuristicType, DefaultConstructionReason) { use crate::builder::context::list_access::ListAccessCapability; if slot.supports(ListAccessCapability::Savings) { - ConstructionHeuristicType::ListClarkeWright + ( + ConstructionHeuristicType::ListClarkeWright, + DefaultConstructionReason::SavingsDeclared, + ) } else if slot.precedence_policy().is_explicit() && slot.construction_order_policy().is_explicit() && slot.ownership_policy().is_explicit() { - ConstructionHeuristicType::ListRegretInsertion + ( + ConstructionHeuristicType::ListRegretInsertion, + DefaultConstructionReason::PrecedenceOrderAndOwnership, + ) } else if slot.precedence_policy().is_explicit() && slot.construction_order_policy().is_explicit() { - ConstructionHeuristicType::ListRoundRobin + ( + ConstructionHeuristicType::ListRoundRobin, + DefaultConstructionReason::PrecedenceAndOrder, + ) } else { - ConstructionHeuristicType::ListCheapestInsertion + ( + ConstructionHeuristicType::ListCheapestInsertion, + DefaultConstructionReason::NoSpecializedListPolicy, + ) } } @@ -295,6 +349,11 @@ fn assignment_step( } else { DefaultConstructionStepKind::AssignmentOptional }, + reason: if required_only { + DefaultConstructionReason::RequiredAssignmentsRemain + } else { + DefaultConstructionReason::OnlyOptionalAssignmentsRemain + }, construction: CompiledConstruction::GroupedScalar { config, group_index: binding.group_index, diff --git a/crates/solverforge-solver/src/runtime/compiler/defaults_tests.rs b/crates/solverforge-solver/src/runtime/compiler/defaults_tests.rs index 1f392cf56..f3424f754 100644 --- a/crates/solverforge-solver/src/runtime/compiler/defaults_tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/defaults_tests.rs @@ -14,8 +14,8 @@ use solverforge_core::domain::{ use solverforge_core::score::SoftScore; use super::{ - compile_runtime_graph, DefaultConstructionStage, DefaultConstructionStepKind, - DefaultLocalSearchAcceptorPolicy, DefaultLocalSearchEligibility, + compile_runtime_graph, DefaultConstructionReason, DefaultConstructionStage, + DefaultConstructionStepKind, DefaultLocalSearchAcceptorPolicy, DefaultLocalSearchEligibility, DefaultLocalSearchForagerPolicy, DefaultLocalSearchPlan, DefaultLocalSearchSelectorFamily, DefaultPreconstructionStage, DefaultSelectorCapabilityPolicy, RuntimeGraphInput, }; @@ -247,6 +247,19 @@ fn resolved_preconstruction_kinds( stage: DefaultPreconstructionStage, plan: &Plan, ) -> (DefaultConstructionStage, Vec) { + let (stage, steps) = resolved_preconstruction_steps(model, config, stage, plan); + (stage, steps.into_iter().map(|(kind, _)| kind).collect()) +} + +fn resolved_preconstruction_steps( + model: Model, + config: SolverConfig, + stage: DefaultPreconstructionStage, + plan: &Plan, +) -> ( + DefaultConstructionStage, + Vec<(DefaultConstructionStepKind, DefaultConstructionReason)>, +) { let context = SearchContext::new(descriptor(), model, config.resolved_random_seed()) .expect("search context should bind"); let graph = compile_runtime_graph( @@ -261,7 +274,11 @@ fn resolved_preconstruction_kinds( ); ( resolved.stage, - resolved.steps.into_iter().map(|step| step.kind).collect(), + resolved + .steps + .into_iter() + .map(|step| (step.kind, step.reason)) + .collect(), ) } diff --git a/crates/solverforge-solver/src/runtime/compiler/defaults_tests/selection.rs b/crates/solverforge-solver/src/runtime/compiler/defaults_tests/selection.rs index 421eba350..b70a8923a 100644 --- a/crates/solverforge-solver/src/runtime/compiler/defaults_tests/selection.rs +++ b/crates/solverforge-solver/src/runtime/compiler/defaults_tests/selection.rs @@ -41,6 +41,49 @@ fn dynamic_and_native_default_construction_have_equal_cvrp_and_jssp_profiles() { } } +#[test] +fn default_list_construction_records_the_declaration_that_chose_it() { + for (scenario, expected) in [ + ( + Scenario::Cvrp, + ( + ConstructionHeuristicType::ListClarkeWright, + DefaultConstructionReason::SavingsDeclared, + ), + ), + ( + Scenario::Jssp, + ( + ConstructionHeuristicType::ListRegretInsertion, + DefaultConstructionReason::PrecedenceOrderAndOwnership, + ), + ), + ( + Scenario::Cheapest, + ( + ConstructionHeuristicType::ListCheapestInsertion, + DefaultConstructionReason::NoSpecializedListPolicy, + ), + ), + ] { + for model in [static_model(scenario), dynamic_model(scenario)] { + let (_, steps) = resolved_preconstruction_steps( + model, + SolverConfig::default(), + DefaultPreconstructionStage::ListConstruction, + &initial_plan(), + ); + assert_eq!( + steps, + vec![( + DefaultConstructionStepKind::ListConstruction(expected.0), + expected.1 + )] + ); + } + } +} + #[test] fn empty_savings_routes_stage_clarke_wright_before_postconstruction_kopt() { let empty = initial_plan(); @@ -176,6 +219,13 @@ fn equivalent_typed_and_dynamic_cvrp_capabilities_freeze_the_same_default_local_ typed.components.forager, DefaultLocalSearchForagerPolicy::AcceptedCount { limit: 256 } ); + let typed_excluded = typed + .excluded + .iter() + .map(|excluded| excluded.family) + .collect::>(); + assert_eq!(typed_excluded, ["list_precedence_and_permute"]); + assert_eq!(typed.excluded[0].reason, "missing=precedence"); assert!(typed.candidate_trace_plan().is_complete()); assert!(dynamic.candidate_trace_plan().is_complete()); } @@ -219,7 +269,29 @@ fn reduced_dynamic_list_capabilities_select_named_policy_rows() { ], ); + let excluded = cvrp_without_position_metrics + .excluded + .iter() + .map(|excluded| excluded.family) + .collect::>(); + assert_eq!( + excluded, + [ + "list_precedence_and_permute", + "nearby_list_change", + "list_swap", + "sublist_change_and_swap", + "list_reverse", + "k_opt", + ] + ); + let nearby = &cvrp_without_position_metrics.excluded[1]; + assert_eq!(nearby.reason, "missing=cross_position_distance"); + let plan = cvrp_without_position_metrics.candidate_trace_plan(); + assert!(plan.attributes.iter().any(|attribute| { + attribute.key == "excluded_families" && attribute.value.contains("nearby_list_change@") + })); assert!(plan.children.iter().any(|child| { child.attributes.iter().any(|attribute| { attribute.key == "capability_policy" diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs b/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs index a95b61547..a626ed3fb 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/execute.rs @@ -356,6 +356,7 @@ where )?; steps.push(ResolvedConstructionExecutionStep { kind: step.kind, + reason: step.reason, required_only: step.required_only, target: step.target.clone(), list_policies: step.list_policies.clone(), 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 8e332f4a8..19619e042 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/execution_record.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/execution_record.rs @@ -7,7 +7,8 @@ use crate::builder::RuntimeScalarSlotId; use crate::runtime::compiler::{ - DefaultConstructionStage, DefaultConstructionStepKind, DefaultListPolicyProvenance, + DefaultConstructionReason, DefaultConstructionStage, DefaultConstructionStepKind, + DefaultListPolicyProvenance, }; /// What happened to one resolved construction child. @@ -65,6 +66,7 @@ impl ConstructionExecution { #[derive(Clone, Debug)] pub(crate) struct ResolvedConstructionExecutionStep { pub(crate) kind: DefaultConstructionStepKind, + pub(crate) reason: DefaultConstructionReason, pub(crate) required_only: bool, pub(crate) target: Option, pub(crate) list_policies: Option, diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs index 76fae73e7..e6395acef 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs @@ -436,7 +436,7 @@ where phase.on_solver_terminal(solver_scope); } } - solver_scope.finalize_candidate_trace_resolved_phase_plan(self.final_phase_plan()); + solver_scope.finalize_resolved_phase_plan(self.final_phase_plan()); let phase_index = self .phases .last() diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner/phase_plan.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner/phase_plan.rs index de760649d..1cac868f8 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner/phase_plan.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner/phase_plan.rs @@ -8,8 +8,12 @@ use solverforge_core::score::Score; use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; use crate::stats::CandidateTracePhasePlan; +use crate::CandidateTracePhaseAttribute; -use super::super::trace::{default_construction_plan, phase_with_outcome}; +use super::super::trace::{ + default_construction_plan, effective_accepted_count_limit, phase_with_outcome, +}; +use super::local_search::RuntimeLocalSearch; use super::RunnerPhase; impl RunnerPhase @@ -31,16 +35,24 @@ where pub(super) fn candidate_trace_plan(&self) -> CandidateTracePhasePlan { match self { - Self::Construction { + Self::LocalSearch { phase_index, declaration, + local_search, outcome, + } => { + let mut declaration = declaration.clone(); + insert_attribute( + &mut declaration, + "forager_accepted_count_limit", + accepted_count_limit(local_search), + ); + phase_with_outcome(*phase_index, outcome.trace_label(), declaration) } - | Self::LocalSearch { + Self::Construction { phase_index, declaration, outcome, - .. } | Self::Extension { phase_index, @@ -74,3 +86,45 @@ where } } } + +/// The accepted-count horizon a lowered local-search phase runs with; a +/// descent phase has no forager and reports `none`. +fn accepted_count_limit(local_search: &RuntimeLocalSearch) -> String +where + S: PlanningSolution + Clone + Send + Sync + 'static, + S::Score: Score, + V: Clone + PartialEq + Send + Sync + Debug + 'static, + DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, + IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, +{ + match local_search { + RuntimeLocalSearch::AcceptorForager { + components, + acceptor, + forager, + .. + } => effective_accepted_count_limit( + acceptor + .as_ref() + .is_some_and(|acceptor| acceptor.is_tabu_search()), + forager.as_ref().map(|forager| forager.config()), + *components, + ), + RuntimeLocalSearch::VariableNeighborhoodDescent { .. } => "none".to_string(), + } +} + +/// Adds `key` to a plan node, keeping its attributes sorted and unique. +fn insert_attribute(plan: &mut CandidateTracePhasePlan, key: &str, value: String) { + let position = plan + .attributes + .binary_search_by(|attribute| attribute.key.as_str().cmp(key)) + .expect_err("a resolved attribute is added once"); + plan.attributes.insert( + position, + CandidateTracePhaseAttribute { + key: key.to_string(), + value, + }, + ); +} diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/trace.rs b/crates/solverforge-solver/src/runtime/compiler/executor/trace.rs index f11914390..0392c4c9e 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/trace.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/trace.rs @@ -139,6 +139,7 @@ fn default_step_plan(step: &ResolvedConstructionExecutionStep) -> CandidateTrace default_step_kind_label(step.kind).to_string(), ), ("outcome".to_string(), step.outcome.as_str().to_string()), + ("reason".to_string(), step.reason.trace_label().to_string()), ("required_only".to_string(), step.required_only.to_string()), ( "target".to_string(), @@ -231,6 +232,35 @@ fn local_search_attributes( ] } +/// The accepted-count horizon an acceptor/forager phase runs with: an +/// omitted forager takes the default policy's, an explicit `accepted_count` +/// with no `limit` takes 1, and foragers without an accepted-count horizon +/// report `none`. +/// +/// Resolved from the lowered phase when the solve publishes its plan, not +/// at compile time: compiling a runner allocates nothing for diagnostics. +pub(super) fn effective_accepted_count_limit( + tabu_acceptor: bool, + forager: Option<&solverforge_config::ForagerConfig>, + components: DefaultLocalSearchComponents, +) -> String { + use crate::runtime::compiler::DefaultLocalSearchForagerPolicy; + use solverforge_config::ForagerConfig; + + let limit = match forager { + Some(ForagerConfig::AcceptedCount(accepted)) => Some(accepted.limit.unwrap_or(1)), + Some(_) => None, + None if tabu_acceptor => None, + None => match components.forager { + DefaultLocalSearchForagerPolicy::AcceptedCount { limit } => Some(limit), + DefaultLocalSearchForagerPolicy::FirstLastStepScoreImproving { + accepted_count_limit, + } => accepted_count_limit, + }, + }; + limit.map_or_else(|| "none".to_string(), |limit| limit.to_string()) +} + fn construction_config_signature(config: &ConstructionHeuristicConfig) -> String { format!("{config:?}") } 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 3968cfa30..1e96d42aa 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/trace_tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/trace_tests.rs @@ -6,18 +6,21 @@ use super::execution_record::{ }; use super::trace::default_construction_plan; use crate::runtime::compiler::{ - DefaultConstructionStage, DefaultConstructionStepKind, DefaultPreconstructionStage, + DefaultConstructionReason, DefaultConstructionStage, DefaultConstructionStepKind, + DefaultPreconstructionStage, }; fn executed_stage( stage: DefaultConstructionStage, kind: DefaultConstructionStepKind, + reason: DefaultConstructionReason, ) -> DefaultConstructionStageExecutionRecord { DefaultConstructionStageExecutionRecord { stage, outcome: ResolvedConstructionExecutionOutcome::Executed, steps: vec![ResolvedConstructionExecutionStep { kind, + reason, required_only: false, target: None, list_policies: None, @@ -38,10 +41,12 @@ fn default_terminal_trace_keeps_clarke_wright_then_k_opt_exactly() { DefaultConstructionStepKind::ListConstruction( ConstructionHeuristicType::ListClarkeWright, ), + DefaultConstructionReason::SavingsDeclared, ), executed_stage( DefaultConstructionStage::PostConstructionKOpt, DefaultConstructionStepKind::ListKOpt, + DefaultConstructionReason::RouteWithContent, ), ], }; @@ -61,6 +66,24 @@ fn default_terminal_trace_keeps_clarke_wright_then_k_opt_exactly() { "solverforge.runtime.construction.k_opt", ] ); + let reasons = plan + .children + .iter() + .flat_map(|stage| stage.children.iter()) + .map(|step| { + step.attributes + .iter() + .find(|attribute| attribute.key == "reason") + .map(|attribute| attribute.value.as_str()) + }) + .collect::>(); + assert_eq!( + reasons, + [ + Some("savings_hooks_declared"), + Some("route_hooks_declared_and_route_non_empty"), + ] + ); assert!( plan.is_complete(), "terminal construction trace must not be opaque" diff --git a/crates/solverforge-solver/src/runtime/compiler/mod.rs b/crates/solverforge-solver/src/runtime/compiler/mod.rs index cd965cabc..3528413f5 100644 --- a/crates/solverforge-solver/src/runtime/compiler/mod.rs +++ b/crates/solverforge-solver/src/runtime/compiler/mod.rs @@ -38,9 +38,9 @@ pub(crate) use default_local_search::{ DefaultLocalSearchAcceptorPolicy, DefaultLocalSearchComponents, DefaultLocalSearchForagerPolicy, }; pub(crate) use defaults::{ - DefaultConstructionStage, DefaultConstructionStepKind, DefaultListPolicyProvenance, - DefaultLocalSearchEligibility, DefaultPreconstructionStage, DefaultRuntimeBindings, - ResolvedDefaultConstructionPlan, + DefaultConstructionReason, DefaultConstructionStage, DefaultConstructionStepKind, + DefaultListPolicyProvenance, DefaultLocalSearchEligibility, DefaultPreconstructionStage, + DefaultRuntimeBindings, ResolvedDefaultConstructionPlan, }; pub(crate) use executor::CompiledRuntimeExecutor; pub(crate) use graph::{ diff --git a/crates/solverforge-solver/src/scope/solver/scope_trace.rs b/crates/solverforge-solver/src/scope/solver/scope_trace.rs index ecbda7261..bf69d5ec0 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_trace.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_trace.rs @@ -16,15 +16,16 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> self.stats.begin_candidate_trace_phase() } - /// Publishes the executor-supplied terminal phase plan into the enabled - /// candidate trace. This is intentionally a direct forwarding boundary: - /// the scope never infers a plan from progress, snapshots, or callbacks. - pub(crate) fn finalize_candidate_trace_resolved_phase_plan( + /// Publishes the executor-supplied terminal phase plan into the final + /// telemetry and, when enabled, the candidate trace. This is + /// intentionally a direct forwarding boundary: the scope never infers a + /// plan from progress, snapshots, or callbacks. + pub(crate) fn finalize_resolved_phase_plan( &mut self, resolved_phase_plan: crate::stats::CandidateTracePhasePlan, ) { self.stats - .finalize_candidate_trace_resolved_phase_plan(resolved_phase_plan); + .finalize_resolved_phase_plan(resolved_phase_plan); } /// Records one engine-consumed cursor candidate when tracing is enabled. diff --git a/crates/solverforge-solver/src/scope/tests.rs b/crates/solverforge-solver/src/scope/tests.rs index 2239ab163..a82c31f62 100644 --- a/crates/solverforge-solver/src/scope/tests.rs +++ b/crates/solverforge-solver/src/scope/tests.rs @@ -426,7 +426,7 @@ fn solver_scope_forwards_candidate_trace_plan_finalization() { let terminal_plan = CandidateTracePhasePlan::known("test.terminal", [("outcome", "completed")], Vec::new()); - scope.finalize_candidate_trace_resolved_phase_plan(terminal_plan.clone()); + scope.finalize_resolved_phase_plan(terminal_plan.clone()); let trace = scope .stats() diff --git a/crates/solverforge-solver/src/solver_tests.rs b/crates/solverforge-solver/src/solver_tests.rs index ee194f777..2db2715c6 100644 --- a/crates/solverforge-solver/src/solver_tests.rs +++ b/crates/solverforge-solver/src/solver_tests.rs @@ -128,7 +128,7 @@ where solver_scope: &mut SolverScope<'_, TestSolution, TestDirector, ProgressCb>, ) { self.terminal_count.fetch_add(1, Ordering::SeqCst); - solver_scope.finalize_candidate_trace_resolved_phase_plan(self.terminal_plan.clone()); + solver_scope.finalize_resolved_phase_plan(self.terminal_plan.clone()); } } diff --git a/crates/solverforge-solver/src/stats/solver.rs b/crates/solverforge-solver/src/stats/solver.rs index 006e161cc..c6639119e 100644 --- a/crates/solverforge-solver/src/stats/solver.rs +++ b/crates/solverforge-solver/src/stats/solver.rs @@ -4,7 +4,9 @@ use std::time::{Duration, Instant}; use smallvec::SmallVec; -use super::{AppliedMoveTelemetry, CandidateTraceTelemetry, PhaseStats, Throughput}; +use super::{ + AppliedMoveTelemetry, CandidateTracePhasePlan, CandidateTraceTelemetry, PhaseStats, Throughput, +}; mod candidate_trace; mod snapshot; @@ -52,6 +54,9 @@ pub struct SolverStats { scalar_assignment_required_remaining_by_group: BTreeMap<&'static str, u64>, problem_changes_applied: u64, candidate_trace: Option, + // Boxed so a solve that never resolves a plan keeps the stats one word + // wider, not one plan wider. + resolved_phase_plan: Option>, } /// Phases a solve keeps without allocating: construction, local search, and @@ -82,6 +87,7 @@ impl Default for SolverStats { scalar_assignment_required_remaining_by_group: BTreeMap::new(), problem_changes_applied: 0, candidate_trace: None, + resolved_phase_plan: None, } } } diff --git a/crates/solverforge-solver/src/stats/solver/candidate_trace.rs b/crates/solverforge-solver/src/stats/solver/candidate_trace.rs index c0ff48255..c8e27f4f3 100644 --- a/crates/solverforge-solver/src/stats/solver/candidate_trace.rs +++ b/crates/solverforge-solver/src/stats/solver/candidate_trace.rs @@ -28,18 +28,23 @@ impl SolverStats { .map(CandidateTraceTelemetry::begin_phase) } - /// Finalizes the exact phase plan for an enabled candidate trace. + /// Records the exact resolved phase plan once, for the final telemetry + /// and, when enabled, for the candidate trace. /// - /// A trace-free solve intentionally has no recorder to update. The - /// one-way invariant itself is enforced by `CandidateTraceTelemetry` when - /// a trace exists. - pub(crate) fn finalize_candidate_trace_resolved_phase_plan( + /// The one-way invariant is enforced here for every solve and again by + /// `CandidateTraceTelemetry` when a trace exists. + pub(crate) fn finalize_resolved_phase_plan( &mut self, resolved_phase_plan: CandidateTracePhasePlan, ) { + assert!( + self.resolved_phase_plan.is_none(), + "the resolved phase plan may be finalized only once per solve" + ); if let Some(trace) = self.candidate_trace.as_mut() { - trace.finalize_resolved_phase_plan(resolved_phase_plan); + trace.finalize_resolved_phase_plan(resolved_phase_plan.clone()); } + self.resolved_phase_plan = Some(Box::new(resolved_phase_plan)); } pub(crate) fn record_prepared_candidate_trace_pull( diff --git a/crates/solverforge-solver/src/stats/solver/snapshot.rs b/crates/solverforge-solver/src/stats/solver/snapshot.rs index f9bbd9efd..99d30721d 100644 --- a/crates/solverforge-solver/src/stats/solver/snapshot.rs +++ b/crates/solverforge-solver/src/stats/solver/snapshot.rs @@ -79,6 +79,7 @@ impl SolverStats { } else { None }, + resolved_phase_plan: self.resolved_phase_plan.as_deref().cloned(), } } } diff --git a/crates/solverforge-solver/src/stats/telemetry.rs b/crates/solverforge-solver/src/stats/telemetry.rs index be02fe7da..864689bdf 100644 --- a/crates/solverforge-solver/src/stats/telemetry.rs +++ b/crates/solverforge-solver/src/stats/telemetry.rs @@ -4,7 +4,7 @@ use std::time::Duration; -use super::CandidateTraceTelemetry; +use super::{CandidateTracePhasePlan, CandidateTraceTelemetry}; /// Counters for one move selector of a phase, keyed by its index. /// @@ -245,6 +245,12 @@ pub struct SolverTelemetry { /// Present only when `SolverConfig.candidate_trace` enabled bounded /// core-owned candidate-pull diagnostics for this run. pub candidate_trace: Option, + /// The policy the solve actually ran, once the compiled runtime has + /// resolved it: every phase, the construction chosen for each default + /// stage and why, the move families and their limits, family ordering, + /// acceptor and forager. Set when the solve ends, whether or not + /// `candidate_trace` is enabled; `None` before that. + pub resolved_phase_plan: Option, } impl SolverTelemetry { @@ -286,6 +292,7 @@ impl SolverTelemetry { move_telemetry: Vec::new(), applied_move_trace: Vec::new(), candidate_trace: None, + resolved_phase_plan: None, } } diff --git a/crates/solverforge-solver/src/stats/tests.rs b/crates/solverforge-solver/src/stats/tests.rs index 660eb3862..b36a4cc16 100644 --- a/crates/solverforge-solver/src/stats/tests.rs +++ b/crates/solverforge-solver/src/stats/tests.rs @@ -396,7 +396,7 @@ fn candidate_trace_plan_stays_provisional_across_pause_and_resume_until_finaliza )], ); let expected_digest = CandidateTraceDigest::of_bytes(&terminal_plan.canonical_bytes()); - stats.finalize_candidate_trace_resolved_phase_plan(terminal_plan.clone()); + stats.finalize_resolved_phase_plan(terminal_plan.clone()); let terminal = stats .snapshot() diff --git a/crates/solverforge/tests/resolved_policy_telemetry.rs b/crates/solverforge/tests/resolved_policy_telemetry.rs new file mode 100644 index 000000000..710436b60 --- /dev/null +++ b/crates/solverforge/tests/resolved_policy_telemetry.rs @@ -0,0 +1,167 @@ +//! A solve on the compiled runtime reports the policy it actually ran in its +//! final telemetry, whether or not candidate tracing is enabled. + +use solverforge::{CandidateTracePhasePlan, SolverEvent, SolverManager, SolverTelemetry}; + +#[path = "list_cvrp_k_opt_time_window/domain/mod.rs"] +mod domain; + +use domain::{build_plan, Plan}; + +const DEFAULT_POLICY_SOLVER_TOML: &str = "\ +environment_mode = \"reproducible\" +random_seed = 7 + +[termination] +step_count_limit = 20 +"; + +fn completed_telemetry(solver_toml: &'static str) -> SolverTelemetry { + static MANAGER: SolverManager = SolverManager::new(); + + let mut plan = build_plan(); + plan.routes[0].visits.clear(); + plan.solver_toml = solver_toml; + let (job_id, mut receiver) = MANAGER.solve(plan).expect("solve should start"); + let telemetry = loop { + match receiver + .blocking_recv() + .expect("event stream should reach a terminal event") + { + SolverEvent::Completed { metadata, .. } => break metadata.telemetry, + SolverEvent::Failed { error, .. } => panic!("solve unexpectedly failed: {error}"), + SolverEvent::Cancelled { metadata } => { + panic!("solve was cancelled: {:?}", metadata.terminal_reason) + } + _ => {} + } + }; + MANAGER + .delete(job_id) + .expect("completed job should delete cleanly"); + telemetry +} + +fn find<'a>(plan: &'a CandidateTracePhasePlan, kind: &str) -> Option<&'a CandidateTracePhasePlan> { + if plan.kind == kind { + return Some(plan); + } + plan.children.iter().find_map(|child| find(child, kind)) +} + +fn attribute<'a>(plan: &'a CandidateTracePhasePlan, key: &str) -> &'a str { + plan.attributes + .iter() + .find(|attribute| attribute.key == key) + .unwrap_or_else(|| panic!("{} has no {key} attribute", plan.kind)) + .value + .as_str() +} + +#[test] +fn final_telemetry_names_the_default_construction_and_why() { + let telemetry = completed_telemetry(DEFAULT_POLICY_SOLVER_TOML); + assert!( + telemetry.candidate_trace.is_none(), + "the policy must not depend on candidate tracing" + ); + let plan = telemetry + .resolved_phase_plan + .expect("a completed compiled solve reports its resolved plan"); + assert!(plan.is_complete(), "{plan:#?}"); + + let construction = find(&plan, "solverforge.runtime.construction.clarke_wright") + .unwrap_or_else(|| panic!("default construction ran Clarke-Wright: {plan:#?}")); + assert_eq!(attribute(construction, "reason"), "savings_hooks_declared"); + + let local_search = find(&plan, "solverforge.runtime.default_local_search") + .unwrap_or_else(|| panic!("default local search is reported: {plan:#?}")); + assert_eq!(attribute(local_search, "acceptor"), "late_acceptance"); + assert_eq!( + attribute(local_search, "forager_accepted_count_limit"), + "256" + ); + assert_eq!(attribute(local_search, "weighting"), "equal"); + assert_eq!( + attribute(local_search, "selection_order"), + "stratified_random" + ); +} + +const EXPLICIT_PREFIX: &str = "\ +environment_mode = \"reproducible\" +random_seed = 7 + +[termination] +step_count_limit = 20 + +[[phases]] +type = \"construction_heuristic\" +construction_heuristic_type = \"list_cheapest_insertion\" + +[[phases]] +type = \"local_search\" +"; + +fn explicit_local_search(forager: &str) -> &'static str { + Box::leak(format!("{EXPLICIT_PREFIX}{forager}").into_boxed_str()) +} + +fn explicit_local_search_plan(forager: &str) -> CandidateTracePhasePlan { + let plan = completed_telemetry(explicit_local_search(forager)) + .resolved_phase_plan + .expect("a completed compiled solve reports its resolved plan"); + find(&plan, "solverforge.runtime.local_search.acceptor_forager") + .unwrap_or_else(|| panic!("explicit local search is reported: {plan:#?}")) + .clone() +} + +#[test] +fn an_omitted_forager_inherits_the_default_policy() { + let local_search = explicit_local_search_plan(""); + assert_eq!( + attribute(&local_search, "forager"), + "default:AcceptedCount { limit: 256 }" + ); + assert_eq!( + attribute(&local_search, "forager_accepted_count_limit"), + "256" + ); +} + +#[test] +fn an_explicit_accepted_count_forager_without_a_limit_takes_one() { + let local_search = + explicit_local_search_plan("\n[phases.forager]\ntype = \"accepted_count\"\n"); + assert!( + attribute(&local_search, "forager").starts_with("configured:AcceptedCount"), + "{local_search:#?}" + ); + assert_eq!( + attribute(&local_search, "forager_accepted_count_limit"), + "1" + ); +} + +#[test] +fn an_implicit_tabu_forager_has_no_accepted_count_horizon() { + let local_search = explicit_local_search_plan( + "\n[phases.acceptor]\ntype = \"tabu_search\"\nentity_tabu_size = 3\n", + ); + assert_eq!( + attribute(&local_search, "forager_accepted_count_limit"), + "none" + ); +} + +#[test] +fn variable_neighborhood_descent_has_no_accepted_count_horizon() { + let local_search = explicit_local_search_plan( + "local_search_type = \"variable_neighborhood_descent\"\n\n\ + [[phases.neighborhoods]]\ntype = \"list_change_move_selector\"\n", + ); + assert_eq!( + attribute(&local_search, "forager_accepted_count_limit"), + "none" + ); +} diff --git a/docs/configuration.md b/docs/configuration.md index c8c8cfef4..1993f3319 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -111,6 +111,18 @@ Construction always runs first and is state-aware: - remaining scalar variables that no assignment group owns use descriptor-backed single-slot construction. +Each list slot gets the first construction whose declarations it has: + +| Slot declares | Construction | Reported `reason` | +|---|---|---| +| savings hooks (`domain = "cvrp"` or `savings_hooks`) | `ListClarkeWright` | `savings_hooks_declared` | +| precedence, construction order and ownership | `ListRegretInsertion` | `precedence_construction_order_and_ownership_declared` | +| precedence and construction order | `ListRoundRobin` | `precedence_and_construction_order_declared` | +| none of these | `ListCheapestInsertion` | `no_specialized_list_policy_declared` | + +After list construction, a slot with route hooks and a non-empty route runs +`ListKOpt` (`route_hooks_declared_and_route_non_empty`). + The dense required batch collects independent assignments directly. Bounded augmenting rematches stay with the following required cursor rather than being explored inside a batch that cannot retain multi-entity edits. Keeping an @@ -154,9 +166,42 @@ neighborhoods: scalar, compound conflict-repair and ordinary scalar families. Leaf order is seeded `Random`. A single family uses `Sequential`; a -multi-family union uses `StratifiedRandom`. The stock forager applies finite -accepted-count horizons where they apply, and `limited_neighborhood` remains -the explicit cap for configured exhaustive selectors. +multi-family union uses `StratifiedRandom` with equal family weights. +`limited_neighborhood` remains the explicit cap for configured exhaustive +selectors. + +The acceptor and forager follow the model's shape: + +| Model | Acceptor | Forager | +|---|---|---| +| list variables, precedence moves available | Late Acceptance, history 400 | first last-step-score improving, accepted-count ceiling 256 | +| list variables | Late Acceptance, history 400 | accepted count 256 | +| scalar groups, no list variables | Diversified Late Acceptance, history 400 | accepted count 256 | +| scalar variables with nearby hooks or conflict repairs | Simulated Annealing, auto-calibrated | accepted count 256 | +| other scalar variables | Simulated Annealing, auto-calibrated | accepted count 1 | + +### Omitted and explicit components + +An omitted value takes the documented default; an explicit value is used as +written: + +- **No `phases`:** construction as above, then the default local search when + termination has an effective limit. +- **An explicit phase list** replaces the defaults. It does not add a + construction phase in front. +- **An explicit `local_search` phase without `move_selector`** gets the + default families above. +- **Without `acceptor` or `forager`**, that phase takes the default acceptor + and forager for the model. An omitted forager after a Tabu Search acceptor + is the best-score forager. +- **An explicit forager with omitted fields** uses that forager's own field + defaults, not the default policy's: `type = "accepted_count"` without + `limit` collects 1 accepted move per step, while an omitted forager on a list + model collects 256. + +`telemetry.resolved_phase_plan` reports the resolved choice for every phase, +including the families a slot did not receive and the capability each was +missing; see [Running solves](running-solves.md#telemetry). [Extend the solver](extend-solver.md#canonical-selector-defaults) explains how these defaults interact with explicit selector configuration. diff --git a/docs/running-solves.md b/docs/running-solves.md index a0849ba5c..8d3c0b914 100644 --- a/docs/running-solves.md +++ b/docs/running-solves.md @@ -103,6 +103,16 @@ Retained status and events expose generated, evaluated and accepted move counts together with generation and evaluation durations. The `moves/s` figure you see in the console is derived for display only. +When a solve on the compiled runtime ends, `telemetry.resolved_phase_plan` +holds the policy it actually ran: each phase, the construction each default +stage chose and the `reason` for it, the move families with their limits, the +families left out and the capability they were missing, the family ordering +and weighting, and the acceptor, forager and effective +`forager_accepted_count_limit`. It is set whether or not `candidate_trace` is +enabled. Together with the per-phase `step_count`, `moves_evaluated`, +`moves_accepted` and elapsed time in `telemetry.phases`, it separates a +costly step selection from a lack of useful moves. + Generic and specialized construction phases publish the same lifecycle and progress telemetry as local search. With verbose logging, the first phase work is reported promptly and long phases continue at roughly one-second intervals.