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
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
//! Per-thread solver workspace, workspace pool, and per-scenario basis store.
//!
//! [`SolverWorkspace`] bundles all mutable per-thread resources needed for one LP solve sequence.
//! [`WorkspacePool`] allocates one workspace per worker thread.
//! [`BasisStore`] provides per-scenario, per-stage basis storage for warm-starting LP solves.

use cobre_solver::{Basis, ProfiledSolver, SolverInterface};

use crate::backward::StagedCut;
use crate::dcs::DcsSolveScratch;
use crate::lp_builder::PatchBuffer;
use crate::risk_measure::{BackwardOutcome, RiskMeasureScratch};

// ---------------------------------------------------------------------------
// CapturedBasis
// ---------------------------------------------------------------------------

/// A solver basis augmented with slot-tracking metadata for cut-set-aware
/// warm-start reconstruction.
///
/// `CapturedBasis` wraps a raw [`Basis`] and attaches two pieces of metadata
/// that the reconstruction algorithm needs:
///
/// - `base_row_count`: the number of template (non-cut) rows in the LP when
///   the basis was captured.  Row statuses at indices `0..base_row_count`
///   belong to template rows and are always valid.
///
/// - `cut_row_slots`: maps each cut row in the captured basis to the cut pool
///   slot it occupied at capture time.  Entry `i` corresponds to LP row
///   `base_row_count + i`.  Length must equal
///   `basis.row_status.len() - base_row_count` when both are populated;
///
/// - `state_at_capture`: the state vector `x_hat` at which the basis was
///   captured.  Used by the backward warm-start to evaluate newly added cuts
///   at the correct operating point.
///
/// # Zero-allocation design
///
/// `cut_row_slots` and `state_at_capture` are sized via explicit capacity
/// parameters in [`CapturedBasis::new`] so the forward capture site can
/// pre-allocate once and reuse the same `CapturedBasis` on subsequent
/// iterations without heap reallocation.
#[derive(Clone, Debug)]
pub struct CapturedBasis {
    /// The underlying solver basis (row and column statuses).
    pub basis: Basis,
    /// Number of template (non-cut) LP rows at capture time.
    pub base_row_count: usize,
    /// Cut pool slot for each cut row in `basis.row_status[base_row_count..]`.
    pub cut_row_slots: Vec<u32>,
    /// State vector `x_hat` at which this basis was captured.
    pub state_at_capture: Vec<f64>,
}

/// Wire-format version for `CapturedBasis` broadcast payloads.
///
/// Stored as the second `i32` in every `Some`-path payload, immediately
/// after the presence sentinel (`1_i32`). Bump this constant and update
/// `try_from_broadcast_payload` whenever the field layout changes.
///
/// Version 1 carries: column statuses, template-row statuses, cut-row
/// statuses, `cut_row_slots`, and `state_at_capture`. `cut_row_slots` is
/// load-bearing on the reconstruction path — `build_slot_lookup` reads
/// it to bind stored cut-row statuses to target-LP cut rows by slot id.
/// `state_at_capture` carries a real captured state only on the baked
/// path: there it is written by the forward capture and refreshed by the
/// backward reuse path. The DCS arm captures no basis by design (a captured
/// basis would describe the baked layout, not the DCS resident subset — see
/// `StageOpeningSolver::solve_lazy` in `backward.rs`), so on that arm the
/// field is diagnostic-only and is never part of a consumed warm-start.
/// Even on the baked path it is not read by any current reconstruction
/// reader; it is retained for diagnostic value and to preserve the option
/// of re-introducing a state-dependent reuse policy without a wire-format
/// change.
pub const BASIS_BROADCAST_WIRE_VERSION: i32 = 1;

impl CapturedBasis {
    /// Construct an empty `CapturedBasis` with the given capacities.
    ///
    /// - `num_cols` / `num_rows`: forwarded to [`Basis::new`].
    /// - `base_row_count`: stored as-is; typically `ctx.templates[t].num_rows`.
    /// - `cut_slot_capacity`: pre-allocated capacity for `cut_row_slots`
    ///   (`basis_row_capacity - base_row_count` in the forward pass).
    /// - `n_state`: pre-allocated capacity for `state_at_capture`.
    ///
    /// `cut_row_slots` and `state_at_capture` start empty (length 0);
    #[must_use]
    pub fn new(
        num_cols: usize,
        num_rows: usize,
        base_row_count: usize,
        cut_slot_capacity: usize,
        n_state: usize,
    ) -> Self {
        Self {
            basis: Basis::new(num_cols, num_rows),
            base_row_count,
            cut_row_slots: Vec::with_capacity(cut_slot_capacity),
            state_at_capture: Vec::with_capacity(n_state),
        }
    }

    /// Clear slot and state metadata in place.
    ///
    /// Does **not** touch `basis` — the solver's `get_basis` call overwrites
    /// that on the next capture.  Keeps the allocated capacity of both vectors
    /// so subsequent pushes are allocation-free.
    pub fn clear(&mut self) {
        self.cut_row_slots.clear();
        self.state_at_capture.clear();
    }

    /// Append this basis's wire-format payload to the output buffers.
    ///
    /// The layout mirrors the pack loop in
    /// `broadcast_basis_cache` (`training/training.rs`). This method is the
    /// type-level owner of the wire format; any future change must
    /// update both this method and
    /// [`CapturedBasis::try_from_broadcast_payload`] together.
    ///
    /// Pushes the following into `i32_buf` in order:
    /// - `1_i32` sentinel (present)
    /// - [`BASIS_BROADCAST_WIRE_VERSION`] as `i32` (wire version)
    /// - `col_status.len()` as `i32`
    /// - `row_status.len()` as `i32`
    /// - `base_row_count` as `i32`
    /// - `cut_row_slots.len()` as `i32`
    /// - `state_at_capture.len()` as `i32`
    /// - `col_status[..]`
    /// - `row_status[..]`
    /// - `cut_row_slots[..]` cast to `i32`
    ///
    /// Pushes `state_at_capture[..]` into `f64_buf`.
    ///
    /// The callers (currently `broadcast_basis_cache`) are
    /// responsible for writing the `0_i32` "no basis" sentinel
    /// when `Option<CapturedBasis>` is `None`.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    pub fn to_broadcast_payload(&self, i32_buf: &mut Vec<i32>, f64_buf: &mut Vec<f64>) {
        i32_buf.push(1_i32);
        i32_buf.push(BASIS_BROADCAST_WIRE_VERSION);
        i32_buf.push(self.basis.col_status.len() as i32);
        i32_buf.push(self.basis.row_status.len() as i32);
        i32_buf.push(self.base_row_count as i32);
        i32_buf.push(self.cut_row_slots.len() as i32);
        i32_buf.push(self.state_at_capture.len() as i32);
        i32_buf.extend_from_slice(&self.basis.col_status);
        i32_buf.extend_from_slice(&self.basis.row_status);
        // u32 -> i32: slot values are LP pool indices (always
        // non-negative) that fit comfortably in i32.
        for &slot in &self.cut_row_slots {
            i32_buf.push(slot as i32);
        }
        f64_buf.extend_from_slice(&self.state_at_capture);
    }

    /// Deserialise one stage's payload from the two wire-format
    /// buffers, advancing the cursors past the consumed bytes.
    ///
    /// Returns `Ok(None)` when the sentinel read is `0` (no basis
    /// for this stage). Returns `Ok(Some(captured))` when the
    /// sentinel is `1`, the version matches [`BASIS_BROADCAST_WIRE_VERSION`],
    /// and the payload is complete.
    ///
    /// # Layout (`Some` path)
    ///
    /// Reads from `i32_buf` in order:
    /// - `1_i32` sentinel (present)
    /// - [`BASIS_BROADCAST_WIRE_VERSION`] as `i32` (wire version)
    /// - `col_status.len()` as `i32`
    /// - `row_status.len()` as `i32`
    /// - `base_row_count` as `i32`
    /// - `cut_row_slots.len()` as `i32`
    /// - `state_at_capture.len()` as `i32`
    /// - `col_status[..]`
    /// - `row_status[..]`
    /// - `cut_row_slots[..]` (stored as `i32`, cast back to `u32`)
    ///
    /// Reads `state_at_capture[..]` from `f64_buf`.
    ///
    /// # Errors
    ///
    /// Returns `SddpError::Validation` if the `i32_buf` or
    /// `f64_buf` is truncated at any of the bounded reads
    /// (sentinel, version, five length fields, `col_status`, `row_status`,
    /// `cut_row_slots`, `state_at_capture`), or if the version field does
    /// not match [`BASIS_BROADCAST_WIRE_VERSION`]. The error message names
    /// the affected stage and the expected vs. available byte count.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        clippy::cast_sign_loss
    )]
    pub fn try_from_broadcast_payload(
        stage: usize,
        i32_buf: &[i32],
        i32_cursor: &mut usize,
        f64_buf: &[f64],
        f64_cursor: &mut usize,
    ) -> Result<Option<Self>, crate::SddpError> {
        // Read sentinel.
        if *i32_cursor >= i32_buf.len() {
            return Err(crate::SddpError::Validation(format!(
                "try_from_broadcast_payload: buffer truncated at stage {stage} \
                 (pos={}, len={})",
                *i32_cursor,
                i32_buf.len()
            )));
        }
        let sentinel = i32_buf[*i32_cursor];
        *i32_cursor += 1;

        if sentinel == 0 {
            return Ok(None);
        }

        // Read wire version — present only on the Some path, immediately after
        // the presence sentinel.
        if *i32_cursor >= i32_buf.len() {
            return Err(crate::SddpError::Validation(format!(
                "try_from_broadcast_payload: buffer truncated reading version at stage {stage}"
            )));
        }
        let version = i32_buf[*i32_cursor];
        *i32_cursor += 1;
        if version != BASIS_BROADCAST_WIRE_VERSION {
            return Err(crate::SddpError::Validation(format!(
                "try_from_broadcast_payload: unsupported wire version {version} at stage \
                 {stage} (expected {BASIS_BROADCAST_WIRE_VERSION})"
            )));
        }

        // Read 5 length/metadata fields: col_len, row_len, base_row_count,
        // cut_slot_count, state_len.
        if *i32_cursor + 5 > i32_buf.len() {
            return Err(crate::SddpError::Validation(format!(
                "try_from_broadcast_payload: buffer truncated reading lengths at stage {stage}"
            )));
        }
        let col_len = i32_buf[*i32_cursor] as usize;
        *i32_cursor += 1;
        let row_len = i32_buf[*i32_cursor] as usize;
        *i32_cursor += 1;
        let base_row_count = i32_buf[*i32_cursor] as usize;
        *i32_cursor += 1;
        let cut_slot_count = i32_buf[*i32_cursor] as usize;
        *i32_cursor += 1;
        let state_len = i32_buf[*i32_cursor] as usize;
        *i32_cursor += 1;

        // Read col_status.
        if *i32_cursor + col_len > i32_buf.len() {
            return Err(crate::SddpError::Validation(format!(
                "try_from_broadcast_payload: buffer truncated reading col_status at stage \
                 {stage} (need {col_len}, have {})",
                i32_buf.len() - *i32_cursor
            )));
        }
        let col_status = i32_buf[*i32_cursor..*i32_cursor + col_len].to_vec();
        *i32_cursor += col_len;

        // Read row_status.
        if *i32_cursor + row_len > i32_buf.len() {
            return Err(crate::SddpError::Validation(format!(
                "try_from_broadcast_payload: buffer truncated reading row_status at stage \
                 {stage} (need {row_len}, have {})",
                i32_buf.len() - *i32_cursor
            )));
        }
        let row_status = i32_buf[*i32_cursor..*i32_cursor + row_len].to_vec();
        *i32_cursor += row_len;

        // Read cut_row_slots (stored as i32, cast back to u32).
        if *i32_cursor + cut_slot_count > i32_buf.len() {
            return Err(crate::SddpError::Validation(format!(
                "try_from_broadcast_payload: buffer truncated reading cut_row_slots at stage \
                 {stage} (need {cut_slot_count}, have {})",
                i32_buf.len() - *i32_cursor
            )));
        }
        // cast_sign_loss: values were originally u32 LP pool indices cast to
        // i32 on the pack side; casting back to u32 is lossless.
        let cut_row_slots: Vec<u32> = i32_buf[*i32_cursor..*i32_cursor + cut_slot_count]
            .iter()
            .map(|&v| v as u32)
            .collect();
        *i32_cursor += cut_slot_count;

        // Read state_at_capture from the f64 buffer.
        if *f64_cursor + state_len > f64_buf.len() {
            return Err(crate::SddpError::Validation(format!(
                "try_from_broadcast_payload: f64 buffer truncated reading state_at_capture at \
                 stage {stage} (need {state_len}, have {})",
                f64_buf.len() - *f64_cursor
            )));
        }
        let state_at_capture = f64_buf[*f64_cursor..*f64_cursor + state_len].to_vec();
        *f64_cursor += state_len;

        Ok(Some(Self {
            basis: cobre_solver::Basis {
                col_status,
                row_status,
            },
            base_row_count,
            cut_row_slots,
            state_at_capture,
        }))
    }
}

/// Sizing parameters shared by [`SolverWorkspace`], [`WorkspacePool`], and
/// `ScratchBuffers` constructors.
///
/// Grouping these eight dimensions into one struct keeps constructor argument
/// counts within the clippy budget while making the sizing relationship
/// explicit: every workspace allocates a [`PatchBuffer`], `ScratchBuffers`,
/// and `BackwardAccumulators` from exactly these values.
///
/// Set `max_openings`, `initial_pool_capacity`, and `n_state` to `0` for
/// simulation-only workspaces that do not participate in the backward pass.
/// The `BackwardAccumulators` buffers will then start empty and grow
/// on-demand via the growth-only resize semantics in the backward pass.
#[derive(Clone, Copy, Debug, Default)]
pub struct WorkspaceSizing {
    /// Number of hydro plants in the study.
    pub hydro_count: usize,
    /// Maximum PAR order across all hydro plants.
    pub max_par_order: usize,
    /// Number of load buses (0 if no stochastic load).
    pub n_load_buses: usize,
    /// Maximum number of blocks per stage (0 if no stochastic load).
    pub max_blocks: usize,
    /// PAR order of the downstream (coarser) resolution for multi-resolution
    /// studies. Pass `0` for uniform-resolution studies (no downstream
    /// transition).
    pub downstream_par_order: usize,
    /// Maximum number of openings across all successor stages. Used to
    /// pre-size `BackwardAccumulators::outcomes`. Pass `0` for
    /// simulation-only workspaces.
    pub max_openings: usize,
    /// Initial cut pool capacity for pre-sizing
    /// `BackwardAccumulators::slot_increments`. Pass `0` for
    /// simulation-only workspaces.
    pub initial_pool_capacity: usize,
    /// State dimension `n_state` for pre-sizing
    /// `BackwardAccumulators::agg_coefficients`. Pass `0` for
    /// simulation-only workspaces.
    pub n_state: usize,
    /// Maximum number of forward-pass scenarios assigned to this rank.
    ///
    /// Used to pre-size `ScratchBuffers::trajectory_costs_buf`. Pass `0`
    /// for backward-only or simulation-only workspaces; the buffer will start
    /// empty and resize on first use.
    pub max_local_fwd: usize,
    /// Total forward passes across all MPI ranks.
    ///
    /// Used to pre-size `ScratchBuffers::perm_scratch`. Pass `0` for
    /// backward-only or simulation-only workspaces.
    pub total_forward_passes: usize,
    /// Noise dimension for forward-pass sampling buffers.
    ///
    /// Used to pre-size `ScratchBuffers::raw_noise_buf`. Pass `0` for
    /// backward-only or simulation-only workspaces.
    pub noise_dim: usize,
    /// Number of anticipated thermals (A).
    ///
    /// Used to pre-size `ScratchBuffers::anticipated_state_buf` and the
    /// `PatchBuffer` Category 6 region. Pass `0` when there are no
    /// anticipated thermals.
    pub n_anticipated: usize,
    /// Maximum lead-time horizon across anticipated thermals (K).
    ///
    /// Used together with `n_anticipated` to determine the size of the
    /// anticipated-state ring buffer. Pass `0` when there are no anticipated
    /// thermals.
    pub k_max: usize,
}

/// Pre-allocated accumulators for the backward pass trial-point loop.
///
/// Survives across stages and trial points without per-call allocation.
/// Buffers grow monotonically (never shrink) using growth-only resize
/// semantics — excess capacity from earlier stages is retained and reused.
///
/// Each rayon worker owns an exclusive [`SolverWorkspace`] and therefore an
/// exclusive `BackwardAccumulators` instance; no synchronisation is needed.
#[derive(Default)]
pub(crate) struct BackwardAccumulators {
    /// Per-opening backward outcomes. Grown monotonically to the maximum
    /// `n_openings` seen so far via `push`.
    pub(crate) outcomes: Vec<BackwardOutcome>,
    /// Per-slot binding count, indexed by cut pool slot. Grown via
    /// `.resize(pop, 0)` and zeroed per trial point via `.fill(0)`.
    pub(crate) slot_increments: Vec<u64>,
    /// Scratch buffer for aggregated cut coefficients (`n_state` entries).
    /// Written by `aggregate_weighted_into` and then copied into the
    /// per-worker [`agg_arena`](Self::agg_arena) at the trial point's slot.
    pub(crate) agg_coefficients: Vec<f64>,
    /// Per-worker flat arena holding every staged cut's coefficient vector for
    /// the current stage.
    ///
    /// Sized lazily in the per-worker stage setup to at least
    /// `(end_m - start_m) * n_state` `f64`s and **never shrunk** (capacity is
    /// retained across stages/iterations, like [`staged_cuts_buf`](Self::staged_cuts_buf)).
    /// Slot `i` of the trial point with local index `local_idx = m - start_m`
    /// lives at `agg_arena[local_idx * n_state + i]`. Each [`StagedCut`] stores
    /// a `Range<usize>` into this arena instead of an owned `Vec<f64>`; the FCF
    /// merge reads the slice after the parallel region returns (the arena is
    /// exclusive to one rayon worker during the parallel region). The content
    /// is overwritten per trial point before any read, so no zero-fill is
    /// required.
    pub(crate) agg_arena: Vec<f64>,
    /// Per-worker metadata sync contribution, indexed by cut pool slot.
    ///
    /// Accumulates binding increments across all trial points processed by
    /// this worker for a given stage. Grown via `.resize(pop, 0)` when the
    /// pool grows, and zeroed once per stage (not per trial point) via
    /// `.fill(0)`. After the parallel region the sequential merge phase sums
    /// contributions across all workers into `metadata_sync_buf`, replacing
    /// the old per-`StagedCut` `binding_increments` Vec iteration.
    pub(crate) metadata_sync_contribution: Vec<u64>,
    /// Per-opening solver-statistics accumulator for this worker.
    ///
    /// Length equals `n_openings` for the current stage. Re-initialised to
    /// `vec![Default::default(); n_openings]` once per stage at the start of
    /// the parallel region (in `process_stage_backward`). Each trial point
    /// processed by this worker adds its per-opening delta element-wise.
    /// After the parallel region the sequential merge phase sums
    /// contributions across all workers to produce the per-stage
    /// `Vec<SolverStatsDelta>` stored in `BackwardResult::stage_stats`.
    pub(crate) per_opening_stats: Vec<crate::solver_stats::SolverStatsDelta>,
    /// Per-opening scratch buffer for state-fixing-row duals.
    ///
    /// Reused across openings and trial points. Cleared via `clear()` then
    /// filled with `extend_from_slice` or `extend(iter.map(...))` at the start
    /// of each opening. Capacity grows monotonically to `indexer.n_state`; no
    /// shrink ever occurs. Avoids the per-opening `to_vec()` allocation in
    /// `process_trial_point_backward`.
    pub(crate) state_duals_buf: Vec<f64>,
    /// Per-opening scratch buffer for cut-row duals.
    ///
    /// Reused across openings and trial points. Cleared via `clear()` then
    /// filled with `extend_from_slice` at the start of each opening that has
    /// cuts. Capacity grows monotonically to `succ.num_cuts_at_successor`.
    /// Avoids the per-opening `to_vec()` or `Vec::new()` allocation in
    /// `process_trial_point_backward`.
    pub(crate) cut_duals_buf: Vec<f64>,
    /// Per-worker staging buffer for cuts produced within one stage.
    ///
    /// Cleared via `clear()` at the start of each stage's trial-point loop.
    /// Populated with `push()` per trial point. At the rayon closure boundary
    /// drained via `drain(..).collect::<Vec<_>>()` so the ownership can cross
    /// the closure return. Avoids the per-stage `Vec::with_capacity(n_local)`
    /// allocation in `process_stage_backward`.
    pub(crate) staged_cuts_buf: Vec<StagedCut>,
    /// Scratch buffers for `CVaR` weight computation in `RiskMeasure::CVaR`.
    ///
    /// The three internal `Vec`s (`upper_bounds`, `order`, `mu`) grow lazily
    /// to `n_openings` on the first `CVaR` call and are reused thereafter.
    /// For `RiskMeasure::Expectation` these buffers are never accessed.
    pub(crate) risk_scratch: RiskMeasureScratch,
    /// Reusable scratch for the dynamic-cut-selection lazy solve. Only touched
    /// when the dynamic cut-selection method is active; its internal buffers
    /// grow monotonically and are reused across openings and trial points.
    pub(crate) dcs_solve: DcsSolveScratch,
    /// Metadata-seeded initial resident-cut set for the dynamic-cut-selection
    /// lazy solve. Cleared and refilled per (trial point, opening); capacity
    /// grows to the cut-pool size and is then reused.
    pub(crate) dcs_initial_resident: Vec<u32>,
    /// Reusable solver-statistics snapshot buffer for the per-opening
    /// before-solve metrics. Filled via `statistics_into` (reusing the
    /// histogram allocation) and then diffed against `stats_after_buf`.
    /// Avoids the per-opening histogram clone of `statistics()`.
    pub(crate) stats_before_buf: cobre_solver::SolverStatistics,
    /// Reusable solver-statistics snapshot buffer for the per-opening
    /// after-solve metrics. Counterpart to `stats_before_buf`.
    pub(crate) stats_after_buf: cobre_solver::SolverStatistics,
}

impl BackwardAccumulators {
    /// Allocate accumulators pre-sized from the given workspace dimensions.
    ///
    /// `max_openings`, `initial_pool_capacity`, and `n_state` may all be
    /// `0` for simulation-only workspaces; buffers will then start empty
    /// and grow lazily on the first backward pass stage.
    pub(crate) fn new(max_openings: usize, initial_pool_capacity: usize, n_state: usize) -> Self {
        let outcomes = (0..max_openings)
            .map(|_| BackwardOutcome {
                intercept: 0.0,
                coefficients: vec![0.0_f64; n_state],
                objective_value: 0.0,
            })
            .collect();
        let mut dcs_solve = DcsSolveScratch::default();
        dcs_solve.reserve(n_state, initial_pool_capacity);
        Self {
            outcomes,
            slot_increments: vec![0u64; initial_pool_capacity],
            agg_coefficients: vec![0.0_f64; n_state],
            agg_arena: Vec::new(),
            metadata_sync_contribution: vec![0u64; initial_pool_capacity],
            per_opening_stats: Vec::new(),
            state_duals_buf: Vec::new(),
            cut_duals_buf: Vec::new(),
            staged_cuts_buf: Vec::new(),
            risk_scratch: RiskMeasureScratch::new(),
            dcs_solve,
            dcs_initial_resident: Vec::with_capacity(initial_pool_capacity),
            stats_before_buf: cobre_solver::SolverStatistics::default(),
            stats_after_buf: cobre_solver::SolverStatistics::default(),
        }
    }
}

/// Pre-allocated scratch buffers for noise transformation and simulation.
///
/// Grouped here for readability; individual fields are passed by `&mut`
/// reference to noise transformation functions in `noise.rs`.
#[allow(clippy::struct_field_names)]
pub(crate) struct ScratchBuffers {
    pub(crate) noise_buf: Vec<f64>,
    pub(crate) inflow_m3s_buf: Vec<f64>,
    pub(crate) lag_matrix_buf: Vec<f64>,
    pub(crate) par_inflow_buf: Vec<f64>,
    pub(crate) eta_floor_buf: Vec<f64>,
    pub(crate) zero_targets_buf: Vec<f64>,
    pub(crate) ncs_col_upper_buf: Vec<f64>,
    pub(crate) ncs_col_lower_buf: Vec<f64>,
    pub(crate) ncs_col_indices_buf: Vec<usize>,
    pub(crate) load_rhs_buf: Vec<f64>,
    pub(crate) row_lower_buf: Vec<f64>,
    pub(crate) z_inflow_rhs_buf: Vec<f64>,
    pub(crate) effective_eta_buf: Vec<f64>,
    pub(crate) unscaled_primal: Vec<f64>,
    pub(crate) unscaled_dual: Vec<f64>,
    // Used by accumulate_and_shift_lag_state.
    pub(crate) lag_accumulator: Vec<f64>,
    pub(crate) lag_weight_accum: f64,
    // Downstream ring buffer for multi-resolution lag accumulation.
    pub(crate) downstream_accumulator: Vec<f64>,
    pub(crate) downstream_weight_accum: f64,
    // Slot-major: `completed_lags[slot * hydro_count + hydro]`.
    // Slot 0 = oldest completed quarter, slot n-1 = most recent.
    pub(crate) downstream_completed_lags: Vec<f64>,
    pub(crate) downstream_n_completed: usize,
    /// Scratch lookup table for basis reconstruction.
    ///
    /// Maps each cut pool slot to its position in the stored
    /// `CapturedBasis::cut_row_slots`, so the reconstruction algorithm can
    /// locate the row status for any active cut in O(1) without allocation.
    /// Pre-filled with `None` to `initial_pool_capacity` entries so the
    /// first call can index up to that bound without resize.
    ///
    /// When `initial_pool_capacity == 0` (simulation-only workspaces), this
    /// vec starts empty and grows in-place if needed.
    pub(crate) recon_slot_lookup: Vec<Option<u32>>,

    /// Per-worker trajectory-cost accumulator for the forward pass.
    ///
    /// Pre-sized to `max_local_fwd` at construction via [`WorkspaceSizing`].
    /// Inside `run_forward_worker` the buffer is `clear()`ed then
    /// `resize(n_local, 0.0)`d so no heap allocation occurs on the hot path.
    /// At the worker boundary ownership is transferred via `std::mem::take`,
    /// leaving this field empty until the next iteration's resize.
    ///
    /// Named `trajectory_costs_buf` (not `trajectory_costs`) to avoid
    /// collision with the identically-named field on `ForwardWorkerResult`.
    pub(crate) trajectory_costs_buf: Vec<f64>,

    /// Per-worker raw-noise scratch for the forward-pass sampler and simulation
    /// worker loop.
    ///
    /// Distinct from [`ScratchBuffers::noise_buf`] which is used by the
    /// backward inflow-patch path.  Pre-sized to `noise_dim` at construction.
    /// Inside `run_forward_worker` the buffer is `resize(noise_dim, 0.0)`d
    /// before the inner scenario loop so no per-call allocation occurs.
    /// Inside `run_worker_scenarios` the buffer is `resize(noise_dim, 0.0)`d
    /// before the scenario loop; neither use overlaps the other within a single
    /// `SolverWorkspace`.
    pub(crate) raw_noise_buf: Vec<f64>,

    /// Per-worker permutation scratch for the forward-pass sampler and
    /// simulation worker loop.
    ///
    /// Pre-sized to `total_forward_passes.max(1)` at construction.
    /// Inside `run_forward_worker` the buffer is
    /// `resize(total_forward_passes.max(1), 0)`d before the inner scenario
    /// loop so no per-call allocation occurs.
    /// Inside `run_worker_scenarios` the buffer is
    /// `resize(n_scenarios.max(1), 0)`d before the scenario loop; neither
    /// use overlaps the other within a single `SolverWorkspace`.
    pub(crate) perm_scratch: Vec<usize>,

    /// Snapshot of the incoming anticipated-state slice saved before
    /// `ws.current_state.clear()` clears the forward-stage state vector.
    ///
    /// Written in `run_forward_stage` (one `extend_from_slice` per stage) and
    /// read by `shift_anticipated_state` to produce the new ring-buffer state.
    /// Capacity is `n_anticipated * k_max`; when either dimension is zero the
    /// vec starts empty and the anticipated-state path is skipped entirely.
    pub(crate) anticipated_state_buf: Vec<f64>,
}

/// All per-thread mutable resources required for one LP solve sequence.
///
/// Each field is exclusively owned by the thread — there is no shared state
/// between workspaces. Distributed to worker threads via mutable references
/// from a [`WorkspacePool`].
///
/// # Identity fields
///
/// `rank` and `worker_id` are assigned at [`WorkspacePool::new`] construction
/// time and never change. They provide a stable identity for per-worker
/// observability without any thread-local lookup at call sites, and are the
/// keys used by per-worker instrumentation buffers.
pub struct SolverWorkspace<S: SolverInterface> {
    /// MPI rank that owns this workspace. Stable across the run.
    ///
    /// Set to `i32::try_from(comm.rank()).expect("rank fits in i32")` at
    /// [`WorkspacePool::new`] time. MPI world sizes are bounded well below
    /// `i32::MAX` in practice.
    pub rank: i32,
    /// Rayon worker index within this rank's pool, assigned at
    /// [`WorkspacePool::new`]. Stable across the run. Range:
    /// `0..n_workers_local`.
    pub worker_id: i32,
    /// LP solver instance owned exclusively by this workspace.
    ///
    /// Wrapped in [`ProfiledSolver`] so that per-phase solver configuration
    /// (tolerances, iteration limits) can be applied at phase boundaries via
    /// [`ProfiledSolver::set_profile`] without modifying call sites that use
    /// the solver through the [`SolverInterface`] trait.
    pub solver: ProfiledSolver<S>,
    /// Pre-allocated row-bound patch buffer.
    pub patch_buf: PatchBuffer,
    /// Scratch buffer for the current state vector.
    pub current_state: Vec<f64>,
    /// Pre-allocated scratch buffers for noise transformation and simulation.
    pub(crate) scratch: ScratchBuffers,
    /// Pre-allocated destination basis for [`reconstruct_basis`].
    ///
    /// Filled in-place from the read-only [`CapturedBasis`] in [`BasisStore`]
    /// before being passed to `solve(Some(&basis))`. Sized after construction
    /// via [`WorkspacePool::resize_scratch_bases`] to the maximum LP dimensions
    /// so reconstruction never reallocates on the hot path.
    ///
    /// [`reconstruct_basis`]: crate::basis_reconstruct::reconstruct_basis
    pub(crate) scratch_basis: Basis,
    /// Pre-allocated accumulators for the backward pass trial-point loop.
    ///
    /// Survives across stages without reallocation. Buffers grow
    /// monotonically (never shrink) as larger stages are encountered.
    /// Simulation-only workspaces (constructed with `max_openings = 0`)
    /// start with empty buffers; the backward pass will never touch them.
    pub(crate) backward_accum: BackwardAccumulators,

    /// Zero-allocation timing payload buffer for [`cobre_core::TrainingEvent::WorkerTiming`].
    ///
    /// Accumulated by the rayon closure inside the parallel region (forward or
    /// backward) and moved by value into the event payload after the region
    /// completes. Reset to `WorkerPhaseTimings::default()` at the start of
    /// each iteration boundary before any accumulation begins.
    /// `WorkerPhaseTimings` is `Copy` and stack-resident; no heap allocation
    /// occurs per event.
    ///
    /// Field-to-slot mapping for the writer record:
    /// `forward_wall_ms` → `WORKER_TIMING_SLOT_FWD_WALL`,
    /// `backward_wall_ms` → `WORKER_TIMING_SLOT_BWD_WALL`,
    /// `bwd_setup_ms` → `WORKER_TIMING_SLOT_BWD_SETUP`,
    /// `fwd_setup_ms` → `WORKER_TIMING_SLOT_FWD_SETUP`.
    pub worker_timing_buf: cobre_core::WorkerPhaseTimings,
}

impl<S: SolverInterface> SolverWorkspace<S> {
    /// Construct a workspace with explicit identity, solver, patch buffer, and state capacity.
    ///
    /// `rank` is the MPI rank that owns this workspace (stable across the run).
    /// `worker_id` is the rayon worker index within the rank's pool (range
    /// `0..n_workers_local`, assigned sequentially at [`WorkspacePool::new`]).
    ///
    /// `sizing` provides the buffer-dimension parameters shared between the
    /// [`PatchBuffer`], the internal `ScratchBuffers`, and the
    /// `BackwardAccumulators` allocation. Pass `max_openings = 0`,
    /// `initial_pool_capacity = 0`, and `n_state = 0` in `sizing` for
    /// simulation-only workspaces that do not participate in the backward pass.
    ///
    /// The `scratch_basis` starts empty. Call `WorkspacePool::resize_scratch_bases`
    /// after construction to pre-allocate it for in-place basis reconstruction.
    #[must_use]
    pub fn new(
        rank: i32,
        worker_id: i32,
        solver: S,
        patch_buf: PatchBuffer,
        n_state: usize,
        sizing: WorkspaceSizing,
    ) -> Self {
        Self {
            rank,
            worker_id,
            solver: ProfiledSolver::new(solver),
            patch_buf,
            current_state: Vec::with_capacity(n_state),
            scratch: ScratchBuffers::new(sizing),
            scratch_basis: Basis::new(0, 0),
            backward_accum: BackwardAccumulators::new(
                sizing.max_openings,
                sizing.initial_pool_capacity,
                sizing.n_state,
            ),
            worker_timing_buf: cobre_core::WorkerPhaseTimings::default(),
        }
    }
}

impl ScratchBuffers {
    /// Allocate scratch buffers sized for the given per-worker parameters.
    ///
    /// Shared by all three `SolverWorkspace` construction sites
    /// (`SolverWorkspace::new`, `WorkspacePool::new`, `WorkspacePool::try_new`)
    /// to keep them in sync.
    pub(crate) fn new(s: WorkspaceSizing) -> Self {
        let WorkspaceSizing {
            hydro_count,
            max_par_order,
            n_load_buses,
            max_blocks,
            downstream_par_order,
            initial_pool_capacity,
            max_local_fwd,
            total_forward_passes,
            noise_dim,
            n_anticipated,
            k_max,
            // `n_state` (state_at_capture sizing) and `max_openings` are used by
            // CapturedBasis / BackwardAccumulators only.
            ..
        } = s;
        Self {
            noise_buf: Vec::with_capacity(hydro_count),
            inflow_m3s_buf: Vec::with_capacity(hydro_count),
            lag_matrix_buf: Vec::with_capacity(max_par_order * hydro_count),
            par_inflow_buf: Vec::with_capacity(hydro_count),
            eta_floor_buf: Vec::with_capacity(hydro_count),
            zero_targets_buf: vec![0.0_f64; hydro_count],
            ncs_col_upper_buf: Vec::new(),
            ncs_col_lower_buf: Vec::new(),
            ncs_col_indices_buf: Vec::new(),
            load_rhs_buf: Vec::with_capacity(n_load_buses * max_blocks),
            row_lower_buf: Vec::new(),
            z_inflow_rhs_buf: Vec::with_capacity(hydro_count),
            effective_eta_buf: Vec::with_capacity(hydro_count),
            unscaled_primal: Vec::new(),
            unscaled_dual: Vec::new(),
            lag_accumulator: vec![0.0_f64; hydro_count],
            lag_weight_accum: 0.0,
            downstream_accumulator: if downstream_par_order > 0 {
                vec![0.0_f64; hydro_count]
            } else {
                Vec::new()
            },
            downstream_weight_accum: 0.0,
            downstream_completed_lags: if downstream_par_order > 0 {
                vec![0.0_f64; hydro_count * downstream_par_order]
            } else {
                Vec::new()
            },
            downstream_n_completed: 0,
            recon_slot_lookup: vec![None; initial_pool_capacity],
            trajectory_costs_buf: Vec::with_capacity(max_local_fwd),
            raw_noise_buf: Vec::with_capacity(noise_dim),
            perm_scratch: Vec::with_capacity(total_forward_passes.max(1)),
            anticipated_state_buf: Vec::with_capacity(n_anticipated * k_max),
        }
    }
}

/// A pool of [`SolverWorkspace`] instances, one per worker thread.
///
/// Create once at algorithm startup via [`WorkspacePool::new`] and distribute
/// workspaces to threads by indexing into [`workspaces`](WorkspacePool::workspaces).
///
/// The pool size equals the number of worker threads. Each workspace is
/// independently allocated and does not share any mutable state with the others.
pub struct WorkspacePool<S: SolverInterface> {
    /// The individual workspaces, indexed by thread number.
    pub workspaces: Vec<SolverWorkspace<S>>,
}

impl<S: SolverInterface> WorkspacePool<S> {
    /// Construct a pool of `n_threads` independently allocated workspaces.
    ///
    /// `rank` is the MPI rank that owns this pool. Each workspace in the pool
    /// receives a sequentially assigned `worker_id` in `0..n_threads`.
    ///
    /// Each workspace receives a fresh solver instance, patch buffer, and state buffer.
    /// `solver_factory` is called once per thread.
    ///
    /// `sizing` provides all buffer-dimension parameters; pass
    /// `WorkspaceSizing { n_load_buses: 0, max_blocks: 0, .. }` when there is
    /// no stochastic load.
    ///
    /// # Panics
    ///
    /// Panics if `n_threads > i32::MAX`. Rayon pools are bounded by CPU count,
    /// so this is physically impossible on any real system.
    #[must_use]
    #[allow(clippy::expect_used)]
    pub fn new(
        rank: i32,
        n_threads: usize,
        n_state: usize,
        sizing: WorkspaceSizing,
        solver_factory: impl Fn() -> S,
    ) -> Self {
        let workspaces = (0..n_threads)
            .map(|idx| {
                let worker_id =
                    i32::try_from(idx).expect("worker_id fits in i32 (rayon pools are small)");
                SolverWorkspace {
                    rank,
                    worker_id,
                    solver: ProfiledSolver::new(solver_factory()),
                    patch_buf: PatchBuffer::new(
                        sizing.hydro_count,
                        sizing.max_par_order,
                        sizing.n_load_buses,
                        sizing.max_blocks,
                        sizing.n_anticipated,
                        sizing.k_max,
                    ),
                    current_state: Vec::with_capacity(n_state),
                    scratch: ScratchBuffers::new(sizing),
                    scratch_basis: Basis::new(0, 0),
                    backward_accum: BackwardAccumulators::new(
                        sizing.max_openings,
                        sizing.initial_pool_capacity,
                        sizing.n_state,
                    ),
                    worker_timing_buf: cobre_core::WorkerPhaseTimings::default(),
                }
            })
            .collect();
        Self { workspaces }
    }

    /// Construct a pool of `n_threads` independently allocated workspaces using
    /// a fallible factory.
    ///
    /// `rank` is the MPI rank that owns this pool. Each workspace in the pool
    /// receives a sequentially assigned `worker_id` in `0..n_threads`.
    ///
    /// Identical to [`WorkspacePool::new`] except that `solver_factory` returns
    /// `Result<S, E>`. The first error from any factory call is returned
    /// immediately and no partial pool is produced.
    ///
    /// # Errors
    ///
    /// Returns `Err(E)` if any call to `solver_factory` fails.
    ///
    /// # Panics
    ///
    /// Panics if `n_threads > i32::MAX`. Rayon pools are bounded by CPU count,
    /// so this is physically impossible on any real system.
    #[allow(clippy::expect_used)]
    pub fn try_new<E>(
        rank: i32,
        n_threads: usize,
        n_state: usize,
        sizing: WorkspaceSizing,
        solver_factory: impl Fn() -> Result<S, E>,
    ) -> Result<Self, E> {
        let mut workspaces = Vec::with_capacity(n_threads);
        for idx in 0..n_threads {
            let worker_id =
                i32::try_from(idx).expect("worker_id fits in i32 (rayon pools are small)");
            workspaces.push(SolverWorkspace {
                rank,
                worker_id,
                solver: ProfiledSolver::new(solver_factory()?),
                patch_buf: PatchBuffer::new(
                    sizing.hydro_count,
                    sizing.max_par_order,
                    sizing.n_load_buses,
                    sizing.max_blocks,
                    sizing.n_anticipated,
                    sizing.k_max,
                ),
                current_state: Vec::with_capacity(n_state),
                scratch: ScratchBuffers::new(sizing),
                scratch_basis: Basis::new(0, 0),
                backward_accum: BackwardAccumulators::new(
                    sizing.max_openings,
                    sizing.initial_pool_capacity,
                    sizing.n_state,
                ),
                worker_timing_buf: cobre_core::WorkerPhaseTimings::default(),
            });
        }
        Ok(Self { workspaces })
    }

    /// Pre-allocate each workspace's `scratch_basis` to the given LP dimensions.
    ///
    /// The allocation happens once during setup; basis reconstruction on the
    /// hot path then reuses the existing capacity without reallocating.
    pub(crate) fn resize_scratch_bases(&mut self, max_cols: usize, max_rows: usize) {
        for ws in &mut self.workspaces {
            ws.scratch_basis = Basis::new(max_cols, max_rows);
        }
    }
}

// ---------------------------------------------------------------------------
// BasisStore
// ---------------------------------------------------------------------------

/// Per-scenario, per-stage basis storage for warm-starting LP solves.
///
/// The store is indexed as `store[scenario_index][stage_index]`. During the
/// forward pass, each worker writes to its disjoint scenario range. During
/// the backward pass, all workers read from any scenario's basis.
///
/// Internally, data is stored flat as
/// `bases[scenario * num_stages + stage]` for cache-friendly sequential
/// access within a single scenario's stage loop.
///
/// # Cut selection interaction
///
/// Basis row statuses are positional: `row_status[i]` corresponds to LP
/// row `i`. When cut selection changes the active cut set between
/// iterations, the number of cut rows in the LP changes and the stored
/// basis row statuses become stale — they no longer align with the
/// current LP row layout.
///
/// **Current behavior (option 1):** We accept the degraded warm-start.
/// `HiGHS` detects the dimension mismatch when `solve(Some(&basis))` is called
/// with a basis whose row count differs from the current LP row count and
/// falls back to a crash start. This is tracked as a `basis_rejection` in
/// [`SolverStatistics`]. The template (non-cut) row statuses remain valid;
/// only the cut row portion becomes meaningless.
///
/// **If degradation is problematic (option 3):** After cut selection runs,
/// discard the cut row statuses from all stored bases, retaining only the
/// template row portion. This gives a clean partial warm-start at zero
/// implementation cost beyond a single truncation.
///
/// [`SolverStatistics`]: cobre_solver::SolverStatistics
pub struct BasisStore {
    /// Flat storage: `bases[scenario * num_stages + stage]`.
    bases: Vec<Option<CapturedBasis>>,
    /// Number of stages per scenario.
    num_stages: usize,
}

impl BasisStore {
    /// Allocate a new store for `num_scenarios` scenarios and `num_stages`
    /// stages, with every slot initialised to `None`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cobre_sddp::workspace::BasisStore;
    ///
    /// let store = BasisStore::new(4, 10);
    /// assert_eq!(store.num_scenarios(), 4);
    /// assert_eq!(store.num_stages(), 10);
    /// assert!(store.get(0, 0).is_none());
    /// ```
    #[must_use]
    pub fn new(num_scenarios: usize, num_stages: usize) -> Self {
        let len = num_scenarios * num_stages;
        Self {
            bases: vec![None; len],
            num_stages,
        }
    }

    /// Return the number of scenarios this store was allocated for.
    #[must_use]
    pub fn num_scenarios(&self) -> usize {
        self.bases.len().checked_div(self.num_stages).unwrap_or(0)
    }

    /// Return the number of stages.
    #[must_use]
    pub fn num_stages(&self) -> usize {
        self.num_stages
    }

    /// Get an immutable reference to the basis at `[scenario][stage]`.
    ///
    /// Returns `None` if the slot has not yet been populated.
    #[must_use]
    pub fn get(&self, scenario: usize, stage: usize) -> Option<&CapturedBasis> {
        self.bases[scenario * self.num_stages + stage].as_ref()
    }

    /// Get a mutable reference to the basis slot at `[scenario][stage]`.
    pub fn get_mut(&mut self, scenario: usize, stage: usize) -> &mut Option<CapturedBasis> {
        &mut self.bases[scenario * self.num_stages + stage]
    }

    /// Split the store into `n_workers` disjoint mutable sub-views by scenario
    /// range, one per worker.
    ///
    /// Worker `w` receives the scenarios in the range produced by
    /// `partition(num_scenarios, n_workers, w)`. Each [`BasisStoreSliceMut`]
    /// carries its scenario offset so that callers can index using absolute
    /// scenario indices.
    ///
    /// When `n_workers` exceeds `num_scenarios`, some workers receive empty
    /// slices (`start == end`), which is valid — their slice covers zero
    /// scenarios.
    ///
    /// # Panics (debug only)
    ///
    /// Panics if `n_workers == 0`.
    #[must_use]
    pub fn split_workers_mut(&mut self, n_workers: usize) -> Vec<BasisStoreSliceMut<'_>> {
        debug_assert!(n_workers > 0, "n_workers must be > 0");
        let total_scenarios = self.num_scenarios();
        let mut slices = Vec::with_capacity(n_workers);
        let mut bases_rem = self.bases.as_mut_slice();
        let mut offset = 0usize;

        for w in 0..n_workers {
            let (start, end) = crate::solve::partition(total_scenarios, n_workers, w);
            let count = end - start;
            let chunk = count * self.num_stages;
            let (bases_left, bases_rest) = bases_rem.split_at_mut(chunk);
            bases_rem = bases_rest;
            slices.push(BasisStoreSliceMut {
                bases: bases_left,
                scenario_offset: offset,
                num_stages: self.num_stages,
            });
            offset += count;
        }
        slices
    }
}

/// A mutable sub-view of a [`BasisStore`] covering a contiguous range of
/// scenarios.
///
/// Produced by [`BasisStore::split_workers_mut`]. Each slice is exclusive
/// to one worker thread; multiple slices can coexist because they cover
/// disjoint memory regions.
pub struct BasisStoreSliceMut<'a> {
    /// Sub-slice of the flat basis array for this worker's scenario range.
    bases: &'a mut [Option<CapturedBasis>],
    /// Absolute scenario index of the first scenario in this slice.
    scenario_offset: usize,
    /// Number of stages per scenario.
    num_stages: usize,
}

impl BasisStoreSliceMut<'_> {
    /// Get an immutable reference to the basis at absolute scenario index
    /// `scenario` and stage `stage`.
    ///
    /// Returns `None` if the slot has not yet been populated.
    ///
    /// # Panics
    ///
    /// Panics if `scenario < self.scenario_offset` (scenario not in this slice).
    #[must_use]
    pub fn get(&self, scenario: usize, stage: usize) -> Option<&CapturedBasis> {
        let local = scenario - self.scenario_offset;
        self.bases[local * self.num_stages + stage].as_ref()
    }

    /// Get a mutable reference to the basis slot at absolute scenario index
    /// `scenario` and stage `stage`.
    ///
    /// # Panics
    ///
    /// Panics if `scenario < self.scenario_offset` (scenario not in this slice).
    pub fn get_mut(&mut self, scenario: usize, stage: usize) -> &mut Option<CapturedBasis> {
        let local = scenario - self.scenario_offset;
        &mut self.bases[local * self.num_stages + stage]
    }
}

#[cfg(test)]
mod tests {
    use super::{
        BasisStore, CapturedBasis, ScratchBuffers, SolverWorkspace, WorkspacePool, WorkspaceSizing,
    };
    use cobre_solver::{
        Basis, SolutionView, SolverError, SolverInterface, SolverStatistics,
        types::{RowBatch, StageTemplate},
    };

    /// Minimal no-op solver for workspace tests.
    struct MockSolver;

    impl SolverInterface for MockSolver {
        type Profile = cobre_solver::ActiveProfile;

        fn apply_profile(&mut self, _profile: &cobre_solver::ActiveProfile) {}

        fn solver_name_version(&self) -> String {
            "MockSolver 0.0.0".to_string()
        }
        fn load_model(&mut self, _t: &StageTemplate) {}
        fn add_rows(&mut self, _r: &RowBatch) {}
        fn set_row_bounds(&mut self, _i: &[usize], _l: &[f64], _u: &[f64]) {}
        fn set_col_bounds(&mut self, _i: &[usize], _l: &[f64], _u: &[f64]) {}
        fn solve(&mut self, _basis: Option<&Basis>) -> Result<SolutionView<'_>, SolverError> {
            Err(SolverError::InternalError {
                message: "mock".into(),
                error_code: None,
            })
        }
        fn get_basis(&mut self, _out: &mut Basis) {}
        fn statistics(&self) -> SolverStatistics {
            SolverStatistics::default()
        }
        fn statistics_into(&self, out: &mut SolverStatistics) {
            out.copy_from(&SolverStatistics::default());
        }
        fn name(&self) -> &'static str {
            "Mock"
        }
    }

    /// Compile-time assertion that `SolverWorkspace<MockSolver>` is `Send`.
    fn assert_send<T: Send>() {}

    #[test]
    fn test_workspace_send_bound() {
        assert_send::<SolverWorkspace<MockSolver>>();
    }

    fn sizing(
        hydro_count: usize,
        max_par_order: usize,
        downstream_par_order: usize,
    ) -> WorkspaceSizing {
        WorkspaceSizing {
            hydro_count,
            max_par_order,
            n_load_buses: 0,
            max_blocks: 0,
            downstream_par_order,
            ..WorkspaceSizing::default()
        }
    }

    #[test]
    fn test_workspace_pool_size() {
        let pool = WorkspacePool::new(0, 4, 9, sizing(3, 2, 0), || MockSolver);
        assert_eq!(pool.workspaces.len(), 4);
    }

    #[test]
    fn test_workspace_buffer_dimensions() {
        // N=3, L=2, M=0, B=0 → patch_buf length = N + M*B + N = 3 + 0 + 3 = 6
        // n_state=9 → current_state capacity = 9
        let pool = WorkspacePool::new(0, 4, 9, sizing(3, 2, 0), || MockSolver);
        for ws in &pool.workspaces {
            assert_eq!(ws.patch_buf.indices.len(), 6, "patch_buf length");
            assert_eq!(ws.current_state.capacity(), 9, "current_state capacity");
            assert_eq!(ws.current_state.len(), 0, "current_state starts empty");
        }
    }

    #[test]
    fn test_workspace_pool_zero_threads() {
        let pool = WorkspacePool::new(0, 0, 9, sizing(3, 2, 0), || MockSolver);
        assert_eq!(pool.workspaces.len(), 0);
    }

    #[test]
    fn test_workspace_pool_single_thread() {
        let pool = WorkspacePool::new(0, 1, 0, sizing(0, 0, 0), || MockSolver);
        assert_eq!(pool.workspaces.len(), 1);
        assert_eq!(pool.workspaces[0].patch_buf.indices.len(), 0);
    }

    #[test]
    fn test_workspace_pool_each_solver_independent() {
        // Factory is called n_threads times; each workspace gets its own instance.
        // Verify by checking pool size matches factory call expectation.
        let n = 6;
        let pool = WorkspacePool::new(0, n, 1, sizing(1, 0, 0), || MockSolver);
        assert_eq!(pool.workspaces.len(), n);
    }

    #[test]
    fn test_scratch_buffers_zero_downstream_par_order_empty_buffers() {
        // AC: downstream_par_order=0 → all downstream fields are zero/empty.
        let scratch = ScratchBuffers::new(WorkspaceSizing {
            hydro_count: 5,
            max_par_order: 2,
            n_load_buses: 0,
            max_blocks: 1,
            downstream_par_order: 0,
            ..WorkspaceSizing::default()
        });
        assert!(
            scratch.downstream_accumulator.is_empty(),
            "downstream_accumulator must be empty when downstream_par_order=0"
        );
        assert!(
            scratch.downstream_completed_lags.is_empty(),
            "downstream_completed_lags must be empty when downstream_par_order=0"
        );
        assert_eq!(
            scratch.downstream_weight_accum, 0.0,
            "downstream_weight_accum must be 0.0"
        );
        assert_eq!(
            scratch.downstream_n_completed, 0,
            "downstream_n_completed must be 0"
        );
    }

    #[test]
    fn test_scratch_buffers_nonzero_downstream_par_order_allocates_correctly() {
        // AC: downstream_par_order=2, hydro_count=3 → lengths 3 and 6, all 0.0.
        let scratch = ScratchBuffers::new(WorkspaceSizing {
            hydro_count: 3,
            max_par_order: 2,
            n_load_buses: 0,
            max_blocks: 1,
            downstream_par_order: 2,
            ..WorkspaceSizing::default()
        });
        assert_eq!(
            scratch.downstream_accumulator.len(),
            3,
            "downstream_accumulator.len() must equal hydro_count"
        );
        assert_eq!(
            scratch.downstream_completed_lags.len(),
            6,
            "downstream_completed_lags.len() must equal hydro_count * downstream_par_order"
        );
        assert!(
            scratch.downstream_accumulator.iter().all(|&v| v == 0.0),
            "downstream_accumulator must be initialized to 0.0"
        );
        assert!(
            scratch.downstream_completed_lags.iter().all(|&v| v == 0.0),
            "downstream_completed_lags must be initialized to 0.0"
        );
        assert_eq!(scratch.downstream_weight_accum, 0.0);
        assert_eq!(scratch.downstream_n_completed, 0);
    }

    #[test]
    fn test_workspace_pool_propagates_downstream_par_order() {
        // AC: WorkspacePool propagates downstream_par_order=2, hydro_count=3.
        let pool = WorkspacePool::new(
            0,
            2,
            6,
            WorkspaceSizing {
                hydro_count: 3,
                max_par_order: 2,
                n_load_buses: 0,
                max_blocks: 1,
                downstream_par_order: 2,
                ..WorkspaceSizing::default()
            },
            || MockSolver,
        );
        for ws in &pool.workspaces {
            assert_eq!(
                ws.scratch.downstream_accumulator.len(),
                3,
                "downstream_accumulator.len() per workspace"
            );
            assert_eq!(
                ws.scratch.downstream_completed_lags.len(),
                6,
                "downstream_completed_lags.len() per workspace"
            );
            assert_eq!(ws.scratch.downstream_weight_accum, 0.0);
            assert_eq!(ws.scratch.downstream_n_completed, 0);
        }
    }

    // ---------------------------------------------------------------------------
    // BasisStore tests
    // ---------------------------------------------------------------------------

    #[test]
    fn basis_store_new_all_none() {
        let store = BasisStore::new(3, 5);
        assert_eq!(store.num_scenarios(), 3);
        assert_eq!(store.num_stages(), 5);
        for s in 0..3 {
            for t in 0..5 {
                assert!(
                    store.get(s, t).is_none(),
                    "slot [{s}][{t}] must start as None"
                );
            }
        }
    }

    #[test]
    fn basis_store_get_mut_set_and_retrieve() {
        let mut store = BasisStore::new(2, 3);
        // test shim: zero metadata is acceptable for tests exercising the length path
        *store.get_mut(1, 2) = Some(CapturedBasis::new(4, 2, 0, 0, 0));
        assert!(store.get(1, 2).is_some());
        assert!(store.get(0, 0).is_none());
        assert!(store.get(1, 0).is_none());
    }

    #[test]
    fn basis_store_zero_scenarios() {
        let store = BasisStore::new(0, 5);
        assert_eq!(store.num_scenarios(), 0);
        assert_eq!(store.num_stages(), 5);
    }

    #[test]
    fn basis_store_zero_stages() {
        let store = BasisStore::new(3, 0);
        assert_eq!(store.num_scenarios(), 0);
        assert_eq!(store.num_stages(), 0);
    }

    #[test]
    fn basis_store_split_workers_mut_disjoint_writes() {
        // 4 scenarios, 3 stages, 2 workers.
        // Worker 0 covers scenarios 0..2; worker 1 covers scenarios 2..4.
        let mut store = BasisStore::new(4, 3);
        let mut slices = store.split_workers_mut(2);

        // Worker 0 writes to scenario 0 stage 1.
        // test shim: zero metadata is acceptable for tests exercising the length path
        *slices[0].get_mut(0, 1) = Some(CapturedBasis::new(2, 1, 0, 0, 0));
        // Worker 1 writes to scenario 3 stage 2.
        // test shim: zero metadata is acceptable for tests exercising the length path
        *slices[1].get_mut(3, 2) = Some(CapturedBasis::new(2, 1, 0, 0, 0));

        // Drop slices to release the borrow on store.
        drop(slices);

        assert!(
            store.get(0, 1).is_some(),
            "scenario 0 stage 1 must be populated"
        );
        assert!(
            store.get(3, 2).is_some(),
            "scenario 3 stage 2 must be populated"
        );
        assert!(store.get(0, 0).is_none());
        assert!(store.get(3, 0).is_none());
    }

    #[test]
    fn basis_store_split_single_worker() {
        let mut store = BasisStore::new(3, 2);
        let mut slices = store.split_workers_mut(1);
        // test shim: zero metadata is acceptable for tests exercising the length path
        *slices[0].get_mut(2, 1) = Some(CapturedBasis::new(1, 0, 0, 0, 0));
        drop(slices);
        assert!(store.get(2, 1).is_some());
    }

    #[test]
    fn basis_store_split_more_workers_than_scenarios() {
        // 2 scenarios, 4 workers → workers 2 and 3 receive empty slices.
        let mut store = BasisStore::new(2, 3);
        let slices = store.split_workers_mut(4);
        assert_eq!(slices.len(), 4);
        // Workers 0 and 1 cover 1 scenario each; workers 2 and 3 cover 0.
        assert_eq!(slices[0].bases.len(), 3); // 1 scenario × 3 stages
        assert_eq!(slices[1].bases.len(), 3);
        assert_eq!(slices[2].bases.len(), 0);
        assert_eq!(slices[3].bases.len(), 0);
    }

    #[test]
    fn basis_store_slice_offset_correct() {
        // 6 scenarios, 2 stages, 3 workers → 2 scenarios each.
        let mut store = BasisStore::new(6, 2);
        let mut slices = store.split_workers_mut(3);

        // Worker 1 covers absolute scenarios 2..4.
        // test shim: zero metadata is acceptable for tests exercising the length path
        *slices[1].get_mut(2, 0) = Some(CapturedBasis::new(1, 0, 0, 0, 0));
        // test shim: zero metadata is acceptable for tests exercising the length path
        *slices[1].get_mut(3, 1) = Some(CapturedBasis::new(1, 0, 0, 0, 0));
        drop(slices);

        assert!(store.get(2, 0).is_some());
        assert!(store.get(3, 1).is_some());
        assert!(store.get(0, 0).is_none());
        assert!(store.get(4, 0).is_none());
    }

    #[test]
    fn test_captured_basis_new_capacities() {
        // AC: CapturedBasis::new(4, 6, 3, 10, 2) must produce:
        //   basis.row_status.len() == 6, base_row_count == 3,
        //   cut_row_slots.capacity() >= 10, cut_row_slots.len() == 0,
        //   state_at_capture.capacity() >= 2, state_at_capture.len() == 0.
        let cb = CapturedBasis::new(4, 6, 3, 10, 2);
        assert_eq!(cb.basis.row_status.len(), 6, "row_status length");
        assert_eq!(cb.base_row_count, 3, "base_row_count");
        assert!(
            cb.cut_row_slots.capacity() >= 10,
            "cut_row_slots capacity must be >= 10 (got {})",
            cb.cut_row_slots.capacity()
        );
        assert_eq!(cb.cut_row_slots.len(), 0, "cut_row_slots starts empty");
        assert!(
            cb.state_at_capture.capacity() >= 2,
            "state_at_capture capacity must be >= 2 (got {})",
            cb.state_at_capture.capacity()
        );
        assert_eq!(
            cb.state_at_capture.len(),
            0,
            "state_at_capture starts empty"
        );
    }

    #[test]
    fn test_basis_store_holds_captured_basis() {
        // AC: BasisStore after migration holds Option<CapturedBasis>, not Option<Basis>.
        // slot set, slot read, default None holds for all 15 cells.
        let mut store = BasisStore::new(3, 5);
        // All 15 slots start as None.
        for s in 0..3 {
            for t in 0..5 {
                assert!(
                    store.get(s, t).is_none(),
                    "slot [{s}][{t}] must be None before any write"
                );
            }
        }
        // Write a CapturedBasis at [1][3]; read it back.
        *store.get_mut(1, 3) = Some(CapturedBasis::new(4, 6, 3, 10, 2));
        let retrieved = store.get(1, 3);
        assert!(retrieved.is_some(), "slot [1][3] must be Some after write");
        let cb = retrieved.expect("just checked is_some");
        assert_eq!(cb.base_row_count, 3);
        // All other slots remain None.
        for s in 0..3 {
            for t in 0..5 {
                if s == 1 && t == 3 {
                    continue;
                }
                assert!(
                    store.get(s, t).is_none(),
                    "slot [{s}][{t}] must remain None"
                );
            }
        }
    }

    #[test]
    fn test_recon_slot_lookup_presized() {
        // AC: every workspace in a freshly constructed WorkspacePool with
        //   WorkspaceSizing { initial_pool_capacity: 50, .. }
        //   must have recon_slot_lookup.len() == 50 and every entry is None.
        let pool = WorkspacePool::new(
            0,
            4,
            0,
            WorkspaceSizing {
                initial_pool_capacity: 50,
                ..WorkspaceSizing::default()
            },
            || MockSolver,
        );
        for (i, ws) in pool.workspaces.iter().enumerate() {
            assert_eq!(
                ws.scratch.recon_slot_lookup.len(),
                50,
                "workspace {i}: recon_slot_lookup.len() must equal initial_pool_capacity (50)"
            );
            assert!(
                ws.scratch.recon_slot_lookup.iter().all(Option::is_none),
                "workspace {i}: all recon_slot_lookup entries must be None"
            );
        }
        // Verify zero initial_pool_capacity produces an empty vec.
        let pool_empty = WorkspacePool::new(0, 1, 0, WorkspaceSizing::default(), || MockSolver);
        assert_eq!(
            pool_empty.workspaces[0].scratch.recon_slot_lookup.len(),
            0,
            "initial_pool_capacity=0 must produce empty recon_slot_lookup"
        );
    }

    #[test]
    fn test_workspace_pool_assigns_sequential_worker_ids() {
        let pool = WorkspacePool::new(
            /* rank = */ 3,
            /* n_workers = */ 5,
            /* n_state = */ 0,
            WorkspaceSizing::default(),
            || MockSolver,
        );
        let ws_slice = &pool.workspaces;
        assert_eq!(ws_slice.len(), 5);
        let mut seen: std::collections::HashSet<i32> = std::collections::HashSet::new();
        for ws in ws_slice {
            assert_eq!(ws.rank, 3);
            assert!(ws.worker_id >= 0 && ws.worker_id < 5);
            assert!(seen.insert(ws.worker_id), "worker_id duplicated");
        }
    }

    // ---------------------------------------------------------------------------
    // CapturedBasis wire-format round-trip tests
    // ---------------------------------------------------------------------------

    /// Round-trip test: single stage with fully populated metadata.
    ///
    /// Constructs a `CapturedBasis` with known fields, packs via
    /// `to_broadcast_payload`, then unpacks via `try_from_broadcast_payload`.
    /// Asserts field-by-field equality with the original.
    #[test]
    fn test_captured_basis_round_trip_populated() {
        let original = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32, 2, 3],
                row_status: vec![4_i32, 5],
            },
            base_row_count: 1,
            cut_row_slots: vec![10_u32, 20],
            state_at_capture: vec![1.5_f64, 2.5, 3.5],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        original.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let result = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("round-trip must not fail");
        let recovered = result.expect("sentinel is 1; must return Some");

        assert_eq!(
            recovered.basis.col_status, original.basis.col_status,
            "col_status"
        );
        assert_eq!(
            recovered.basis.row_status, original.basis.row_status,
            "row_status"
        );
        assert_eq!(
            recovered.base_row_count, original.base_row_count,
            "base_row_count"
        );
        assert_eq!(
            recovered.cut_row_slots, original.cut_row_slots,
            "cut_row_slots"
        );
        assert_eq!(
            recovered.state_at_capture, original.state_at_capture,
            "state_at_capture"
        );
        // Cursors must have advanced past the full payload.
        assert_eq!(i32_cursor, i32_buf.len(), "i32_cursor must be at end");
        assert_eq!(f64_cursor, f64_buf.len(), "f64_cursor must be at end");
    }

    /// Round-trip test: single stage with empty `cut_row_slots` and
    /// empty `state_at_capture`.
    #[test]
    fn test_captured_basis_round_trip_empty_metadata() {
        let original = CapturedBasis {
            basis: Basis {
                col_status: vec![7_i32, 8],
                row_status: vec![9_i32],
            },
            base_row_count: 1,
            cut_row_slots: vec![],
            state_at_capture: vec![],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        original.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let result = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("round-trip must not fail");
        let recovered = result.expect("sentinel is 1; must return Some");

        assert_eq!(recovered.basis.col_status, original.basis.col_status);
        assert_eq!(recovered.basis.row_status, original.basis.row_status);
        assert_eq!(recovered.base_row_count, original.base_row_count);
        assert!(
            recovered.cut_row_slots.is_empty(),
            "cut_row_slots must be empty"
        );
        assert!(
            recovered.state_at_capture.is_empty(),
            "state_at_capture must be empty"
        );
        assert_eq!(i32_cursor, i32_buf.len(), "i32_cursor must be at end");
        assert_eq!(f64_cursor, f64_buf.len(), "f64_cursor must be at end");
    }

    /// Multi-stage round-trip: one `Some` stage followed by one `None` stage.
    ///
    /// Packs the `Some` stage via `to_broadcast_payload`, writes a `0_i32`
    /// sentinel for the `None` stage, then loops `try_from_broadcast_payload`
    /// twice and asserts the recovered `Option`s match.
    #[test]
    fn test_captured_basis_round_trip_multi_stage() {
        let populated = CapturedBasis {
            basis: Basis {
                col_status: vec![11_i32, 22, 33],
                row_status: vec![44_i32, 55, 66],
            },
            base_row_count: 2,
            cut_row_slots: vec![100_u32, 200, 300],
            state_at_capture: vec![0.1_f64, 0.2],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();

        // Stage 0: Some — pack via method.
        populated.to_broadcast_payload(&mut i32_buf, &mut f64_buf);
        // Stage 1: None — caller writes the 0 sentinel directly.
        i32_buf.push(0_i32);

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;

        // Unpack stage 0.
        let stage0 = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("stage 0 must not fail")
        .expect("stage 0 sentinel is 1; must return Some");

        assert_eq!(stage0.basis.col_status, populated.basis.col_status);
        assert_eq!(stage0.basis.row_status, populated.basis.row_status);
        assert_eq!(stage0.base_row_count, populated.base_row_count);
        assert_eq!(stage0.cut_row_slots, populated.cut_row_slots);
        assert_eq!(stage0.state_at_capture, populated.state_at_capture);

        // Unpack stage 1 — must return None, advancing cursor by 1.
        let stage1 = CapturedBasis::try_from_broadcast_payload(
            1,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("stage 1 must not fail");
        assert!(stage1.is_none(), "stage 1 sentinel is 0; must return None");

        assert_eq!(
            i32_cursor,
            i32_buf.len(),
            "i32_cursor must be at end after both stages"
        );
        assert_eq!(
            f64_cursor,
            f64_buf.len(),
            "f64_cursor must be at end after both stages"
        );
    }

    /// Truncated i32 buffer: truncate the packed buffer by 1 element, assert
    /// `Err(SddpError::Validation(msg))` where `msg` contains "truncated" and
    /// the stage index.
    #[test]
    fn test_captured_basis_truncated_i32_buffer() {
        use crate::SddpError;

        let cb = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32, 2],
                row_status: vec![3_i32],
            },
            base_row_count: 1,
            cut_row_slots: vec![5_u32],
            state_at_capture: vec![9.9_f64],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        cb.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        // Truncate i32 buffer by 1.
        i32_buf.pop();

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let err = CapturedBasis::try_from_broadcast_payload(
            7,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect_err("truncated buffer must return Err");

        match err {
            SddpError::Validation(ref msg) => {
                assert!(
                    msg.contains("truncated"),
                    "error message must contain 'truncated', got: {msg}"
                );
                assert!(
                    msg.contains('7'),
                    "error message must contain stage index 7, got: {msg}"
                );
            }
            other => panic!("expected SddpError::Validation, got {other:?}"),
        }
    }

    /// Truncated f64 buffer: pack a basis with non-empty `state_at_capture`,
    /// truncate the f64 buffer by 1, assert `Err(SddpError::Validation(msg))`
    /// where `msg` mentions `state_at_capture` and the stage index.
    #[test]
    fn test_captured_basis_truncated_f64_buffer() {
        use crate::SddpError;

        let cb = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32],
                row_status: vec![2_i32],
            },
            base_row_count: 1,
            cut_row_slots: vec![],
            state_at_capture: vec![1.0_f64, 2.0, 3.0],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        cb.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        // Truncate f64 buffer by 1.
        f64_buf.pop();

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let err = CapturedBasis::try_from_broadcast_payload(
            3,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect_err("truncated f64 buffer must return Err");

        match err {
            SddpError::Validation(ref msg) => {
                assert!(
                    msg.contains("state_at_capture"),
                    "error message must contain 'state_at_capture', got: {msg}"
                );
                assert!(
                    msg.contains('3'),
                    "error message must contain stage index 3, got: {msg}"
                );
            }
            other => panic!("expected SddpError::Validation, got {other:?}"),
        }
    }

    // ---------------------------------------------------------------------------
    // Version-byte tests
    // ---------------------------------------------------------------------------

    /// Round-trip verification that `to_broadcast_payload` emits
    /// `BASIS_BROADCAST_WIRE_VERSION` at offset 1 of the `i32_buf` (immediately
    /// after the presence sentinel).
    ///
    /// AC1 + AC5: the constant is referenced by the pack method; the unpacked
    /// basis matches the input field-by-field.
    #[test]
    fn to_broadcast_payload_emits_version_byte() {
        use super::BASIS_BROADCAST_WIRE_VERSION;

        let original = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32, 2, 3, 4],
                row_status: vec![5_i32, 6, 7, 8],
            },
            base_row_count: 2,
            cut_row_slots: vec![10_u32, 20],
            state_at_capture: vec![0.5_f64, 1.5],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        original.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        // Offset 0 is the presence sentinel (1_i32).
        assert_eq!(i32_buf[0], 1_i32, "offset 0 must be the presence sentinel");
        // Offset 1 must be the wire version.
        assert_eq!(
            i32_buf[1], BASIS_BROADCAST_WIRE_VERSION,
            "offset 1 must be BASIS_BROADCAST_WIRE_VERSION"
        );

        // Full round-trip must return a bit-equal CapturedBasis.
        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let recovered = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("round-trip must not fail")
        .expect("sentinel is 1; must return Some");

        assert_eq!(recovered.basis.col_status, original.basis.col_status);
        assert_eq!(recovered.basis.row_status, original.basis.row_status);
        assert_eq!(recovered.base_row_count, original.base_row_count);
        assert_eq!(recovered.cut_row_slots, original.cut_row_slots);
        assert_eq!(recovered.state_at_capture, original.state_at_capture);
        assert_eq!(i32_cursor, i32_buf.len(), "i32_cursor must be at end");
        assert_eq!(f64_cursor, f64_buf.len(), "f64_cursor must be at end");
    }

    /// Manually overwrite the version field (offset 1) to `2_i32` and assert
    /// that `try_from_broadcast_payload` returns `Err(SddpError::Validation)`
    /// whose message contains `"unsupported wire version 2"`.
    ///
    /// AC2: future-version peer detection.
    #[test]
    fn try_from_broadcast_payload_rejects_wrong_version() {
        use crate::SddpError;

        let cb = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32, 2, 3, 4],
                row_status: vec![5_i32, 6, 7, 8],
            },
            base_row_count: 2,
            cut_row_slots: vec![10_u32, 20],
            state_at_capture: vec![0.5_f64, 1.5],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        cb.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        // Corrupt the version field (offset 1) to simulate a future-version peer.
        i32_buf[1] = 2_i32;

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let err = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect_err("mismatched version must return Err");

        match err {
            SddpError::Validation(ref msg) => {
                assert!(
                    msg.contains("unsupported wire version 2"),
                    "error must contain 'unsupported wire version 2', got: {msg}"
                );
            }
            other => panic!("expected SddpError::Validation, got {other:?}"),
        }
    }

    /// A `None` payload (sentinel `0_i32`) returns `Ok(None)` and advances the
    /// i32 cursor by exactly 1 — the version byte is never consumed.
    ///
    /// AC3: version byte is absent on the `None` path.
    #[test]
    fn try_from_broadcast_payload_none_does_not_consume_version_byte() {
        // Build a buffer that starts with a 0 sentinel followed by sentinel=1
        // data for a second stage.  After unpacking stage 0 the cursor must
        // sit at offset 1 (i.e. the 0 sentinel was the only consumed element).
        let populated = CapturedBasis {
            basis: Basis {
                col_status: vec![7_i32],
                row_status: vec![8_i32],
            },
            base_row_count: 1,
            cut_row_slots: vec![],
            state_at_capture: vec![],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        // Stage 0: None sentinel.
        i32_buf.push(0_i32);
        // Stage 1: Some.
        populated.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;

        // Unpack stage 0 — must return None.
        let stage0 = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("stage 0 must not fail");
        assert!(stage0.is_none(), "stage 0 sentinel is 0; must return None");
        // Only the sentinel was consumed (1 element).
        assert_eq!(
            i32_cursor, 1,
            "None path must advance cursor by exactly 1 (only the sentinel)"
        );

        // Unpack stage 1 — must still succeed (version byte is intact).
        let stage1 = CapturedBasis::try_from_broadcast_payload(
            1,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("stage 1 must not fail")
        .expect("stage 1 sentinel is 1; must return Some");
        assert_eq!(stage1.basis.col_status, populated.basis.col_status);
        assert_eq!(stage1.basis.row_status, populated.basis.row_status);
        assert_eq!(i32_cursor, i32_buf.len(), "i32_cursor must be at end");
        assert_eq!(f64_cursor, f64_buf.len(), "f64_cursor must be at end");
    }

    // ---------------------------------------------------------------------------
    // Anticipated-state roundtrip tests
    // ---------------------------------------------------------------------------

    /// Roundtrip a basis whose `state_at_capture` has the
    /// `N*(1+L) + n_anticipated*k_max` layout introduced by the
    /// anticipated-thermals feature, with numerically distinct regions.
    ///
    /// AC-1, AC-2: pack then unpack; assert bit-equality of the full
    /// state slice and of the anticipated sub-slice.
    #[test]
    fn test_captured_basis_round_trip_includes_anticipated_state() {
        // Layout: N=2 hydros, L=1 PAR lag, n_anticipated=1, k_max=2.
        // n_state = 2 * (1 + 1) + 1 * 2 = 6.
        //
        // Region populations (numerically distinct so truncation shows up):
        //   storage      [0..2)  = [1.0, 2.0]
        //   lags         [2..4)  = [100.0, 200.0]
        //   anticipated  [4..6)  = [1000.0, 2000.0]
        let state_at_capture = vec![1.0_f64, 2.0, 100.0, 200.0, 1000.0, 2000.0];

        let original = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32, 2, 3, 4],
                row_status: vec![5_i32, 6, 7],
            },
            base_row_count: 2,
            cut_row_slots: vec![10_u32, 20],
            state_at_capture: state_at_capture.clone(),
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        original.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let recovered = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("round-trip must not fail")
        .expect("sentinel is 1; must return Some");

        assert_eq!(
            recovered.state_at_capture, state_at_capture,
            "full state must roundtrip bit-exactly"
        );
        assert_eq!(
            &recovered.state_at_capture[4..6],
            &[1000.0, 2000.0],
            "anticipated slice must roundtrip bit-exactly"
        );
        assert_eq!(
            &recovered.state_at_capture[2..4],
            &[100.0, 200.0],
            "lag slice must roundtrip bit-exactly"
        );
        assert_eq!(
            &recovered.state_at_capture[0..2],
            &[1.0, 2.0],
            "storage slice must roundtrip bit-exactly"
        );

        assert_eq!(i32_cursor, i32_buf.len(), "i32_cursor at end");
        assert_eq!(f64_cursor, f64_buf.len(), "f64_cursor at end");
    }

    /// Explicit length-field inspection: verify that the recorded
    /// `state_at_capture` length field in the wire payload equals `n_state`
    /// for three layouts (`n_anticipated=0` baseline, `n_anticipated` > 0 small,
    /// and a larger realistic layout).
    ///
    /// AC-3, AC-4, AC-5: introspect `i32_buf` positions.
    #[test]
    fn test_captured_basis_state_at_capture_length_is_recorded_correctly() {
        // Layout 1: small with anticipated.
        // n_state = 2 * (1+1) + 1 * 2 = 6.
        let small = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32; 4],
                row_status: vec![1_i32; 3],
            },
            base_row_count: 2,
            cut_row_slots: vec![],
            state_at_capture: vec![0.0_f64; 6],
        };
        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        small.to_broadcast_payload(&mut i32_buf, &mut f64_buf);
        // i32_buf layout (Some path):
        //   [0] = 1 (sentinel)
        //   [1] = BASIS_BROADCAST_WIRE_VERSION = 1
        //   [2] = col_len = 4
        //   [3] = row_len = 3
        //   [4] = base_row_count = 2
        //   [5] = cut_slot_count = 0
        //   [6] = state_len = 6   <-- AC-3
        assert_eq!(
            i32_buf[6], 6_i32,
            "state_at_capture length field must be 6 for N=2 L=1 A=1 K=2"
        );

        // Layout 2: n_state == 0 boundary case (AC-4).
        let empty_state = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32],
                row_status: vec![1_i32],
            },
            base_row_count: 1,
            cut_row_slots: vec![],
            state_at_capture: vec![],
        };
        let mut i32_buf2: Vec<i32> = Vec::new();
        let mut f64_buf2: Vec<f64> = Vec::new();
        empty_state.to_broadcast_payload(&mut i32_buf2, &mut f64_buf2);
        assert_eq!(
            i32_buf2[6], 0_i32,
            "state_at_capture length field must be 0 for empty state"
        );

        // Layout 3: larger realistic layout N=3 L=2 A=2 K_max=3 (AC-5).
        // n_state = 3 * (1+2) + 2 * 3 = 9 + 6 = 15.
        let large_state: Vec<f64> = (0..15).map(|i| f64::from(i) * 10.0).collect();
        let large = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32; 5],
                row_status: vec![1_i32; 5],
            },
            base_row_count: 3,
            cut_row_slots: vec![1_u32, 2],
            state_at_capture: large_state.clone(),
        };
        let mut i32_buf3: Vec<i32> = Vec::new();
        let mut f64_buf3: Vec<f64> = Vec::new();
        large.to_broadcast_payload(&mut i32_buf3, &mut f64_buf3);
        assert_eq!(
            i32_buf3[6], 15_i32,
            "state_at_capture length field must be 15 for N=3 L=2 A=2 K=3"
        );

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let recovered = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf3,
            &mut i32_cursor,
            &f64_buf3,
            &mut f64_cursor,
        )
        .expect("round-trip must not fail")
        .expect("sentinel is 1; must return Some");
        assert_eq!(
            &recovered.state_at_capture[9..15],
            &large_state[9..15],
            "anticipated slice (last 6 entries) must roundtrip bit-exactly"
        );
    }

    /// Pre-horizon seeding roundtrip: slot 0 carries sentinel 12345.5.
    #[test]
    fn test_captured_basis_round_trip_with_pre_horizon_seed_in_slot_zero() {
        let state_at_capture = vec![1.0_f64, 2.0, 100.0, 200.0, 12345.5, 0.0];
        let original = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32, 2, 3, 4],
                row_status: vec![5_i32, 6, 7, 8],
            },
            base_row_count: 3,
            cut_row_slots: vec![10_u32, 20],
            state_at_capture: state_at_capture.clone(),
        };

        let mut i32_buf = Vec::new();
        let mut f64_buf = Vec::new();
        original.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        let mut i32_cursor = 0;
        let mut f64_cursor = 0;
        let recovered = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("round-trip must not fail")
        .expect("sentinel is 1; must return Some");

        assert_eq!(recovered.state_at_capture[4], 12345.5);
        assert_eq!(recovered.basis.row_status.len(), 4);
        assert_eq!(recovered.state_at_capture, state_at_capture);
        assert_eq!(i32_cursor, i32_buf.len());
        assert_eq!(f64_cursor, f64_buf.len());
    }

    // ---------------------------------------------------------------------------
    // Layout-invariance tests (indexer-layout-impact.md Q4, Q5)
    // ---------------------------------------------------------------------------

    /// Locks `state_at_capture.len() == n_state` across the layout change.
    /// Per `indexer-layout-impact.md` Q4, the new `anticipated_state_out`
    /// column does not contribute to `state_at_capture`.
    #[test]
    fn test_state_at_capture_length_equals_n_state_after_layout_change() {
        // Layout: N=2 hydros, L=1 PAR lag, n_anticipated=1, k_max=2.
        // n_state = 2*(1+1) + 1*2 = 6.
        //
        // col_status length includes the new anticipated_state_out column slot;
        // that slot lives outside the n_state prefix and must not affect
        // state_at_capture recovery.
        let state_at_capture = vec![1.0_f64, 2.0, 100.0, 200.0, 1000.0, 2000.0];
        let original = CapturedBasis {
            basis: Basis {
                // col_status length includes the anticipated_state_out column.
                // 12 is a representative LP num_cols.
                col_status: vec![1_i32; 12],
                row_status: vec![5_i32; 8],
            },
            base_row_count: 6,
            cut_row_slots: vec![10_u32, 20],
            state_at_capture: state_at_capture.clone(),
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        original.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let recovered = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("round-trip must not fail")
        .expect("sentinel is 1; must return Some");

        assert_eq!(
            recovered.state_at_capture.len(),
            6,
            "state_at_capture.len() must equal n_state regardless of new LP columns"
        );
        assert_eq!(
            recovered.state_at_capture, state_at_capture,
            "state_at_capture round-trips bit-identically"
        );
        assert_eq!(
            recovered.basis.col_status.len(),
            12,
            "col_status length round-trips bit-identically (including the new column slot)"
        );
        assert_eq!(
            recovered.cut_row_slots, original.cut_row_slots,
            "cut_row_slots round-trips bit-identically"
        );
    }

    /// Locks `BASIS_BROADCAST_WIRE_VERSION` at 1 across the layout change.
    /// Per `indexer-layout-impact.md` Q5, adding the new `anticipated_state_out`
    /// column does not bump the wire version.
    #[test]
    fn test_basis_broadcast_wire_version_stays_one_with_state_out_column() {
        use super::BASIS_BROADCAST_WIRE_VERSION;

        // Representative basis with enough col_status entries to include the
        // new anticipated_state_out columns.
        let original = CapturedBasis {
            basis: Basis {
                col_status: vec![1_i32; 16], // includes new anticipated_state_out block
                row_status: vec![1_i32; 10],
            },
            base_row_count: 8,
            cut_row_slots: vec![],
            state_at_capture: vec![0.0_f64; 6],
        };

        let mut i32_buf: Vec<i32> = Vec::new();
        let mut f64_buf: Vec<f64> = Vec::new();
        original.to_broadcast_payload(&mut i32_buf, &mut f64_buf);

        // i32_buf layout per workspace.rs to_broadcast_payload:
        //   [0]: sentinel (1)
        //   [1]: BASIS_BROADCAST_WIRE_VERSION
        //   [2]: col_status.len()
        //   [3]: row_status.len()
        //   [4]: base_row_count
        //   [5]: cut_row_slots.len()
        //   [6]: state_at_capture.len()
        //   [7..]: col_status elements, then row_status, then cut_row_slots
        assert_eq!(i32_buf[0], 1, "sentinel must be 1");
        assert_eq!(
            i32_buf[1], BASIS_BROADCAST_WIRE_VERSION,
            "wire version field must equal BASIS_BROADCAST_WIRE_VERSION (= 1)"
        );
        assert_eq!(
            BASIS_BROADCAST_WIRE_VERSION, 1,
            "broadcast wire-format version constant must remain stable across releases"
        );

        // Full round-trip confirms no data drift.
        let mut i32_cursor = 0_usize;
        let mut f64_cursor = 0_usize;
        let recovered = CapturedBasis::try_from_broadcast_payload(
            0,
            &i32_buf,
            &mut i32_cursor,
            &f64_buf,
            &mut f64_cursor,
        )
        .expect("round-trip must not fail")
        .expect("sentinel is 1; must return Some");

        assert_eq!(recovered.basis.col_status, original.basis.col_status);
        assert_eq!(recovered.basis.row_status, original.basis.row_status);
        assert_eq!(recovered.base_row_count, original.base_row_count);
        assert_eq!(recovered.cut_row_slots, original.cut_row_slots);
        assert_eq!(recovered.state_at_capture, original.state_at_capture);
    }

    // ---------------------------------------------------------------------------
    // ProfiledSolver integration
    // ---------------------------------------------------------------------------

    /// A freshly constructed workspace must expose a solver whose
    /// `current_profile()` equals `HighsProfile::default()`.
    ///
    /// Confirms that `ProfiledSolver::new` wraps the inner solver without
    /// issuing any FFI calls and that `WorkspacePool::new` correctly initialises
    /// every workspace.
    ///
    /// Gated to `feature = "highs"` because it embeds the backend-specific
    /// default-profile value `HighsProfile::default()`; a CLP analog is a
    /// separate assertion.
    #[cfg(all(test, feature = "highs"))]
    #[test]
    fn workspace_solver_initialised_with_default_profile() {
        use cobre_solver::HighsProfile;

        let pool = WorkspacePool::new(0, 2, 0, WorkspaceSizing::default(), || MockSolver);
        for ws in &pool.workspaces {
            assert_eq!(
                ws.solver.current_profile(),
                &HighsProfile::default(),
                "solver.current_profile() must equal HighsProfile::default() after construction"
            );
        }

        // Also verify SolverWorkspace::new directly.
        let ws = SolverWorkspace::new(
            0,
            0,
            MockSolver,
            crate::lp_builder::PatchBuffer::new(0, 0, 0, 0, 0, 0),
            0,
            WorkspaceSizing::default(),
        );
        assert_eq!(
            ws.solver.current_profile(),
            &HighsProfile::default(),
            "SolverWorkspace::new must initialise solver with default profile"
        );
    }
}