Skip to main content

solverforge_core/domain/
dynamic.rs

1//! Dynamic model contracts for host-language integrations.
2
3use std::fmt;
4use std::sync::Arc;
5
6use crate::domain::{EntityClassId, SolutionDescriptor, VariableId};
7use crate::score::Score;
8
9mod backend;
10mod resolution;
11
12use backend::{BackendListAccess, BackendScalarAccess};
13use resolution::{resolve_dynamic_descriptor_indexes, DynamicVariableKind};
14
15mod assignment;
16
17pub use assignment::{
18    DynamicScalarAssignmentMetadata, DynamicScalarAssignmentMetadataCapabilities,
19};
20
21mod list_slot;
22pub use list_slot::DynamicListVariableSlot;
23
24mod scalar_slot;
25pub use scalar_slot::DynamicScalarVariableSlot;
26
27/// Rust-owned dynamic planning model backend.
28///
29/// Binding crates implement this trait on their concrete dynamic solution
30/// state. The trait is expressed in logical entity and variable IDs rather
31/// than Rust `TypeId`s.
32pub trait DynamicModelBackend: Clone + Send + Sync + 'static {
33    /// Score type produced for this model.
34    type Score: Score;
35
36    /// Number of rows (entities) of class `entity`.
37    fn entity_count(&self, entity: EntityClassId) -> usize;
38
39    /// Value of a scalar variable on one row; `None` means unassigned.
40    fn get_scalar(&self, entity: EntityClassId, row: usize, variable: VariableId) -> Option<usize>;
41
42    /// Assigns (`Some`) or unassigns (`None`) a scalar variable on one row.
43    fn set_scalar(
44        &mut self,
45        entity: EntityClassId,
46        row: usize,
47        variable: VariableId,
48        value: Option<usize>,
49    );
50
51    /// Length of a list variable on one row.
52    fn list_len(&self, entity: EntityClassId, row: usize, variable: VariableId) -> usize;
53
54    /// Element at `pos` in a row's list; `None` when `pos` is out of range.
55    fn list_get(
56        &self,
57        entity: EntityClassId,
58        row: usize,
59        variable: VariableId,
60        pos: usize,
61    ) -> Option<usize>;
62
63    /// Inserts `value` at `pos` in a row's list.
64    fn list_insert(
65        &mut self,
66        entity: EntityClassId,
67        row: usize,
68        variable: VariableId,
69        pos: usize,
70        value: usize,
71    );
72
73    /// Removes and returns the element at `pos` in a row's list; `None` when `pos` is out of range.
74    fn list_remove(
75        &mut self,
76        entity: EntityClassId,
77        row: usize,
78        variable: VariableId,
79        pos: usize,
80    ) -> Option<usize>;
81
82    /// Candidate values for a scalar variable on one row.
83    fn candidate_values(&self, entity: EntityClassId, row: usize, variable: VariableId)
84        -> &[usize];
85
86    /// Returns `true` when `value` is a legal assignment for a scalar variable on one row.
87    fn scalar_value_is_legal(
88        &self,
89        entity: EntityClassId,
90        row: usize,
91        variable: VariableId,
92        value: usize,
93    ) -> bool;
94
95    /// Number of declared elements a list variable distributes; defaults to `0`.
96    fn list_element_count(&self, _entity: EntityClassId, _variable: VariableId) -> usize {
97        0
98    }
99
100    /// Element value at declared source index `element_index`; `None` when the
101    /// element is missing. Defaults to the index itself.
102    fn list_element(
103        &self,
104        _entity: EntityClassId,
105        _variable: VariableId,
106        element_index: usize,
107    ) -> Option<usize> {
108        Some(element_index)
109    }
110
111    /// Elements currently placed in any row's list; defaults to none.
112    fn list_assigned_elements(&self, _entity: EntityClassId, _variable: VariableId) -> Vec<usize> {
113        Vec::new()
114    }
115}
116
117/// Object-safe dynamic scalar variable access.
118pub trait DynamicScalarAccess<S>: Send + Sync {
119    /// Entity class this access is bound to.
120    fn entity_class(&self) -> EntityClassId;
121    /// Variable this access is bound to.
122    fn variable(&self) -> VariableId;
123    /// Number of rows of the bound entity class.
124    fn entity_count(&self, solution: &S) -> usize;
125    /// Value on one row; `None` means unassigned.
126    fn get(&self, solution: &S, row: usize) -> Option<usize>;
127    /// Assigns (`Some`) or unassigns (`None`) the value on one row.
128    fn set(&self, solution: &mut S, row: usize, value: Option<usize>);
129    /// Candidate values for one row.
130    fn candidate_values<'a>(&self, solution: &'a S, row: usize) -> &'a [usize];
131    /// Returns `true` when `value` is a legal assignment for one row.
132    fn value_is_legal(&self, solution: &S, row: usize, value: usize) -> bool;
133
134    /// Whether this slot structurally supplies an ordered nearby-value source.
135    ///
136    /// This reports schema capability rather than a row result. The runtime
137    /// still calls [`Self::visit_nearby_value_candidates`] for each row, since
138    /// a row-local source or callback may intentionally be absent for one row.
139    fn has_nearby_value_candidates(&self) -> bool {
140        false
141    }
142
143    /// Visits the ordered nearby-value source for one row.
144    ///
145    /// `limit` is a source-consumption limit, not a result limit. Implementors
146    /// that bridge lazy host-language iterables must not consume values after
147    /// that limit. Return `true` when this row supplied a source, including an
148    /// empty source. Return `false` when no row source is available so the
149    /// solver can use the ordinary candidate-value fallback.
150    fn visit_nearby_value_candidates(
151        &self,
152        _solution: &S,
153        _row: usize,
154        _limit: usize,
155        _visit: &mut dyn FnMut(usize),
156    ) -> bool {
157        false
158    }
159
160    /// Returns the nearby-value distance for a source candidate when one is
161    /// available. `None` preserves source order as the distance fallback.
162    fn nearby_value_distance(&self, _solution: &S, _row: usize, _candidate: usize) -> Option<f64> {
163        None
164    }
165
166    /// Whether this slot structurally supplies an ordered nearby-entity source.
167    fn has_nearby_entity_candidates(&self) -> bool {
168        false
169    }
170
171    /// Visits the ordered nearby-entity source for one left-hand row.
172    ///
173    /// `limit` has the same source-consumption contract as
174    /// [`Self::visit_nearby_value_candidates`]. Return `true` when a row
175    /// source was supplied, including an empty source; otherwise return
176    /// `false` to request the all-entity fallback.
177    fn visit_nearby_entity_candidates(
178        &self,
179        _solution: &S,
180        _left_row: usize,
181        _limit: usize,
182        _visit: &mut dyn FnMut(usize),
183    ) -> bool {
184        false
185    }
186
187    /// Returns the nearby-entity distance for a source candidate when one is
188    /// available. `None` preserves source order as the distance fallback.
189    fn nearby_entity_distance(
190        &self,
191        _solution: &S,
192        _left_row: usize,
193        _right_row: usize,
194    ) -> Option<f64> {
195        None
196    }
197}
198
199/// Object-safe dynamic list variable access.
200///
201/// Basic list mutation capabilities are explicit. `false`/`None` from the
202/// optional range operations means the access implementation did not bind that
203/// operation; it is not permission for a phase to emulate it piecemeal. A
204/// canonical list kernel must validate these bits before creating a reverse,
205/// sublist, permute, swap, ruin, or route phase.
206#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
207pub struct DynamicListAccessCapabilities {
208    /// [`DynamicListAccess::set`] is bound.
209    pub set: bool,
210    /// [`DynamicListAccess::replace`] is bound.
211    pub replace: bool,
212    /// [`DynamicListAccess::reverse`] is bound.
213    pub reverse: bool,
214    /// [`DynamicListAccess::sublist_remove`] and [`DynamicListAccess::sublist_insert`] are bound.
215    pub sublist: bool,
216}
217
218/// Object-safe dynamic list variable access.
219///
220/// Optional operations return `false`/`None` when they are not bound; check
221/// [`capabilities`](Self::capabilities) before relying on them.
222pub trait DynamicListAccess<S>: Send + Sync {
223    /// Entity class this access is bound to.
224    fn entity_class(&self) -> EntityClassId;
225    /// Variable this access is bound to.
226    fn variable(&self) -> VariableId;
227    /// Number of rows of the bound entity class.
228    fn entity_count(&self, solution: &S) -> usize;
229    /// Number of declared elements the list variable distributes.
230    fn element_count(&self, solution: &S) -> usize;
231    /// Element value at declared source index `element_index`; `None` when the element is missing.
232    fn element(&self, solution: &S, element_index: usize) -> Option<usize>;
233    /// Elements currently placed in any row's list.
234    fn assigned_elements(&self, solution: &S) -> Vec<usize>;
235    /// Length of one row's list.
236    fn len(&self, solution: &S, row: usize) -> usize;
237    /// Element at `pos` in one row's list; `None` when `pos` is out of range.
238    fn get(&self, solution: &S, row: usize, pos: usize) -> Option<usize>;
239    /// Inserts `value` at `pos` in one row's list.
240    fn insert(&self, solution: &mut S, row: usize, pos: usize, value: usize);
241    /// Removes and returns the element at `pos` in one row's list; `None` when
242    /// `pos` is out of range.
243    fn remove(&self, solution: &mut S, row: usize, pos: usize) -> Option<usize>;
244
245    /// Optional operations this access binds; defaults to none.
246    fn capabilities(&self) -> DynamicListAccessCapabilities {
247        DynamicListAccessCapabilities::default()
248    }
249
250    /// Overwrites the element at `pos`; returns `false` when the operation is not bound.
251    fn set(&self, _solution: &mut S, _row: usize, _pos: usize, _value: usize) -> bool {
252        false
253    }
254
255    /// Replaces one complete row list as one logical mutation.
256    fn replace(&self, _solution: &mut S, _row: usize, _values: Vec<usize>) -> bool {
257        false
258    }
259
260    /// Reverses positions `start..end` of one row's list; returns `false` when
261    /// the operation is not bound.
262    fn reverse(&self, _solution: &mut S, _row: usize, _start: usize, _end: usize) -> bool {
263        false
264    }
265
266    /// Removes and returns positions `start..end` of one row's list; `None`
267    /// when the operation is not bound.
268    fn sublist_remove(
269        &self,
270        _solution: &mut S,
271        _row: usize,
272        _start: usize,
273        _end: usize,
274    ) -> Option<Vec<usize>> {
275        None
276    }
277
278    /// Inserts `values` at `pos` in one row's list; returns `false` when the
279    /// operation is not bound.
280    fn sublist_insert(
281        &self,
282        _solution: &mut S,
283        _row: usize,
284        _pos: usize,
285        _values: Vec<usize>,
286    ) -> bool {
287        false
288    }
289}
290
291/// Immutable capabilities bound to one dynamic planning-list slot.
292///
293/// A `true` bit means the corresponding method on
294/// [`DynamicListMetadata`] is structurally available. It does *not* install a
295/// semantic fallback: phase assembly must reject a selected heuristic when a
296/// required capability is absent. Optional owner restriction remains distinct
297/// from a missing owner capability: when `element_owner` is available, an
298/// individual element may still return `None` to mean unrestricted.
299#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
300pub struct DynamicListMetadataCapabilities {
301    /// [`DynamicListMetadata::element_owner`] is available.
302    pub element_owner: bool,
303    /// [`DynamicListMetadata::construction_order_key`] is available.
304    pub construction_order_key: bool,
305    /// Duration metadata. Full precedence-aware construction requires this
306    /// together with `precedence_successors`; successor-only metadata remains
307    /// a valid ListRuin contract.
308    pub precedence_duration: bool,
309    /// Ordered successor metadata. This is intentionally independent from
310    /// duration so dynamic bindings preserve the same successor-only policy
311    /// as native list slots.
312    pub precedence_successors: bool,
313    /// [`DynamicListMetadata::cross_position_distance`] is available.
314    pub cross_position_distance: bool,
315    /// [`DynamicListMetadata::intra_position_distance`] is available.
316    pub intra_position_distance: bool,
317    /// The route bundle (`route_depot`, `route_distance`, `route_feasible`) is available.
318    pub route: bool,
319    /// The savings bundle (`savings_depot`, `savings_metric_class`,
320    /// `savings_distance`, `savings_feasible`) is available.
321    pub savings: bool,
322}
323
324/// Slot-bound immutable metadata used by canonical dynamic-list phases.
325///
326/// This deliberately contains no discovery API, current-phase lookup, or
327/// global/TLS state. Binding crates compile schema fields and callbacks once
328/// into one implementation for a specific `(entity_class, variable)` pair,
329/// then attach it to the corresponding [`DynamicListVariableSlot`]. Runtime
330/// callers validate [`Self::capabilities`] before invoking a selected family;
331/// an implementation must not synthesize depot, metric, distance, feasibility,
332/// precedence, or ownership defaults.
333pub trait DynamicListMetadata<S>: Send + Sync {
334    /// Entity class this metadata is bound to.
335    fn entity_class(&self) -> EntityClassId;
336    /// Variable this metadata is bound to.
337    fn variable(&self) -> VariableId;
338    /// Metadata this implementation declares.
339    fn capabilities(&self) -> DynamicListMetadataCapabilities;
340
341    /// Fixed owner for one element when owner restriction is declared.
342    /// `None` means that element is unrestricted; callers must consult
343    /// `capabilities().element_owner` to distinguish an unavailable owner
344    /// source from an unrestricted element.
345    fn element_owner(&self, solution: &S, element: usize) -> Option<usize>;
346
347    /// Deterministic construction ordering key for one element.
348    fn construction_order_key(&self, solution: &S, element: usize) -> Option<i64>;
349
350    /// Duration used by full precedence-aware construction and scheduling.
351    /// It may be absent when this slot deliberately supplies successor-only
352    /// metadata for ListRuin.
353    fn precedence_duration(&self, solution: &S, element: usize) -> Option<usize>;
354
355    /// Extends `successors` with fixed successors in declared order. Returns
356    /// `false` only when successor metadata is unavailable for this slot.
357    ///
358    /// The concrete output buffer preserves the object-safe dynamic metadata
359    /// seam without putting a `dyn FnMut` dispatch in a precedence candidate
360    /// loop.
361    fn extend_precedence_successors(
362        &self,
363        solution: &S,
364        element: usize,
365        successors: &mut Vec<usize>,
366    ) -> bool;
367
368    /// Explicit cross-route position metric for nearby list neighborhoods.
369    fn cross_position_distance(
370        &self,
371        solution: &S,
372        from_entity: usize,
373        from_position: usize,
374        to_entity: usize,
375        to_position: usize,
376    ) -> Option<f64>;
377
378    /// Explicit within-route position metric for nearby K-opt/neighborhoods.
379    fn intra_position_distance(
380        &self,
381        solution: &S,
382        entity: usize,
383        from_position: usize,
384        to_position: usize,
385    ) -> Option<f64>;
386
387    /// Strict route-local bundle used by K-opt and other route phases.
388    ///
389    /// Reading and replacing a route are deliberately *not* metadata
390    /// callbacks. They come from the slot's [`DynamicListAccess`] (`get` and
391    /// one logical `replace` operation) so every route mutation follows the
392    /// same dirty-row/revision path as every other list mutation. A canonical
393    /// phase must require both that base access and this complete metadata
394    /// bundle: depot, distance, and feasibility.
395    fn route_depot(&self, solution: &S, entity: usize) -> Option<usize>;
396    /// Distance from element `from` to element `to` on one route; `None` when unavailable.
397    fn route_distance(&self, solution: &S, entity: usize, from: usize, to: usize) -> Option<i64>;
398    /// Whether a complete candidate route is feasible for one entity; `None` when unavailable.
399    fn route_feasible(&self, solution: &S, entity: usize, route: &[usize]) -> Option<bool>;
400
401    /// Savings-specific bundle used only by Clarke-Wright construction.
402    fn savings_depot(&self, solution: &S, entity: usize) -> Option<usize>;
403    /// Savings metric class of one owner; owners in the same class must share
404    /// depot and distance behavior.
405    fn savings_metric_class(&self, solution: &S, entity: usize) -> Option<usize>;
406    /// Distance from element `from` to element `to` used for savings; `None` when unavailable.
407    fn savings_distance(&self, solution: &S, entity: usize, from: usize, to: usize) -> Option<i64>;
408    /// Whether a merged candidate route is feasible for savings construction;
409    /// `None` when unavailable.
410    fn savings_feasible(&self, solution: &S, entity: usize, route: &[usize]) -> Option<bool>;
411}