cobre-io 0.15.0

Case directory loading and validation for the Cobre power systems ecosystem
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
//! Training-phase configuration types for `config.json → training`.

use std::fmt;
use std::num::NonZeroUsize;

use serde::{Deserialize, Deserializer, Serialize};

use super::scenario_source::RawScenarioSourceConfig;

/// Training parameters (`config.json → training`).
///
/// A forward-pass count (via `selection`) and `stopping_rules` are mandatory —
/// the loader returns [`crate::LoadError::SchemaError`] if either is absent.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TrainingConfig {
    /// Enable the training phase. When `false`, skip directly to simulation.
    #[serde(default = "TrainingConfig::default_enabled")]
    pub enabled: bool,

    /// Random seed for the opening scenario tree (reproducible training).
    #[serde(default)]
    pub tree_seed: Option<i64>,

    /// List of stopping rule configurations.
    ///
    /// **Mandatory** — no default. Must contain at least one `iteration_limit` rule.
    pub stopping_rules: Option<Vec<StoppingRuleConfig>>,

    /// How multiple stopping rules combine: `any` (OR) or `all` (AND).
    #[serde(default)]
    pub stopping_mode: StoppingMode,

    /// Row-selection settings.
    // Rationale: the type stays algorithm-neutral (`RowSelectionConfig`) per the
    // infrastructure genericity rule, while the serialized key uses the
    // domain-standard term every practitioner types. The key/type divergence is
    // deliberate, not an unfinished rename.
    #[serde(default)]
    pub cut_selection: RowSelectionConfig,

    /// LP solver retry settings and optional per-phase solver profiles.
    #[serde(default)]
    pub solver: TrainingSolverConfig,

    /// Parallel-execution settings.
    #[serde(default)]
    pub parallelism: ParallelismConfig,

    /// Scenario source configuration for the training forward pass.
    /// When absent, all classes default to `in_sample`.
    #[serde(default)]
    pub scenario_source: Option<RawScenarioSourceConfig>,

    /// Phase-level scenario selection. The forward-pass count lives in the
    /// `sampled` arm; absent is a missing-count load error.
    #[serde(default)]
    pub selection: Option<TrainingSelection>,
}

/// Training-phase scenario selection and its method-specific parameters
/// (`config.json → training.selection`).
///
/// Internally tagged on `method`; the tag is the semantic selection word, never
/// a mechanism name. `sampled` runs `forward_passes` trajectories per iteration;
/// `enumerated` walks the scenario openings exhaustively. Each variant carries
/// only its own parameters, so pairing a count with `enumerated` is a parse
/// error under `deny_unknown_fields` rather than a runtime-gated combination.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum TrainingSelection {
    /// Sampled forward passes: `forward_passes` trajectories per iteration.
    Sampled {
        /// Number of forward-pass trajectories per iteration.
        forward_passes: u32,
    },
    /// Exhaustive enumeration of the scenario openings.
    // A braced variant, not a unit one: serde enforces `deny_unknown_fields`
    // only for braced variants of an internally tagged enum, and this variant
    // must reject a stray `forward_passes`.
    Enumerated {},
}

/// Effective training forward-pass resolution
/// ([`Config::resolve_forward_passes`](super::Config::resolve_forward_passes)):
/// either a concrete sampled count or a signal that the count is derived from
/// the policy graph downstream, since config load holds no graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ForwardPassesResolution {
    /// `forward_passes` sampled trajectories per iteration.
    Sampled(u32),
    /// Exhaustive enumeration; the count is derived from the policy graph.
    Enumerated,
}

impl TrainingConfig {
    pub(super) fn default_enabled() -> bool {
        true
    }
}

/// How multiple stopping rules combine into a single stop decision
/// (`config.json → training.stopping_mode`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Default)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum StoppingMode {
    /// Stop when any configured rule triggers (OR).
    #[default]
    Any,
    /// Stop when all configured rules trigger at the same iteration (AND).
    All,
}

impl<'de> Deserialize<'de> for StoppingMode {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "any" => Ok(Self::Any),
            "all" => Ok(Self::All),
            other => Err(serde::de::Error::unknown_variant(other, &["any", "all"])),
        }
    }
}

impl fmt::Display for StoppingMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Any => f.write_str("any"),
            Self::All => f.write_str("all"),
        }
    }
}

/// Row-selection settings (`config.json → training.cut_selection`).
///
/// Row selection bounds the per-solve LP size by limiting how many constraint
/// rows from the row pool are carried into each solve. `selection` chooses the
/// method and carries only that method's parameters; omitting it (the default)
/// disables row selection.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RowSelectionConfig {
    /// Minimum dual-multiplier magnitude for a constraint row to count as
    /// binding at a solution point. Rows whose dual value falls below this are
    /// treated as inactive in activity tracking. Default `0.0` when absent.
    #[serde(default)]
    pub row_activity_tolerance: Option<f64>,

    /// Hard cap on active rows per stage LP, enforced after the selection
    /// method runs. Rows are evicted least-recently-active first, tie-broken by
    /// least-frequently-active; rows added in the current iteration are never
    /// evicted. `None` (default) = no cap.
    #[serde(default)]
    pub max_active_per_stage: Option<u32>,

    /// Active selection method and its parameters. Absent/`null` (default)
    /// disables row selection.
    #[serde(default)]
    pub selection: Option<SelectionMethod>,
}

/// Row-selection method and its method-specific parameters.
///
/// Internally tagged on `method`; each variant carries only the fields it uses,
/// so supplying a parameter that does not belong to the chosen method is a
/// load-time error under `deny_unknown_fields`, and a misspelled `method` is an
/// `unknown variant` error at parse time.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum SelectionMethod {
    /// Level-1: retain any row near-optimal at some visited state.
    Level1 {
        /// Tie tolerance: a row is active at a state when within this of the
        /// best row value there. Default `1e-10`.
        #[serde(default = "default_tie_tolerance")]
        tie_tolerance: f64,
        /// Iterations between periodic pruning checks. Must be `> 0`. Default `5`.
        #[serde(default = "default_check_frequency")]
        check_frequency: u32,
    },
    /// Limited-memory Level-1: retain only the oldest eligible near-optimal row
    /// per visited state.
    Lml1 {
        /// Tie tolerance: a row is active at a state when within this of the
        /// best row value there. Default `1e-10`.
        #[serde(default = "default_tie_tolerance")]
        tie_tolerance: f64,
        /// Iterations between periodic pruning checks. Must be `> 0`. Default `5`.
        #[serde(default = "default_check_frequency")]
        check_frequency: u32,
    },
    /// Domination: remove rows dominated at all visited states.
    Domination {
        /// Activity tolerance: a row survives if within this of the maximum at
        /// any visited state. Required (no default).
        domination_tolerance: f64,
        /// Iterations between periodic pruning checks. Must be `> 0`. Default `5`.
        #[serde(default = "default_check_frequency")]
        check_frequency: u32,
    },
    /// Dynamic: a per-solve lazy loop that loads only a small resident subset of
    /// rows per solve while retaining the full pool.
    Dynamic {
        /// First 1-based iteration at which the lazy loop becomes active.
        /// Must be `>= 1`. Default `2`.
        #[serde(default = "default_start_iteration")]
        start_iteration: u32,
        /// Number of most-recent iterations whose rows seed the initial resident
        /// set. `0` is valid (seeds only the current iteration). Default `5`.
        #[serde(default = "default_seed_window")]
        seed_window: u32,
        /// Only rows generated within the last `candidate_recency` iterations are
        /// scored. `None` (default) = unbounded: every pool row is a candidate,
        /// which preserves exactness. `Some(n)` (must be `>= 1`) makes the loop
        /// deliberately inexact — rows older than the window are never added.
        #[serde(default)]
        candidate_recency: Option<u32>,
        /// Maximum rows added per lazy-solve round. Must be `>= 1`. Default `10`.
        #[serde(default = "default_max_added_per_round")]
        max_added_per_round: u32,
        /// Violation tolerance for accepting a candidate row. Must be `> 0`.
        /// Default `1e-10`.
        #[serde(default = "default_violation_tolerance")]
        violation_tolerance: f64,
    },
}

fn default_tie_tolerance() -> f64 {
    1e-10
}

fn default_check_frequency() -> u32 {
    5
}

fn default_start_iteration() -> u32 {
    2
}

fn default_seed_window() -> u32 {
    5
}

fn default_max_added_per_round() -> u32 {
    10
}

fn default_violation_tolerance() -> f64 {
    1e-10
}

/// LP solver settings (`config.json → training.solver`): retry policy plus
/// optional per-phase solver profiles.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TrainingSolverConfig {
    /// Maximum solver retry attempts before propagating a hard error.
    pub retry_max_attempts: u32,

    /// Total time budget in seconds across all retry attempts for one solve.
    pub retry_time_budget_seconds: f64,

    /// Backward-pass solver profile. Absent leaves the phase's built-in
    /// tuned profile.
    #[serde(default)]
    pub backward: Option<PhaseSolverProfileConfig>,

    /// Forward-pass solver profile. Absent leaves the phase's built-in
    /// tuned profile.
    #[serde(default)]
    pub forward: Option<PhaseSolverProfileConfig>,
}

impl Default for TrainingSolverConfig {
    fn default() -> Self {
        Self {
            retry_max_attempts: 5,
            retry_time_budget_seconds: 30.0,
            backward: None,
            forward: None,
        }
    }
}

/// Per-phase LP solver profile (`config.json → training.solver.backward` /
/// `.forward`, and `simulation.solver`).
///
/// Backend-agnostic. Every field is optional: an absent field leaves the
/// corresponding option at the phase's built-in tuned-profile value.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PhaseSolverProfileConfig {
    /// Dual simplex edge-weight strategy override.
    #[serde(default)]
    pub dual_edge_weight: Option<DualEdgeWeight>,

    /// Constraint-matrix scaling strategy override.
    #[serde(default)]
    pub scale: Option<ScaleStrategy>,

    /// Simplex pricing strategy override.
    #[serde(default)]
    pub price: Option<PriceStrategy>,

    /// Primal feasibility tolerance override.
    #[serde(default)]
    pub primal_feasibility_tolerance: Option<f64>,

    /// Dual feasibility tolerance override.
    #[serde(default)]
    pub dual_feasibility_tolerance: Option<f64>,

    /// Presolve mode override. Warm-started solves skip presolve regardless
    /// of this setting, so it affects only genuinely cold solves.
    #[serde(default)]
    pub presolve: Option<PresolveMode>,

    /// Simplex update-count limit override before a refactorization.
    #[serde(default)]
    pub simplex_update_limit: Option<u32>,

    /// Dual simplex cost-perturbation multiplier override.
    #[serde(default)]
    pub cost_perturbation: Option<f64>,

    /// Refactorization solution-error tolerance override.
    #[serde(default)]
    pub refactor_error_tolerance: Option<f64>,

    /// Matrix factorization pivot-threshold override.
    #[serde(default)]
    pub factor_pivot_threshold: Option<f64>,

    /// Warm-start override. This is a diagnostic setting: disabling it forces
    /// every solve cold.
    #[serde(default)]
    pub use_warm_start: Option<bool>,

    /// Dual steepest-edge weight log-error threshold override above which the
    /// solver falls back to Devex pricing.
    #[serde(default)]
    pub steepest_edge_devex_fallback_threshold: Option<f64>,
}

/// Presolve mode for a solver profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum PresolveMode {
    /// Presolve enabled.
    On,
    /// Presolve disabled.
    Off,
    /// Solver decides whether to presolve.
    Choose,
}

/// Parallel-execution settings (`config.json → training.parallelism`).
///
/// Groups the result-preserving knobs that shape how training work is
/// scheduled across workers, apart from the algorithm-semantics fields at the
/// `training` root. Thread count itself stays a CLI concern (`--threads`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ParallelismConfig {
    /// Backward-pass scheduler selection.
    pub backward_scheduler: BackwardScheduler,
}

/// Backward-pass scheduler and its scheduler-specific parameters
/// (`config.json → training.parallelism.backward_scheduler`).
///
/// Internally tagged on `method`; each variant carries only the fields it
/// uses, so supplying a parameter that does not belong to the chosen method is
/// a load-time error under `deny_unknown_fields`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum BackwardScheduler {
    /// By-scenario backward scheduling (the default): each parallel work
    /// unit claims one whole trial point (a row of the backward work
    /// rectangle).
    // A braced variant, not a unit one: serde enforces `deny_unknown_fields`
    // only for braced variants of an internally tagged enum, and this variant
    // must reject `block_size`.
    ByScenario {},
    /// By-node backward scheduling: each parallel work unit claims one
    /// (trial point, opening-block) tile of the backward work rectangle.
    ByNode {
        /// Openings per block. Absent resolves per stage to `⌈|Ω_s|/2⌉` (half
        /// the openings, rounded up); a set value is clamped to
        /// `min(|Ω_s|, block_size)`.
        #[serde(default)]
        block_size: Option<NonZeroUsize>,
    },
}

impl Default for BackwardScheduler {
    fn default() -> Self {
        Self::ByScenario {}
    }
}

/// Dual simplex edge-weight (pricing) strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum DualEdgeWeight {
    /// Devex approximate edge weights.
    Devex,
    /// Exact steepest-edge weights.
    SteepestEdge,
    /// Dantzig most-negative-reduced-cost rule.
    Dantzig,
}

/// LP constraint-matrix scaling strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum ScaleStrategy {
    /// No scaling.
    Off,
    /// Solver-managed scaling.
    SolverScaling,
}

/// Simplex pricing (column-selection) strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum PriceStrategy {
    /// Row-wise pricing.
    Row,
    /// Row-wise pricing with hyper-sparse updates.
    RowHyperSparse,
}

/// Deserialized configuration for one entry in `training.stopping_rules[]`.
///
/// Uses a `"type"` discriminator field (internally tagged) with `snake_case`
/// variant names matching the JSON schema. `deny_unknown_fields` makes a
/// parameter belonging to a different rule type a load-time error rather
/// than a silently ignored key.
///
/// The `GracefulShutdown` rule has no JSON representation — it is injected at
/// runtime by `StoppingRuleSet` construction and is never deserialized.
///
/// # Examples
///
/// ```
/// use cobre_io::config::StoppingRuleConfig;
///
/// let json = r#"{"type": "iteration_limit", "limit": 100}"#;
/// let rule: StoppingRuleConfig = serde_json::from_str(json).unwrap();
/// assert!(matches!(rule, StoppingRuleConfig::IterationLimit { limit: 100 }));
/// ```
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum StoppingRuleConfig {
    /// Stop after a fixed number of iterations. **Mandatory** — every rule set must
    /// contain at least one `iteration_limit` rule.
    IterationLimit {
        /// Maximum iteration count $k_{max}$.
        limit: u32,
    },
    /// Stop after a wall-clock time limit.
    TimeLimit {
        /// Time limit in seconds.
        seconds: f64,
    },
    /// Stop when the lower bound stalls (relative improvement falls below tolerance).
    BoundStalling {
        /// Window size $\tau$ (number of past iterations to compare).
        iterations: u32,
        /// Relative improvement threshold.
        tolerance: f64,
    },
    /// Stop when the exact upper bound is within tolerance of the lower
    /// bound. At least one of `tolerance` / `relative_tolerance` must be
    /// present (checked at `from_config`). Admissible only under enumerated
    /// forward selection, where the upper bound is the exact bound a gap rule
    /// requires rather than a statistical estimate.
    Gap {
        /// Absolute gap tolerance, canonical R$.
        #[serde(default)]
        tolerance: Option<f64>,
        /// Relative gap tolerance in percent (e.g. `0.01` means 0.01%), compared
        /// against `100·gap / max(1, |lower_bound|)` — the same convention the
        /// reported `gap_percent` uses.
        #[serde(default)]
        relative_tolerance: Option<f64>,
    },
}

/// Upper-bound evaluation settings (`config.json → upper_bound_evaluation`).
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UpperBoundEvaluationConfig {
    /// Enable vertex-based inner approximation for upper bound computation.
    #[serde(default)]
    pub enabled: Option<bool>,

    /// First iteration to compute the upper bound.
    #[serde(default)]
    pub initial_iteration: Option<u32>,

    /// Iterations between upper-bound evaluations.
    #[serde(default)]
    pub interval_iterations: Option<u32>,

    /// Lipschitz constant settings.
    #[serde(default)]
    pub lipschitz: LipschitzConfig,
}

/// Lipschitz constant settings for inner approximation.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct LipschitzConfig {
    /// Computation mode: `"auto"`.
    #[serde(default)]
    pub mode: Option<String>,

    /// Fallback value when automatic computation fails.
    #[serde(default)]
    pub fallback_value: Option<f64>,

    /// Multiplicative safety margin applied to computed Lipschitz constants.
    #[serde(default)]
    pub scale_factor: Option<f64>,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::{
        BackwardScheduler, DualEdgeWeight, NonZeroUsize, PresolveMode, PriceStrategy,
        ScaleStrategy, SelectionMethod, StoppingRuleConfig, TrainingConfig, TrainingSelection,
    };

    /// A `dynamic` selection block round-trips through the tagged enum, with
    /// every method-specific field landing in the `Dynamic` variant.
    #[test]
    fn dynamic_selection_block_round_trips() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "cut_selection": {
                "row_activity_tolerance": 1e-6,
                "max_active_per_stage": 4000,
                "selection": {
                    "method": "dynamic",
                    "start_iteration": 5,
                    "seed_window": 0,
                    "candidate_recency": 20,
                    "max_added_per_round": 3,
                    "violation_tolerance": 1e-9
                }
            }
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        let cs = &cfg.cut_selection;
        assert_eq!(cs.row_activity_tolerance, Some(1e-6));
        assert_eq!(cs.max_active_per_stage, Some(4000));
        match cs.selection.as_ref().expect("selection present") {
            SelectionMethod::Dynamic {
                start_iteration,
                seed_window,
                candidate_recency,
                max_added_per_round,
                violation_tolerance,
            } => {
                assert_eq!(*start_iteration, 5);
                assert_eq!(*seed_window, 0);
                assert_eq!(*candidate_recency, Some(20));
                assert_eq!(*max_added_per_round, 3);
                assert!((*violation_tolerance - 1e-9).abs() < f64::EPSILON);
            }
            other => panic!("expected Dynamic, got {other:?}"),
        }
    }

    /// A `level1` selection block round-trips and fills the variant defaults
    /// when its fields are omitted.
    #[test]
    fn level1_selection_block_round_trips_with_defaults() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "cut_selection": { "selection": { "method": "level1" } }
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        match cfg
            .cut_selection
            .selection
            .as_ref()
            .expect("selection present")
        {
            SelectionMethod::Level1 {
                tie_tolerance,
                check_frequency,
            } => {
                assert!((*tie_tolerance - 1e-10).abs() < 1e-20);
                assert_eq!(*check_frequency, 5);
            }
            other => panic!("expected Level1, got {other:?}"),
        }
    }

    #[test]
    fn omitting_selection_disables_row_selection() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "cut_selection": {}
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        assert!(cfg.cut_selection.selection.is_none());
    }

    /// A parameter that belongs to a different method is a deserialize error
    /// under `deny_unknown_fields` (here `max_added_per_round` under `level1`).
    #[test]
    fn wrong_method_field_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "cut_selection": {
                "selection": { "method": "level1", "max_added_per_round": 3 }
            }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(
            result.is_err(),
            "a Dynamic-only field under level1 must be rejected"
        );
    }

    /// A misspelled `method` is an unknown-variant deserialize error.
    #[test]
    fn bad_method_string_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "cut_selection": { "selection": { "method": "dynmic" } }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(result.is_err(), "an unknown method tag must be rejected");
    }

    #[test]
    fn domination_without_tolerance_is_missing_field_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "cut_selection": { "selection": { "method": "domination" } }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(
            result.is_err(),
            "domination requires domination_tolerance; absence must be rejected"
        );
    }

    /// A full `training.solver.backward` block round-trips: every per-field
    /// override lands in `PhaseSolverProfileConfig`, and the sibling `forward`
    /// phase stays absent.
    #[test]
    fn backward_solver_profile_block_round_trips() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "solver": {
                "backward": {
                    "dual_edge_weight": "steepest_edge",
                    "scale": "solver_scaling",
                    "price": "row",
                    "primal_feasibility_tolerance": 1e-7
                }
            }
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        let backward = cfg.solver.backward.as_ref().expect("backward present");
        assert_eq!(
            backward.dual_edge_weight,
            Some(DualEdgeWeight::SteepestEdge)
        );
        assert_eq!(backward.scale, Some(ScaleStrategy::SolverScaling));
        assert_eq!(backward.price, Some(PriceStrategy::Row));
        assert_eq!(backward.primal_feasibility_tolerance, Some(1e-7));
        assert!(cfg.solver.forward.is_none());
    }

    /// A `training.solver.backward` block setting `presolve`, `use_warm_start`,
    /// and `factor_pivot_threshold` round-trips into the new fields.
    #[test]
    fn backward_solver_profile_new_fields_round_trip() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "solver": {
                "backward": {
                    "presolve": "off",
                    "use_warm_start": false,
                    "factor_pivot_threshold": 0.2
                }
            }
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        let backward = cfg.solver.backward.as_ref().expect("backward present");
        assert_eq!(backward.presolve, Some(PresolveMode::Off));
        assert_eq!(backward.use_warm_start, Some(false));
        assert_eq!(backward.factor_pivot_threshold, Some(0.2));
        assert!(backward.dual_feasibility_tolerance.is_none());
        assert!(backward.simplex_update_limit.is_none());
        assert!(backward.cost_perturbation.is_none());
        assert!(backward.refactor_error_tolerance.is_none());
        assert!(backward.steepest_edge_devex_fallback_threshold.is_none());
    }

    /// A `training.solver.forward` block round-trips independently of `backward`.
    #[test]
    fn forward_solver_profile_block_round_trips() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "solver": {
                "forward": {
                    "price": "row_hyper_sparse",
                    "dual_edge_weight": "dantzig"
                }
            }
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        let forward = cfg.solver.forward.as_ref().expect("forward present");
        assert_eq!(forward.price, Some(PriceStrategy::RowHyperSparse));
        assert_eq!(forward.dual_edge_weight, Some(DualEdgeWeight::Dantzig));
        assert!(cfg.solver.backward.is_none());
    }

    /// An unknown field under `backward` (here the misspelling `dual_edge_weght`)
    /// is a deserialize error under `deny_unknown_fields`.
    #[test]
    fn backward_solver_profile_unknown_field_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "solver": { "backward": { "dual_edge_weght": "devex" } }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(
            result.is_err(),
            "an unknown field under backward must be rejected"
        );
    }

    /// The misspelled `presolv` field under `backward` is a deserialize error
    /// under `deny_unknown_fields`.
    #[test]
    fn backward_solver_profile_presolv_typo_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "solver": { "backward": { "presolv": "off" } }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(
            result.is_err(),
            "the presolv typo under backward must be rejected"
        );
    }

    /// A misspelled enum value is an unknown-variant deserialize error; the
    /// informal `curtis_reid` spelling is not a valid `scale` value.
    #[test]
    fn backward_solver_profile_bad_enum_value_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "solver": { "backward": { "scale": "curtis_reid" } }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(result.is_err(), "an unknown scale value must be rejected");
    }

    #[test]
    fn backward_scheduler_defaults_to_by_scenario_when_absent() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }]
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        assert_eq!(
            cfg.parallelism.backward_scheduler,
            BackwardScheduler::ByScenario {}
        );
    }

    /// `{"method": "by_node", "block_size": 4}` round-trips into the
    /// `ByNode` variant carrying `Some(4)`.
    #[test]
    fn by_node_scheduler_and_block_size_round_trip() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "parallelism": {
                "backward_scheduler": { "method": "by_node", "block_size": 4 }
            }
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        assert_eq!(
            cfg.parallelism.backward_scheduler,
            BackwardScheduler::ByNode {
                block_size: NonZeroUsize::new(4)
            }
        );
    }

    /// A `by_node` scheduler without `block_size` round-trips into
    /// `block_size: None` (the per-stage `⌈|Ω_s|/2⌉` resolution).
    #[test]
    fn by_node_scheduler_without_block_size_round_trips() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "parallelism": {
                "backward_scheduler": { "method": "by_node" }
            }
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        assert_eq!(
            cfg.parallelism.backward_scheduler,
            BackwardScheduler::ByNode { block_size: None }
        );
    }

    /// `block_size` under `by_scenario` is a deserialize error under
    /// `deny_unknown_fields` — the invalid combination is unrepresentable, not
    /// warned-and-ignored.
    #[test]
    fn block_size_under_by_scenario_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "parallelism": {
                "backward_scheduler": { "method": "by_scenario", "block_size": 4 }
            }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(
            result.is_err(),
            "block_size under by_scenario must be rejected"
        );
    }

    /// The retired `trial_point` / `opening_block` spellings are unknown-variant
    /// deserialize errors — no `serde(alias)` accepts them (clean break, no
    /// deprecated-with-fallback).
    #[test]
    fn retired_scheduler_spellings_are_deserialize_error() {
        for method in ["trial_point", "opening_block"] {
            let json = format!(
                r#"{{
                    "selection": {{ "method": "sampled", "forward_passes": 4 }},
                    "stopping_rules": [{{ "type": "iteration_limit", "limit": 100 }}],
                    "parallelism": {{
                        "backward_scheduler": {{ "method": "{method}" }}
                    }}
                }}"#
            );
            let result = serde_json::from_str::<TrainingConfig>(&json);
            assert!(
                result.is_err(),
                "retired scheduler spelling '{method}' must be an unknown-variant error"
            );
        }
    }

    /// A misspelled scheduler `method` is an unknown-variant deserialize error.
    #[test]
    fn unknown_scheduler_method_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "parallelism": {
                "backward_scheduler": { "method": "by_nod" }
            }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(result.is_err(), "an unknown method tag must be rejected");
    }

    /// `block_size: 0` is an out-of-range deserialize error (`NonZeroUsize`).
    #[test]
    fn block_size_zero_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "parallelism": {
                "backward_scheduler": { "method": "by_node", "block_size": 0 }
            }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(
            result.is_err(),
            "block_size = 0 must be rejected by NonZeroUsize"
        );
    }

    /// The retired root-level scheduler keys are hard-rejected, never silently
    /// ignored: the scheduler lives under `training.parallelism`, and the
    /// backward solve order is intrinsic (no config field selects it).
    #[test]
    fn removed_root_scheduler_keys_are_rejected() {
        for stale in [
            r#""backward_scheduler": "opening_block""#,
            r#""opening_block_size": 4"#,
            r#""backward_opening_order": "sigma_key""#,
        ] {
            let json = format!(
                r#"{{
                    "selection": {{ "method": "sampled", "forward_passes": 4 }},
                    "stopping_rules": [{{ "type": "iteration_limit", "limit": 100 }}],
                    {stale}
                }}"#
            );
            let result = serde_json::from_str::<TrainingConfig>(&json);
            assert!(
                result.is_err(),
                "removed root key must be rejected, got Ok for: {stale}"
            );
        }
    }

    /// A `sampled` phase selection round-trips into the `Sampled` variant.
    #[test]
    fn sampled_selection_round_trips() {
        let json = r#"{
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "selection": { "method": "sampled", "forward_passes": 8 }
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        assert_eq!(
            cfg.selection,
            Some(TrainingSelection::Sampled { forward_passes: 8 })
        );
    }

    /// The removed root `forward_passes` alias is an unknown-field deserialize
    /// error under `deny_unknown_fields`; the count lives solely in the
    /// `selection.sampled` arm.
    #[test]
    fn root_forward_passes_alias_is_deserialize_error() {
        let alias = r#"{
            "forward_passes": 4,
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }]
        }"#;
        assert!(
            serde_json::from_str::<TrainingConfig>(alias).is_err(),
            "root forward_passes must be rejected as an unknown field"
        );

        let arm = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }]
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(arm).unwrap();
        assert_eq!(
            cfg.selection,
            Some(TrainingSelection::Sampled { forward_passes: 4 })
        );
    }

    /// A count under `enumerated` is unrepresentable — `deny_unknown_fields` on
    /// the braced variant rejects it at parse time, so the invalid pairing is
    /// never gated at runtime.
    #[test]
    fn enumerated_selection_with_count_is_deserialize_error() {
        let json = r#"{
            "stopping_rules": [{ "type": "iteration_limit", "limit": 100 }],
            "selection": { "method": "enumerated", "forward_passes": 8 }
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(
            result.is_err(),
            "a count under enumerated must be rejected as unrepresentable"
        );
    }

    /// A parameter belonging to a different stopping-rule type is a
    /// deserialize error under `deny_unknown_fields` (here `seconds` under
    /// `iteration_limit`), never a silently ignored key.
    #[test]
    fn wrong_stopping_rule_field_is_deserialize_error() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [
                { "type": "iteration_limit", "limit": 100, "seconds": 60.0 }
            ]
        }"#;
        let result = serde_json::from_str::<TrainingConfig>(json);
        assert!(
            result.is_err(),
            "a time_limit-only field under iteration_limit must be rejected"
        );
    }

    /// A `gap` rule with only `tolerance` set deserializes into
    /// `StoppingRuleConfig::Gap`.
    #[test]
    fn gap_stopping_rule_tolerance_only_round_trips() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "gap", "tolerance": 1000.0 }]
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        let rules = cfg.stopping_rules.expect("stopping_rules present");
        assert!(matches!(
            rules[0],
            StoppingRuleConfig::Gap {
                tolerance: Some(t),
                relative_tolerance: None
            } if (t - 1000.0).abs() < f64::EPSILON
        ));
    }

    /// A `gap` rule with only `relative_tolerance` set deserializes into
    /// `StoppingRuleConfig::Gap`.
    #[test]
    fn gap_stopping_rule_relative_tolerance_only_round_trips() {
        let json = r#"{
            "selection": { "method": "sampled", "forward_passes": 4 },
            "stopping_rules": [{ "type": "gap", "relative_tolerance": 0.01 }]
        }"#;
        let cfg: TrainingConfig = serde_json::from_str(json).unwrap();
        let rules = cfg.stopping_rules.expect("stopping_rules present");
        assert!(matches!(
            rules[0],
            StoppingRuleConfig::Gap {
                tolerance: None,
                relative_tolerance: Some(rt)
            } if (rt - 0.01).abs() < f64::EPSILON
        ));
    }
}