solverforge-core 0.26.0

Core types and traits for SolverForge constraint solver
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# solverforge-core WIREFRAME

Core types and traits for the SolverForge constraint solver framework.

**Location:** `crates/solverforge-core/`
**Workspace Release:** `0.26.0`

## Dependencies

- `thiserror` (workspace) — error derive macros
- `serde` (workspace, optional, feature-gated) — serialization for score types and `ConstraintWeights`
- `toml` (workspace, dev-dependency) — serde round-trip tests

| Feature | Effect |
|---------|--------|
| `default` | Empty default feature set |
| `serde` | Enables `Serialize` / `Deserialize` for score types and `ConstraintWeights` (a transparent name-to-multiplier map) |

## File Map

```
src/
├── lib.rs                                 — Crate root; module declarations, public re-exports
├── constraint.rs                          — ConstraintRef (package/name identifier) and ImpactType enum
├── constraint_weights.rs                  — ConstraintWeights multiplier map, ConstraintWeightError, MAX_CONSTRAINT_WEIGHT_MULTIPLIER
├── constraint_tests.rs                    — Tests for ConstraintRef, ImpactType, and ConstraintWeights
├── score/
│   ├── mod.rs                             — Module declarations and re-exports for score types
│   ├── traits.rs                          — Score trait, ParseableScore trait, ScoreParseError
│   ├── macros.rs                          — Declarative macros: impl_score_ops!, impl_score_scale!, impl_score_parse!
│   ├── level.rs                           — ScoreLevel enum (Hard, Medium, Soft)
│   ├── scale.rs                           — Strict exact integer level scaling shared by built-in scores
│   ├── soft.rs                            — SoftScore: single i64 level
│   ├── hard_soft.rs                       — HardSoftScore: two i64 levels (hard, soft)
│   ├── hard_medium_soft.rs                — HardMediumSoftScore: three i64 levels
│   ├── hard_soft_decimal.rs               — HardSoftDecimalScore: two levels with x100000 scaling
│   ├── bendable.rs                        — BendableScore<H, S>: const-generic multi-level score
│   ├── bendable_serde.rs                  — Serialize/Deserialize for BendableScore (feature `serde`)
│   └── tests/
│       ├── mod.rs                         — Test module declarations
│       ├── soft_score.rs                  — SoftScore tests
│       ├── hard_soft_score.rs             — HardSoftScore tests
│       ├── hard_medium_soft_score.rs      — HardMediumSoftScore tests
│       ├── hard_soft_decimal_score.rs     — HardSoftDecimalScore tests
│       ├── scale.rs                       — Exact integer scaling tests for every score type
│       ├── bendable_score.rs              — BendableScore tests
│       ├── bendable_serde.rs              — BendableScore serde round-trip and level-count tests
│       └── custom_score.rs                — Custom Score contract tests
├── domain/
│   ├── mod.rs                             — Module declarations and re-exports for domain types
│   ├── traits.rs                          — PlanningSolution, PlanningEntity, ProblemFact, PlanningId
│   ├── dynamic.rs                         — DynamicModelBackend, scalar/list access contracts, explicit list access/metadata capabilities
│   ├── dynamic/
│   │   ├── assignment.rs                  — Dynamic scalar-assignment metadata contract and structural capabilities
│   │   ├── backend.rs                     — DynamicModelBackend-backed scalar/list access adapters
│   │   ├── list_slot.rs                   — DynamicListVariableSlot descriptor-resolved list slot adapter
│   │   ├── resolution.rs                  — Logical ID to descriptor-index resolution and validation
│   │   └── scalar_slot.rs                 — DynamicScalarVariableSlot descriptor-resolved scalar slot adapter
│   ├── entity_ref.rs                      — EntityRef, EntityExtractor trait, EntityCollectionExtractor
│   ├── variable.rs                        — VariableType, ShadowVariableKind, ValueRangeType
│   ├── descriptor/
│   │   ├── mod.rs                         — Re-exports descriptor types
│   │   ├── entity.rs                      — EntityDescriptor struct
│   │   ├── identity.rs                    — EntityClassId, ProblemFactClassId, VariableId logical descriptor identifiers
│   │   ├── solution.rs                    — SolutionDescriptor struct
│   │   ├── problem_fact.rs                — ProblemFactDescriptor struct
│   │   ├── var_descriptor.rs              — VariableDescriptor struct
│   │   └── tests/
│   │       ├── mod.rs                     — Test module declarations and shared imports
│   │       ├── fixtures.rs                — Shared TestEntity/TestSolution fixtures and entity descriptor builder
│   │       ├── entity_descriptor.rs       — EntityDescriptor tests
│   │       ├── solution_descriptor.rs     — SolutionDescriptor tests
│   │       └── variable_descriptor.rs     — VariableDescriptor tests
│   └── tests/
│       ├── mod.rs                         — Test module declarations
│       ├── dynamic_list_tests.rs          — Dynamic list access, metadata, and slot validation tests
│       ├── entity_ref_tests.rs            — EntityCollectionExtractor tests
│       └── variable_tests.rs             — VariableType and ShadowVariableKind tests
```

## Public Re-exports (lib.rs)

```rust
pub use constraint::{ConstraintRef, ImpactType};
pub use constraint_weights::{
    ConstraintWeightError, ConstraintWeights, MAX_CONSTRAINT_WEIGHT_MULTIPLIER,
};
pub use domain::{PlanningEntity, PlanningId, PlanningSolution, ProblemFact};
pub use score::{
    BendableScore, HardMediumSoftScore, HardSoftDecimalScore, HardSoftScore,
    ParseableScore, Score, ScoreParseError, SoftScore,
};
```

Additionally, `pub mod constraint`, `pub mod constraint_weights`, `pub mod domain`, `pub mod score` are all public modules.

## Public Traits

### `Score`

**Bounds:** `Copy + Debug + Display + Default + Send + Sync + PartialEq + Eq + PartialOrd + Ord + Add<Output=Self> + Sub<Output=Self> + Neg<Output=Self> + 'static`

| Method | Signature | Note |
|--------|-----------|------|
| `is_feasible` | `fn is_feasible(&self) -> bool` | True when all hard scores >= 0 |
| `zero` | `fn zero() -> Self` | Additive identity |
| `levels_count` | `fn levels_count() -> usize` | Number of score levels |
| `level_number` | `fn level_number(&self, index: usize) -> i64` | Required allocation-free per-level accessor |
| `to_level_numbers` | `fn to_level_numbers(&self) -> Vec<i64>` | Defaulted allocating vector view, high-priority first |
| `from_level_numbers` | `fn from_level_numbers(levels: &[i64]) -> Self` | Panics on wrong count |
| `multiply` | `fn multiply(&self, multiplicand: f64) -> Self` | Scalar multiply, rounded; panics for a non-finite factor or a level outside `i64` |
| `divide` | `fn divide(&self, divisor: f64) -> Self` | Scalar divide, rounded; panics for a zero or non-finite divisor or a level outside `i64` |
| `scale` | `fn scale(&self, factor: i64) -> Self` | Required exact integer multiply of every level; panics on `i64` overflow in every profile |
| `abs` | `fn abs(&self) -> Self` | Absolute value; panics for an `i64::MIN` level |
| `overflowing_add` / `overflowing_sub` / `overflowing_neg` | `fn overflowing_add(self, other: Self) -> (Self, bool)` (and the analogous `sub`/`neg`) | Wrapping result plus a flag set when any level overflowed; lets a caller sum a batch and check once. Default delegates to `Add`/`Sub`/`Neg` with flag `false` |
| `overflowing_scale` | `fn overflowing_scale(&self, factor: i64) -> (Self, bool)` | `scale` without panicking; default delegates to `scale` |
| `overflowing_multiply` | `fn overflowing_multiply(&self, multiplicand: f64) -> (Self, bool)` | `multiply` without panicking; flag also set for a non-finite multiplicand; default delegates to `multiply` |
| `to_scalar` | `fn to_scalar(&self) -> f64` | Weighted single f64 for SA temperature |
| `level_label` | `fn level_label(index: usize) -> ScoreLevel` | Semantic label per level |
| `compare` | `fn compare(&self, other: &Self) -> Ordering` | Default: `self.cmp(other)` |
| `is_better_than` | `fn is_better_than(&self, other: &Self) -> bool` | Default: `self > other` |
| `is_worse_than` | `fn is_worse_than(&self, other: &Self) -> bool` | Default: `self < other` |
| `is_equal_to` | `fn is_equal_to(&self, other: &Self) -> bool` | Default: `self == other` |
| `one_hard` | `fn one_hard() -> Self` | Score with 1 at first Hard level, 0 elsewhere |
| `one_soft` | `fn one_soft() -> Self` | Score with 1 at last Soft level, 0 elsewhere |
| `one_medium` | `fn one_medium() -> Self` | Score with 1 at first Medium level, 0 elsewhere |

**Overflow contract:** score arithmetic never wraps. On every built-in score type, `Add`, `Sub`, `Neg`, `abs`, `scale`, `multiply` and `divide` panic in every build profile (`score addition overflows i64`, ...) when a level does not fit `i64`, and `HardSoftDecimalScore::of` / `of_hard` / `of_soft` panic when the unscaled value times 100,000 overflows (a compile error in a `const` context). A wrapped level would flip sign and turn a penalty into a reward; saturating would break the `a + d - d == a` identity incremental scoring relies on.

### `ParseableScore`

**Bounds:** `Score`

| Method | Signature | Note |
|--------|-----------|------|
| `parse` | `fn parse(s: &str) -> Result<Self, ScoreParseError>` | Parse from string (e.g. `"0hard/-100soft"`) |
| `to_string_repr` | `fn to_string_repr(&self) -> String` | Serialized string form |

### `PlanningSolution`

**Bounds:** `Clone + Send + Sync + 'static`

| Method | Signature | Note |
|--------|-----------|------|
| `score` | `fn score(&self) -> Option<Self::Score>` | Current score, None if unscored |
| `set_score` | `fn set_score(&mut self, score: Option<Self::Score>)` | Set the score |
| `update_entity_shadows` | `fn update_entity_shadows(&mut self, descriptor_index: usize, entity_index: usize)` | Default: no-op shadow update hook |
| `update_all_shadows` | `fn update_all_shadows(&mut self)` | Default: no-op full shadow refresh hook |
| `HAS_CONSTRAINT_WEIGHTS` | `const HAS_CONSTRAINT_WEIGHTS: bool` | Default: `false`; `true` exactly when the type carries runtime constraint weights. Solves pick a weighted-mode score director only when it is `true` and some multiplier differs from `1`; `#[planning_solution]` also routes such types through the weighted solve entrypoint; a manual `constraint_weights` override must set it |
| `constraint_weights` | `fn constraint_weights(&self) -> Option<&ConstraintWeights>` | Default: `None`; generated for a `#[constraint_weights]` field. Weighted-mode score directors bind it on construction and before every (re)initialization; unweighted-mode directors never read it |
| `list_shadow_elements` | `fn list_shadow_elements(&self, descriptor_index: usize, entity_index: usize) -> Option<(usize, &[usize])>` | Default: `None`; the elements an owner's shadow update writes, with the change source their stream rows use |
| `clear_list_shadows` | `fn clear_list_shadows(&mut self, element: usize)` | Default: no-op; clears the list shadows of an element no list holds |
| `list_shadow_source` | `fn list_shadow_source(collection: &str) -> Option<usize>` | Default: `None`; change source of a collection whose rows carry list shadows |
| `is_initialized` | `fn is_initialized(&self) -> bool` | Default: `true` |

**Associated type:** `type Score: Score`

### `PlanningEntity`

**Bounds:** `Clone + Send + Sync + Any + 'static`

| Method | Signature | Note |
|--------|-----------|------|
| `is_pinned` | `fn is_pinned(&self) -> bool` | Default: `false`; a manually assembled descriptor also needs `with_pin_predicate()` to expose this value to solver phases |
| `as_any` | `fn as_any(&self) -> &dyn Any` | Dynamic typing support |
| `as_any_mut` | `fn as_any_mut(&mut self) -> &mut dyn Any` | Mutable dynamic typing |

### `ProblemFact`

**Bounds:** `Clone + Send + Sync + Any + 'static`

| Method | Signature | Note |
|--------|-----------|------|
| `as_any` | `fn as_any(&self) -> &dyn Any` | Dynamic typing support |

### `PlanningId`

| Method | Signature | Note |
|--------|-----------|------|
| `planning_id` | `fn planning_id(&self) -> Self::Id` | Stable unique identifier |

**Associated type:** `type Id: Eq + Hash + Clone + Send + Sync + 'static`

### `EntityExtractor`

**Bounds:** `Send + Sync`

| Method | Signature | Note |
|--------|-----------|------|
| `count` | `fn count(&self, solution: &dyn Any) -> Option<usize>` | Entity count in collection |
| `get` | `fn get<'a>(&self, solution: &'a dyn Any, index: usize) -> Option<&'a dyn Any>` | Get entity by index |
| `get_mut` | `fn get_mut<'a>(&self, solution: &'a mut dyn Any, index: usize) -> Option<&'a mut dyn Any>` | Mutable entity by index |
| `entity_refs` | `fn entity_refs(&self, solution: &dyn Any) -> Vec<EntityRef>` | All entity references |
| `clone_box` | `fn clone_box(&self) -> Box<dyn EntityExtractor>` | Clone as trait object |
| `clone_entity_boxed` | `fn clone_entity_boxed(&self, solution: &dyn Any, index: usize) -> Option<Box<dyn Any + Send + Sync>>` | Clone entity as boxed Any |
| `entity_type_id` | `fn entity_type_id(&self) -> TypeId` | TypeId of entity type |

## Public Structs

### Score Types

#### `SoftScore`

Fields: `score: i64` (private)

Constants: `ZERO`, `ONE`

Constructors: `of(i64)`, `From<i64>`

Accessors: `score() -> i64`

Implements: `Score`, `ParseableScore`, `Ord`, `Copy`, `Eq`, `Hash`, `Default`, `Debug`, `Display`

Optional: `serde::Serialize + Deserialize` (feature `serde`)

#### `HardSoftScore`

Fields: `hard: i64`, `soft: i64` (private)

Constants: `ZERO`, `ONE_HARD`, `ONE_SOFT`

Constructors: `of(i64, i64)`, `of_hard(i64)`, `of_soft(i64)`

Accessors: `hard() -> i64`, `soft() -> i64`, `hard_score() -> HardSoftScore`, `soft_score() -> HardSoftScore`

Implements: `Score`, `ParseableScore`, `Ord`, `Copy`, `Eq`, `Hash`, `Default`, `Debug`, `Display`

Optional: `serde::Serialize + Deserialize` (feature `serde`)

#### `HardMediumSoftScore`

Fields: `hard: i64`, `medium: i64`, `soft: i64` (private)

Constants: `ZERO`, `ONE_HARD`, `ONE_MEDIUM`, `ONE_SOFT`

Constructors: `of(i64, i64, i64)`, `of_hard(i64)`, `of_medium(i64)`, `of_soft(i64)`

Accessors: `hard() -> i64`, `medium() -> i64`, `soft() -> i64`

Implements: `Score`, `ParseableScore`, `Ord`, `Copy`, `Eq`, `Hash`, `Default`, `Debug`, `Display`

Optional: `serde::Serialize + Deserialize` (feature `serde`)

#### `HardSoftDecimalScore`

Fields: `hard: i64`, `soft: i64` (private, stored pre-scaled by 100,000)

Constants: `ZERO`, `ONE_HARD`, `ONE_SOFT`

Constructors: `of(i64, i64)` (unscaled), `of_scaled(i64, i64)` (pre-scaled), `of_hard(i64)`, `of_soft(i64)`, `of_hard_scaled(i64)`, `of_soft_scaled(i64)`

Parsing one level: `parse_level(&str) -> Result<i64, ScoreParseError>` (decimal units in, scaled value out; same rules as `parse`)

Accessors: `hard_scaled() -> i64`, `soft_scaled() -> i64`, `hard_score() -> HardSoftDecimalScore`, `soft_score() -> HardSoftDecimalScore`, `has_hard_component() -> bool`

Implements: `Score`, `ParseableScore`, `Ord`, `Copy`, `Eq`, `Hash`, `Default`, `Debug`, `Display`

Optional: `serde::Serialize + Deserialize` (feature `serde`)

#### `BendableScore<const H: usize, const S: usize>`

Fields: `hard: [i64; H]`, `soft: [i64; S]` (private)

Constructors: `of([i64; H], [i64; S])`, `zero()`, `one_hard(usize)`, `one_soft(usize)`

Accessors: `hard_levels_count() -> usize`, `soft_levels_count() -> usize`, `hard_score(usize) -> i64`, `soft_score(usize) -> i64`, `hard_scores() -> &[i64; H]`, `soft_scores() -> &[i64; S]`

Implements: `Score`, `Ord`, `Copy`, `Eq`, `Hash`, `Default`, `Debug`, `Display`

Does **not** implement `ParseableScore`.

Optional: `serde::Serialize + Deserialize` (feature `serde`), hand-written in `score/bendable_serde.rs`: the wire shape is `{"hard": [...], "soft": [...]}`, and a level list whose length is not exactly `H` (or `S`) is rejected with an `invalid length` error.

### Other Score Types

#### `ScoreLevel`

```rust
enum ScoreLevel { Hard, Medium, Soft }
```

Derives: `Debug, Clone, Copy, PartialEq, Eq, Hash`

### Constraint Weights

#### `ConstraintWeights`

Per-constraint `u32` multipliers keyed by `ConstraintRef::full_name()`. Unlisted constraints keep multiplier `1`; `0` disables a constraint; `n` scales its coded contribution `n` times, for every terminal carrying that name.

Derives: `Clone, Debug, Default, PartialEq, Eq`; with the `serde` feature, `Serialize`/`Deserialize` as a transparent name-to-multiplier map.

| Method | Signature | Note |
|--------|-----------|------|
| `new` | `fn new() -> Self` | Empty map |
| `set` | `fn set(&mut self, constraint: impl Into<String>, multiplier: u32) -> &mut Self` | Insert or replace |
| `remove` | `fn remove(&mut self, constraint: &str) -> Option<u32>` | |
| `get` | `fn get(&self, constraint: &str) -> Option<u32>` | Listed multiplier only |
| `multiplier_for` | `fn multiplier_for(&self, constraint: &ConstraintRef) -> u32` | `1` when unlisted |
| `is_empty` / `len` | `fn is_empty(&self) -> bool` / `fn len(&self) -> usize` | |
| `iter` | `fn iter(&self) -> impl Iterator<Item = (&str, u32)>` | Sorted by name |
| `validate` | `fn validate<'a>(&self, known: impl IntoIterator<Item = &'a ConstraintRef>) -> Result<(), ConstraintWeightError>` | Rejects unknown names (with close-match suggestions) and multipliers above the cap |

#### `ConstraintWeightError`

`UnknownConstraint { name, suggestions: Vec<String>, known: Vec<String> }` and `MultiplierTooLarge { name, multiplier, max }`. Implements `Debug`, `Clone`, `PartialEq`, `Eq`, `Display`, `std::error::Error`.

#### `MAX_CONSTRAINT_WEIGHT_MULTIPLIER`

`pub const MAX_CONSTRAINT_WEIGHT_MULTIPLIER: u32 = 1_000_000;` keeps a scaled per-match contribution up to about 9.2e12 per level exact in `i64`.

#### `ScoreParseError`

Fields: `pub message: String`

Implements: `Debug`, `Clone`, `PartialEq`, `Eq`, `Display`, `std::error::Error`

### Domain Types

#### `EntityRef`

```rust
pub struct EntityRef {
    pub index: usize,
    pub type_name: &'static str,
    pub collection_field: &'static str,
}
```

Derives: `Debug, Clone`

#### `EntityCollectionExtractor<S, E>`

```rust
pub struct EntityCollectionExtractor<S, E> {
    type_name: &'static str,                       // private
    collection_field: &'static str,                 // private
    get_collection: fn(&S) -> &Vec<E>,              // private
    get_collection_mut: fn(&mut S) -> &mut Vec<E>,  // private
}
```

Bounds on impl: `S: Send + Sync + 'static`, `E: Clone + Send + Sync + 'static`

Implements: `EntityExtractor`, `Debug`

#### `VariableType`

```rust
pub enum VariableType {
    Genuine,
    List,
    Shadow(ShadowVariableKind),
}
```

Methods: `is_genuine()`, `is_shadow()`, `is_list()`, `is_basic()`

#### `ShadowVariableKind`

```rust
pub enum ShadowVariableKind {
    Custom, InverseRelation, Index, NextElement,
    PreviousElement, Cascading, Piggyback,
}
```

Methods: `requires_listener()`, `is_automatic()`, `is_piggyback()`

#### `ValueRangeType`

```rust
pub enum ValueRangeType {
    Collection,
    CountableRange { from: i64, to: i64 },
    EntityDependent,
}
```

### Descriptors

#### `EntityDescriptor`

```rust
pub struct EntityDescriptor {
    pub type_name: &'static str,
    pub type_id: TypeId,
    pub logical_id: Option<EntityClassId>,
    pub solution_field: &'static str,
    pub is_collection: bool,
    pub variable_descriptors: Vec<VariableDescriptor>,
    pub extractor: Option<Box<dyn EntityExtractor>>,
    pub id_field: Option<&'static str>,
    pub pin_field: Option<&'static str>,
}
```

Builder methods: `with_extractor()`, `with_logical_id()`, `with_variable()`, `with_id_field()`, `with_pin_field()`, `with_pin_predicate()`.
`is_pinned(solution, index)` reads the current entity pin state through the typed predicate; descriptors without one return `false`. Manually assembled descriptors must supply `with_pin_predicate()` to make a custom `PlanningEntity::is_pinned()` visible to the solver.

Query methods: `genuine_variable_descriptors()`, `shadow_variable_descriptors()`, `find_variable(&str)`, `has_genuine_variables()`, `has_extractor()`, `has_pin_predicate()`, `entity_count(&dyn Any)`, `is_pinned(&dyn Any, usize)`, `get_entity()`, `get_entity_mut()`, `entity_refs()`, `for_each_entity()`, `for_each_entity_mut()`

Manual `Clone` and `Debug` impls.

Logical IDs: `with_logical_id(EntityClassId)` binds dynamic host-language entity classes to descriptor indexes independently of descriptor order.

#### `SolutionDescriptor`

```rust
pub struct SolutionDescriptor {
    pub type_name: &'static str,
    pub type_id: TypeId,
    pub entity_descriptors: Vec<EntityDescriptor>,
    pub problem_fact_descriptors: Vec<ProblemFactDescriptor>,
    pub score_field: &'static str,
    pub score_is_optional: bool,
    entity_type_index: HashMap<TypeId, usize>,  // private, O(1) lookup
    entity_logical_index: HashMap<EntityClassId, usize>,  // private, logical ID -> descriptor index
}
```

Builder methods: `with_entity()`, `with_problem_fact()`, `with_score_field()`

Query methods: `find_entity_descriptor(&str)`, `find_entity_descriptor_by_type(TypeId)`, `find_entity_descriptor_by_logical_id(EntityClassId)`, `entity_descriptor_index_by_logical_id(EntityClassId)`, `genuine_variable_descriptors()`, `shadow_variable_descriptors()`, `total_entity_count(&dyn Any)`, `all_entity_refs(&dyn Any)`, `for_each_entity()`, `get_entity()`, `get_entity_mut()`, `entity_descriptor_count()`, `problem_fact_descriptor_count()`, `all_extractors_configured()`

#### `ProblemFactDescriptor`

```rust
pub struct ProblemFactDescriptor {
    pub type_name: &'static str,
    pub type_id: TypeId,
    pub logical_id: Option<ProblemFactClassId>,
    pub solution_field: &'static str,
    pub is_collection: bool,
    pub id_field: Option<&'static str>,
    pub extractor: Option<Box<dyn EntityExtractor>>,
}
```

Builder methods: `with_extractor()`, `with_logical_id()`, `single()`, `with_id_field()`

#### `VariableDescriptor`

```rust
pub struct VariableDescriptor {
    pub name: &'static str,
    pub logical_id: Option<VariableId>,
    pub variable_type: VariableType,
    pub allows_unassigned: bool,
    pub value_range_provider: Option<&'static str>,
    pub value_range_type: ValueRangeType,
    pub source_variable: Option<&'static str>,
    pub source_entity: Option<&'static str>,
    pub usize_getter: Option<UsizeGetter>,
    pub usize_setter: Option<UsizeSetter>,
    pub entity_value_provider: Option<UsizeEntityValueProvider>,
    pub candidate_values: Option<UsizeCandidateValues>,
    pub nearby_value_candidates: Option<UsizeCandidateValues>,
    pub nearby_entity_candidates: Option<UsizeCandidateValues>,
    pub nearby_value_distance_meter: Option<UsizeNearbyValueDistanceMeter>,
    pub nearby_entity_distance_meter: Option<UsizeNearbyEntityDistanceMeter>,
    pub construction_entity_order_key: Option<UsizeConstructionEntityOrderKey>,
    pub construction_value_order_key: Option<UsizeConstructionValueOrderKey>,
    pub search_entity_order_key: Option<UsizeSearchEntityOrderKey>,
    pub search_value_order_key: Option<UsizeSearchValueOrderKey>,
}
```

Constructors: `genuine(&str)`, `list(&str)`, `shadow(&str, ShadowVariableKind)`, `piggyback(&str, &str)`

Builder methods: `with_value_range()`, `with_allows_unassigned()`, `with_logical_id()`, `with_value_range_type()`, `with_source()`, `with_usize_accessors()`, `with_entity_value_provider()`, `with_candidate_values()`, `with_nearby_value_candidates()`, `with_nearby_entity_candidates()`, `with_nearby_value_distance_meter()`, `with_nearby_entity_distance_meter()`, `with_construction_entity_order_key()`, `with_construction_value_order_key()`, `with_search_entity_order_key()`, `with_search_value_order_key()`

### Dynamic Binding Slots

`DynamicModelBackend` is the Rust-owned dynamic planning model backend contract for host-language integrations. It exposes logical `EntityClassId`/`VariableId` scalar and list access, candidate values, scalar legality, and list element enumeration.

Required methods: `entity_count()`, `get_scalar()`, `set_scalar()`,
`list_len()`, `list_get()`, `list_insert()`, `list_remove()`,
`candidate_values()`, and `scalar_value_is_legal()`.

Default list-element methods: `list_element_count()` returns `0`,
`list_element()` returns the element index, and `list_assigned_elements()`
returns an empty vector.

`DynamicScalarAccess<S>` is the object-safe scalar access trait used by custom
slot adapters. Methods: `entity_class()`, `variable()`, `entity_count()`,
`get()`, `set()`, `candidate_values()`, and `value_is_legal()`. Optional nearby-source methods are
`has_nearby_value_candidates()`, `visit_nearby_value_candidates()`,
`nearby_value_distance()`, `has_nearby_entity_candidates()`,
`visit_nearby_entity_candidates()`, and `nearby_entity_distance()`. The
`has_*` methods declare structural source capability; each visitor returns
whether that row supplied a source and receives a source-consumption limit.
Returning `false` requests the ordinary per-row value or all-entity fallback;
`None` distance preserves source order. Visitors must not consume a lazy host
source past their supplied limit.

`DynamicListAccess<S>` is the object-safe list access trait used by custom slot
adapters. Required methods: `entity_class()`, `variable()`, `entity_count()`,
`element_count()`, `element()`, `assigned_elements()`, `len()`, `get()`,
`insert()`, and `remove()`. `capabilities()` returns
`DynamicListAccessCapabilities { set, replace, reverse, sublist }`; the
matching optional operations are `set()`, whole-row `replace()`, `reverse()`,
`sublist_remove()`, and `sublist_insert()`. An absent capability is a hard
phase-validation boundary, not permission to synthesize the operation from
basic mutations.

`DynamicListMetadataCapabilities` declares immutable, slot-bound
`element_owner`, `construction_order_key`, `precedence_duration`,
`precedence_successors`, `cross_position_distance`,
`intra_position_distance`, `route`, and `savings` bundles.
`DynamicListMetadata<S>` exposes the bound logical identity and the matching
owner/order/precedence, distance, route, and savings methods. Route metadata
contains depot, distance, and feasibility; route reads and whole-row writes
remain on `DynamicListAccess`. Savings metadata contains depot, metric class,
distance, and construction feasibility. SolverForge never manufactures
metadata defaults for an undeclared bundle.

`DynamicScalarVariableSlot<S>` carries logical entity/variable IDs, display
names, `allows_unassigned`, a dynamic access adapter, and the resolved entity
descriptor and variable indexes. Public fields: `entity`, `variable`,
`entity_type_name`, `variable_name`, and `allows_unassigned`; both indexes and
the access adapter are private. Constructors: `new()` for
`S: DynamicModelBackend`, or `with_access()` for custom adapters. Descriptor
methods: `resolve_descriptor_index(&SolutionDescriptor)`,
`resolved_against(&SolutionDescriptor)`, `is_descriptor_resolved()`,
`descriptor_index()`, and `descriptor_variable_index()`.
`resolve_descriptor_index()` validates the complete logical target and
establishes both indexes.
`is_descriptor_resolved()` is true only when both indexes are present. Runtime access methods:
`matches_target()`, `entity_count()`, `current_value()`, `set_value()`,
`candidate_values()`, `has_nearby_value_candidates()`,
`visit_nearby_value_candidates()`, `nearby_value_distance()`,
`has_nearby_entity_candidates()`, `visit_nearby_entity_candidates()`,
`nearby_entity_distance()`, and `value_is_legal()`.

`DynamicListVariableSlot<S>` carries logical entity/variable IDs, display
names, a dynamic list access adapter, optional immutable metadata, and the
resolved entity descriptor and variable indexes. Public fields: `entity`, `variable`, `entity_type_name`, and
`variable_name`; both indexes and the access adapter are private. Constructors:
`new()` for `S: DynamicModelBackend`, `new_with_metadata()` for backend access
plus immutable metadata, `try_with_access()` for custom adapters,
`with_access_and_metadata()` for custom adapters with immutable metadata, or
`with_metadata()` to attach and identity-check metadata after access creation.
Descriptor methods: `resolve_descriptor_index(&SolutionDescriptor)`,
`resolved_against(&SolutionDescriptor)`, `is_descriptor_resolved()`,
`descriptor_index()`, and `descriptor_variable_index()`.
`resolve_descriptor_index()` establishes both indexes after full validation;
`is_descriptor_resolved()` is true only when both are present. Runtime access methods:
`matches_target()`, `entity_count()`, `element_count()`, `element()`,
`assigned_elements()`, `list_len()`, `list_get()`, `list_insert()`, and
`list_remove()`. Capability-aware operations are `access_capabilities()`,
`list_set()`, `list_replace()`, `list_reverse()`, `sublist_remove()`, and
`sublist_insert()`. Metadata access uses `metadata()`,
`metadata_capabilities()`, and `require_metadata()`.

Dynamic slot resolution validates logical entity ID, entity type name, logical
variable ID, variable name, and scalar/list variable kind before runtime
construction or local-search selectors use score-director notifications. That
model-compilation boundary also establishes canonical dynamic construction-slot
identity.

### Dynamic Scalar Assignment Metadata

`DynamicScalarAssignmentMetadata<S>` is the public declarative metadata
boundary for one dynamic nullable scalar assignment group. A binding registers
one `Send + Sync` metadata object against one group-owned dynamic scalar slot;
it does not register a construction phase, selector, move stream, thread-local
lookup, or group-name lookup callback.

`DynamicScalarAssignmentMetadataCapabilities` exposes the boolean fields
`required_entity`, `capacity_key`, `position_key`, `sequence_key`,
`entity_order`, `value_order`, and `assignment_rule`. These are structural
declarations, not values inferred during a solve. If a capability is false, its
corresponding method must return the neutral result (`false`, `None`, or `true`
for `assignment_edge_allowed`). An assignment rule requires sequence-key
metadata.

The metadata methods are `required_entity()`, `capacity_key()`,
`position_key()`, `sequence_key()`, `entity_order_key()`,
`value_order_key()`, and `assignment_edge_allowed()`. SolverForge owns the
resulting candidate generation, canonical construction, and grouped local
search; host bindings supply only this declarative group metadata.

Scalar hook type aliases:
Scalar planning variables use `Option<usize>` candidate indexes. Domain IDs can
use other Rust types on entities or facts, but the runtime scalar getter/setter
surface is index-based.

| Alias | Signature | Note |
|-------|-----------|------|
| `UsizeGetter` | `for<'a> fn(&'a dyn Any) -> Option<usize>` | Scalar getter |
| `UsizeSetter` | `fn(&mut dyn Any, Option<usize>)` | Scalar setter |
| `UsizeEntityValueProvider` | `for<'a> fn(&'a dyn Any) -> Vec<usize>` | Entity-local legal values |
| `UsizeCandidateValues` | `for<'a> fn(&'a dyn Any, usize, usize) -> &'a [usize]` | Bounded scalar candidates |
| `UsizeNearbyValueDistanceMeter` | `fn(&dyn Any, usize, usize) -> f64` | Ranks already bounded nearby values |
| `UsizeNearbyEntityDistanceMeter` | `fn(&dyn Any, usize, usize) -> f64` | Ranks already bounded nearby entities |
| `UsizeConstructionEntityOrderKey` | `fn(&dyn Any, usize) -> i64` | Construction entity order key |
| `UsizeConstructionValueOrderKey` | `fn(&dyn Any, usize, usize) -> i64` | Construction value order key |

### Fast Hashing (`fast_hash`)

- `FastHasher` — deterministic hasher for engine-minted index keys (row
  handles, source indexes, descriptor ids): a multiply-xor round for integer
  writes, byte-wise FNV-1a for opaque keys. Bucket order is reproducible across
  processes.
- `FastMap<K, V>` = `HashMap<K, V, BuildHasherDefault<FastHasher>>`;
  `FastSet<T>` = `HashSet<T, BuildHasherDefault<FastHasher>>`.

### Constraint Types

#### `ConstraintRef`

```rust
pub struct ConstraintRef {
    pub package: String,
    pub name: String,
}
```

Methods: `new(impl Into<String>, impl Into<String>)`, `full_name() -> String`

Derives: `Debug, Clone, PartialEq, Eq, Hash`

#### `ImpactType`

```rust
pub enum ImpactType { Penalty, Reward }
```

Derives: `Debug, Clone, Copy, PartialEq, Eq, Hash`

## Architectural Notes

### Score Macros

Three declarative macros reduce boilerplate for score types:

- `impl_score_ops!($type { $fields } => $ctor)` — generates `PartialOrd`, `Add`, `Sub`, `Neg`
- `impl_score_scale!($type { $fields } => $ctor)` — generates `multiply`, `divide`, `abs` method bodies (used inside `impl Score`)
- `impl_score_parse!($type { $field => $suffix } => $ctor)` — generates `ParseableScore` impl for slash-separated formats

`SoftScore` and `HardSoftDecimalScore` have custom parse logic and do not use `impl_score_parse!`.

### Score Scalar Weighting

`to_scalar()` uses powers of 10^6 to separate levels:
- `HardSoftScore`: `hard * 1_000_000 + soft`
- `HardMediumSoftScore`: `hard * 1_000_000_000_000 + medium * 1_000_000 + soft`
- `BendableScore`: dynamic weighting via `10^((total_levels - 1 - i) * 6)`

### HardSoftDecimalScore Scaling

Internal values are stored multiplied by 100,000 (`SCALE` constant). `of()` auto-scales; `of_scaled()` takes pre-scaled values. Text conversions use integer arithmetic only: `Display` and `Debug` print each level exactly (at most five fractional digits, trailing zeros trimmed, `i64::MIN` included), and `parse` accepts `[-+]?digits(.digits)?` with at most five fractional digits per level, rejecting `NaN`, infinities, exponents, extra decimals and values outside `i64` after scaling. Every value round-trips through `Display` and `parse`.

### BendableScore Const Generics

`BendableScore<const H: usize, const S: usize>` uses fixed-size arrays `[i64; H]` and `[i64; S]`. This enables `Copy` with zero heap allocation. It cannot use the declarative macros due to const generic array iteration. For the same reason serde's derive does not apply (serde implements array traits only up to length 32), so its serde impls are written by hand.

### EntityExtractor as Intentional dyn Boundary

`EntityExtractor` is a `dyn` trait object — this is an **intentional type-erasure boundary**. Descriptors need to work with entities of unknown concrete type at runtime. The `EntityCollectionExtractor<S, E>` provides the concrete implementation that downcasts via `Any`. `Box<dyn EntityExtractor>` appears in `EntityDescriptor` and `ProblemFactDescriptor`.

## Cross-Crate Dependencies

This is the leaf crate — it depends on no other solverforge crates. All other solverforge crates depend on it.