cobre-core 0.14.1

Power system data model — buses, branches, generators, loads, and network topology
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
//! Initial conditions for the optimization study.
//!
//! [`InitialConditions`] holds the reservoir storage levels and past inflow
//! values at the start of the study. Two storage arrays are kept separate
//! because filling hydros can have an initial volume below dead storage
//! (`min_storage_hm3`), which is not a valid operating level for regular hydros.
//!
//! See `internal-structures.md §16` and `input-constraints.md §1` for the
//! full specification including validation rules.
//!
//! # Examples
//!
//! ```
//! use chrono::NaiveDate;
//! use cobre_core::{AnticipatedCommitmentHistory, EntityId, HydroStorage, InitialConditions};
//!
//! let ic = InitialConditions {
//!     storage: vec![
//!         HydroStorage { hydro_id: EntityId(0), value_hm3: 15_000.0 },
//!         HydroStorage { hydro_id: EntityId(1), value_hm3:  8_500.0 },
//!     ],
//!     filling_storage: vec![
//!         HydroStorage { hydro_id: EntityId(10), value_hm3: 200.0 },
//!     ],
//!     past_anticipated_commitments: vec![
//!         AnticipatedCommitmentHistory {
//!             thermal_id: EntityId(20),
//!             start_date: NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
//!             end_date: NaiveDate::from_ymd_opt(2026, 2, 1).unwrap(),
//!             value_mw: 100.0,
//!         },
//!     ],
//!     recent_observations: vec![],
//!     past_defluences: vec![],
//!     future_anticipated_deliveries: vec![],
//! };
//!
//! assert_eq!(ic.storage.len(), 2);
//! assert_eq!(ic.filling_storage.len(), 1);
//! assert_eq!(ic.past_anticipated_commitments.len(), 1);
//! assert_eq!(ic.recent_observations.len(), 0);
//! assert_eq!(ic.past_defluences.len(), 0);
//! assert_eq!(ic.future_anticipated_deliveries.len(), 0);
//! ```

use chrono::NaiveDate;

use crate::EntityId;

/// Initial storage volume for a single hydro plant.
///
/// For operating hydros, `value_hm3` must be within
/// `[min_storage_hm3, max_storage_hm3]` (validated by `cobre-io`).
/// For filling hydros (present in [`InitialConditions::filling_storage`]),
/// `value_hm3` must be within `[0.0, min_storage_hm3)` — strictly below the
/// dead volume (validated by `cobre-io`). Equality with `min_storage_hm3`
/// belongs to neither the filling range nor the operating range.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HydroStorage {
    /// Hydro plant identifier. Must reference a hydro entity in the system.
    pub hydro_id: EntityId,
    /// Reservoir volume at the start of the study, in hm³.
    pub value_hm3: f64,
}

/// Past defluence (release) for the arc fed by a single upstream hydro over a
/// specific date range.
///
/// Used to seed the in-transit water travel-time buckets from an arc's
/// pre-study upstream releases. Each entry represents the average release rate
/// (in m³/s) over `[start_date, end_date)` — `end_date` exclusive, must be
/// after `start_date` — for one upstream hydro. Multiple entries per hydro are
/// allowed; date ranges for the same hydro must not overlap, though adjacent
/// ranges (`start_date == previous end_date`) are accepted.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HydroPastDefluence {
    /// Upstream hydro plant identifier whose release feeds the arc. Must
    /// reference a hydro entity in the system.
    pub hydro_id: EntityId,
    /// Start of the release window (inclusive).
    pub start_date: NaiveDate,
    /// End of the release window (exclusive). Must be after `start_date`.
    pub end_date: NaiveDate,
    /// Average release rate over the window, in m³/s. Must be finite and
    /// non-negative.
    pub value_m3s: f64,
}

/// One externally-decided anticipated-commitment window for a single thermal
/// plant.
///
/// A commitment is a `[start_date, end_date)` window (`end_date` exclusive,
/// after `start_date`) carrying `value_mw`, the MW rate the LP delivers held
/// constant over the window — mirroring [`HydroPastDefluence`]'s windowed
/// shape. A plant with `N` committed pre-study delivery stages is expressed as
/// contiguous windows tiling those stages; the LP integrates the rate against
/// each covered stage's duration through the fishing equality
/// `sum_b gen[i][b] * block_hours_b == value_mw * stage_total_hours`. The
/// decisions are sunk cost: their per-MWh cost does not enter the study
/// objective.
///
/// # Sorting invariant
///
/// Callers MUST sort the containing `Vec<AnticipatedCommitmentHistory>` by
/// `(thermal_id, start_date)` ascending before
/// `SystemBuilder::initial_conditions`, to satisfy declaration-order invariance.
///
/// # Division of responsibility
///
/// `cobre-core` has no view of the entity registry or the stage calendar, so
/// the `cobre-io` semantic validator (not `cobre-core`) enforces:
/// - The plant's windows tile its calendar-derived leading delivery stages at
///   coverage `1.0` — no gap, no overlap, none beyond the horizon (a hard
///   error, no fallback; the "Pre-study anticipated commitments:
///   calendar-derived coverage" contract).
/// - Every window's `value_mw` in `[min_generation_mw, max_generation_mw]` (an
///   out-of-bounds rate makes the covered stage's fishing equality infeasible).
/// - `thermal_id` references a thermal whose `anticipated_config` is `Some`.
/// - Every anticipated thermal has at least one window and no two windows share
///   a `(thermal_id, start_date)`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AnticipatedCommitmentHistory {
    /// Thermal plant identifier. Must reference an anticipated thermal entity.
    pub thermal_id: EntityId,
    /// Start of the commitment window (inclusive).
    pub start_date: NaiveDate,
    /// End of the commitment window (exclusive). Must be after `start_date`.
    pub end_date: NaiveDate,
    /// Externally-decided MW rate delivered over the window, held constant.
    pub value_mw: f64,
}

/// One in-study decided anticipated-delivery window for a single thermal
/// plant, delivered after the study horizon — the right-boundary counterpart
/// to [`AnticipatedCommitmentHistory`]'s left-boundary declaration.
///
/// A delivery is a `[delivery_start, delivery_end)` window (`delivery_end`
/// exclusive, after `delivery_start`) carrying a `[min_mw, max_mw]` bound: the
/// delivered MW rate is a decision the LP solves within the interval, not an
/// externally-fixed value. `min_mw == max_mw` pins a fixed commitment.
///
/// # Sorting invariant
///
/// Callers MUST sort the containing `Vec<FutureAnticipatedDelivery>` by
/// `(thermal_id, delivery_start)` ascending before
/// `SystemBuilder::initial_conditions`, to satisfy declaration-order invariance.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FutureAnticipatedDelivery {
    /// Thermal plant identifier. Must reference an anticipated thermal entity.
    pub thermal_id: EntityId,
    /// Start of the delivery window (inclusive).
    pub delivery_start: NaiveDate,
    /// End of the delivery window (exclusive). Must be after `delivery_start`.
    pub delivery_end: NaiveDate,
    /// Lower bound of the delivered MW rate over the window.
    pub min_mw: f64,
    /// Upper bound of the delivered MW rate over the window. `min_mw ==
    /// max_mw` pins a fixed commitment.
    pub max_mw: f64,
}

/// Observed inflow for a single hydro plant over a specific date range.
///
/// Used to seed the lag accumulator when a study begins mid-season. Each entry
/// represents the average inflow (in m³/s) observed between `start_date`
/// (inclusive) and `end_date` (exclusive) for one hydro. Multiple entries per
/// hydro are allowed for rolling revisions with several observed weeks.
///
/// Date ranges for the same hydro must not overlap; adjacent ranges
/// (`start_date == previous end_date`) are accepted.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RecentObservation {
    /// Hydro plant identifier. Must reference a hydro entity in the system.
    pub hydro_id: EntityId,
    /// Start of the observation period (inclusive).
    pub start_date: NaiveDate,
    /// End of the observation period (exclusive). Must be after `start_date`.
    pub end_date: NaiveDate,
    /// Average inflow observed during the period, in m³/s. Must be finite;
    /// negative values are accepted (the quantity is incremental inflow).
    pub value_m3s: f64,
}

/// Initial system state at the start of the optimization study.
///
/// All arrays are sorted by their entity ID after loading to satisfy
/// declaration-order invariance.
///
/// A hydro must appear in exactly one of the two storage arrays, never both:
/// hydros with a `filling` configuration belong in [`filling_storage`], all
/// others (including late-entry hydros) in
/// [`storage`](InitialConditions::storage).
///
/// The `#[serde(default)]` fields below (`past_anticipated_commitments` onward)
/// are part of the postcard wire format MPI broadcast round-trips: a new field
/// must be appended at the end, never inserted earlier in the struct.
///
/// [`filling_storage`]: InitialConditions::filling_storage
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InitialConditions {
    /// Initial storage for operating hydros, in hm³ per hydro.
    pub storage: Vec<HydroStorage>,
    /// Initial storage for filling hydros (below dead volume), in hm³ per hydro.
    ///
    /// Tied to the hydro's
    /// [`FillingConfig::start_stage_id`](crate::FillingConfig::start_stage_id):
    /// `start_stage_id == 0` means a partially-filled stage-0 level in
    /// `[0, min_storage_hm3)`; `> 0` means `0` (empty pit), frozen through the
    /// `PreFilling` phase until Filling begins.
    pub filling_storage: Vec<HydroStorage>,
    /// Past externally-decided anticipated commitments per anticipated thermal
    /// plant; empty without any. See [`AnticipatedCommitmentHistory`] for the
    /// per-entry contract and sunk-cost semantics.
    #[cfg_attr(feature = "serde", serde(default))]
    pub past_anticipated_commitments: Vec<AnticipatedCommitmentHistory>,
    /// Observed inflow data for partial periods before the study start, to seed
    /// the lag accumulator when a study begins mid-season. See
    /// [`RecentObservation`] for the per-entry contract.
    #[cfg_attr(feature = "serde", serde(default))]
    pub recent_observations: Vec<RecentObservation>,
    /// Past defluence (release) windows per arc, keyed by the upstream hydro
    /// whose release feeds the arc; empty when no arcs need seeding. See
    /// [`HydroPastDefluence`] for the per-entry contract.
    ///
    /// Always emitted on output even when empty — omitting it would break the
    /// postcard round-trip used by MPI broadcast.
    #[cfg_attr(feature = "serde", serde(default))]
    pub past_defluences: Vec<HydroPastDefluence>,
    /// Future in-study decided anticipated deliveries per anticipated thermal
    /// plant, delivered after the study horizon; empty without any. See
    /// [`FutureAnticipatedDelivery`] for the per-entry contract.
    #[cfg_attr(feature = "serde", serde(default))]
    pub future_anticipated_deliveries: Vec<FutureAnticipatedDelivery>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_initial_conditions_construction() {
        let ic = InitialConditions {
            storage: vec![
                HydroStorage {
                    hydro_id: EntityId(0),
                    value_hm3: 15_000.0,
                },
                HydroStorage {
                    hydro_id: EntityId(1),
                    value_hm3: 8_500.0,
                },
            ],
            filling_storage: vec![HydroStorage {
                hydro_id: EntityId(10),
                value_hm3: 200.0,
            }],
            past_anticipated_commitments: vec![],
            recent_observations: vec![],
            past_defluences: vec![],
            future_anticipated_deliveries: vec![],
        };

        assert_eq!(ic.storage.len(), 2);
        assert_eq!(ic.filling_storage.len(), 1);
        assert_eq!(ic.storage[0].hydro_id, EntityId(0));
        assert_eq!(ic.storage[0].value_hm3, 15_000.0);
        assert_eq!(ic.storage[1].hydro_id, EntityId(1));
        assert_eq!(ic.filling_storage[0].hydro_id, EntityId(10));
        assert_eq!(ic.filling_storage[0].value_hm3, 200.0);
        assert!(ic.recent_observations.is_empty());
    }

    #[test]
    fn test_initial_conditions_default_is_empty() {
        let ic = InitialConditions::default();
        assert!(ic.storage.is_empty());
        assert!(ic.filling_storage.is_empty());
        assert!(ic.recent_observations.is_empty());
    }

    #[test]
    fn test_hydro_storage_clone() {
        let hs = HydroStorage {
            hydro_id: EntityId(5),
            value_hm3: 1_234.5,
        };
        let cloned = hs.clone();
        assert_eq!(hs, cloned);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_initial_conditions_serde_roundtrip() {
        let ic = InitialConditions {
            storage: vec![
                HydroStorage {
                    hydro_id: EntityId(0),
                    value_hm3: 15_000.0,
                },
                HydroStorage {
                    hydro_id: EntityId(1),
                    value_hm3: 8_500.0,
                },
            ],
            filling_storage: vec![HydroStorage {
                hydro_id: EntityId(10),
                value_hm3: 200.0,
            }],
            past_anticipated_commitments: vec![],
            recent_observations: vec![],
            past_defluences: vec![],
            future_anticipated_deliveries: vec![],
        };

        let json = serde_json::to_string(&ic).unwrap();
        let deserialized: InitialConditions = serde_json::from_str(&json).unwrap();
        assert_eq!(ic, deserialized);
    }

    #[test]
    fn test_recent_observation_construction_and_clone() {
        let obs = RecentObservation {
            hydro_id: EntityId(2),
            start_date: NaiveDate::from_ymd_opt(2026, 4, 1)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            end_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            value_m3s: 500.0,
        };
        let cloned = obs.clone();
        assert_eq!(obs, cloned);
    }

    #[test]
    fn test_initial_conditions_construction_with_recent_observations() {
        let ic = InitialConditions {
            storage: vec![HydroStorage {
                hydro_id: EntityId(0),
                value_hm3: 1_000.0,
            }],
            filling_storage: vec![],
            past_anticipated_commitments: vec![],
            recent_observations: vec![RecentObservation {
                hydro_id: EntityId(0),
                start_date: NaiveDate::from_ymd_opt(2026, 4, 1)
                    .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                end_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                    .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                value_m3s: 500.0,
            }],
            past_defluences: vec![],
            future_anticipated_deliveries: vec![],
        };
        assert_eq!(ic.recent_observations.len(), 1);
        assert_eq!(ic.recent_observations[0].hydro_id, EntityId(0));
        assert_eq!(ic.recent_observations[0].value_m3s, 500.0);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_initial_conditions_serde_roundtrip_with_recent_observations() {
        let ic = InitialConditions {
            storage: vec![HydroStorage {
                hydro_id: EntityId(0),
                value_hm3: 1_000.0,
            }],
            filling_storage: vec![],
            past_anticipated_commitments: vec![],
            recent_observations: vec![
                RecentObservation {
                    hydro_id: EntityId(0),
                    start_date: NaiveDate::from_ymd_opt(2026, 4, 1)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    end_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    value_m3s: 500.0,
                },
                RecentObservation {
                    hydro_id: EntityId(0),
                    start_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    end_date: NaiveDate::from_ymd_opt(2026, 4, 11)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    value_m3s: 480.0,
                },
            ],
            past_defluences: vec![],
            future_anticipated_deliveries: vec![],
        };
        let json = serde_json::to_string(&ic).unwrap();
        let deserialized: InitialConditions = serde_json::from_str(&json).unwrap();
        assert_eq!(ic, deserialized);
        assert_eq!(deserialized.recent_observations.len(), 2);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_initial_conditions_serde_default_recent_observations_absent() {
        let json = r#"{"storage":[],"filling_storage":[]}"#;
        let ic: InitialConditions = serde_json::from_str(json).unwrap();
        assert!(ic.recent_observations.is_empty());
    }

    // --- AnticipatedCommitmentHistory tests ---

    #[test]
    fn test_past_anticipated_commitments_default_empty() {
        let ic = InitialConditions::default();
        assert!(ic.past_anticipated_commitments.is_empty());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_anticipated_commitment_history_serde_roundtrip() {
        let ach = AnticipatedCommitmentHistory {
            thermal_id: EntityId(7),
            start_date: NaiveDate::from_ymd_opt(2026, 1, 1)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            end_date: NaiveDate::from_ymd_opt(2026, 2, 1)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            value_mw: 100.0,
        };
        let json = serde_json::to_string(&ach).unwrap();
        let deserialized: AnticipatedCommitmentHistory = serde_json::from_str(&json).unwrap();
        assert_eq!(ach, deserialized);
        assert!(
            !json.contains("season_ids"),
            "JSON must not contain 'season_ids', got: {json}"
        );
    }

    #[test]
    fn test_initial_conditions_with_anticipated_commitments() {
        let ic = InitialConditions {
            storage: vec![],
            filling_storage: vec![],
            past_anticipated_commitments: vec![
                AnticipatedCommitmentHistory {
                    thermal_id: EntityId(3),
                    start_date: NaiveDate::from_ymd_opt(2026, 1, 1)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    end_date: NaiveDate::from_ymd_opt(2026, 2, 1)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    value_mw: 50.0,
                },
                AnticipatedCommitmentHistory {
                    thermal_id: EntityId(5),
                    start_date: NaiveDate::from_ymd_opt(2026, 1, 1)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    end_date: NaiveDate::from_ymd_opt(2026, 2, 1)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    value_mw: 200.0,
                },
            ],
            recent_observations: vec![],
            past_defluences: vec![],
            future_anticipated_deliveries: vec![],
        };
        assert_eq!(ic.past_anticipated_commitments.len(), 2);
        assert_eq!(ic.past_anticipated_commitments[0].thermal_id, EntityId(3));
        assert_eq!(ic.past_anticipated_commitments[0].value_mw, 50.0);
        assert_eq!(ic.past_anticipated_commitments[1].thermal_id, EntityId(5));
        assert_eq!(ic.past_anticipated_commitments[1].value_mw, 200.0);
    }

    /// Compile-time enforcement that `AnticipatedCommitmentHistory` carries the
    /// windowed field set (`thermal_id`, `start_date`, `end_date`, `value_mw`)
    /// and no `season_ids` or positional per-stage MW vector field.
    ///
    /// Rust's exhaustive struct-literal syntax will fail to compile if any
    /// undeclared field is present or any declared field is missing.
    #[test]
    fn test_anticipated_commitment_history_has_no_season_ids_field() {
        let ach = AnticipatedCommitmentHistory {
            thermal_id: EntityId(0),
            start_date: NaiveDate::from_ymd_opt(2026, 1, 1)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            end_date: NaiveDate::from_ymd_opt(2026, 2, 1)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            value_mw: 0.0,
        };
        assert_eq!(ach.thermal_id, EntityId(0));
        assert_eq!(ach.value_mw, 0.0);
    }

    // --- HydroPastDefluence / past_defluences tests ---

    #[test]
    fn test_hydro_past_defluence_construction_and_clone() {
        let hpd = HydroPastDefluence {
            hydro_id: EntityId(4),
            start_date: NaiveDate::from_ymd_opt(2026, 4, 1)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            end_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            value_m3s: 700.0,
        };
        assert_eq!(hpd.hydro_id, EntityId(4));
        assert_eq!(hpd.value_m3s, 700.0);
        assert_eq!(hpd.clone(), hpd);
    }

    #[test]
    fn test_past_defluences_default_empty() {
        let ic = InitialConditions::default();
        assert!(ic.past_defluences.is_empty());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_initial_conditions_serde_default_past_defluences_absent() {
        let json = r#"{"storage":[],"filling_storage":[]}"#;
        let ic: InitialConditions = serde_json::from_str(json).unwrap();
        assert!(ic.past_defluences.is_empty());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_past_defluences_postcard_round_trip() {
        let ic = InitialConditions {
            storage: vec![HydroStorage {
                hydro_id: EntityId(0),
                value_hm3: 1_000.0,
            }],
            filling_storage: vec![],
            past_anticipated_commitments: vec![],
            recent_observations: vec![],
            past_defluences: vec![
                HydroPastDefluence {
                    hydro_id: EntityId(0),
                    start_date: NaiveDate::from_ymd_opt(2026, 4, 1)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    end_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    value_m3s: 700.0,
                },
                HydroPastDefluence {
                    hydro_id: EntityId(0),
                    start_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    end_date: NaiveDate::from_ymd_opt(2026, 4, 11)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    value_m3s: 650.0,
                },
            ],
            future_anticipated_deliveries: vec![],
        };

        let bytes = postcard::to_allocvec(&ic).unwrap();
        let restored: InitialConditions = postcard::from_bytes(&bytes).unwrap();
        assert_eq!(ic, restored);
        assert_eq!(bytes, postcard::to_allocvec(&restored).unwrap());
        assert_eq!(restored.past_defluences.len(), 2);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_past_defluences_postcard_field_order_precedes_future_anticipated_deliveries() {
        let base = InitialConditions {
            storage: vec![HydroStorage {
                hydro_id: EntityId(0),
                value_hm3: 1_000.0,
            }],
            filling_storage: vec![],
            past_anticipated_commitments: vec![],
            recent_observations: vec![RecentObservation {
                hydro_id: EntityId(0),
                start_date: NaiveDate::from_ymd_opt(2026, 4, 1)
                    .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                end_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                    .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                value_m3s: 500.0,
            }],
            past_defluences: vec![],
            future_anticipated_deliveries: vec![],
        };
        let mut with_defl = base.clone();
        with_defl.past_defluences = vec![HydroPastDefluence {
            hydro_id: EntityId(0),
            start_date: NaiveDate::from_ymd_opt(2026, 4, 1)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            end_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            value_m3s: 700.0,
        }];

        let prefix = postcard::to_allocvec(&base).unwrap();
        let full = postcard::to_allocvec(&with_defl).unwrap();

        // past_defluences and future_anticipated_deliveries are both empty in
        // `base`, each a 1-byte zero-length varint: the shared prefix ends 2
        // bytes before `prefix`'s end.
        let shared_prefix_len = prefix.len() - 2;
        assert!(full.len() > prefix.len());
        assert_eq!(
            &full[..shared_prefix_len],
            &prefix[..shared_prefix_len],
            "past_defluences must serialize after recent_observations and before \
             future_anticipated_deliveries (append-last wire contract)"
        );
        assert_eq!(
            full[full.len() - 1],
            prefix[prefix.len() - 1],
            "future_anticipated_deliveries (trailing, empty in both) must be \
             unaffected by populating past_defluences"
        );
    }

    // --- FutureAnticipatedDelivery / future_anticipated_deliveries tests ---

    #[test]
    fn test_future_anticipated_delivery_construction_and_clone() {
        let fad = FutureAnticipatedDelivery {
            thermal_id: EntityId(6),
            delivery_start: NaiveDate::from_ymd_opt(2026, 9, 5)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            delivery_end: NaiveDate::from_ymd_opt(2026, 9, 12)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            min_mw: 0.0,
            max_mw: 350.0,
        };
        assert_eq!(fad.thermal_id, EntityId(6));
        assert_eq!(fad.max_mw, 350.0);
        assert_eq!(fad.clone(), fad);
    }

    #[test]
    fn test_future_anticipated_deliveries_default_empty() {
        let ic = InitialConditions::default();
        assert!(ic.future_anticipated_deliveries.is_empty());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_future_anticipated_delivery_serde_roundtrip() {
        let fad = FutureAnticipatedDelivery {
            thermal_id: EntityId(86),
            delivery_start: NaiveDate::from_ymd_opt(2026, 9, 5)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            delivery_end: NaiveDate::from_ymd_opt(2026, 9, 12)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            min_mw: 0.0,
            max_mw: 350.0,
        };
        let json = serde_json::to_string(&fad).unwrap();
        let deserialized: FutureAnticipatedDelivery = serde_json::from_str(&json).unwrap();
        assert_eq!(fad, deserialized);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_initial_conditions_serde_default_future_anticipated_deliveries_absent() {
        let json = r#"{"storage":[],"filling_storage":[]}"#;
        let ic: InitialConditions = serde_json::from_str(json).unwrap();
        assert!(ic.future_anticipated_deliveries.is_empty());
    }

    #[test]
    fn test_initial_conditions_with_future_anticipated_deliveries() {
        let ic = InitialConditions {
            storage: vec![],
            filling_storage: vec![],
            past_anticipated_commitments: vec![],
            recent_observations: vec![],
            past_defluences: vec![],
            future_anticipated_deliveries: vec![
                FutureAnticipatedDelivery {
                    thermal_id: EntityId(3),
                    delivery_start: NaiveDate::from_ymd_opt(2026, 9, 5)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    delivery_end: NaiveDate::from_ymd_opt(2026, 9, 12)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    min_mw: 0.0,
                    max_mw: 100.0,
                },
                FutureAnticipatedDelivery {
                    thermal_id: EntityId(5),
                    delivery_start: NaiveDate::from_ymd_opt(2026, 9, 5)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    delivery_end: NaiveDate::from_ymd_opt(2026, 9, 12)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    min_mw: 50.0,
                    max_mw: 50.0,
                },
            ],
        };
        assert_eq!(ic.future_anticipated_deliveries.len(), 2);
        assert_eq!(ic.future_anticipated_deliveries[0].thermal_id, EntityId(3));
        assert_eq!(ic.future_anticipated_deliveries[0].max_mw, 100.0);
        assert_eq!(ic.future_anticipated_deliveries[1].thermal_id, EntityId(5));
        assert_eq!(ic.future_anticipated_deliveries[1].min_mw, 50.0);
        assert_eq!(ic.future_anticipated_deliveries[1].max_mw, 50.0);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_future_anticipated_deliveries_postcard_round_trip() {
        let ic = InitialConditions {
            storage: vec![HydroStorage {
                hydro_id: EntityId(0),
                value_hm3: 1_000.0,
            }],
            filling_storage: vec![],
            past_anticipated_commitments: vec![],
            recent_observations: vec![],
            past_defluences: vec![],
            future_anticipated_deliveries: vec![
                FutureAnticipatedDelivery {
                    thermal_id: EntityId(0),
                    delivery_start: NaiveDate::from_ymd_opt(2026, 9, 5)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    delivery_end: NaiveDate::from_ymd_opt(2026, 9, 12)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    min_mw: 0.0,
                    max_mw: 350.0,
                },
                FutureAnticipatedDelivery {
                    thermal_id: EntityId(0),
                    delivery_start: NaiveDate::from_ymd_opt(2026, 9, 12)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    delivery_end: NaiveDate::from_ymd_opt(2026, 9, 19)
                        .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                    min_mw: 100.0,
                    max_mw: 100.0,
                },
            ],
        };

        let bytes = postcard::to_allocvec(&ic).unwrap();
        let restored: InitialConditions = postcard::from_bytes(&bytes).unwrap();
        assert_eq!(ic, restored);
        assert_eq!(bytes, postcard::to_allocvec(&restored).unwrap());
        assert_eq!(restored.future_anticipated_deliveries.len(), 2);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_future_anticipated_deliveries_postcard_field_order_is_last() {
        let base = InitialConditions {
            storage: vec![HydroStorage {
                hydro_id: EntityId(0),
                value_hm3: 1_000.0,
            }],
            filling_storage: vec![],
            past_anticipated_commitments: vec![],
            recent_observations: vec![],
            past_defluences: vec![HydroPastDefluence {
                hydro_id: EntityId(0),
                start_date: NaiveDate::from_ymd_opt(2026, 4, 1)
                    .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                end_date: NaiveDate::from_ymd_opt(2026, 4, 4)
                    .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
                value_m3s: 700.0,
            }],
            future_anticipated_deliveries: vec![],
        };
        let mut with_future = base.clone();
        with_future.future_anticipated_deliveries = vec![FutureAnticipatedDelivery {
            thermal_id: EntityId(9),
            delivery_start: NaiveDate::from_ymd_opt(2026, 9, 5)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            delivery_end: NaiveDate::from_ymd_opt(2026, 9, 12)
                .unwrap_or_else(|| unreachable!("hardcoded date is valid")),
            min_mw: 0.0,
            max_mw: 350.0,
        }];

        let prefix = postcard::to_allocvec(&base).unwrap();
        let full = postcard::to_allocvec(&with_future).unwrap();

        assert!(full.len() > prefix.len());
        assert_eq!(
            &full[..prefix.len() - 1],
            &prefix[..prefix.len() - 1],
            "future_anticipated_deliveries must serialize after past_defluences \
             (append-last wire contract)"
        );
    }
}