Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions crates/solverforge-solver/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion crates/solverforge-solver/public-api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ struct SolverStats: pub struct SolverStats { /* private fields */ }
SolverStats: pub fn moves_applied_improving(&self) -> u64
struct SolverStatus: pub struct SolverStatus<Sc: Score> { pub job_id: usize, pub lifecycle_state: SolverLifecycleState, pub terminal_reason: Option<SolverTerminalReason>, pub checkpoint_available: bool, pub event_sequence: u64, pub latest_snapshot_revision: Option<u64>, pub current_score: Option<Sc>, pub best_score: Option<Sc>, 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<PhaseTelemetry>, pub selector_telemetry: Vec<SelectorTelemetry>, pub move_telemetry: Vec<MoveTelemetry>, pub applied_move_trace: Vec<AppliedMoveTelemetry>, pub candidate_trace: Option<CandidateTraceTelemetry>, }
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<PhaseTelemetry>, pub selector_telemetry: Vec<SelectorTelemetry>, pub move_telemetry: Vec<MoveTelemetry>, pub applied_move_trace: Vec<AppliedMoveTelemetry>, pub candidate_trace: Option<CandidateTraceTelemetry>, pub resolved_phase_plan: Option<CandidateTracePhasePlan>, }
SolverTelemetry: pub const fn new_const() -> Self
struct SolverTelemetryDetail: pub struct SolverTelemetryDetail<Sc: Score> { pub status: SolverStatus<Sc>, pub candidate_trace: Option<CandidateTraceTelemetry>, }
struct StepScope: pub struct StepScope<'t, 'a, 'b, S: PlanningSolution, D: Director<S>, BestCb = ()> { /* private fields */ }
Expand Down
5 changes: 5 additions & 0 deletions crates/solverforge-solver/src/builder/local_search_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<S>(&self, score_tie_break: ScoreTieBreak) -> AnyForager<S>
where
S: PlanningSolution,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,16 @@ pub(crate) struct DefaultLocalSearchSelectorDeclaration {
pub slots: Vec<RuntimeScalarSlotId>,
}

/// 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=<capability>[+<capability>...]`, 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.
Expand All @@ -158,6 +168,8 @@ pub(crate) struct DefaultLocalSearchPlan {
pub components: DefaultLocalSearchComponents,
pub selection_order: UnionSelectionOrder,
pub selectors: Vec<DefaultLocalSearchSelectorDeclaration>,
/// Default families a slot does not receive, with the reason.
pub excluded: Vec<DefaultExcludedFamily>,
}

pub(super) fn target_for(slot: &RuntimeScalarSlotId) -> VariableTargetConfig {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use super::{
DefaultLocalSearchForagerPolicy, DefaultLocalSearchPlan,
};

mod exclusions;
mod list;
mod scalar;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -134,6 +138,7 @@ where
components,
selection_order,
selectors: declarations,
excluded,
},
nodes,
)))
Expand Down
Original file line number Diff line number Diff line change
@@ -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<S, V, DM, IDM>(
list_slots: &[CompiledListSlot<S, V, DM, IDM>],
excluded: &mut Vec<DefaultExcludedFamily>,
) {
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::<Vec<_>>();
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<S>(
scalar_slots: &[DefaultScalarBinding<S>],
excluded: &mut Vec<DefaultExcludedFamily>,
) {
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",
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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::<Vec<_>>()
.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.
Expand Down
4 changes: 2 additions & 2 deletions crates/solverforge-solver/src/runtime/compiler/defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
71 changes: 65 additions & 6 deletions crates/solverforge-solver/src/runtime/compiler/defaults/stages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -79,6 +117,7 @@ pub(crate) struct DefaultListPolicyProvenance {
#[derive(Clone, Debug)]
pub(crate) struct ResolvedDefaultConstructionStep<S, V, DM, IDM> {
pub kind: DefaultConstructionStepKind,
pub reason: DefaultConstructionReason,
pub construction: CompiledConstruction<S, V, DM, IDM>,
/// Required-only selection changes which assignment rows are considered;
/// it never changes the configured termination policy.
Expand Down Expand Up @@ -182,10 +221,11 @@ where
DM: Clone + Send + Sync + fmt::Debug + CrossEntityDistanceMeter<S>,
IDM: Clone + Send + Sync + fmt::Debug + CrossEntityDistanceMeter<S>,
{
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"),
Expand All @@ -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,
Expand Down Expand Up @@ -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),
Expand All @@ -258,22 +300,34 @@ where

fn default_list_construction_heuristic<S, V, DM, IDM>(
slot: &CompiledListSlot<S, V, DM, IDM>,
) -> 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,
)
}
}

Expand All @@ -295,6 +349,11 @@ fn assignment_step<S, V, DM, IDM>(
} else {
DefaultConstructionStepKind::AssignmentOptional
},
reason: if required_only {
DefaultConstructionReason::RequiredAssignmentsRemain
} else {
DefaultConstructionReason::OnlyOptionalAssignmentsRemain
},
construction: CompiledConstruction::GroupedScalar {
config,
group_index: binding.group_index,
Expand Down
Loading
Loading