cobre-sddp 0.8.2

Stochastic Dual Dynamic Programming (SDDP) for hydrothermal dispatch and energy planning
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
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
//! Per-stage cut pool for the Future Cost Function (FCF).
//!
//! The [`CutPool`] is the central data structure for cut storage in the SDDP
//! training loop. Each stage owns one pool. Cuts are stored in pre-allocated
//! slots with a deterministic assignment formula so that results are
//! bit-for-bit identical regardless of execution timing or ordering.
//!
//! ## Slot assignment
//!
//! Each cut inserted during the training loop is assigned a deterministic
//! slot index:
//!
//! ```text
//! slot = warm_start_count + iteration * forward_passes + forward_pass_index
//! ```
//!
//! This guarantees that every run with the same parameters produces the same
//! pool layout, which is required for reproducibility and checkpointing.
//!
//! ## Activity tracking
//!
//! Each slot carries an `active` flag. Inactive cuts are retained in the pool
//! for reproducibility but excluded from LP construction and from
//! [`evaluate_at_state`] queries. The [`CutSelectionStrategy`] determines
//! which cuts to activate or deactivate; [`set_active`] is the canonical
//! toggle that sets the flag and keeps [`active_count`] consistent.
//! [`deactivate`] is a convenience wrapper that calls `set_active(slot, false)`
//! for each index. [`cuts_in_lp`] returns the number of populated slots —
//! the LP-row-count metric for append-only LP tracking.
//!
//! [`evaluate_at_state`]: CutPool::evaluate_at_state
//! [`set_active`]: CutPool::set_active
//! [`deactivate`]: CutPool::deactivate
//! [`active_count`]: CutPool::active_count
//! [`cuts_in_lp`]: CutPool::cuts_in_lp
//! [`CutSelectionStrategy`]: crate::cut_selection::CutSelectionStrategy
//!
//! ## Example
//!
//! ```rust
//! use cobre_sddp::cut::pool::CutPool;
//!
//! // 100-slot pool, 9-dimensional state, 10 forward passes per iteration,
//! // no warm-start cuts.
//! let mut pool = CutPool::new(100, 9, 10, 0);
//! assert_eq!(pool.active_count(), 0);
//!
//! let coeffs = vec![1.0; 9];
//! pool.add_cut(0, 0, 5.0, &coeffs);
//! assert_eq!(pool.active_count(), 1);
//! assert_eq!(pool.cuts_in_lp(), 1);
//! ```

use crate::cut::WARM_START_ITERATION;
use crate::cut_selection::CutMetadata;

/// Pre-allocated per-stage cut pool for the Future Cost Function (FCF).
///
/// All storage is allocated at construction time to avoid heap allocation
/// during the training loop hot path. The pool holds `capacity` slots;
/// each slot stores:
///
/// - A coefficient vector of length `state_dimension`
/// - A scalar intercept
/// - [`CutMetadata`] for cut selection bookkeeping
/// - An `active` flag that controls LP participation
///
/// Slots are addressed by a deterministic formula derived from the iteration
/// counter and forward pass index. The pool tracks a `populated_count`
/// high-water mark to avoid scanning unpopulated slots.
///
/// A `cached_active_count` field is maintained incrementally by [`add_cut`]
/// (increment), [`set_active`] (increment or decrement), and [`deactivate`]
/// (decrement via `set_active`), making [`active_count`] an O(1) query.
/// [`cuts_in_lp`] returns the `populated_count` — the number of slots that
/// have been populated at least once, regardless of activity state.
///
/// [`add_cut`]: CutPool::add_cut
/// [`set_active`]: CutPool::set_active
/// [`deactivate`]: CutPool::deactivate
/// [`active_count`]: CutPool::active_count
/// [`cuts_in_lp`]: CutPool::cuts_in_lp
#[derive(Debug, Clone)]
pub struct CutPool {
    /// Flat coefficient storage. Coefficients for slot `i` occupy the range
    /// `i * state_dimension .. (i + 1) * state_dimension`. Length is always
    /// `capacity * state_dimension`.
    pub coefficients: Vec<f64>,

    /// Per-slot intercept values.
    pub intercepts: Vec<f64>,

    /// Per-slot cut tracking metadata for cut selection strategies.
    pub metadata: Vec<CutMetadata>,

    /// Per-slot activity flags. `false` means the cut is excluded from LP
    /// construction and evaluations. Inactive cuts are still retained in the
    /// pool so that their slots remain deterministic.
    pub active: Vec<bool>,

    /// High-water mark: the number of slots that have been populated at least
    /// once. Iteration over the pool uses this bound to skip trailing
    /// unpopulated slots. Updated by [`add_cut`] when the new slot index
    /// is at or beyond the current mark.
    ///
    /// [`add_cut`]: CutPool::add_cut
    pub populated_count: usize,

    /// Total number of pre-allocated slots. Fixed after construction.
    pub capacity: usize,

    /// Length of each coefficient vector. Fixed after construction.
    pub state_dimension: usize,

    /// Number of forward passes per SDDP iteration. Used by the slot
    /// assignment formula. Fixed after construction.
    pub forward_passes: u32,

    /// Number of warm-start cuts loaded before training begins. Acts as a
    /// base offset in the slot assignment formula. Fixed after construction.
    pub warm_start_count: u32,

    /// Training-iteration number that maps to the first training slot
    /// (`warm_start_count`). The slot formula subtracts it so that 1-based
    /// iterations pack densely from `warm_start_count` with no reserved leading
    /// block. Defaults to 0 (legacy layout, where slot grows with the raw
    /// iteration and the block `[warm_start_count, +forward_passes)` is unused);
    /// production sets it to `start_iteration + 1` via [`set_iteration_base`].
    /// Both layouts are correct; dense is tighter.
    ///
    /// [`set_iteration_base`]: CutPool::set_iteration_base
    pub iteration_base: u64,

    /// Cached count of active cuts, maintained incrementally by [`add_cut`]
    /// (increment) and [`deactivate`] (decrement). Makes [`active_count`]
    /// O(1) instead of O(`populated_count`).
    ///
    /// [`add_cut`]: CutPool::add_cut
    /// [`deactivate`]: CutPool::deactivate
    /// [`active_count`]: CutPool::active_count
    pub cached_active_count: usize,

    /// Cumulative count of cuts ever generated (written via [`add_cut`]),
    /// including warm-start cuts loaded at construction. Unlike
    /// [`populated_count`] — a slot high-water mark that includes any reserved
    /// but unwritten leading slots — this counts only real cut insertions, so
    /// it is the true number of policy rows generated over the run.
    ///
    /// [`add_cut`]: CutPool::add_cut
    /// [`populated_count`]: CutPool::populated_count
    pub generated_count: usize,

    /// Scratch buffer for [`enforce_budget`] candidate collection.
    ///
    /// Reused across calls to avoid per-call `Vec<u32>` allocation. Cleared
    /// at the start of each `enforce_budget` invocation and populated with
    /// active slot indices that are eligible for eviction.
    ///
    /// [`enforce_budget`]: CutPool::enforce_budget
    pub(crate) candidates_buf: Vec<u32>,
}

impl CutPool {
    /// Create a new `CutPool` with all slots pre-allocated and initialized
    /// to zero / inactive.
    ///
    /// # Parameters
    ///
    /// - `capacity`: total number of cut slots to allocate.
    /// - `state_dimension`: length of the state vector (number of coefficients
    ///   per cut).
    /// - `forward_passes`: number of forward passes per training iteration.
    ///   Used by the slot formula: `slot = warm_start_count + iteration *
    ///   forward_passes + forward_pass_index`.
    /// - `warm_start_count`: number of warm-start cuts that occupy the first
    ///   slots. Offsets slot indices for iteration-generated cuts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let pool = CutPool::new(50, 4, 5, 0);
    /// assert_eq!(pool.capacity, 50);
    /// assert_eq!(pool.state_dimension, 4);
    /// assert_eq!(pool.active_count(), 0);
    /// assert_eq!(pool.populated_count, 0);
    /// ```
    #[must_use]
    pub fn new(
        capacity: usize,
        state_dimension: usize,
        forward_passes: u32,
        warm_start_count: u32,
    ) -> Self {
        let default_meta = CutMetadata {
            iteration_generated: 0,
            forward_pass_index: 0,
            active_count: 0,
            last_active_iter: 0,
        };

        Self {
            coefficients: vec![0.0; capacity * state_dimension],
            intercepts: vec![0.0; capacity],
            metadata: vec![default_meta; capacity],
            active: vec![false; capacity],
            populated_count: 0,
            capacity,
            state_dimension,
            forward_passes,
            warm_start_count,
            iteration_base: 0,
            cached_active_count: 0,
            generated_count: warm_start_count as usize,
            candidates_buf: Vec::new(),
        }
    }

    /// Compute the deterministic slot index for a cut.
    ///
    /// Formula:
    /// ```text
    /// slot = warm_start_count
    ///      + (iteration - iteration_base) * forward_passes
    ///      + forward_pass_index
    /// ```
    ///
    /// `iteration_base` (default 0) lets 1-based iterations pack densely from
    /// `warm_start_count`; see [`iteration_base`](CutPool::iteration_base).
    #[inline]
    fn slot_index(&self, iteration: u64, forward_pass_index: u32) -> usize {
        debug_assert!(
            iteration >= self.iteration_base,
            "slot_index: iteration {iteration} < iteration_base {}",
            self.iteration_base
        );
        // Slot indices are bounded by `capacity` (a usize), so the result
        // always fits in usize. The intermediate cast of `iteration` to usize
        // cannot realistically truncate: any platform capable of running SDDP
        // at scale is 64-bit, and pool capacity is enforced to be < usize::MAX.
        #[allow(clippy::cast_possible_truncation)]
        let iter_usize = (iteration - self.iteration_base) as usize;
        self.warm_start_count as usize
            + iter_usize * self.forward_passes as usize
            + forward_pass_index as usize
    }

    /// Set the iteration that maps to the first training slot.
    ///
    /// Pass `start_iteration + 1` so the first training iteration's cuts land at
    /// slot `warm_start_count` (dense packing). The default of 0 reproduces the
    /// legacy layout where the slot block
    /// `[warm_start_count, warm_start_count + forward_passes)` is left unused.
    ///
    /// Should be called before the first [`add_cut`](CutPool::add_cut) of a
    /// training run: with a fresh or warm-started pool this gives dense slots.
    /// Changing the base on a pool that still holds *active* training cuts is
    /// caught downstream by `add_cut`'s no-overwrite guard; re-setting on a pool
    /// whose cuts are all inactive (e.g. multi-phase tests) safely reuses slots.
    pub fn set_iteration_base(&mut self, iteration_base: u64) {
        self.iteration_base = iteration_base;
    }

    /// Insert a Benders cut into the pool at the deterministic slot.
    ///
    /// The slot is computed from `warm_start_count + iteration *
    /// forward_passes + forward_pass_index`. The cut is marked active
    /// immediately. [`CutMetadata`] is initialized with `iteration_generated`
    /// and `forward_pass_index`; activity tracking fields start at zero /
    /// `iteration_generated`.
    ///
    /// `populated_count` is updated if the slot index is at or beyond the
    /// current high-water mark.
    ///
    /// # Panics (debug builds only)
    ///
    /// Panics if the computed slot is >= `capacity` or if
    /// `coefficients.len() != state_dimension`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let mut pool = CutPool::new(20, 3, 5, 0);
    /// pool.add_cut(1, 2, 10.0, &[1.0, 2.0, 3.0]);
    /// // slot = 0 + 1*5 + 2 = 7
    /// assert!(pool.active[7]);
    /// assert_eq!(pool.intercepts[7], 10.0);
    /// ```
    pub fn add_cut(
        &mut self,
        iteration: u64,
        forward_pass_index: u32,
        intercept: f64,
        coefficients: &[f64],
    ) {
        let slot = self.slot_index(iteration, forward_pass_index);

        debug_assert!(
            slot < self.capacity,
            "cut slot {slot} is out of bounds (capacity = {})",
            self.capacity
        );
        debug_assert!(
            coefficients.len() == self.state_dimension,
            "coefficients length {} != state_dimension {}",
            coefficients.len(),
            self.state_dimension
        );

        self.intercepts[slot] = intercept;
        let start = slot * self.state_dimension;
        self.coefficients[start..start + self.state_dimension].copy_from_slice(coefficients);
        debug_assert!(
            !self.active[slot],
            "add_cut: slot {slot} is already active (double-insert)"
        );
        self.active[slot] = true;
        self.cached_active_count += 1;
        self.metadata[slot] = CutMetadata {
            iteration_generated: iteration,
            forward_pass_index,
            active_count: 0,
            last_active_iter: iteration,
        };

        if slot >= self.populated_count {
            self.populated_count = slot + 1;
        }
        self.generated_count += 1;
    }

    /// Iterate over active cuts in the populated range.
    ///
    /// Yields `(slot_index, intercept, coefficient_slice)` for every slot
    /// where `active[slot]` is `true`. Only scans up to `populated_count`
    /// to avoid touching uninitialized slots.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let mut pool = CutPool::new(10, 2, 1, 0);
    /// pool.add_cut(0, 0, 3.0, &[1.0, 2.0]);
    /// pool.add_cut(1, 0, 7.0, &[3.0, 4.0]);
    ///
    /// let active: Vec<_> = pool.active_cuts().collect();
    /// assert_eq!(active.len(), 2);
    /// ```
    pub fn active_cuts(&self) -> impl Iterator<Item = (usize, f64, &[f64])> {
        let mut remaining = self.cached_active_count;
        self.active[..self.populated_count]
            .iter()
            .enumerate()
            .scan((), move |(), (i, &is_active)| {
                if remaining == 0 {
                    return None;
                }
                if is_active {
                    remaining -= 1;
                    let start = i * self.state_dimension;
                    Some(Some((
                        i,
                        self.intercepts[i],
                        &self.coefficients[start..start + self.state_dimension],
                    )))
                } else {
                    Some(None)
                }
            })
            .flatten()
    }

    /// Iterate over active cuts generated in a specific training iteration.
    ///
    /// Yields `(slot_index, intercept, coefficient_slice)` for every slot
    /// where `active[slot]` is `true` AND
    /// `metadata[slot].iteration_generated == current_iteration`.
    ///
    /// Warm-start cuts (whose `iteration_generated` is
    /// [`WARM_START_ITERATION`]) are always excluded, even if
    /// `current_iteration` were to equal the sentinel numerically — the
    /// sentinel is chosen as `u64::MAX` to make such a collision impossible
    /// in practice, but the explicit guard is retained for clarity.
    ///
    /// Only scans up to `populated_count` to avoid touching uninitialized
    /// slots. Iterates in insertion order, preserving declaration-order
    /// invariance.
    pub(crate) fn active_delta_cuts(
        &self,
        current_iteration: u64,
    ) -> impl Iterator<Item = (usize, f64, &[f64])> {
        let mut remaining = self.cached_active_count;
        self.active[..self.populated_count]
            .iter()
            .enumerate()
            .scan((), move |(), (slot, &is_active)| {
                if remaining == 0 {
                    return None;
                }
                if is_active {
                    remaining -= 1;
                    Some(Some(slot))
                } else {
                    Some(None)
                }
            })
            .flatten()
            .filter(move |&slot| {
                self.metadata[slot].iteration_generated == current_iteration
                    && self.metadata[slot].iteration_generated != WARM_START_ITERATION
            })
            .map(|i| {
                let start = i * self.state_dimension;
                (
                    i,
                    self.intercepts[i],
                    &self.coefficients[start..start + self.state_dimension],
                )
            })
    }

    /// Count the number of active cuts.
    ///
    /// Returns the cached count in O(1). A debug assertion verifies consistency
    /// with the computed count in debug builds.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let mut pool = CutPool::new(10, 1, 1, 0);
    /// assert_eq!(pool.active_count(), 0);
    /// pool.add_cut(0, 0, 1.0, &[1.0]);
    /// assert_eq!(pool.active_count(), 1);
    /// ```
    #[must_use]
    pub fn active_count(&self) -> usize {
        debug_assert_eq!(
            self.cached_active_count,
            self.active[..self.populated_count]
                .iter()
                .filter(|&&a| a)
                .count(),
            "cached active_count {} != computed {}",
            self.cached_active_count,
            self.active[..self.populated_count]
                .iter()
                .filter(|&&a| a)
                .count(),
        );
        self.cached_active_count
    }

    /// Return the number of populated slots — the LP-row-count metric.
    ///
    /// Each call to [`add_cut`] increments `populated_count` when the slot
    /// index is at or beyond the current high-water mark. This count is the
    /// total number of cut rows that have ever been inserted into the pool,
    /// regardless of whether they are currently active or inactive.
    ///
    /// [`add_cut`]: CutPool::add_cut
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let mut pool = CutPool::new(10, 1, 1, 0);
    /// pool.add_cut(0, 0, 1.0, &[1.0]);
    /// pool.add_cut(1, 0, 2.0, &[2.0]);
    /// assert_eq!(pool.cuts_in_lp(), 2);
    ///
    /// // Deactivation does not change the LP-row count.
    /// pool.deactivate(&[0]);
    /// assert_eq!(pool.cuts_in_lp(), 2);
    /// assert_eq!(pool.active_count(), 1);
    /// ```
    #[must_use]
    #[inline]
    pub fn cuts_in_lp(&self) -> usize {
        self.populated_count
    }

    /// Deactivate the cuts at the given slot indices.
    ///
    /// Sets `active[i] = false` for each index in `indices`. Indices are
    /// zero-based slot positions. Out-of-bounds indices are silently ignored
    /// in release builds; a debug assertion fires for out-of-bounds access.
    ///
    /// # Idempotency
    ///
    /// Passing an index that is already inactive is a silent no-op: the
    /// `active` flag stays `false` and `cached_active_count` is not
    /// decremented a second time, preventing underflow. This means passing
    /// the same index more than once in `indices` is safe — only the first
    /// occurrence takes effect. In debug builds a `debug_assert!` fires on
    /// the second occurrence to surface accidental duplicate-index calls
    /// during testing.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let mut pool = CutPool::new(10, 1, 1, 0);
    /// pool.add_cut(0, 0, 1.0, &[1.0]);
    /// pool.add_cut(1, 0, 2.0, &[2.0]);
    /// pool.deactivate(&[0]);
    /// assert_eq!(pool.active_count(), 1);
    /// assert!(!pool.active[0]);
    /// assert!(pool.active[1]);
    /// ```
    pub fn deactivate(&mut self, indices: &[u32]) {
        for &idx in indices {
            self.set_active(idx, false);
        }
    }

    /// Apply a batch of activity changes from a [`CutActivityUpdates`] result.
    ///
    /// Deactivates every slot in `updates.updates` and reactivates every slot
    /// in `updates.reactivations` via [`set_active`]. This is the canonical
    /// way to apply the output of [`CutSelectionStrategy::select_for_stage`]
    /// to a pool — it folds both deactivations and reactivations into a single
    /// call so the training loop never silently drops reactivation entries.
    ///
    /// Idempotency follows [`set_active`]: applying the same change twice (or
    /// requesting a state that already holds) is a no-op. Out-of-bounds slot
    /// indices are silently ignored in release builds; a debug assertion
    /// fires in debug builds.
    ///
    /// [`set_active`]: CutPool::set_active
    /// [`CutActivityUpdates`]: crate::cut_selection::CutActivityUpdates
    /// [`CutSelectionStrategy::select_for_stage`]: crate::cut_selection::CutSelectionStrategy::select_for_stage
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    /// use cobre_sddp::cut_selection::CutActivityUpdates;
    ///
    /// let mut pool = CutPool::new(10, 1, 1, 0);
    /// pool.add_cut(0, 0, 1.0, &[1.0]);
    /// pool.add_cut(1, 0, 2.0, &[2.0]);
    /// pool.add_cut(2, 0, 3.0, &[3.0]);
    ///
    /// // Deactivate slot 1, then reactivate it via apply_updates.
    /// pool.deactivate(&[1]);
    /// assert_eq!(pool.active_count(), 2);
    ///
    /// let updates = CutActivityUpdates {
    ///     stage_index: 0,
    ///     updates: vec![0],          // deactivate slot 0
    ///     reactivations: vec![1],    // reactivate slot 1
    /// };
    /// pool.apply_updates(&updates);
    /// assert!(!pool.active[0]);
    /// assert!(pool.active[1]);
    /// assert!(pool.active[2]);
    /// assert_eq!(pool.active_count(), 2);
    /// ```
    pub fn apply_updates(&mut self, updates: &crate::cut_selection::CutActivityUpdates) {
        for &slot in &updates.updates {
            self.set_active(slot, false);
        }
        for &slot in &updates.reactivations {
            self.set_active(slot, true);
        }
    }

    /// Toggle the activity flag for a single slot.
    ///
    /// Sets `active[slot] = active` and keeps `cached_active_count` consistent:
    ///
    /// - If `active == false` and the slot is currently active, `active[slot]`
    ///   is set to `false` and `cached_active_count` is decremented by 1.
    /// - If `active == true` and the slot is currently inactive, `active[slot]`
    ///   is set to `true` and `cached_active_count` is incremented by 1.
    /// - If the slot already has the requested state, the call is a no-op.
    ///
    /// [`deactivate`]: CutPool::deactivate
    ///
    /// # Panics (debug builds only)
    ///
    /// Panics if `slot >= populated_count`. In release builds the bounds check
    /// is skipped, matching the existing [`deactivate`] debug-assert pattern.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let mut pool = CutPool::new(10, 1, 1, 0);
    /// pool.add_cut(0, 0, 1.0, &[1.0]);
    /// pool.add_cut(1, 0, 2.0, &[2.0]);
    /// pool.add_cut(2, 0, 3.0, &[3.0]);
    ///
    /// pool.set_active(1, false);
    /// assert_eq!(pool.active_count(), 2);
    /// assert!(!pool.active[1]);
    /// assert_eq!(pool.cuts_in_lp(), 3); // populated count unchanged
    ///
    /// pool.set_active(1, true);
    /// assert_eq!(pool.active_count(), 3);
    /// assert!(pool.active[1]);
    /// ```
    pub fn set_active(&mut self, slot: u32, active: bool) {
        let i = slot as usize;
        debug_assert!(
            i < self.populated_count,
            "set_active slot {i} out of populated range"
        );
        if self.active[i] == active {
            return;
        }
        if active {
            self.active[i] = true;
            self.cached_active_count += 1;
        } else {
            self.active[i] = false;
            self.cached_active_count -= 1;
        }
    }

    /// Evaluate the FCF at the given state vector.
    ///
    /// Returns the maximum over all active cuts of `intercept + coefficients
    /// · state`. Returns [`f64::NEG_INFINITY`] if no active cuts exist (the
    /// pool is empty or all cuts have been deactivated).
    ///
    /// # Panics (debug builds only)
    ///
    /// Panics if `state.len() != state_dimension`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let mut pool = CutPool::new(10, 2, 1, 0);
    /// pool.add_cut(0, 0, 10.0, &[1.0, 0.0]);
    /// pool.add_cut(1, 0,  5.0, &[0.0, 2.0]);
    ///
    /// // max(10 + 1*3 + 0*4, 5 + 0*3 + 2*4) = max(13, 13) = 13
    /// assert_eq!(pool.evaluate_at_state(&[3.0, 4.0]), 13.0);
    ///
    /// // Empty pool returns NEG_INFINITY.
    /// let empty = CutPool::new(10, 2, 1, 0);
    /// assert_eq!(empty.evaluate_at_state(&[1.0, 1.0]), f64::NEG_INFINITY);
    /// ```
    #[must_use]
    pub fn evaluate_at_state(&self, state: &[f64]) -> f64 {
        debug_assert!(
            state.len() == self.state_dimension,
            "state length {} != state_dimension {}",
            state.len(),
            self.state_dimension
        );

        self.active_cuts()
            .map(|(_, intercept, coeffs)| {
                let dot: f64 = coeffs.iter().zip(state).map(|(a, b)| a * b).sum();
                intercept + dot
            })
            .fold(f64::NEG_INFINITY, f64::max)
    }

    /// Diagnostic: count exact-zero coefficients across all active cuts.
    ///
    /// Walks every coefficient of every active cut and tallies exact
    /// zeros (`value == 0.0`). Returns a [`SparsityReport`] with the
    /// aggregate count, fraction, and per-dimension breakdown.
    ///
    /// Not on the hot path: allocates one `Vec<usize>` of length
    /// `state_dimension` per call. Intended for offline analysis or
    /// pre-release diagnostics, not per-iteration use.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let mut pool = CutPool::new(10, 3, 1, 0);
    /// pool.add_cut(0, 0, 1.0, &[1.0, 0.0, 2.0]);
    /// pool.add_cut(1, 0, 2.0, &[0.0, 0.0, 3.0]);
    ///
    /// let report = pool.sparsity_report();
    /// assert_eq!(report.total_coefficients, 6);   // 2 cuts * 3 dims
    /// assert_eq!(report.exact_zero_count, 3);      // (0,1), (1,0), (1,1)
    /// assert!((report.sparsity_fraction - 0.5).abs() < 1e-10);
    /// assert_eq!(report.per_dimension_zeros, vec![1, 2, 0]);
    /// ```
    #[must_use]
    pub fn sparsity_report(&self) -> SparsityReport {
        let active_count = self.active_count();
        let mut exact_zero_count = 0usize;
        let mut per_dimension_zeros = vec![0usize; self.state_dimension];

        for (_slot, _intercept, coeffs) in self.active_cuts() {
            for (j, &c) in coeffs.iter().enumerate() {
                if c == 0.0 {
                    exact_zero_count += 1;
                    per_dimension_zeros[j] += 1;
                }
            }
        }

        let total = active_count * self.state_dimension;
        #[allow(clippy::cast_precision_loss)]
        let fraction = if total > 0 {
            exact_zero_count as f64 / total as f64
        } else {
            0.0
        };

        SparsityReport {
            total_coefficients: total,
            exact_zero_count,
            sparsity_fraction: fraction,
            per_dimension_zeros,
        }
    }

    /// Construct a `CutPool` from deserialized cut records.
    ///
    /// The pool capacity is set to `records.len()` (no room for new training
    /// cuts). All loaded cuts are populated and their active flags are set
    /// from the deserialized records.
    ///
    /// `forward_passes` is set to 0 and `warm_start_count` is set to
    /// `records.len()` since this pool is not intended for incremental
    /// training addition (only for FCF evaluation during simulation).
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_io::OwnedPolicyCutRecord;
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let records = vec![
    ///     OwnedPolicyCutRecord {
    ///         cut_id: 0,
    ///         slot_index: 0,
    ///         iteration: 0,
    ///         forward_pass_index: 0,
    ///         intercept: 5.0,
    ///         coefficients: vec![1.0, 2.0],
    ///         is_active: true,
    ///     },
    /// ];
    ///
    /// let pool = CutPool::from_deserialized(2, &records);
    /// assert_eq!(pool.capacity, 1);
    /// assert_eq!(pool.populated_count, 1);
    /// assert_eq!(pool.active_count(), 1);
    /// ```
    #[must_use]
    pub fn from_deserialized(
        state_dimension: usize,
        records: &[cobre_io::OwnedPolicyCutRecord],
    ) -> Self {
        let capacity = records.len();
        let mut coefficients = Vec::with_capacity(capacity * state_dimension);
        let mut intercepts = Vec::with_capacity(capacity);
        let mut active = Vec::with_capacity(capacity);
        let mut metadata = Vec::with_capacity(capacity);
        let mut cached_active_count = 0usize;

        for record in records {
            debug_assert!(
                record.coefficients.len() == state_dimension,
                "from_deserialized: coefficients length {} != state_dimension {}",
                record.coefficients.len(),
                state_dimension
            );
            coefficients.extend_from_slice(&record.coefficients);
            intercepts.push(record.intercept);
            active.push(record.is_active);
            if record.is_active {
                cached_active_count += 1;
            }
            metadata.push(CutMetadata {
                iteration_generated: u64::from(record.iteration),
                forward_pass_index: record.forward_pass_index,
                active_count: 0,
                last_active_iter: u64::from(record.iteration),
            });
        }

        #[allow(clippy::cast_possible_truncation)]
        Self {
            coefficients,
            intercepts,
            metadata,
            active,
            populated_count: capacity,
            capacity,
            state_dimension,
            forward_passes: 0,
            warm_start_count: capacity as u32,
            iteration_base: 0,
            cached_active_count,
            generated_count: capacity,
            candidates_buf: Vec::new(),
        }
    }

    /// Construct a `CutPool` with warm-start cuts plus capacity for training.
    ///
    /// The loaded cuts occupy the first `records.len()` slots. The remaining
    /// `max_iterations * forward_passes` slots are allocated for new training
    /// cuts. The slot formula `warm_start_count + iteration * forward_passes +
    /// forward_pass_index` correctly offsets training cuts past the warm-start
    /// region.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cobre_io::OwnedPolicyCutRecord;
    /// use cobre_sddp::cut::pool::CutPool;
    ///
    /// let records = vec![
    ///     OwnedPolicyCutRecord {
    ///         cut_id: 0, slot_index: 0, iteration: 0, forward_pass_index: 0,
    ///         intercept: 5.0, coefficients: vec![1.0, 2.0],
    ///         is_active: true,
    ///     },
    /// ];
    /// let pool = CutPool::new_with_warm_start(2, 4, 10, &records);
    /// assert_eq!(pool.warm_start_count, 1);
    /// assert_eq!(pool.capacity, 1 + 10 * 4); // 41
    /// assert_eq!(pool.populated_count, 1);
    /// assert_eq!(pool.active_count(), 1);
    /// ```
    #[must_use]
    pub fn new_with_warm_start(
        state_dimension: usize,
        forward_passes: u32,
        max_iterations: u64,
        records: &[cobre_io::OwnedPolicyCutRecord],
    ) -> Self {
        let warm_start_count = records.len();
        #[allow(clippy::cast_possible_truncation)]
        let capacity = warm_start_count + (max_iterations as usize) * (forward_passes as usize);

        let default_meta = CutMetadata {
            iteration_generated: 0,
            forward_pass_index: 0,
            active_count: 0,
            last_active_iter: 0,
        };

        let mut coefficients = vec![0.0_f64; capacity * state_dimension];
        let mut intercepts = vec![0.0; capacity];
        let mut active = vec![false; capacity];
        let mut metadata = vec![default_meta; capacity];
        let mut cached_active_count = 0usize;

        for (i, record) in records.iter().enumerate() {
            debug_assert!(
                record.coefficients.len() == state_dimension,
                "new_with_warm_start: coefficients length {} != state_dimension {}",
                record.coefficients.len(),
                state_dimension
            );
            let start = i * state_dimension;
            coefficients[start..start + state_dimension].copy_from_slice(&record.coefficients);
            intercepts[i] = record.intercept;
            active[i] = record.is_active;
            if record.is_active {
                cached_active_count += 1;
            }
            // Use WARM_START_ITERATION as the iteration_generated sentinel so
            // warm-start cuts are never matched by pack_local_cuts (which
            // filters on the current training iteration).  This prevents
            // double-counting warm-start cuts as new training cuts in cut sync.
            metadata[i] = CutMetadata {
                iteration_generated: WARM_START_ITERATION,
                forward_pass_index: record.forward_pass_index,
                active_count: 0,
                last_active_iter: u64::from(record.iteration),
            };
        }

        #[allow(clippy::cast_possible_truncation)]
        Self {
            coefficients,
            intercepts,
            metadata,
            active,
            populated_count: warm_start_count,
            capacity,
            state_dimension,
            forward_passes,
            warm_start_count: warm_start_count as u32,
            iteration_base: 0,
            cached_active_count,
            generated_count: warm_start_count,
            candidates_buf: Vec::new(),
        }
    }
}

/// Diagnostic report of exact-zero coefficients across active cuts in a [`CutPool`].
///
/// Produced by [`CutPool::sparsity_report`]. Counts only exact
/// zeros (`value == 0.0`); near-zero values are not collapsed to
/// zero by this report.
#[derive(Debug, Clone)]
pub struct SparsityReport {
    /// Total number of coefficients scanned (`active_count * state_dimension`).
    pub total_coefficients: usize,
    /// Number of exact-zero coefficients (`value == 0.0`).
    pub exact_zero_count: usize,
    /// Fraction of exact-zero coefficients (0.0 to 1.0).
    pub sparsity_fraction: f64,
    /// Per-dimension zero count (length = `state_dimension`). Entry `j` is the
    /// number of active cuts where `coefficient[j] == 0.0`.
    pub per_dimension_zeros: Vec<usize>,
}

/// Result of a [`CutPool::enforce_budget`] call.
///
/// Reports how many cuts were evicted and the active-cut counts before and
/// after the enforcement pass.
#[derive(Debug, Clone)]
pub struct BudgetEnforcementResult {
    /// Number of cuts deactivated during this enforcement pass.
    pub evicted_count: u32,
    /// Active cut count before enforcement.
    pub active_before: u32,
    /// Active cut count after enforcement (`active_before - evicted_count`).
    pub active_after: u32,
}

impl CutPool {
    /// Enforce a hard cap on the number of active cuts per stage.
    ///
    /// If `active_count() <= budget`, returns immediately with zero evictions.
    ///
    /// Otherwise, collects all active slots where
    /// `metadata[slot].iteration_generated != current_iteration` (protecting
    /// cuts from the current backward pass), sorts them by
    /// `(last_active_iter ASC, active_count ASC)` — stalest and least-used
    /// first — and deactivates the first `active_count - budget` of them.
    ///
    /// Uses `select_nth_unstable_by` (partial sort) when the number of excess
    /// cuts is small relative to the candidate set, otherwise `sort_unstable_by`.
    ///
    /// Cuts generated in `current_iteration` are **never** evicted. If the
    /// current-iteration cuts alone exceed the budget, all current-iteration
    /// cuts are preserved and `active_count()` may remain above `budget` after
    /// the call.
    ///
    /// # Parameters
    ///
    /// - `budget`: maximum number of active cuts allowed.
    /// - `current_iteration`: cuts generated in this iteration are protected.
    /// - `forward_passes`: unused by the method; present for call-site
    ///   uniformity with the training loop (which uses it for the warning
    ///   validation in `StudyParams::from_config`).
    pub fn enforce_budget(
        &mut self,
        budget: u32,
        current_iteration: u64,
        _forward_passes: u32,
    ) -> BudgetEnforcementResult {
        #[allow(clippy::cast_possible_truncation)]
        let active_before = self.active_count() as u32;
        let budget_usize = budget as usize;

        if self.cached_active_count <= budget_usize {
            return BudgetEnforcementResult {
                evicted_count: 0,
                active_before,
                active_after: active_before,
            };
        }

        let excess = self.cached_active_count - budget_usize;

        // Collect eviction candidates into the reused scratch buffer:
        // active slots not from current_iteration.
        self.candidates_buf.clear();
        #[allow(clippy::cast_possible_truncation)]
        self.candidates_buf.extend(
            self.active[..self.populated_count]
                .iter()
                .enumerate()
                .filter(|&(slot, &is_active)| {
                    is_active && self.metadata[slot].iteration_generated != current_iteration
                })
                .map(|(slot, _)| slot as u32),
        );

        if self.candidates_buf.is_empty() {
            // All active cuts are from the current iteration; preserve them all.
            return BudgetEnforcementResult {
                evicted_count: 0,
                active_before,
                active_after: active_before,
            };
        }

        // Eviction key: (last_active_iter ASC, active_count ASC).
        // Stalest, least-frequently-used cuts are evicted first.
        let evict_count = excess.min(self.candidates_buf.len());

        let key = |&slot: &u32| {
            let meta = &self.metadata[slot as usize];
            (meta.last_active_iter, meta.active_count)
        };

        // Use partial sort when only a small fraction of candidates need
        // evicting; fall back to full sort otherwise.
        if evict_count < self.candidates_buf.len() / 2 {
            // select_nth_unstable_by partitions so that candidates_buf[..evict_count]
            // contains the evict_count smallest elements (in any order).
            self.candidates_buf
                .select_nth_unstable_by(evict_count, |a, b| key(a).cmp(&key(b)));
        } else {
            self.candidates_buf.sort_unstable_by_key(|a| key(a));
        }

        // Copy the eviction slice into a local Vec to release the borrow on
        // self.candidates_buf before calling deactivate, which takes &mut self.
        let to_evict: Vec<u32> = self.candidates_buf[..evict_count].to_vec();
        self.deactivate(&to_evict);

        #[allow(clippy::cast_possible_truncation)]
        let evicted_count = evict_count as u32;
        #[allow(clippy::cast_possible_truncation)]
        let active_after = self.active_count() as u32;

        BudgetEnforcementResult {
            evicted_count,
            active_before,
            active_after,
        }
    }
}

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

    #[test]
    fn new_creates_pool_with_correct_capacity_and_all_inactive() {
        let pool = CutPool::new(100, 9, 10, 0);
        assert_eq!(pool.capacity, 100);
        assert_eq!(pool.state_dimension, 9);
        assert_eq!(pool.forward_passes, 10);
        assert_eq!(pool.warm_start_count, 0);
        assert_eq!(pool.populated_count, 0);
        assert_eq!(pool.active_count(), 0);
        assert!(pool.active.iter().all(|&a| !a));
        assert_eq!(pool.coefficients.len(), 100 * 9);
        assert!(pool.coefficients.iter().all(|&v| v == 0.0));
        assert!(pool.intercepts.iter().all(|&v| v == 0.0));
    }

    #[test]
    fn new_zero_capacity_is_valid() {
        let pool = CutPool::new(0, 4, 5, 0);
        assert_eq!(pool.capacity, 0);
        assert_eq!(pool.active_count(), 0);
    }

    #[test]
    fn add_cut_at_slot_zero_stores_intercept_coefficients_and_active_flag() {
        let mut pool = CutPool::new(100, 9, 10, 0);
        let coeffs = vec![1.0; 9];
        pool.add_cut(0, 0, 5.0, &coeffs);

        assert_eq!(pool.active_count(), 1);
        assert!(pool.active[0]);
        assert_eq!(pool.intercepts[0], 5.0);
        assert_eq!(&pool.coefficients[0..9], vec![1.0; 9].as_slice());
        assert_eq!(pool.metadata[0].iteration_generated, 0);
        assert_eq!(pool.metadata[0].forward_pass_index, 0);
        assert_eq!(pool.populated_count, 1);
    }

    #[test]
    fn add_cut_deterministic_slot_formula_no_warmstart() {
        // slot = 0 + iteration * forward_passes + forward_pass_index
        let mut pool = CutPool::new(200, 2, 10, 0);

        pool.add_cut(0, 0, 1.0, &[1.0, 2.0]); // slot = 0
        pool.add_cut(0, 3, 2.0, &[3.0, 4.0]); // slot = 3
        pool.add_cut(1, 0, 3.0, &[5.0, 6.0]); // slot = 10
        pool.add_cut(2, 5, 4.0, &[7.0, 8.0]); // slot = 25

        assert!(pool.active[0]);
        assert_eq!(pool.intercepts[0], 1.0);

        assert!(pool.active[3]);
        assert_eq!(pool.intercepts[3], 2.0);

        assert!(pool.active[10]);
        assert_eq!(pool.intercepts[10], 3.0);

        assert!(pool.active[25]);
        assert_eq!(pool.intercepts[25], 4.0);
    }

    #[test]
    fn add_cut_warm_start_count_offsets_slot() {
        // slot = 5 + 0*10 + 0 = 5
        let mut pool = CutPool::new(100, 9, 10, 5);
        let coeffs = vec![0.0; 9];
        pool.add_cut(0, 0, 42.0, &coeffs);

        assert!(pool.active[5]);
        assert_eq!(pool.intercepts[5], 42.0);
        assert_eq!(pool.populated_count, 6);
    }

    #[test]
    fn add_cut_metadata_initialized_correctly() {
        let mut pool = CutPool::new(50, 3, 5, 0);
        pool.add_cut(3, 2, 7.0, &[1.0, 2.0, 3.0]);
        // slot = 0 + 3*5 + 2 = 17
        let meta = &pool.metadata[17];
        assert_eq!(meta.iteration_generated, 3);
        assert_eq!(meta.forward_pass_index, 2);
        assert_eq!(meta.active_count, 0);
        assert_eq!(meta.last_active_iter, 3);
    }

    #[test]
    fn populated_count_tracks_high_water_mark() {
        let mut pool = CutPool::new(50, 1, 5, 0);

        pool.add_cut(0, 0, 1.0, &[1.0]); // slot 0 → populated_count = 1
        assert_eq!(pool.populated_count, 1);

        pool.add_cut(1, 0, 2.0, &[2.0]); // slot 5 → populated_count = 6
        assert_eq!(pool.populated_count, 6);

        pool.add_cut(0, 2, 3.0, &[3.0]); // slot 2 → no change (2 < 6)
        assert_eq!(pool.populated_count, 6);
    }

    #[test]
    fn set_iteration_base_packs_training_cuts_densely() {
        // base = 1 (start_iteration 0) maps iteration 1 to slot warm_start_count
        // (0 here), so 1-based iterations leave no reserved leading block.
        let mut pool = CutPool::new(30, 1, 3, 0);
        pool.set_iteration_base(1);
        pool.add_cut(1, 0, 1.0, &[1.0]); // slot 0
        pool.add_cut(1, 1, 2.0, &[1.0]); // slot 1
        pool.add_cut(1, 2, 3.0, &[1.0]); // slot 2
        pool.add_cut(2, 0, 4.0, &[1.0]); // slot 3
        assert!(pool.active[0] && pool.active[1] && pool.active[2] && pool.active[3]);
        assert_eq!(pool.populated_count, 4, "dense packing leaves no gap");
        assert_eq!(pool.generated_count, 4);
        // metadata keeps the TRUE iteration, not the re-based slot iteration.
        assert_eq!(pool.metadata[0].iteration_generated, 1);
        assert_eq!(pool.metadata[3].iteration_generated, 2);
    }

    #[test]
    fn active_cuts_returns_only_active_cuts() {
        let mut pool = CutPool::new(20, 2, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0, 2.0]); // slot 0
        pool.add_cut(1, 0, 2.0, &[3.0, 4.0]); // slot 1
        pool.add_cut(2, 0, 3.0, &[5.0, 6.0]); // slot 2

        pool.deactivate(&[1]);

        let active: Vec<_> = pool.active_cuts().collect();
        assert_eq!(active.len(), 2);

        let slots: Vec<usize> = active.iter().map(|(s, _, _)| *s).collect();
        assert!(slots.contains(&0));
        assert!(slots.contains(&2));
        assert!(!slots.contains(&1));
    }

    #[test]
    fn active_cuts_empty_pool_returns_empty_iterator() {
        let pool = CutPool::new(10, 3, 5, 0);
        let active: Vec<_> = pool.active_cuts().collect();
        assert!(active.is_empty());
    }

    #[test]
    fn active_count_is_correct_after_add_and_deactivate() {
        let mut pool = CutPool::new(20, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]); // slot 0
        pool.add_cut(1, 0, 2.0, &[2.0]); // slot 1
        pool.add_cut(2, 0, 3.0, &[3.0]); // slot 2

        assert_eq!(pool.active_count(), 3);
        pool.deactivate(&[1]);
        assert_eq!(pool.active_count(), 2);
    }

    #[test]
    fn deactivate_sets_flags_correctly() {
        let mut pool = CutPool::new(20, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]); // slot 0
        pool.add_cut(1, 0, 2.0, &[2.0]); // slot 1
        pool.add_cut(2, 0, 3.0, &[3.0]); // slot 2

        pool.deactivate(&[1]);

        assert!(pool.active[0]);
        assert!(!pool.active[1]);
        assert!(pool.active[2]);
        assert_eq!(pool.active_count(), 2);
    }

    #[test]
    fn deactivate_multiple_indices() {
        let mut pool = CutPool::new(20, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]); // slot 0
        pool.add_cut(1, 0, 2.0, &[2.0]); // slot 1
        pool.add_cut(2, 0, 3.0, &[3.0]); // slot 2

        pool.deactivate(&[0, 2]);

        assert!(!pool.active[0]);
        assert!(pool.active[1]);
        assert!(!pool.active[2]);
        assert_eq!(pool.active_count(), 1);
    }

    #[test]
    fn deactivate_empty_slice_is_noop() {
        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]);
        pool.deactivate(&[]);
        assert_eq!(pool.active_count(), 1);
    }

    /// `deactivate` silently skips already-inactive indices.
    ///
    /// In debug builds the `debug_assert!` would fire on a duplicate
    /// input, so the test is gated to release-only. When a release
    /// build receives `&[0, 0, 0]`, the active count drops by exactly
    /// 1 (not 3) and `active[0]` becomes `false`.
    #[test]
    #[cfg(not(debug_assertions))]
    fn deactivate_duplicate_index_is_silently_skipped() {
        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]);
        pool.add_cut(1, 0, 2.0, &[2.0]);
        assert_eq!(pool.active_count(), 2);
        pool.deactivate(&[0, 0, 0]);
        assert_eq!(
            pool.active_count(),
            1,
            "duplicate indices must not double-decrement"
        );
        assert!(!pool.active[0]);
        assert!(pool.active[1]);
    }

    #[test]
    fn evaluate_at_state_returns_max_cut_value() {
        // cuts: (intercept=10, coeffs=[1, 0]) and (intercept=5, coeffs=[0, 2])
        // state = [3, 4]
        // cut 0: 10 + 1*3 + 0*4 = 13
        // cut 1:  5 + 0*3 + 2*4 = 13
        // max = 13
        let mut pool = CutPool::new(10, 2, 1, 0);
        pool.add_cut(0, 0, 10.0, &[1.0, 0.0]);
        pool.add_cut(1, 0, 5.0, &[0.0, 2.0]);

        let result = pool.evaluate_at_state(&[3.0, 4.0]);
        assert_eq!(result, 13.0);
    }

    #[test]
    fn evaluate_at_state_selects_correct_max() {
        // cut 0: intercept=2, coeffs=[1] → at state [10]: 2 + 10 = 12
        // cut 1: intercept=5, coeffs=[2] → at state [10]: 5 + 20 = 25
        // max = 25
        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 2.0, &[1.0]);
        pool.add_cut(1, 0, 5.0, &[2.0]);

        let result = pool.evaluate_at_state(&[10.0]);
        assert_eq!(result, 25.0);
    }

    #[test]
    fn evaluate_at_state_empty_pool_returns_neg_infinity() {
        let pool = CutPool::new(10, 3, 5, 0);
        assert_eq!(pool.evaluate_at_state(&[1.0, 2.0, 3.0]), f64::NEG_INFINITY);
    }

    #[test]
    fn evaluate_at_state_all_deactivated_returns_neg_infinity() {
        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 100.0, &[1.0]);
        pool.deactivate(&[0]);
        assert_eq!(pool.evaluate_at_state(&[5.0]), f64::NEG_INFINITY);
    }

    #[test]
    fn evaluate_at_state_ignores_deactivated_cuts() {
        // slot 0: active, intercept=10, coeff=[1]  → at state [3]: 13
        // slot 1: INACTIVE, intercept=100, coeff=[1] → would be 103, but ignored
        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 10.0, &[1.0]);
        pool.add_cut(1, 0, 100.0, &[1.0]);
        pool.deactivate(&[1]);

        assert_eq!(pool.evaluate_at_state(&[3.0]), 13.0);
    }

    #[test]
    fn ac_add_cut_stores_at_slot_zero_and_active_count_is_one() {
        // Given CutPool::new(100, 9, 10, 0), when add_cut(0, 0, ...) is called,
        // then the cut is stored at slot 0 and active_count() returns 1.
        let mut pool = CutPool::new(100, 9, 10, 0);
        let coeffs = vec![0.0; 9];
        pool.add_cut(0, 0, 5.0, &coeffs);

        assert!(pool.active[0]);
        assert_eq!(pool.active_count(), 1);
    }

    #[test]
    fn ac_deactivate_reduces_active_count_correctly() {
        // Given a pool with 3 cuts at slots 0, 1, 2, when deactivate(&[1]) is
        // called, then active_count() returns 2 and slot 1 is inactive.
        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]);
        pool.add_cut(1, 0, 2.0, &[2.0]);
        pool.add_cut(2, 0, 3.0, &[3.0]);

        pool.deactivate(&[1]);

        assert_eq!(pool.active_count(), 2);
        assert!(!pool.active[1]);
    }

    #[test]
    fn ac_evaluate_at_state_returns_correct_max() {
        // cuts: (intercept=10, coeffs=[1,0]) and (intercept=5, coeffs=[0,2])
        // state=[3,4] → max(10+3, 5+8) = max(13, 13) = 13
        let mut pool = CutPool::new(10, 2, 1, 0);
        pool.add_cut(0, 0, 10.0, &[1.0, 0.0]);
        pool.add_cut(1, 0, 5.0, &[0.0, 2.0]);

        assert_eq!(pool.evaluate_at_state(&[3.0, 4.0]), 13.0);
    }

    #[test]
    fn ac_warm_start_count_offsets_slot() {
        // Given CutPool::new(100, 9, 10, 5), when add_cut(0, 0, ...) is called,
        // then slot = 5 + 0*10 + 0 = 5.
        let mut pool = CutPool::new(100, 9, 10, 5);
        let coeffs = vec![0.0; 9];
        pool.add_cut(0, 0, 1.0, &coeffs);

        assert!(pool.active[5]);
        assert!(!pool.active[0]);
    }

    #[test]
    fn ac_empty_pool_evaluate_returns_neg_infinity() {
        // Given an empty pool, evaluate_at_state returns NEG_INFINITY.
        let pool = CutPool::new(10, 2, 1, 0);
        assert_eq!(pool.evaluate_at_state(&[1.0, 2.0]), f64::NEG_INFINITY);
    }

    #[test]
    fn cut_pool_derives_debug_and_clone() {
        let mut pool = CutPool::new(5, 2, 1, 0);
        pool.add_cut(0, 0, 3.0, &[1.0, 2.0]);

        let cloned = pool.clone();
        assert_eq!(cloned.active_count(), 1);
        assert_eq!(cloned.intercepts[0], 3.0);

        let debug_str = format!("{pool:?}");
        assert!(!debug_str.is_empty());
    }

    // ── SparsityReport tests ──────────────────────────────────────────

    #[test]
    fn sparsity_report_empty_pool() {
        let pool = CutPool::new(10, 3, 1, 0);
        let report = pool.sparsity_report();
        assert_eq!(report.total_coefficients, 0);
        assert_eq!(report.exact_zero_count, 0);
        assert!((report.sparsity_fraction - 0.0).abs() < f64::EPSILON);
        assert_eq!(report.per_dimension_zeros, vec![0, 0, 0]);
    }

    #[test]
    fn sparsity_report_all_nonzero() {
        let mut pool = CutPool::new(10, 3, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0, 2.0, 3.0]);
        pool.add_cut(1, 0, 2.0, &[4.0, 5.0, 6.0]);

        let report = pool.sparsity_report();
        assert_eq!(report.total_coefficients, 6);
        assert_eq!(report.exact_zero_count, 0);
        assert!((report.sparsity_fraction - 0.0).abs() < f64::EPSILON);
        assert_eq!(report.per_dimension_zeros, vec![0, 0, 0]);
    }

    #[test]
    fn sparsity_report_all_zero() {
        let mut pool = CutPool::new(10, 3, 1, 0);
        pool.add_cut(0, 0, 1.0, &[0.0, 0.0, 0.0]);
        pool.add_cut(1, 0, 2.0, &[0.0, 0.0, 0.0]);

        let report = pool.sparsity_report();
        assert_eq!(report.total_coefficients, 6);
        assert_eq!(report.exact_zero_count, 6);
        assert!((report.sparsity_fraction - 1.0).abs() < f64::EPSILON);
        assert_eq!(report.per_dimension_zeros, vec![2, 2, 2]);
    }

    #[test]
    fn sparsity_report_mixed() {
        let mut pool = CutPool::new(10, 3, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0, 0.0, 2.0]);
        pool.add_cut(1, 0, 2.0, &[0.0, 0.0, 3.0]);

        let report = pool.sparsity_report();
        assert_eq!(report.total_coefficients, 6);
        assert_eq!(report.exact_zero_count, 3);
        assert!((report.sparsity_fraction - 0.5).abs() < 1e-10);
        assert_eq!(report.per_dimension_zeros, vec![1, 2, 0]);
    }

    #[test]
    fn sparsity_report_excludes_inactive_cuts() {
        let mut pool = CutPool::new(10, 2, 1, 0);
        pool.add_cut(0, 0, 1.0, &[0.0, 0.0]); // all zero, then deactivate
        pool.add_cut(1, 0, 2.0, &[1.0, 2.0]); // all non-zero
        pool.deactivate(&[0]);

        let report = pool.sparsity_report();
        // Only the second cut is active.
        assert_eq!(report.total_coefficients, 2);
        assert_eq!(report.exact_zero_count, 0);
        assert!((report.sparsity_fraction - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn sparsity_report_per_dimension_zeros_correct() {
        let mut pool = CutPool::new(10, 4, 1, 0);
        // Cut 0: dims 0,2 are zero
        pool.add_cut(0, 0, 1.0, &[0.0, 1.0, 0.0, 3.0]);
        // Cut 1: dims 0,3 are zero
        pool.add_cut(1, 0, 2.0, &[0.0, 2.0, 4.0, 0.0]);
        // Cut 2: no zeros
        pool.add_cut(2, 0, 3.0, &[5.0, 6.0, 7.0, 8.0]);

        let report = pool.sparsity_report();
        assert_eq!(report.total_coefficients, 12);
        assert_eq!(report.exact_zero_count, 4);
        assert_eq!(report.per_dimension_zeros, vec![2, 0, 1, 1]);
    }

    #[test]
    fn warm_start_cuts_have_sentinel_iteration() {
        use crate::cut::WARM_START_ITERATION;
        use cobre_io::OwnedPolicyCutRecord;

        let records = vec![
            OwnedPolicyCutRecord {
                cut_id: 0,
                slot_index: 0,
                coefficients: vec![1.0, 2.0],
                intercept: 10.0,
                is_active: true,
                iteration: 5,
                forward_pass_index: 0,
            },
            OwnedPolicyCutRecord {
                cut_id: 1,
                slot_index: 1,
                coefficients: vec![3.0, 4.0],
                intercept: 20.0,
                is_active: true,
                iteration: 7,
                forward_pass_index: 1,
            },
        ];

        let pool = CutPool::new_with_warm_start(2, 4, 100, &records);
        assert_eq!(pool.warm_start_count, 2);
        assert_eq!(pool.populated_count, 2);
        // Both warm-start cuts must use the sentinel value.
        assert_eq!(pool.metadata[0].iteration_generated, WARM_START_ITERATION);
        assert_eq!(pool.metadata[1].iteration_generated, WARM_START_ITERATION);
        // The original iteration is preserved in last_active_iter for
        // informational purposes (checkpoint round-trip).
        assert_eq!(pool.metadata[0].last_active_iter, 5);
        assert_eq!(pool.metadata[1].last_active_iter, 7);
    }

    #[test]
    fn terminal_has_boundary_cuts_when_warm_start_count_positive() {
        // A pool with warm_start_count > 0 signals boundary cuts at the
        // terminal stage.
        use cobre_io::OwnedPolicyCutRecord;

        let records = vec![OwnedPolicyCutRecord {
            cut_id: 0,
            slot_index: 0,
            coefficients: vec![1.0],
            intercept: 5.0,
            is_active: true,
            iteration: 0,
            forward_pass_index: 0,
        }];
        let pool = CutPool::new_with_warm_start(1, 4, 100, &records);
        assert!(pool.warm_start_count > 0, "terminal pool has boundary cuts");
    }

    #[test]
    fn no_boundary_cuts_when_warm_start_count_zero() {
        let pool = CutPool::new(100, 2, 10, 0);
        assert_eq!(pool.warm_start_count, 0, "no boundary cuts");
    }

    // ── enforce_budget tests ────────────────────────────────────────────────

    #[test]
    fn enforce_budget_noop_when_under_budget() {
        let mut pool = CutPool::new(100, 2, 10, 0);
        pool.add_cut(0, 0, 1.0, &[1.0, 2.0]);
        pool.add_cut(0, 1, 2.0, &[3.0, 4.0]);
        assert_eq!(pool.active_count(), 2);
        let result = pool.enforce_budget(5, 1, 10);
        assert_eq!(result.evicted_count, 0);
        assert_eq!(result.active_after, 2);
        assert_eq!(pool.active_count(), 2);
    }

    #[test]
    fn enforce_budget_evicts_oldest_last_active_iter() {
        let mut pool = CutPool::new(100, 2, 10, 0);
        // Add 5 cuts at iterations 0-4
        for iter in 0..5_u64 {
            pool.add_cut(iter, 0, 1.0, &[1.0, 0.0]);
            // Set last_active_iter to make older cuts staler
            pool.metadata[pool.populated_count - 1].last_active_iter = iter;
        }
        assert_eq!(pool.active_count(), 5);
        // Budget = 3, current_iteration = 5 → evict 2 oldest
        let result = pool.enforce_budget(3, 5, 10);
        assert_eq!(result.evicted_count, 2);
        assert_eq!(result.active_after, 3);
        assert_eq!(pool.active_count(), 3);
        // The 2 oldest (last_active_iter 0 and 1) should be evicted
        // Slot for (iter=0, fp=0) = 0*10+0 = 0
        // Slot for (iter=1, fp=0) = 1*10+0 = 10
        assert!(!pool.active[0], "oldest cut should be evicted");
        assert!(!pool.active[10], "second oldest should be evicted");
    }

    #[test]
    fn enforce_budget_tiebreaks_by_active_count() {
        let mut pool = CutPool::new(100, 2, 10, 0);
        // Two cuts with same last_active_iter but different active_count
        pool.add_cut(0, 0, 1.0, &[1.0, 0.0]);
        pool.metadata[0].last_active_iter = 1;
        pool.metadata[0].active_count = 5;
        pool.add_cut(0, 1, 2.0, &[0.0, 1.0]);
        pool.metadata[1].last_active_iter = 1;
        pool.metadata[1].active_count = 2;
        assert_eq!(pool.active_count(), 2);
        // Budget = 1 → evict the one with lower active_count (slot 1)
        let result = pool.enforce_budget(1, 1, 10);
        assert_eq!(result.evicted_count, 1);
        assert!(pool.active[0], "higher active_count survives");
        assert!(!pool.active[1], "lower active_count evicted");
    }

    #[test]
    fn enforce_budget_protects_current_iteration() {
        let mut pool = CutPool::new(100, 2, 10, 0);
        // 3 cuts: 2 from iteration 0, 1 from iteration 1 (current)
        pool.add_cut(0, 0, 1.0, &[1.0, 0.0]);
        pool.metadata[0].last_active_iter = 0;
        pool.add_cut(0, 1, 2.0, &[0.0, 1.0]);
        pool.metadata[1].last_active_iter = 0;
        pool.add_cut(1, 0, 3.0, &[1.0, 1.0]);
        pool.metadata[10].last_active_iter = 1;
        assert_eq!(pool.active_count(), 3);
        // Budget = 1, current_iteration = 1 → can only evict iter-0 cuts
        let result = pool.enforce_budget(1, 1, 10);
        assert_eq!(result.evicted_count, 2);
        // Current-iteration cut (slot 10) survives
        assert!(pool.active[10], "current iteration cut preserved");
    }

    #[test]
    fn enforce_budget_all_current_iteration_no_eviction() {
        let mut pool = CutPool::new(100, 2, 10, 0);
        // All cuts from current iteration
        pool.add_cut(5, 0, 1.0, &[1.0, 0.0]);
        pool.add_cut(5, 1, 2.0, &[0.0, 1.0]);
        pool.add_cut(5, 2, 3.0, &[1.0, 1.0]);
        assert_eq!(pool.active_count(), 3);
        // Budget = 1, current_iteration = 5 → no candidates, no eviction
        let result = pool.enforce_budget(1, 5, 10);
        assert_eq!(result.evicted_count, 0);
        assert_eq!(pool.active_count(), 3);
    }

    #[test]
    fn enforce_budget_result_fields() {
        let mut pool = CutPool::new(100, 2, 10, 0);
        pool.add_cut(0, 0, 1.0, &[1.0, 0.0]);
        pool.add_cut(1, 0, 2.0, &[0.0, 1.0]);
        pool.add_cut(2, 0, 3.0, &[1.0, 1.0]);
        assert_eq!(pool.active_count(), 3);
        let result = pool.enforce_budget(1, 3, 10);
        assert_eq!(result.active_before, 3);
        assert_eq!(result.evicted_count, 2);
        assert_eq!(result.active_after, 1);
    }

    // ── active_cuts early-exit tests ─────────────────────────────────────────

    /// Verify that `active_cuts()` stops iterating once all active cuts have
    /// been yielded — it must not scan up to `populated_count` when
    /// `cached_active_count` is small.
    ///
    /// Pool has `populated_count = 100` and only slot 0 is active
    /// (`cached_active_count = 1`).  The early-exit iterator must stop after
    /// visiting slot 0, yielding exactly 1 item.  If the old O(populated)
    /// walk were still in place the count would still be 1, but the
    /// scan-based implementation verifies correctness by construction:
    /// `remaining` hits 0 after the first active slot and `scan` returns
    /// `None` for all subsequent elements, preventing any further polling.
    #[test]
    fn active_cuts_early_exit_stops_at_cached_count() {
        // forward_passes = 1 so slot = warm_start_count + iteration * 1 + fp_index
        let mut pool = CutPool::new(100, 2, 1, 0);

        // Add a cut at slot 0 (iteration 0, fp 0).
        pool.add_cut(0, 0, 5.0, &[1.0, 2.0]);

        // Manually populate a further 99 slots as inactive to extend
        // populated_count to 100 without going through add_cut (which marks
        // them active).  We write directly to the active flag so that
        // populated_count is extended to 100 while cached_active_count stays 1.
        //
        // We do this by exploiting that slot_index(i, 0) = i * 1 + 0 = i.
        // We need slot 99 to be "populated" (high-water mark = 100) so that
        // the old O(populated) walk would have to visit all 100 slots.
        pool.populated_count = 100;
        // active[0] is already true; active[1..100] are all false (default).

        assert_eq!(pool.cached_active_count, 1);
        assert_eq!(pool.populated_count, 100);

        // The iterator must yield exactly 1 item.
        let result: Vec<_> = pool.active_cuts().collect();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].0, 0, "yielded slot must be 0");
        assert_eq!(result[0].1, 5.0, "intercept must match");
        assert_eq!(result[0].2, &[1.0, 2.0], "coefficients must match");
    }

    /// Verify that `candidates_buf` retains its allocation across successive
    /// `enforce_budget` calls (i.e., the scratch buffer is reused, not dropped
    /// and reallocated each time).
    #[test]
    fn enforce_budget_candidates_buf_is_reused() {
        let mut pool = CutPool::new(100, 2, 10, 0);

        // Add cuts spread across several iterations so there are always
        // eviction candidates regardless of current_iteration.
        for iter in 0..5_u64 {
            pool.add_cut(iter, 0, 1.0, &[1.0, 0.0]);
        }
        assert_eq!(pool.active_count(), 5);

        // First enforce: evicts some cuts, candidates_buf gets populated.
        pool.enforce_budget(3, 5, 10);
        let cap_after_first = pool.candidates_buf.capacity();
        assert!(
            cap_after_first >= 1,
            "candidates_buf must have acquired capacity after first enforce_budget"
        );

        // Re-add cuts so the second call also has candidates.
        // We need iteration offsets past the existing slots; restart with a
        // new pool to keep slot arithmetic simple.
        let mut pool2 = CutPool::new(100, 2, 10, 0);
        for iter in 0..5_u64 {
            pool2.add_cut(iter, 0, 1.0, &[1.0, 0.0]);
        }
        pool2.enforce_budget(3, 5, 10);
        let cap_after_first2 = pool2.candidates_buf.capacity();

        // Second call on the same pool2 — re-add some cuts first.
        // Since slots 0, 10, 20, 30, 40 are now inactive, add at iter 6..=8.
        pool2.add_cut(6, 0, 2.0, &[0.0, 1.0]);
        pool2.add_cut(7, 0, 2.0, &[0.0, 1.0]);
        pool2.add_cut(8, 0, 2.0, &[0.0, 1.0]);
        pool2.enforce_budget(2, 9, 10);
        let cap_after_second2 = pool2.candidates_buf.capacity();

        // The capacity must not have shrunk — Vec::clear() preserves the heap
        // allocation, so the second call reuses the buffer.
        assert!(
            cap_after_second2 >= cap_after_first2,
            "candidates_buf capacity must not shrink across calls (was {cap_after_first2}, now {cap_after_second2})"
        );
    }

    // ── set_active / cuts_in_lp tests ────────────────────────────────────────

    #[test]
    fn set_active_false_decrements_active_count() {
        let mut pool = CutPool::new(10, 4, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0, 0.0, 0.0, 0.0]);
        pool.add_cut(1, 0, 2.0, &[0.0, 1.0, 0.0, 0.0]);
        pool.add_cut(2, 0, 3.0, &[0.0, 0.0, 1.0, 0.0]);

        pool.set_active(1, false);

        assert!(!pool.active[1]);
        assert_eq!(pool.active_count(), 2);
        assert_eq!(pool.cuts_in_lp(), 3);
    }

    #[test]
    fn set_active_true_reactivates_deactivated_slot() {
        let mut pool = CutPool::new(10, 4, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0, 0.0, 0.0, 0.0]);
        pool.add_cut(1, 0, 2.0, &[0.0, 1.0, 0.0, 0.0]);
        pool.add_cut(2, 0, 3.0, &[0.0, 0.0, 1.0, 0.0]);
        pool.deactivate(&[1]);

        pool.set_active(1, true);

        assert!(pool.active[1]);
        assert_eq!(pool.active_count(), 3);
        assert_eq!(pool.cuts_in_lp(), 3);
    }

    #[test]
    fn set_active_idempotent_when_state_unchanged() {
        let mut pool = CutPool::new(10, 4, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0, 0.0, 0.0, 0.0]);
        pool.add_cut(1, 0, 2.0, &[0.0, 1.0, 0.0, 0.0]);
        pool.add_cut(2, 0, 3.0, &[0.0, 0.0, 1.0, 0.0]);

        // slot 1 is already active — second call must be a no-op
        pool.set_active(1, true);
        pool.set_active(1, true);

        assert_eq!(pool.active_count(), 3);
    }

    #[test]
    fn deactivate_delegates_to_set_active() {
        let mut pool_a = CutPool::new(10, 4, 1, 0);
        pool_a.add_cut(0, 0, 1.0, &[1.0, 0.0, 0.0, 0.0]);
        pool_a.add_cut(1, 0, 2.0, &[0.0, 1.0, 0.0, 0.0]);
        pool_a.add_cut(2, 0, 3.0, &[0.0, 0.0, 1.0, 0.0]);
        pool_a.deactivate(&[1, 2]);

        let mut pool_b = CutPool::new(10, 4, 1, 0);
        pool_b.add_cut(0, 0, 1.0, &[1.0, 0.0, 0.0, 0.0]);
        pool_b.add_cut(1, 0, 2.0, &[0.0, 1.0, 0.0, 0.0]);
        pool_b.add_cut(2, 0, 3.0, &[0.0, 0.0, 1.0, 0.0]);
        pool_b.set_active(1, false);
        pool_b.set_active(2, false);

        assert_eq!(pool_a.active, pool_b.active);
        assert_eq!(pool_a.cached_active_count, pool_b.cached_active_count);
    }

    #[test]
    fn cuts_in_lp_returns_populated_count() {
        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]);
        pool.add_cut(1, 0, 2.0, &[2.0]);

        assert_eq!(pool.cuts_in_lp(), 2);
        assert_eq!(pool.cuts_in_lp(), pool.populated_count);

        pool.deactivate(&[0]);

        // Deactivation must not change the populated count.
        assert_eq!(pool.cuts_in_lp(), 2);
        assert_eq!(pool.active_count(), 1);
    }

    // ── apply_updates tests ──────────────────────────────────────────────────

    /// `apply_updates` deactivates every slot in `updates.updates` and
    /// reactivates every slot in `updates.reactivations`. Mixed batches
    /// must leave the pool in the expected state and the cached counter
    /// must match the bitmap.
    #[test]
    fn apply_updates_applies_mixed_deactivate_and_reactivate() {
        use crate::cut_selection::CutActivityUpdates;

        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]); // slot 0 active
        pool.add_cut(1, 0, 2.0, &[2.0]); // slot 1 active
        pool.add_cut(2, 0, 3.0, &[3.0]); // slot 2 active
        pool.add_cut(3, 0, 4.0, &[4.0]); // slot 3 active

        // Pre-deactivate slot 2 so the reactivation has something to flip.
        pool.deactivate(&[2]);
        assert_eq!(pool.active_count(), 3);
        assert!(!pool.active[2]);

        let updates = CutActivityUpdates {
            stage_index: 0,
            updates: vec![0, 3],    // deactivate slots 0 and 3
            reactivations: vec![2], // reactivate slot 2
        };
        pool.apply_updates(&updates);

        assert!(!pool.active[0], "slot 0 must be deactivated");
        assert!(pool.active[1], "slot 1 must remain active");
        assert!(pool.active[2], "slot 2 must be reactivated");
        assert!(!pool.active[3], "slot 3 must be deactivated");
        assert_eq!(pool.active_count(), 2);
        // cuts_in_lp is unaffected by activity changes.
        assert_eq!(pool.cuts_in_lp(), 4);
    }

    /// `apply_updates` must be idempotent: applying the same updates twice
    /// must leave the pool in the same state as applying it once. This
    /// follows from `set_active`'s "already-in-target-state is a no-op"
    /// contract.
    #[test]
    fn apply_updates_is_idempotent() {
        use crate::cut_selection::CutActivityUpdates;

        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]);
        pool.add_cut(1, 0, 2.0, &[2.0]);
        pool.add_cut(2, 0, 3.0, &[3.0]);

        // Pre-deactivate slot 1 so the reactivation has something to flip.
        pool.deactivate(&[1]);
        assert_eq!(pool.active_count(), 2);

        let updates = CutActivityUpdates {
            stage_index: 0,
            updates: vec![0],
            reactivations: vec![1],
        };

        // First application flips slot 0 off and slot 1 on.
        pool.apply_updates(&updates);
        let active_snapshot = pool.active.clone();
        let count_snapshot = pool.active_count();

        // Second application: every requested state already holds → no-op.
        pool.apply_updates(&updates);
        assert_eq!(
            pool.active, active_snapshot,
            "active bitmap must not change"
        );
        assert_eq!(
            pool.active_count(),
            count_snapshot,
            "active count must not change"
        );
        assert_eq!(pool.active_count(), 2);
        assert!(!pool.active[0]);
        assert!(pool.active[1]);
        assert!(pool.active[2]);
    }

    /// `apply_updates` on an empty `CutActivityUpdates` must be a no-op.
    #[test]
    fn apply_updates_empty_is_noop() {
        use crate::cut_selection::CutActivityUpdates;

        let mut pool = CutPool::new(10, 1, 1, 0);
        pool.add_cut(0, 0, 1.0, &[1.0]);
        pool.add_cut(1, 0, 2.0, &[2.0]);
        let active_before = pool.active.clone();
        let count_before = pool.active_count();

        let updates = CutActivityUpdates {
            stage_index: 0,
            updates: vec![],
            reactivations: vec![],
        };
        pool.apply_updates(&updates);

        assert_eq!(pool.active, active_before);
        assert_eq!(pool.active_count(), count_before);
    }

    /// `apply_updates` must match the behavior of calling `set_active`
    /// directly for each entry, regardless of which list (`updates` or
    /// `reactivations`) drives the change.
    #[test]
    fn apply_updates_matches_manual_set_active_loop() {
        use crate::cut_selection::CutActivityUpdates;

        let build_pool = || {
            let mut pool = CutPool::new(10, 1, 1, 0);
            pool.add_cut(0, 0, 1.0, &[1.0]);
            pool.add_cut(1, 0, 2.0, &[2.0]);
            pool.add_cut(2, 0, 3.0, &[3.0]);
            pool.add_cut(3, 0, 4.0, &[4.0]);
            pool.deactivate(&[2]); // pre-deactivate so reactivation flips a bit
            pool
        };

        let updates = CutActivityUpdates {
            stage_index: 0,
            updates: vec![0, 3],
            reactivations: vec![2],
        };

        let mut pool_a = build_pool();
        pool_a.apply_updates(&updates);

        let mut pool_b = build_pool();
        for &slot in &updates.updates {
            pool_b.set_active(slot, false);
        }
        for &slot in &updates.reactivations {
            pool_b.set_active(slot, true);
        }

        assert_eq!(pool_a.active, pool_b.active);
        assert_eq!(pool_a.cached_active_count, pool_b.cached_active_count);
    }
}