lp-ip-craft-native 0.34.0

Native Rust LP/MIP engine: dual revised simplex on a sparse LU factorization, presolve, cuts and branch-and-bound
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
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
//! Bounded-variable dual revised simplex for LPs and branch-and-bound nodes.
//!
//! Internal form: `Ã x̃ − r̃ = 0` with `l ≤ (x̃, r̃) ≤ u`. Here `Ã = R A S`
//! is the kept submatrix equilibrated by powers of two, `x̃ = S⁻¹ x` are the
//! scaled structural variables and `r̃ = R (A x)` the scaled row activities
//! ("logicals", basis column `−e_i`); root-fixed columns that presolve drops
//! shift the row bounds instead. The objective `σ c`
//! (`σ = −1` for maximization) becomes `σ c S / C`. Powers of two keep bounds
//! and nonbasic values exact, so every nonbasic variable sits exactly on an
//! original bound. Variable bounds are never rows: branching changes bounds
//! in place and keeps the factorized basis.
//!
//! Each dual simplex iteration chooses a primal infeasible basic variable by
//! dual steepest edge, computes its tableau row from `ρ = B⁻ᵀ e_r` with the
//! row-wise matrix, and chooses the entering variable with a bound-flipping
//! ratio test and Harris tolerances. Dual infeasibility on columns without a
//! finite box is removed by an auxiliary phase 1 (bounds replaced by
//! `{0}`, `[0, 1]`, `[−1, 0]` or `[−1, 1]`). Cost perturbation is switched on
//! after a run of degenerate steps and removed before optimality is declared.
//! Optima are declared on primal and dual values recomputed from scratch
//! (after a refactorization for cold solves); callers check them again.

use crate::Budget;
use crate::lu::{FactorError, Lu};
use lp_ip_craft::{Duals, Error, Model, Result, Sense, Status};

/// Entries of `ρ` at or below this magnitude are skipped in the pivot row.
const DROP: f64 = 1e-14;
const NIL: usize = usize::MAX;
/// Degenerate (zero dual step) iterations before costs are perturbed.
const DEGENERATE_STREAK: usize = 25;
/// Smallest steepest-edge weight kept after an update.
const MIN_WEIGHT: f64 = 1e-6;
const PRICE_BLOCK: usize = 64;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum State {
    Basic,
    Lower,
    Upper,
    /// Nonbasic free variable at zero.
    Zero,
}

/// Kernel controls derived from the solver options.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Controls {
    pub threads: usize,
    pub pivot_tolerance: f64,
    pub refactor_interval: usize,
    pub adaptive_refactor: bool,
    pub basis_update: crate::BasisUpdate,
    pub factor_pivot_search: usize,
    pub factor_ordering: crate::FactorOrdering,
    pub max_factor_entries: usize,
    pub factor_replay: bool,
    pub adaptive_pricing: bool,
    pub devex: bool,
    pub steepest_edge: bool,
    /// Primal tolerance target in original units.
    pub feasibility: f64,
    /// Dual tolerance target in original units (already objective-scaled).
    pub dual: f64,
}

/// Counters accumulated over the lifetime of one LP.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Stats {
    pub peak_entries: usize,
    pub refactors: u64,
    pub phase_one_pivots: u64,
    pub degenerate_pivots: u64,
    pub weight_resets: u64,
    pub row_pricings: u64,
    pub column_pricings: u64,
    pub replayed_pivots: u64,
    pub updates: u64,
    pub ft_updates: u64,
    pub bound_flips: u64,
    pub repairs: u64,
    pub restores: u64,
    pub perturbations: u64,
}

/// A basis with nonbasic states and steepest-edge weights.
pub(crate) struct Basis {
    id: u64,
    basic: Vec<usize>,
    state: Vec<State>,
    weight: Vec<f64>,
}

impl Basis {
    pub fn bytes(&self) -> usize {
        self.state.len() * std::mem::size_of::<State>()
            + self.basic.len() * (std::mem::size_of::<usize>() + std::mem::size_of::<f64>())
    }
}

#[derive(Clone, Copy)]
struct Candidate {
    j: usize,
    /// Pivot row entry with the sign of the leaving direction applied.
    a: f64,
    ratio: f64,
    harris: f64,
}

enum Outcome {
    Optimal,
    Infeasible,
    Restart,
    Stopped(Status),
    Failure,
}

/// The LP's prices and approximate objective are only screening hints.
/// The cutoff is verified on the current, original-coordinate box.
struct Cutoff<'a> {
    model: &'a Model,
    bounds: &'a lp_ip_craft::Bounds,
    upper: f64,
    constant: f64,
    interval: u64,
    lattice: bool,
    verified: Option<f64>,
}

pub(crate) struct Lp {
    execution: crate::parallel::Execution,
    n: usize,
    m: usize,
    rows: Vec<usize>,
    /// Model column of each LP column, and LP column (or `NIL`) of each
    /// model column; dropped columns are fixed at `fixed`.
    cols: Vec<usize>,
    col_of: Vec<usize>,
    fixed: Vec<f64>,
    col_start: Vec<usize>,
    col_index: Vec<usize>,
    col_value: Vec<f64>,
    row_start: Vec<usize>,
    row_index: Vec<usize>,
    row_value: Vec<f64>,
    col_scale: Vec<f64>,
    row_scale: Vec<f64>,
    /// Contribution of dropped fixed columns to each LP row.
    shift: Vec<f64>,
    cost_scale: f64,
    sign: f64,
    cost0: Vec<f64>,
    cost: Vec<f64>,
    lower: Vec<f64>,
    upper: Vec<f64>,
    ptol: Vec<f64>,
    dtol: Vec<f64>,
    basic: Vec<usize>,
    state: Vec<State>,
    x: Vec<f64>,
    d: Vec<f64>,
    pi: Vec<f64>,
    weight: Vec<f64>,
    price_dirty: Vec<bool>,
    price_score: Vec<f64>,
    price_row: Vec<Option<usize>>,
    lu: Option<Lu>,
    factor_workspace: crate::active::FactorWorkspace,
    rho: Vec<f64>,
    rho_index: Vec<usize>,
    column: Vec<f64>,
    column_index: Vec<usize>,
    tau: Vec<f64>,
    work: Vec<f64>,
    alpha: Vec<f64>,
    marked: Vec<bool>,
    touched: Vec<usize>,
    candidates: Vec<Candidate>,
    flips: Vec<usize>,
    controls: Controls,
    perturbed: bool,
    primal_stale: bool,
    dual_stale: bool,
    fresh_optimum: bool,
    seed: u64,
    next_id: u64,
    basis_id: Option<u64>,
    ray: Option<Vec<f64>>,
    iteration_guard: u64,
    pub stats: Stats,
}

fn pow2(v: f64) -> f64 {
    let e = v.log2().round().clamp(-60.0, 60.0) as i32;
    2f64.powi(e)
}

impl Lp {
    /// Builds the scaled LP over the rows with `keep_rows[i]` and columns
    /// with `keep_cols[j]` and the model's variable bounds, with a logical
    /// (slack) starting basis. Dropped columns must be fixed (`l = u`); their
    /// contribution shifts the row bounds.
    pub fn new(
        model: &Model,
        keep_rows: &[bool],
        keep_cols: &[bool],
        controls: Controls,
    ) -> Result<Self> {
        let rows: Vec<usize> = (0..model.m()).filter(|&i| keep_rows[i]).collect();
        let cols: Vec<usize> = (0..model.n()).filter(|&j| keep_cols[j]).collect();
        let (n, m) = (cols.len(), rows.len());
        let mut col_of = vec![NIL; model.n()];
        for (j, &c) in cols.iter().enumerate() {
            col_of[c] = j;
        }
        let fixed = model.variables().lower.clone();
        debug_assert!(
            (0..model.n()).all(|j| keep_cols[j] || fixed[j] == model.variables().upper[j])
        );
        let a = model.matrix();
        let mut col_start = vec![0usize; n + 1];
        let mut shift = vec![0.0; m];
        for (k, &i) in rows.iter().enumerate() {
            for e in a.pattern.indptr[i]..a.pattern.indptr[i + 1] {
                let (c, v) = (a.pattern.indices[e], a.values[e]);
                if v == 0.0 {
                    continue;
                }
                match col_of[c] {
                    NIL => shift[k] += v * fixed[c],
                    j => col_start[j + 1] += 1,
                }
            }
        }
        for j in 0..n {
            col_start[j + 1] += col_start[j];
        }
        let nnz = col_start[n];
        let mut fill = col_start.clone();
        let mut col_index = vec![0usize; nnz];
        let mut col_value = vec![0.0; nnz];
        for (k, &i) in rows.iter().enumerate() {
            for e in a.pattern.indptr[i]..a.pattern.indptr[i + 1] {
                let v = a.values[e];
                let j = col_of[a.pattern.indices[e]];
                if v != 0.0 && j != NIL {
                    col_index[fill[j]] = k;
                    col_value[fill[j]] = v;
                    fill[j] += 1;
                }
            }
        }
        let (row_scale, col_scale) = scale_factors(m, &col_start, &col_index, &col_value);
        for j in 0..n {
            for e in col_start[j]..col_start[j + 1] {
                col_value[e] *= row_scale[col_index[e]] * col_scale[j];
            }
        }
        // Row-wise copy of the scaled matrix.
        let mut row_start = vec![0usize; m + 1];
        for &k in &col_index {
            row_start[k + 1] += 1;
        }
        for k in 0..m {
            row_start[k + 1] += row_start[k];
        }
        let mut fill = row_start.clone();
        let mut row_index = vec![0usize; nnz];
        let mut row_value = vec![0.0; nnz];
        for j in 0..n {
            for e in col_start[j]..col_start[j + 1] {
                let k = col_index[e];
                row_index[fill[k]] = j;
                row_value[fill[k]] = col_value[e];
                fill[k] += 1;
            }
        }
        let sign = if model.sense() == Sense::Minimize {
            1.0
        } else {
            -1.0
        };
        let raw: Vec<f64> = (0..n)
            .map(|j| sign * model.objective()[cols[j]] * col_scale[j])
            .collect();
        let largest = raw.iter().fold(0.0_f64, |s, v| s.max(v.abs()));
        let cost_scale = if largest > 0.0 && largest.is_finite() {
            pow2(largest)
        } else {
            1.0
        };
        let mut cost0: Vec<f64> = raw.iter().map(|v| v / cost_scale).collect();
        cost0.resize(n + m, 0.0);
        if cost0.iter().any(|v| !v.is_finite()) {
            return Err(Error::Unsupported("objective scaling overflow".into()));
        }
        let mut lower = vec![0.0; n + m];
        let mut upper = vec![0.0; n + m];
        for (k, &i) in rows.iter().enumerate() {
            lower[n + k] = scaled(model.rows().lower[i] - shift[k], row_scale[k])?;
            upper[n + k] = scaled(model.rows().upper[i] - shift[k], row_scale[k])?;
        }
        let feasibility = 0.1 * controls.feasibility;
        let dual = 0.1 * controls.dual;
        let mut ptol = Vec::with_capacity(n + m);
        let mut dtol = Vec::with_capacity(n + m);
        for &s in &col_scale {
            ptol.push((feasibility / s).clamp(1e-12, 1e-7));
            dtol.push((dual * s / cost_scale).clamp(1e-12, 1e-7));
        }
        for &r in &row_scale {
            ptol.push((feasibility * r).clamp(1e-12, 1e-7));
            dtol.push((dual / (cost_scale * r)).clamp(1e-12, 1e-7));
        }
        let mut lp = Self {
            execution: if nnz >= 65_536 {
                crate::parallel::Execution::new(controls.threads).map_err(Error::Backend)?
            } else {
                crate::parallel::Execution::default()
            },
            n,
            m,
            rows,
            cols,
            col_of,
            fixed,
            col_start,
            col_index,
            col_value,
            row_start,
            row_index,
            row_value,
            col_scale,
            row_scale,
            shift,
            cost_scale,
            sign,
            cost: cost0.clone(),
            cost0,
            lower,
            upper,
            ptol,
            dtol,
            basic: Vec::new(),
            state: vec![State::Lower; n + m],
            x: vec![0.0; n + m],
            d: vec![0.0; n + m],
            pi: vec![0.0; m],
            weight: vec![1.0; m],
            price_dirty: vec![true; m.div_ceil(PRICE_BLOCK)],
            price_score: vec![0.; m.div_ceil(PRICE_BLOCK)],
            price_row: vec![None; m.div_ceil(PRICE_BLOCK)],
            lu: None,
            factor_workspace: Default::default(),
            rho: vec![0.0; m],
            rho_index: Vec::new(),
            column: vec![0.0; m],
            column_index: Vec::new(),
            tau: vec![0.0; m],
            work: vec![0.0; m],
            alpha: vec![0.0; n + m],
            marked: vec![false; n + m],
            touched: Vec::new(),
            candidates: Vec::new(),
            flips: Vec::new(),
            controls,
            perturbed: false,
            primal_stale: true,
            dual_stale: true,
            fresh_optimum: true,
            seed: 0x9E37_79B9_7F4A_7C15 ^ ((n as u64) << 20) ^ m as u64,
            next_id: 0,
            basis_id: None,
            ray: None,
            iteration_guard: 50 * (n + m) as u64 + 10_000,
            stats: Stats::default(),
        };
        lp.set_bounds(&model.variables().lower, &model.variables().upper)?;
        lp.reset_to_slack();
        Ok(lp)
    }

    /// Shrinks bounds on rows containing continuous columns inward by a margin
    /// above primal tolerance (for incumbent certification). A row whose
    /// interval is too narrow keeps its bounds.
    pub fn shrink_rows(&mut self, model: &Model) {
        let a = model.matrix();
        for k in self.n..self.n + self.m {
            let i = self.rows[k - self.n];
            // Certification fixes integer columns. Shrinking a tight
            // all-integer row would make that fixed point infeasible.
            if (a.pattern.indptr[i]..a.pattern.indptr[i + 1])
                .any(|e| a.values[e] != 0. && !model.kinds()[a.pattern.indices[e]].is_integral())
            {
                self.shrink(k);
            }
        }
        self.primal_stale = true;
    }

    /// Fixes the integral variables at `x` and gives the others their
    /// `bounds` shrunk like [`Lp::shrink_rows`] (original units).
    pub fn fix_for_certification(
        &mut self,
        x: &[f64],
        integral: &[bool],
        bounds: &lp_ip_craft::Bounds,
    ) -> Result<()> {
        for j in 0..self.n {
            let c = self.cols[j];
            if integral[c] {
                self.set_lp_bound(j, x[c], x[c])?;
            } else {
                self.set_lp_bound(j, bounds.lower[c], bounds.upper[c])?;
                self.shrink(j);
            }
        }
        Ok(())
    }

    fn shrink(&mut self, j: usize) {
        let margin = 16.0 * self.ptol[j];
        let (l, u) = (self.lower[j], self.upper[j]);
        let room = if l.is_finite() && u.is_finite() {
            u - l
        } else {
            f64::INFINITY
        };
        if room <= 4.0 * margin {
            return;
        }
        let pad = |v: f64| margin * v.abs().max(1.0);
        if l.is_finite() {
            self.lower[j] = l + pad(l);
        }
        if u.is_finite() {
            self.upper[j] = u - pad(u);
        }
        if self.lower[j] > self.upper[j] {
            (self.lower[j], self.upper[j]) = (l, u);
        }
        if self.state[j] != State::Basic {
            self.state[j] = self.valid_state(j, self.state[j]);
            self.primal_stale = true;
        }
    }

    /// Number of model rows not represented in the LP.
    pub fn removed_rows(&self, model: &Model) -> usize {
        model.m() - self.m
    }

    /// Number of model columns fixed outside the LP.
    pub fn removed_columns(&self) -> usize {
        self.col_of.len() - self.n
    }

    /// Replaces the structural bounds (original units, model columns). The
    /// basis is kept.
    pub fn set_bounds(&mut self, lower: &[f64], upper: &[f64]) -> Result<()> {
        for c in 0..self.col_of.len() {
            self.set_bound(c, lower[c], upper[c])?;
        }
        Ok(())
    }

    /// Replaces the bounds of model column `c` (original units). Columns
    /// dropped as fixed keep their value.
    pub fn set_bound(&mut self, c: usize, lower: f64, upper: f64) -> Result<()> {
        let j = self.col_of[c];
        if j == NIL {
            debug_assert!(lower == self.fixed[c] && upper == self.fixed[c]);
            return Ok(());
        }
        self.set_lp_bound(j, lower, upper)
    }

    /// Replaces the bounds of LP row `k` (original units). The basis is kept.
    pub fn set_row_bounds(&mut self, k: usize, lower: f64, upper: f64) -> Result<()> {
        let l = scaled(lower - self.shift[k], self.row_scale[k])?;
        let u = scaled(upper - self.shift[k], self.row_scale[k])?;
        self.assign_bounds(self.n + k, l, u);
        Ok(())
    }

    fn set_lp_bound(&mut self, j: usize, lower: f64, upper: f64) -> Result<()> {
        let l = scaled(lower, 1.0 / self.col_scale[j])?;
        let u = scaled(upper, 1.0 / self.col_scale[j])?;
        self.assign_bounds(j, l, u);
        Ok(())
    }

    fn assign_bounds(&mut self, j: usize, l: f64, u: f64) {
        if l != self.lower[j] || u != self.upper[j] {
            self.price_dirty.fill(true);
            self.lower[j] = l;
            self.upper[j] = u;
            if self.state[j] != State::Basic {
                self.state[j] = self.valid_state(j, self.state[j]);
                self.primal_stale = true;
            }
        }
    }

    /// A different leaving-row order can escape a cycling MIP node. The retry
    /// starts from the slack basis and uses the parent pivot and time budget.
    pub(crate) fn retry_unweighted(&mut self, budget: &mut Budget<'_>) -> Result<Status> {
        self.unperturb();
        let weighted = std::mem::replace(&mut self.controls.steepest_edge, false);
        self.reset_to_slack();
        let result = self.solve(budget, true);
        self.controls.steepest_edge = weighted;
        self.weight.fill(1.0);
        self.price_dirty.fill(true);
        result
    }

    /// Returns to the logical basis `−I` with unit steepest-edge weights.
    pub fn reset_to_slack(&mut self) {
        let (n, m) = (self.n, self.m);
        self.basic = (n..n + m).collect();
        for k in 0..m {
            self.state[n + k] = State::Basic;
        }
        for j in 0..n {
            let preferred = if self.cost[j] >= 0.0 {
                State::Lower
            } else {
                State::Upper
            };
            self.state[j] = self.valid_state(j, preferred);
        }
        self.weight.fill(1.0);
        self.price_dirty.fill(true);
        self.lu = None;
        self.primal_stale = true;
        self.basis_id = None;
    }

    /// Captures the current basis; [`Lp::matches`] holds until the next solve.
    pub fn snapshot(&mut self) -> Basis {
        self.next_id += 1;
        self.basis_id = Some(self.next_id);
        Basis {
            id: self.next_id,
            basic: self.basic.clone(),
            state: self.state.clone(),
            weight: self.weight.clone(),
        }
    }

    /// Approximate heap bytes of one snapshot.
    pub fn snapshot_bytes(&self) -> usize {
        (self.n + self.m) * std::mem::size_of::<State>()
            + self.m * (std::mem::size_of::<usize>() + std::mem::size_of::<f64>())
    }

    pub fn matches(&self, basis: &Basis) -> bool {
        self.basis_id == Some(basis.id)
    }

    /// Reinstates a snapshot; the next solve refactorizes it.
    pub fn restore(&mut self, basis: &Basis) {
        if basis.basic.len() < self.m {
            let mut extended = Basis {
                id: basis.id,
                basic: basis.basic.clone(),
                state: basis.state.clone(),
                weight: basis.weight.clone(),
            };
            extended
                .basic
                .extend((self.n + basis.basic.len())..(self.n + self.m));
            extended.state.resize(self.n + self.m, State::Basic);
            extended.weight.resize(self.m, 1.);
            self.restore(&extended);
            return;
        }
        if self.matches(basis) {
            return;
        }
        self.stats.restores += 1;
        self.basis_id = Some(basis.id);
        if self.lu.is_some() && self.restore_by_updates(basis) {
            return;
        }
        self.basic.clone_from(&basis.basic);
        self.state.clone_from(&basis.state);
        self.weight.clone_from(&basis.weight);
        self.price_dirty.fill(true);
        for j in 0..self.n + self.m {
            if self.state[j] != State::Basic {
                self.state[j] = self.valid_state(j, self.state[j]);
            }
        }
        self.lu = None;
        self.primal_stale = true;
    }

    /// Reaches a snapshot that differs in a few basis positions by eta
    /// column replacements on the current factorization. Returns false
    /// (leaving the caller to refactorize) when the difference is large or a
    /// replacement pivot is not clearly nonzero.
    fn restore_by_updates(&mut self, basis: &Basis) -> bool {
        let lu = self.lu.as_ref().expect("factorized basis");
        let room = self.controls.refactor_interval.saturating_sub(lu.updates());
        let mut pending: Vec<usize> = (0..self.m)
            .filter(|&p| self.basic[p] != basis.basic[p])
            .collect();
        if pending.len() > room.min(16) {
            return false;
        }
        while !pending.is_empty() {
            // Replace only with currently nonbasic columns, so no column is
            // ever basic twice.
            let Some(k) = pending
                .iter()
                .position(|&p| self.state[basis.basic[p]] != State::Basic)
            else {
                return false;
            };
            let p = pending.swap_remove(k);
            let entering = basis.basic[p];
            self.compute_column(entering);
            let largest = self.column.iter().fold(0.0_f64, |a, v| a.max(v.abs()));
            if self.column[p].abs() < 1e-7 * largest.max(1.0) {
                return false;
            }
            let lu = self.lu.as_mut().expect("factorized basis");
            if !lu.update_sparse(p, &self.column, self.column_index.iter().copied()) {
                return false;
            }
            self.stats.ft_updates += u64::from(lu.uses_ft());
            self.stats.updates += 1;
            self.stats.peak_entries = self.stats.peak_entries.max(lu.entries());
            let leaving = self.basic[p];
            self.basic[p] = entering;
            self.state[entering] = State::Basic;
            self.state[leaving] = State::Lower;
        }
        self.state.clone_from(&basis.state);
        self.weight.clone_from(&basis.weight);
        self.price_dirty.fill(true);
        for j in 0..self.n + self.m {
            if self.state[j] != State::Basic {
                self.state[j] = self.valid_state(j, self.state[j]);
            }
        }
        self.primal_stale = true;
        self.dual_stale = true;
        true
    }

    /// Structural values in original units, for every model column.
    pub fn point(&self) -> Vec<f64> {
        let mut x = self.fixed.clone();
        for (j, &c) in self.cols.iter().enumerate() {
            x[c] = self.x[j] * self.col_scale[j];
        }
        x
    }

    /// Row duals and reduced costs in the original sense and units. A row
    /// price whose sign selects an infinite row bound is within the dual
    /// tolerance at an optimum and is reported as zero, so that it cannot
    /// make a conservative dual bound unavailable.
    pub fn duals(&self, model: &Model) -> Duals {
        let mut y = vec![0.0; model.m()];
        for (k, &i) in self.rows.iter().enumerate() {
            let price = self.pi[k];
            let infinite = if price > 0.0 {
                self.lower[self.n + k] == f64::NEG_INFINITY
            } else {
                self.upper[self.n + k] == f64::INFINITY
            };
            if !infinite {
                y[i] = self.sign * self.cost_scale * self.row_scale[k] * price;
            }
        }
        let mut at = vec![0.0; model.n()];
        model.matrix().multiply_transpose(&y, &mut at);
        Duals {
            reduced_costs: model
                .objective()
                .iter()
                .zip(at)
                .map(|(&c, a)| c - a)
                .collect(),
            row_duals: y,
        }
    }

    /// Re-checks the last infeasibility claim with its Farkas row
    /// `ρᵀ(Ã x̃ − r̃) = 0`: the combination must be bounded away from zero
    /// over the current box, independently of the factorization. A numerical
    /// check (tiny coefficients are ignored), not an exact certificate.
    pub fn infeasibility_verified(&self) -> bool {
        let Some(rho) = &self.ray else {
            return false;
        };
        let mut coefficient = Vec::with_capacity(self.n + self.m);
        for j in 0..self.n {
            let mut v = 0.0;
            for e in self.col_start[j]..self.col_start[j + 1] {
                v += self.col_value[e] * rho[self.col_index[e]];
            }
            coefficient.push(v);
        }
        coefficient.extend(rho.iter().map(|v| -v));
        let largest = coefficient.iter().fold(0.0_f64, |s, v| s.max(v.abs()));
        if largest == 0.0 || !largest.is_finite() {
            return false;
        }
        // Range [lo, hi] of the combination over the box, with the sums of
        // magnitudes of each side for a rounding margin.
        let (mut lo, mut hi) = (0.0_f64, 0.0_f64);
        let (mut lo_size, mut hi_size) = (largest, largest);
        for (j, &v) in coefficient.iter().enumerate() {
            if v.abs() <= 1e-12 * largest {
                continue;
            }
            let (l, u) = (self.lower[j], self.upper[j]);
            let (a, b) = if v > 0.0 {
                (v * l, v * u)
            } else {
                (v * u, v * l)
            };
            lo += a;
            hi += b;
            lo_size += a.abs();
            hi_size += b.abs();
        }
        hi < -1e-9 * hi_size || lo > 1e-9 * lo_size
    }

    fn lu(&mut self) -> &mut Lu {
        self.lu.as_mut().expect("factorized basis")
    }

    fn valid_state(&self, j: usize, preferred: State) -> State {
        let (l, u) = (self.lower[j], self.upper[j]);
        match (l.is_finite(), u.is_finite()) {
            (true, true) if l == u => State::Lower,
            (true, true) => match preferred {
                State::Upper => State::Upper,
                State::Lower => State::Lower,
                _ if self.d[j] < 0.0 => State::Upper,
                _ => State::Lower,
            },
            (true, false) => State::Lower,
            (false, true) => State::Upper,
            (false, false) => State::Zero,
        }
    }

    fn state_from_dual(&self, j: usize) -> State {
        let preferred = if self.d[j] >= 0.0 {
            State::Lower
        } else {
            State::Upper
        };
        self.valid_state(j, preferred)
    }

    fn value(&self, j: usize) -> f64 {
        match self.state[j] {
            State::Lower => self.lower[j],
            State::Upper => self.upper[j],
            State::Zero => 0.0,
            State::Basic => self.x[j],
        }
    }

    fn boxed(&self, j: usize) -> bool {
        self.lower[j].is_finite() && self.upper[j].is_finite()
    }

    /// Adds `scale * a_j` (structural or logical column) to a row vector.
    fn add_column(
        col_start: &[usize],
        col_index: &[usize],
        col_value: &[f64],
        n: usize,
        j: usize,
        scale: f64,
        out: &mut [f64],
    ) {
        if j < n {
            for e in col_start[j]..col_start[j + 1] {
                out[col_index[e]] += scale * col_value[e];
            }
        } else {
            out[j - n] -= scale;
        }
    }

    /// Factorizes the basis, replacing dependent columns by logicals.
    /// Returns whether the basis had to be repaired.
    fn refactor(&mut self) -> Result<bool> {
        let _profile = crate::profile::enter("refactor_other");
        let mut repaired = false;
        for attempt in 0..4 {
            if attempt == 3 {
                // Repairs did not converge numerically; the slack basis always does.
                self.reset_to_slack();
            }
            let column = |p: usize, out: &mut Vec<(usize, f64)>| {
                let j = self.basic[p];
                if j < self.n {
                    let range = self.col_start[j]..self.col_start[j + 1];
                    out.extend(
                        self.col_index[range.clone()]
                            .iter()
                            .copied()
                            .zip(self.col_value[range].iter().copied()),
                    );
                } else {
                    out.push((j - self.n, -1.0));
                }
            };
            #[cfg(feature = "basis-replay")]
            crate::replay::capture(self.m, column, &[&self.rho, &self.pi]);
            let ordered = match self.controls.factor_ordering {
                crate::FactorOrdering::Natural => false,
                crate::FactorOrdering::MinDegree => true,
                crate::FactorOrdering::Auto => {
                    self.m >= 2048
                        && self
                            .lu
                            .as_ref()
                            .is_some_and(|old| old.dense_dimension() > self.m / 8)
                }
            };
            match Lu::factor_with_execution(
                self.m,
                column,
                self.controls.max_factor_entries,
                &mut self.factor_workspace,
                crate::lu::FactorOptions {
                    replay: self.controls.factor_replay,
                    search: self.controls.factor_pivot_search,
                    ordered,
                },
                &self.execution,
            ) {
                Ok(mut lu) => {
                    #[cfg(feature = "kernel-profile")]
                    if std::env::var_os("LPIP_TRACE_FACTORS").is_some() {
                        eprintln!(
                            "factor {:?}",
                            (
                                self.m,
                                lu.factor_sizes(),
                                self.lu.as_ref().map_or(0, |old| old.average_update_nnz())
                            )
                        );
                    }
                    // FT avoids dense eta files on sparse factors. Keep the
                    // compact product form when previous updates stayed sparse
                    // or the new factors themselves have substantial fill.
                    if self.controls.basis_update == crate::BasisUpdate::ForrestTomlin
                        || (self.controls.basis_update == crate::BasisUpdate::Auto
                            && lu.ft_suitable()
                            && self.lu.as_ref().is_some_and(|old| {
                                old.average_update_nnz()
                                    .saturating_mul(self.controls.refactor_interval)
                                    > 4 * lu.entries()
                            }))
                    {
                        lu.enable_ft();
                    }
                    self.stats.replayed_pivots += lu.replayed_pivots() as u64;
                    self.stats.refactors += 1;
                    self.stats.peak_entries = self.stats.peak_entries.max(lu.entries());
                    self.lu = Some(lu);
                    self.primal_stale = true;
                    return Ok(repaired || attempt == 3);
                }
                Err(FactorError::TooLarge) => {
                    return Err(Error::Unsupported(format!(
                        "basis factorization exceeds max_factor_entries = {}",
                        self.controls.max_factor_entries
                    )));
                }
                Err(FactorError::Singular { positions, rows }) => {
                    repaired = true;
                    self.stats.repairs += positions.len() as u64;
                    for (p, i) in positions.into_iter().zip(rows) {
                        let j = self.basic[p];
                        let logical = self.n + i;
                        let (l, u) = (self.lower[j], self.upper[j]);
                        let nearer = if (self.x[j] - l).abs() <= (u - self.x[j]).abs() {
                            State::Lower
                        } else {
                            State::Upper
                        };
                        self.state[j] = self.valid_state(j, nearer);
                        self.basic[p] = logical;
                        self.state[logical] = State::Basic;
                        self.weight[p] = 1.0;
                    }
                }
            }
        }
        unreachable!("the slack basis factorizes")
    }

    /// Basic values from the nonbasic values: `x_B = −B⁻¹ N x_N`.
    fn compute_primal(&mut self) {
        let _profile = crate::profile::enter("recompute_primal");
        let (n, m) = (self.n, self.m);
        self.work.fill(0.0);
        for j in 0..n + m {
            if self.state[j] != State::Basic {
                let v = self.value(j);
                self.x[j] = v;
                if v != 0.0 {
                    Self::add_column(
                        &self.col_start,
                        &self.col_index,
                        &self.col_value,
                        n,
                        j,
                        v,
                        &mut self.work,
                    );
                }
            }
        }
        let lu = self.lu.as_mut().expect("factorized basis");
        lu.ftran(&mut self.work);
        for p in 0..m {
            self.x[self.basic[p]] = -self.work[p];
        }
        self.primal_stale = false;
        self.price_dirty.fill(true);
    }

    /// Row prices `π = B⁻ᵀ c_B` and reduced costs `d = c − [Ã −I]ᵀ π`.
    fn compute_dual(&mut self) {
        let _profile = crate::profile::enter("recompute_dual");
        self.dual_stale = false;
        debug_assert!(self.execution.threads() <= self.controls.threads);
        let n = self.n;
        for p in 0..self.m {
            self.pi[p] = self.cost[self.basic[p]];
        }
        let lu = self.lu.as_mut().expect("factorized basis");
        lu.btran(&mut self.pi);
        // A basic logical column −e_i forces π_i = 0 exactly.
        for k in 0..self.m {
            if self.state[n + k] == State::Basic {
                self.pi[k] = 0.0;
            }
        }
        let work = if self.execution.threads() > 1 {
            (0..n)
                .filter(|&j| self.state[j] != State::Basic)
                .map(|j| self.col_start[j + 1] - self.col_start[j])
                .sum::<usize>()
        } else {
            0
        };
        if work >= 262_144 {
            let (state, cost, start, index, value, pi) = (
                &self.state,
                &self.cost,
                &self.col_start,
                &self.col_index,
                &self.col_value,
                &self.pi,
            );
            self.execution
                .chunks_mut(&mut self.d[..n], 64, work, |offset, part| {
                    for (local, out) in part.iter_mut().enumerate() {
                        let j = offset + local;
                        *out = if state[j] == State::Basic {
                            0.
                        } else {
                            let mut v = cost[j];
                            for e in start[j]..start[j + 1] {
                                v -= value[e] * pi[index[e]];
                            }
                            v
                        };
                    }
                });
        } else {
            for j in 0..n {
                self.d[j] = if self.state[j] == State::Basic {
                    0.0
                } else {
                    let mut v = self.cost[j];
                    for e in self.col_start[j]..self.col_start[j + 1] {
                        v -= self.col_value[e] * self.pi[self.col_index[e]];
                    }
                    v
                };
            }
        }
        for k in 0..self.m {
            self.d[n + k] = if self.state[n + k] == State::Basic {
                0.0
            } else {
                self.cost[n + k] + self.pi[k]
            };
        }
    }

    /// Moves boxed nonbasic variables with wrong-signed reduced costs to the
    /// other bound. Returns the number of flips.
    fn flip_to_dual_feasible(&mut self) -> usize {
        let mut flips = 0;
        for j in 0..self.n + self.m {
            if self.state[j] == State::Basic || !self.boxed(j) || self.lower[j] == self.upper[j] {
                continue;
            }
            let next = match self.state[j] {
                State::Lower if self.d[j] < -self.dtol[j] => State::Upper,
                State::Upper if self.d[j] > self.dtol[j] => State::Lower,
                _ => continue,
            };
            self.state[j] = next;
            flips += 1;
        }
        if flips > 0 {
            self.primal_stale = true;
            self.stats.bound_flips += flips as u64;
        }
        flips
    }

    fn nonboxed_dual_infeasible(&self) -> bool {
        (0..self.n + self.m).any(|j| {
            if self.state[j] == State::Basic || self.boxed(j) {
                return false;
            }
            let (d, tol) = (self.d[j], self.dtol[j]);
            match self.state[j] {
                State::Lower => d < -tol,
                State::Upper => d > tol,
                _ => d.abs() > tol,
            }
        })
    }

    /// Dual steepest-edge pricing over the primal infeasible basic variables.
    fn row_score(&self, p: usize) -> f64 {
        let j = self.basic[p];
        let v = self.x[j];
        let infeasibility = if v < self.lower[j] - self.ptol[j] {
            self.lower[j] - v
        } else if v > self.upper[j] + self.ptol[j] {
            v - self.upper[j]
        } else {
            return 0.;
        };
        infeasibility * infeasibility / self.weight[p]
    }

    fn choose_row(&mut self) -> Option<usize> {
        let _profile = crate::profile::enter("pricing_choose");
        let mut best = None;
        let mut score = 0.;
        if self.m < 512 {
            for p in 0..self.m {
                let s = self.row_score(p);
                if s > score {
                    score = s;
                    best = Some(p);
                }
            }
            return best;
        }
        for block in 0..self.price_dirty.len() {
            if self.price_dirty[block] {
                let mut winner = None;
                let mut value = 0.;
                for p in block * PRICE_BLOCK..((block + 1) * PRICE_BLOCK).min(self.m) {
                    let s = self.row_score(p);
                    if s > value {
                        value = s;
                        winner = Some(p);
                    }
                }
                self.price_score[block] = value;
                self.price_row[block] = winner;
                self.price_dirty[block] = false;
            }
            if self.price_score[block] > score {
                score = self.price_score[block];
                best = self.price_row[block];
            }
        }
        best
    }

    /// `ρ = B⁻ᵀ e_r` and its pivot row over the nonbasic variables.
    fn compute_row(&mut self, r: usize) {
        let _profile = crate::profile::enter("pricing_row");
        for &j in &self.touched {
            self.alpha[j] = 0.0;
            self.marked[j] = false;
        }
        self.touched.clear();
        for &i in &self.rho_index {
            self.rho[i] = 0.;
        }
        self.rho[r] = 1.0;
        let lu = self.lu.as_mut().expect("factorized basis");
        lu.btran_unit_indexed(r, &mut self.rho, &mut self.rho_index);
        if self.controls.steepest_edge && !self.controls.devex {
            self.price_dirty[r / PRICE_BLOCK] = true;
            self.weight[r] = self
                .rho_index
                .iter()
                .map(|&i| self.rho[i] * self.rho[i])
                .sum::<f64>()
                .max(MIN_WEIGHT);
        }
        let n = self.n;
        if self.controls.adaptive_pricing
            && n >= 128
            && self.rho_index.len() > self.m / 8
            && self
                .rho_index
                .iter()
                .filter(|&&k| self.rho[k].abs() > DROP)
                .map(|&k| self.row_start[k + 1] - self.row_start[k])
                .sum::<usize>()
                > self.col_value.len() / 2
        {
            let _column = crate::profile::enter("pricing_column");
            self.stats.column_pricings += 1;
            let work = if self.execution.threads() > 1 {
                (0..n)
                    .filter(|&j| self.state[j] != State::Basic)
                    .map(|j| self.col_start[j + 1] - self.col_start[j])
                    .sum::<usize>()
            } else {
                0
            };
            if work >= 262_144 {
                let (state, start, index, values, rho) = (
                    &self.state,
                    &self.col_start,
                    &self.col_index,
                    &self.col_value,
                    &self.rho,
                );
                self.execution
                    .chunks_mut(&mut self.alpha[..n], 64, work, |offset, part| {
                        for (local, out) in part.iter_mut().enumerate() {
                            let j = offset + local;
                            let mut value = 0.;
                            if state[j] != State::Basic {
                                for e in start[j]..start[j + 1] {
                                    let r = rho[index[e]];
                                    if r.abs() > DROP {
                                        value += r * values[e];
                                    }
                                }
                            }
                            *out = value;
                        }
                    });
                for j in 0..n {
                    if self.alpha[j] != 0. {
                        self.marked[j] = true;
                        self.touched.push(j);
                    }
                }
            } else {
                for j in 0..n {
                    if self.state[j] == State::Basic {
                        continue;
                    }
                    let mut value = 0.;
                    for e in self.col_start[j]..self.col_start[j + 1] {
                        let rho = self.rho[self.col_index[e]];
                        if rho.abs() > DROP {
                            value += rho * self.col_value[e];
                        }
                    }
                    if value != 0. {
                        self.alpha[j] = value;
                        self.marked[j] = true;
                        self.touched.push(j);
                    }
                }
            }
            for &k in &self.rho_index {
                if self.rho[k].abs() > DROP && self.state[n + k] != State::Basic {
                    self.alpha[n + k] = -self.rho[k];
                    self.marked[n + k] = true;
                    self.touched.push(n + k);
                }
            }
            return;
        }
        self.stats.row_pricings += 1;
        for &k in &self.rho_index {
            let v = self.rho[k];
            if v.abs() <= DROP {
                continue;
            }
            let logical = n + k;
            if self.state[logical] != State::Basic {
                if !self.marked[logical] {
                    self.marked[logical] = true;
                    self.touched.push(logical);
                }
                self.alpha[logical] -= v;
            }
            for e in self.row_start[k]..self.row_start[k + 1] {
                let j = self.row_index[e];
                if self.state[j] != State::Basic {
                    if !self.marked[j] {
                        self.marked[j] = true;
                        self.touched.push(j);
                    }
                    self.alpha[j] += v * self.row_value[e];
                }
            }
        }
    }

    /// Bound-flipping ratio test with Harris tolerances. `s` is +1 if the
    /// leaving variable moves to its upper bound and −1 for the lower bound.
    /// A breakpoint is passed (its boxed variable flipped) only while the
    /// leaving variable stays infeasible by more than `slack`. Returns the
    /// entering variable and the dual step length `θ ≥ 0`; `self.flips`
    /// holds the variables passed on the way.
    fn ratio_test(&mut self, s: f64, infeasibility: f64, slack: f64) -> Option<(usize, f64)> {
        let _profile = crate::profile::enter("ratio_test");
        self.candidates.clear();
        self.flips.clear();
        let tol = self.controls.pivot_tolerance;
        for &j in &self.touched {
            if self.lower[j] == self.upper[j] {
                continue;
            }
            let a = s * self.alpha[j];
            let blocks = match self.state[j] {
                State::Lower => a > tol,
                State::Upper => a < -tol,
                State::Zero => a.abs() > tol,
                State::Basic => false,
            };
            if blocks {
                let d = self.d[j];
                self.candidates.push(Candidate {
                    j,
                    a,
                    ratio: (d / a).max(0.0),
                    harris: ((d + a.signum() * self.dtol[j]) / a).max(0.0),
                });
            }
        }
        if self.candidates.is_empty() {
            return None;
        }
        // Without a flip at the first breakpoint the Harris pass covers all
        // candidates and no ordering is needed.
        let first = self
            .candidates
            .iter()
            .copied()
            .min_by(|x, y| x.ratio.total_cmp(&y.ratio))
            .expect("nonempty");
        let first_drop = first.a.abs() * (self.upper[first.j] - self.lower[first.j]);
        if first_drop >= infeasibility - slack {
            let bound = self
                .candidates
                .iter()
                .fold(f64::INFINITY, |b, c| b.min(c.harris));
            let c = self
                .candidates
                .iter()
                .filter(|c| c.ratio <= bound)
                .max_by(|x, y| x.a.abs().total_cmp(&y.a.abs()))
                .copied()
                .unwrap_or(first);
            return Some((c.j, c.ratio));
        }
        self.candidates
            .sort_unstable_by(|x, y| x.ratio.total_cmp(&y.ratio));
        let mut slope = infeasibility;
        let mut k = 0;
        while k < self.candidates.len() {
            let c = self.candidates[k];
            let drop = c.a.abs() * (self.upper[c.j] - self.lower[c.j]);
            if drop < slope - slack {
                slope -= drop;
                self.flips.push(c.j);
                k += 1;
            } else {
                break;
            }
        }
        if k == self.candidates.len() {
            return None; // Every breakpoint passed: the row stays infeasible.
        }
        let mut bound = f64::INFINITY;
        let mut end = k;
        while end < self.candidates.len() && self.candidates[end].ratio <= bound {
            bound = bound.min(self.candidates[end].harris);
            end += 1;
        }
        let mut q = k;
        for t in k..end {
            let c = self.candidates[t];
            if c.ratio <= bound && c.a.abs() > self.candidates[q].a.abs() {
                q = t;
            }
        }
        let c = self.candidates[q];
        Some((c.j, c.ratio))
    }

    /// `B⁻¹ a_q` into `self.column`.
    fn compute_column(&mut self, q: usize) {
        let _profile = crate::profile::enter("column_setup");
        if self.column_index.len() < self.m / 8 {
            for &i in &self.column_index {
                self.column[i] = 0.;
            }
        } else {
            self.column.fill(0.);
        }
        Self::add_column(
            &self.col_start,
            &self.col_index,
            &self.col_value,
            self.n,
            q,
            1.0,
            &mut self.column,
        );
        let lu = self.lu.as_mut().expect("factorized basis");
        lu.ftran_entering_indexed(&mut self.column, &mut self.column_index);
    }

    fn pivot(&mut self, r: usize, q: usize, theta: f64, s: f64, to_upper: bool) {
        let _profile = crate::profile::enter("pivot_other");
        let (n, m) = (self.n, self.m);
        let p = self.basic[r];
        if !self.flips.is_empty() {
            self.work.fill(0.0);
            for t in 0..self.flips.len() {
                let j = self.flips[t];
                let old = self.value(j);
                self.state[j] = if self.state[j] == State::Lower {
                    State::Upper
                } else {
                    State::Lower
                };
                let new = self.value(j);
                self.x[j] = new;
                Self::add_column(
                    &self.col_start,
                    &self.col_index,
                    &self.col_value,
                    n,
                    j,
                    new - old,
                    &mut self.work,
                );
            }
            let lu = self.lu.as_mut().expect("factorized basis");
            lu.ftran(&mut self.work);
            for i in 0..m {
                self.x[self.basic[i]] -= self.work[i];
            }
            self.stats.bound_flips += self.flips.len() as u64;
        }
        let target = if to_upper {
            self.upper[p]
        } else {
            self.lower[p]
        };
        let step = (self.x[p] - target) / self.column[r];
        if step != 0.0 {
            for &i in &self.column_index {
                let v = self.column[i];
                if v != 0.0 {
                    self.x[self.basic[i]] -= step * v;
                }
            }
        }
        self.x[q] += step;
        self.x[p] = target;
        let t = s * theta;
        if t != 0.0 {
            for &j in &self.touched {
                self.d[j] -= t * self.alpha[j];
            }
        }
        self.d[p] = -t;
        self.d[q] = 0.0;
        if self.controls.steepest_edge {
            let _weights = crate::profile::enter("edge_weights");
            if self.controls.devex {
                let ar = self.column[r];
                let wr = self.weight[r].max(1.);
                let next = (wr / (ar * ar)).max(1.);
                for &i in &self.column_index {
                    if i != r {
                        self.weight[i] = self.weight[i].max(self.column[i] * self.column[i] * next);
                    }
                }
                self.weight[r] = next;
                if self.stats.updates % ((2 * m).max(256) as u64) == 0
                    || self
                        .column_index
                        .iter()
                        .any(|&i| !self.weight[i].is_finite())
                {
                    self.weight.fill(1.);
                    self.price_dirty.fill(true);
                    self.stats.weight_resets += 1;
                }
            } else {
                self.tau.copy_from_slice(&self.rho);
                let lu = self.lu.as_mut().expect("factorized basis");
                lu.ftran(&mut self.tau);
                let (wr, ar) = (self.weight[r], self.column[r]);
                for &i in &self.column_index {
                    let v = self.column[i];
                    if i != r && v != 0.0 {
                        let ratio = v / ar;
                        self.weight[i] = (self.weight[i]
                            + ratio * (ratio * wr - 2.0 * self.tau[i]))
                            .max(MIN_WEIGHT);
                    }
                }
                self.weight[r] = (wr / (ar * ar)).max(MIN_WEIGHT);
            }
        }
        let lu = self.lu.as_mut().expect("factorized basis");
        lu.update_sparse(r, &self.column, self.column_index.iter().copied());
        self.stats.ft_updates += u64::from(lu.uses_ft());
        self.stats.updates += 1;
        self.stats.peak_entries = self.stats.peak_entries.max(lu.entries());
        if self.m >= 512 && self.flips.is_empty() {
            for &i in &self.column_index {
                self.price_dirty[i / PRICE_BLOCK] = true;
            }
            self.price_dirty[r / PRICE_BLOCK] = true;
        } else if self.m >= 512 {
            self.price_dirty.fill(true);
        }
        self.basic[r] = q;
        self.state[q] = State::Basic;
        self.state[p] = if to_upper { State::Upper } else { State::Lower };
        if self.lower[p] == self.upper[p] {
            self.state[p] = State::Lower;
        }
    }

    fn random(&mut self) -> f64 {
        self.seed ^= self.seed << 13;
        self.seed ^= self.seed >> 7;
        self.seed ^= self.seed << 17;
        (self.seed >> 11) as f64 / (1u64 << 53) as f64
    }

    /// Shifts nonbasic costs away from zero reduced cost, keeping dual
    /// feasibility, to break dual degeneracy.
    fn perturb(&mut self) {
        self.perturbed = true;
        self.stats.perturbations += 1;
        for j in 0..self.n + self.m {
            if self.state[j] == State::Basic || self.lower[j] == self.upper[j] {
                continue;
            }
            let magnitude = 5e-7 * (1.0 + self.cost0[j].abs()) * (1.0 + self.random());
            let delta = match self.state[j] {
                State::Lower => magnitude,
                State::Upper => -magnitude,
                _ => continue,
            };
            self.cost[j] += delta;
            self.d[j] += delta;
        }
    }

    /// Restores the unperturbed costs; the caller recomputes duals.
    fn unperturb(&mut self) -> bool {
        if !self.perturbed {
            return false;
        }
        self.cost.clone_from(&self.cost0);
        self.perturbed = false;
        true
    }

    /// Fresh factorization, primal and dual values. Returns whether the
    /// dual simplex must restart (basis repaired or dual feasibility lost).
    fn refresh(&mut self) -> Result<bool> {
        let repaired = self.refactor()?;
        self.compute_dual();
        self.flip_to_dual_feasible();
        self.compute_primal();
        Ok(repaired || self.nonboxed_dual_infeasible())
    }

    /// Diagnostic state only in instrumented builds and when explicitly enabled.
    fn trace(&self, event: &str, iterations: u64) {
        #[cfg(feature = "kernel-profile")]
        if std::env::var_os("LPIP_TRACE_SIMPLEX").is_some() {
            let primal = (0..self.n + self.m)
                .map(|j| {
                    (self.lower[j] - self.x[j])
                        .max(self.x[j] - self.upper[j])
                        .max(0.)
                })
                .fold(0., f64::max);
            let bad = (0..self.n + self.m)
                .filter(|&j| {
                    self.state[j] != State::Basic
                        && !self.boxed(j)
                        && match self.state[j] {
                            State::Lower => self.d[j] < -self.dtol[j],
                            State::Upper => self.d[j] > self.dtol[j],
                            _ => self.d[j].abs() > self.dtol[j],
                        }
                })
                .count();
            eprintln!(
                "simplex {event} m={} n={} pivots={iterations} primal={primal:e} bad_dual={bad} refactors={} repairs={} perturbed={}",
                self.m, self.n, self.stats.refactors, self.stats.repairs, self.perturbed
            );
        }
        #[cfg(not(feature = "kernel-profile"))]
        let _ = (event, iterations);
    }

    fn phase_two(
        &mut self,
        budget: &mut Budget<'_>,
        iterations: &mut u64,
        mut cutoff: Option<&mut Cutoff<'_>>,
    ) -> Result<Outcome> {
        let mut streak = 0;
        loop {
            if let Some(s) = budget.stop() {
                return Ok(Outcome::Stopped(s));
            }
            if *iterations > self.iteration_guard {
                self.trace("iteration_guard", *iterations);
                return Ok(Outcome::Failure);
            }
            let adaptive = self.controls.adaptive_refactor;
            let (interval, cap) = (
                self.controls.refactor_interval,
                self.controls.max_factor_entries,
            );
            let lu = self.lu();
            if lu.needs_refactor(interval, cap, adaptive) && self.refresh()? {
                return Ok(Outcome::Restart);
            }
            let Some(r) = self.choose_row() else {
                return Ok(Outcome::Optimal);
            };
            if let Some(cutoff) = cutoff
                .as_deref_mut()
                .filter(|cutoff| *iterations > 0 && *iterations % cutoff.interval == 0)
            {
                if self.crosses_cutoff(cutoff)? {
                    // Only this internal caller sees GapLimit together with its
                    // verified bound. The MIP tree processes it as a closed node.
                    return Ok(Outcome::Stopped(Status::GapLimit));
                }
            }
            let p = self.basic[r];
            let to_upper = self.x[p] > self.upper[p];
            let target = if to_upper {
                self.upper[p]
            } else {
                self.lower[p]
            };
            let s = if to_upper { 1.0 } else { -1.0 };
            let infeasibility = (self.x[p] - target).abs();
            self.compute_row(r);
            let Some((q, theta)) = self.ratio_test(s, infeasibility, self.ptol[p]) else {
                if self.lu().updates() > 0 {
                    if self.refresh()? {
                        return Ok(Outcome::Restart);
                    }
                    continue;
                }
                self.ray = Some(self.rho.clone());
                return Ok(Outcome::Infeasible);
            };
            self.compute_column(q);
            let (from_column, from_row) = (self.column[r], self.alpha[q]);
            if (from_column - from_row).abs() > 1e-7 * from_column.abs() + 1e-11 {
                if self.lu().updates() > 0 {
                    if self.refresh()? {
                        return Ok(Outcome::Restart);
                    }
                    continue;
                }
                if from_column.abs() < 1e-12 {
                    self.trace("unsafe_pivot", *iterations);
                    return Ok(Outcome::Failure);
                }
            }
            self.stats.degenerate_pivots += u64::from(theta == 0.);
            streak = if theta == 0.0 { streak + 1 } else { 0 };
            self.pivot(r, q, theta, s, to_upper);
            budget.pivots += 1;
            *iterations += 1;
            if streak >= DEGENERATE_STREAK && !self.perturbed {
                self.perturb();
            }
        }
    }

    /// Auxiliary problem with every bound replaced by a small box around 0;
    /// its optimal basis is dual feasible for the true bounds unless the LP
    /// is dual infeasible. Returns `None` to continue with the true bounds.
    fn phase_one(
        &mut self,
        budget: &mut Budget<'_>,
        iterations: &mut u64,
    ) -> Result<Option<Status>> {
        self.trace("phase1_enter", *iterations);
        let true_lower = self.lower.clone();
        let true_upper = self.upper.clone();
        for j in 0..self.n + self.m {
            let (l, u) = (true_lower[j], true_upper[j]);
            (self.lower[j], self.upper[j]) = match (l.is_finite(), u.is_finite()) {
                (true, true) => (0.0, 0.0),
                (true, false) => (0.0, 1.0),
                (false, true) => (-1.0, 0.0),
                (false, false) => (-1.0, 1.0),
            };
        }
        for j in 0..self.n + self.m {
            if self.state[j] != State::Basic {
                self.state[j] = self.state_from_dual(j);
            }
        }
        self.compute_primal();
        let before = *iterations;
        let mut outcome = self.phase_two(budget, iterations, None)?;
        self.stats.phase_one_pivots += *iterations - before;
        self.trace("phase1_auxiliary_finished", *iterations);
        // Optimality for perturbed costs cannot establish dual infeasibility
        // of the original objective. Retry it before classifying the LP.
        if self.unperturb() {
            self.compute_dual();
            if matches!(outcome, Outcome::Optimal) {
                outcome = Outcome::Restart;
            }
        }
        self.lower = true_lower;
        self.upper = true_upper;
        for j in 0..self.n + self.m {
            if self.state[j] != State::Basic {
                self.state[j] = self.state_from_dual(j);
            }
        }
        self.compute_primal();
        Ok(match outcome {
            Outcome::Optimal if self.nonboxed_dual_infeasible() => Some(Status::Unbounded),
            Outcome::Optimal | Outcome::Restart => None,
            Outcome::Stopped(s) => Some(s),
            Outcome::Infeasible | Outcome::Failure => Some(Status::NumericalFailure),
        })
    }

    /// The LP is dual infeasible: unbounded if primal feasible, else
    /// infeasible. Primal feasibility is decided with zero costs, where every
    /// basis is dual feasible.
    fn classify(&mut self, budget: &mut Budget<'_>, iterations: &mut u64) -> Result<Status> {
        let costs = std::mem::replace(&mut self.cost0, vec![0.0; self.n + self.m]);
        self.cost.fill(0.0);
        self.perturbed = false;
        self.compute_dual();
        self.trace("classify_enter", *iterations);
        let status = self.optimize(budget, iterations, false, None)?;
        self.trace("classify_finished", *iterations);
        self.cost0 = costs;
        self.cost.clone_from(&self.cost0);
        self.perturbed = false;
        self.compute_dual();
        Ok(match status {
            Status::Optimal => Status::Unbounded,
            s => s,
        })
    }

    /// For up to `limit` basic integer columns with the most fractional
    /// values, the BTRAN row of the basis inverse in original row units.
    /// Advisory only: the exact cut derivation re-aggregates the original
    /// rows with these multipliers and keeps every residual.
    pub fn tableau_candidates(&mut self, model: &Model, limit: usize) -> Vec<(usize, Vec<f64>)> {
        let mut order: Vec<_> = self
            .basic
            .iter()
            .enumerate()
            .filter_map(|(i, &j)| {
                if j >= self.n {
                    return None;
                }
                let original = self.cols[j];
                let value = self.x[j] * self.col_scale[j];
                let fraction = (value - value.round()).abs();
                (model.kinds()[original].is_integral() && fraction > 1e-6)
                    .then_some((i, original, fraction))
            })
            .collect();
        order.sort_by(|a, b| b.2.total_cmp(&a.2).then(a.1.cmp(&b.1)));
        order.truncate(limit);
        let mut out = Vec::new();
        for (i, j, _) in order {
            let mut rho = vec![0.; self.m];
            rho[i] = 1.;
            let mut index = Vec::new();
            self.lu
                .as_mut()
                .unwrap()
                .btran_unit_indexed(i, &mut rho, &mut index);
            let mut weights = vec![0.; model.m()];
            for (k, &row) in self.rows.iter().enumerate() {
                weights[row] = rho[k] * self.row_scale[k];
            }
            if weights.iter().all(|v| v.is_finite()) {
                out.push((j, weights));
            }
        }
        out
    }
    /// The LP of `model`, which must extend this LP's model by appended rows:
    /// the combinatorial basis and nonbasic states are kept, the new rows'
    /// logicals become basic, and the enlarged factorization is rebuilt.
    pub fn extend_rows(&self, model: &Model, old_rows: usize) -> Result<Self> {
        if old_rows > model.m() || self.rows.iter().any(|&i| i >= old_rows) {
            return Err(Error::Backend("basis row mapping changed".into()));
        }
        let mut keep_rows = vec![true; model.m()];
        keep_rows[..old_rows].fill(false);
        for &i in &self.rows {
            keep_rows[i] = true;
        }
        let mut keep = vec![false; model.n()];
        for &j in &self.cols {
            keep[j] = true;
        }
        let mut next = Self::new(model, &keep_rows, &keep, self.controls)?;
        if next.cols != self.cols || !next.rows.starts_with(&self.rows) {
            return Err(Error::Backend("basis row mapping changed".into()));
        }
        next.basic[..self.m].copy_from_slice(&self.basic);
        next.state[..self.n + self.m].copy_from_slice(&self.state);
        next.weight[..self.m].copy_from_slice(&self.weight);
        next.primal_stale = true;
        next.dual_stale = true;
        next.next_id = self.next_id;
        next.stats = self.stats;
        Ok(next)
    }
    /// Solves the LP from the current basis. `Optimal` is declared only with
    /// primal and dual values recomputed from scratch and feasible; with
    /// `fresh_optimum` (cold solves), also on a fresh factorization.
    pub fn solve(&mut self, budget: &mut Budget<'_>, fresh_optimum: bool) -> Result<Status> {
        self.solve_with_limit(budget, fresh_optimum, None)
    }

    pub fn solve_verified_cutoff(
        &mut self,
        budget: &mut Budget<'_>,
        model: &Model,
        bounds: &lp_ip_craft::Bounds,
        upper: f64,
        lattice: bool,
    ) -> Result<(Status, Option<f64>)> {
        let constant = self.sign
            * (model.objective_offset()
                + self
                    .col_of
                    .iter()
                    .enumerate()
                    .filter(|&(_, &col)| col == NIL)
                    .map(|(j, _)| self.fixed[j] * model.objective()[j])
                    .sum::<f64>());
        let mut cutoff = Cutoff {
            model,
            bounds,
            upper,
            constant,
            interval: budget.settings.dual_cutoff_interval,
            lattice,
            verified: None,
        };
        let status = self.solve_with_limit(budget, false, Some(&mut cutoff))?;
        Ok((status, cutoff.verified))
    }

    fn crosses_cutoff(&mut self, cutoff: &mut Cutoff<'_>) -> Result<bool> {
        let estimate = cutoff.constant
            + self.cost_scale
                * self.cost0[..self.n]
                    .iter()
                    .zip(&self.x)
                    .map(|(c, x)| c * x)
                    .sum::<f64>();
        if estimate < cutoff.upper - 1e-7 * (1. + cutoff.upper.abs()) {
            return Ok(false);
        }
        let mut prices: Vec<_> = self.basic.iter().map(|&j| self.cost0[j]).collect();
        self.lu
            .as_mut()
            .expect("factorized basis")
            .btran(&mut prices);
        let mut row_duals = vec![0.; cutoff.model.m()];
        for (k, &i) in self.rows.iter().enumerate() {
            let price = prices[k];
            if (price > 0. && self.lower[self.n + k].is_finite())
                || (price < 0. && self.upper[self.n + k].is_finite())
            {
                row_duals[i] = self.sign * self.cost_scale * self.row_scale[k] * price;
            }
        }
        if row_duals.iter().any(|v| !v.is_finite()) {
            return Ok(false);
        }
        let report =
            lp_ip_craft::safe_dual_bound_with_bounds(cutoff.model, cutoff.bounds, &row_duals)?;
        cutoff.verified = report
            .bound
            .map(|b| crate::oriented(cutoff.model, b))
            .map(|b| {
                if cutoff.lattice {
                    crate::incumbent::lattice_ceil(b)
                } else {
                    b
                }
            })
            .filter(|&b| b >= cutoff.upper);
        Ok(cutoff.verified.is_some())
    }

    fn solve_with_limit(
        &mut self,
        budget: &mut Budget<'_>,
        fresh_optimum: bool,
        cutoff: Option<&mut Cutoff<'_>>,
    ) -> Result<Status> {
        self.ray = None;
        self.basis_id = None;
        if let Some(s) = budget.stop() {
            return Ok(s);
        }
        if self.lu.is_none() {
            self.refactor()?;
            self.dual_stale = true;
        }
        if self.dual_stale {
            self.compute_dual();
        }
        if self.primal_stale {
            self.compute_primal();
        }
        let mut iterations = 0u64;
        self.fresh_optimum = fresh_optimum;
        self.optimize(budget, &mut iterations, true, cutoff)
    }

    /// Restartable driver: dual phase 1 when needed, phase 2, and the final
    /// unperturbed recomputation. Without `classify`, dual infeasibility can
    /// only come from perturbation drift (zero costs) and is recomputed away.
    fn optimize(
        &mut self,
        budget: &mut Budget<'_>,
        iterations: &mut u64,
        classify: bool,
        mut cutoff: Option<&mut Cutoff<'_>>,
    ) -> Result<Status> {
        let mut fresh = self.fresh_optimum;
        // Useful pivots may require many cost cleanups/refactorizations. Bound
        // consecutive no-progress restarts, not the number of successful ones.
        // The pivot guard and shared user budget still bound the whole solve.
        let mut previous_iterations = *iterations;
        let mut stalled_restarts = 0;
        loop {
            if let Some(status) = budget.stop() {
                return Ok(status);
            }
            if *iterations > previous_iterations {
                stalled_restarts = 0;
            } else {
                stalled_restarts += 1;
                if stalled_restarts > 12 {
                    self.trace("stalled_restart_limit", *iterations);
                    return Ok(Status::NumericalFailure);
                }
            }
            previous_iterations = *iterations;
            self.trace("restart", *iterations);
            if self.flip_to_dual_feasible() > 0 {
                self.compute_primal();
            }
            if self.nonboxed_dual_infeasible() {
                if self.unperturb() {
                    self.compute_dual();
                    continue;
                }
                if !classify {
                    self.compute_dual();
                    continue;
                }
                match self.phase_one(budget, iterations)? {
                    None => continue,
                    Some(Status::Unbounded) => {
                        self.trace("dual_unbounded", *iterations);
                        return self.classify(budget, iterations);
                    }
                    Some(s) => return Ok(s),
                }
            }
            match self.phase_two(budget, iterations, cutoff.as_deref_mut())? {
                Outcome::Optimal => {
                    self.unperturb();
                    if fresh && self.lu().updates() > 0 && self.refactor()? {
                        self.compute_dual();
                        continue;
                    }
                    self.compute_dual();
                    self.compute_primal();
                    if self.flip_to_dual_feasible() > 0 {
                        self.compute_primal();
                    }
                    if self.nonboxed_dual_infeasible() || self.choose_row().is_some() {
                        fresh = true; // recheck on a fresh factorization
                        continue;
                    }
                    self.trace("optimal", *iterations);
                    return Ok(Status::Optimal);
                }
                Outcome::Restart => continue,
                Outcome::Infeasible => {
                    if self.unperturb() {
                        self.compute_dual();
                    }
                    return Ok(Status::Infeasible);
                }
                Outcome::Stopped(s) => {
                    if self.unperturb() {
                        self.compute_dual();
                    }
                    return Ok(s);
                }
                Outcome::Failure => {
                    self.trace("phase2_failure", *iterations);
                    return Ok(Status::NumericalFailure);
                }
            }
        }
    }
}

/// `v * scale` for a finite or infinite bound; finite bounds must stay finite.
fn scaled(v: f64, scale: f64) -> Result<f64> {
    if !v.is_finite() {
        return Ok(v);
    }
    let s = v * scale;
    if s.is_finite() && (s != 0.0 || v == 0.0) {
        Ok(s)
    } else {
        Err(Error::Unsupported(
            "bound out of range after power-of-two scaling".into(),
        ))
    }
}

/// Geometric-mean row and column scaling followed by column equilibration,
/// rounded to powers of two.
fn scale_factors(
    m: usize,
    col_start: &[usize],
    col_index: &[usize],
    col_value: &[f64],
) -> (Vec<f64>, Vec<f64>) {
    let n = col_start.len() - 1;
    let mut r = vec![1.0; m];
    let mut s = vec![1.0; n];
    let (small, large) = col_value
        .iter()
        .fold((f64::INFINITY, 0.0_f64), |(a, b), v| {
            (a.min(v.abs()), b.max(v.abs()))
        });
    if small >= 1.0 / 32.0 && large <= 32.0 {
        return (r, s); // already well scaled
    }
    let mut lo = vec![0.0_f64; m];
    let mut hi = vec![0.0_f64; m];
    for _ in 0..4 {
        lo.fill(f64::INFINITY);
        hi.fill(0.0);
        for j in 0..n {
            for e in col_start[j]..col_start[j + 1] {
                let (k, v) = (col_index[e], col_value[e].abs() * s[j]);
                lo[k] = lo[k].min(v);
                hi[k] = hi[k].max(v);
            }
        }
        for k in 0..m {
            if hi[k] > 0.0 {
                r[k] = 1.0 / (lo[k].sqrt() * hi[k].sqrt());
            }
        }
        for j in 0..n {
            let (mut a, mut b) = (f64::INFINITY, 0.0_f64);
            for e in col_start[j]..col_start[j + 1] {
                let v = col_value[e].abs() * r[col_index[e]];
                a = a.min(v);
                b = b.max(v);
            }
            if b > 0.0 {
                s[j] = 1.0 / (a.sqrt() * b.sqrt());
            }
        }
    }
    for v in &mut r {
        *v = pow2(*v);
    }
    for j in 0..n {
        let mut b = 0.0_f64;
        for e in col_start[j]..col_start[j + 1] {
            b = b.max(col_value[e].abs() * r[col_index[e]]);
        }
        s[j] = if b > 0.0 { pow2(1.0 / b) } else { 1.0 };
    }
    (r, s)
}

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

    fn controls() -> Controls {
        Controls {
            threads: 1,
            pivot_tolerance: 1e-9,
            refactor_interval: 16,
            adaptive_refactor: true,
            basis_update: crate::BasisUpdate::ForrestTomlin,
            factor_pivot_search: 4,
            factor_ordering: crate::FactorOrdering::Auto,
            max_factor_entries: usize::MAX,
            factor_replay: false,
            adaptive_pricing: true,
            devex: false,
            steepest_edge: true,
            feasibility: 1e-7,
            dual: 1e-7,
        }
    }

    fn solve(model: &Model) -> (Status, Lp) {
        let settings = NativeOptions::default();
        let cancel = CancellationToken::default();
        let mut budget = Budget {
            start: std::time::Instant::now(),
            settings: &settings,
            cancel: &cancel,
            pivots: 0,
        };
        let mut lp = Lp::new(
            model,
            &vec![true; model.m()],
            &vec![true; model.n()],
            controls(),
        )
        .unwrap();
        let status = lp.solve(&mut budget, true).unwrap();
        (status, lp)
    }

    #[test]
    fn column_and_row_prices_match_on_dense_btran_with_logical_columns() {
        let m = 128;
        let n = 2 * m;
        let a: Vec<f64> = (0..m * n)
            .map(|e| if e / n == e % n { 4. } else { 0.125 })
            .collect();
        let model = Model::new(ModelData {
            sense: Sense::Minimize,
            objective: vec![1.; n],
            objective_offset: 0.,
            variables: Bounds::new(vec![0.; n], vec![2.; n]),
            kinds: vec![VariableKind::Continuous; n],
            matrix: CsrMatrix::from_dense(m, n, &a).unwrap(),
            rows: Bounds::new(vec![f64::NEG_INFINITY; m], vec![10.; m]),
        })
        .unwrap();
        let mut settings = controls();
        settings.basis_update = crate::BasisUpdate::Eta;
        let mut lps: Vec<Lp> = [false, true]
            .into_iter()
            .map(|column| {
                let mut c = settings;
                c.adaptive_pricing = column;
                let mut lp = Lp::new(&model, &vec![true; m], &vec![true; n], c).unwrap();
                for i in 0..m {
                    lp.basic[i] = i;
                    lp.state[i] = State::Basic;
                    lp.state[n + i] = State::Upper;
                }
                lp.refactor().unwrap();
                lp
            })
            .collect();
        for r in [0, 17, 127] {
            for lp in &mut lps {
                lp.compute_row(r);
            }
            for (a, b) in lps[0].alpha.iter().zip(&lps[1].alpha) {
                assert!((a - b).abs() < 1e-12);
            }
        }
        assert!(lps[0].stats.row_pricings > 0);
        assert!(lps[1].stats.column_pricings > 0);
    }

    #[test]
    fn cached_pricing_matches_full_scan_after_sparse_changes_and_reset() {
        let m = 1025;
        let model = Model::new(ModelData {
            sense: Sense::Minimize,
            objective: vec![0.; m],
            objective_offset: 0.,
            variables: Bounds::new(vec![0.; m], vec![2.; m]),
            kinds: vec![VariableKind::Continuous; m],
            matrix: CsrMatrix::new(m, m, (0..=m).collect(), (0..m).collect(), vec![1.; m]),
            rows: Bounds::new(vec![0.; m], vec![1.; m]),
        })
        .unwrap();
        let mut lp = Lp::new(&model, &vec![true; m], &vec![true; m], controls()).unwrap();
        for step in 0..300 {
            let p = (step * 67) % m;
            lp.x[lp.basic[p]] = (step % 7) as f64 - 3.;
            lp.weight[p] = 1. + (step % 3) as f64;
            lp.price_dirty[p / PRICE_BLOCK] = true;
            let mut expected = None;
            let mut score = 0.;
            for r in 0..m {
                let s = lp.row_score(r);
                if s > score {
                    score = s;
                    expected = Some(r);
                }
            }
            assert_eq!(lp.choose_row(), expected);
            assert_eq!(lp.choose_row(), expected);
            if step % 17 == 0 {
                lp.reset_to_slack();
            }
            if step % 23 == 0 {
                lp.set_bound(p, 0., 1.).unwrap();
            }
        }
    }

    #[test]
    fn scaling_is_by_powers_of_two() {
        for v in [1e-11, 0.3, 1.0, 7.0, 1e9] {
            let p = pow2(v);
            assert_eq!(p.to_bits() & ((1u64 << 52) - 1), 0, "{p}");
            assert!(p / v < 1.5 && v / p < 1.5);
        }
    }

    #[test]
    fn production_lp_duals_match_the_tutorial() {
        let model = Model::new(ModelData {
            sense: Sense::Maximize,
            objective: vec![45.0, 80.0, 110.0],
            objective_offset: 0.0,
            variables: Bounds::non_negative(3),
            kinds: vec![VariableKind::Continuous; 3],
            matrix: CsrMatrix::from_dense(
                3,
                3,
                &[5.0, 20.0, 25.0, 10.0, 15.0, 20.0, 1.0, 3.0, 5.0],
            )
            .unwrap(),
            rows: Bounds::new(vec![f64::NEG_INFINITY; 3], vec![400.0, 450.0, 60.0]),
        })
        .unwrap();
        let (status, lp) = solve(&model);
        assert_eq!(status, Status::Optimal);
        let x = lp.point();
        for (a, b) in x.iter().zip([30.0, 10.0, 0.0]) {
            assert!((a - b).abs() < 1e-9, "{x:?}");
        }
        let duals = lp.duals(&model);
        for (a, b) in duals.row_duals.iter().zip([0.0, 11.0 / 3.0, 25.0 / 3.0]) {
            assert!((a - b).abs() < 1e-9, "{duals:?}");
        }
        assert!(check::lp_residuals(&model, &x, &duals).unwrap().max() < 1e-9);
    }

    #[test]
    fn alternate_pricing_recovers_a_guarded_lp_and_shares_its_pivot_budget() {
        // This basis takes five weighted pivots or three unweighted ones.
        let model = Model::new(ModelData {
            sense: Sense::Maximize,
            objective: vec![3., 16., 10., 3.],
            objective_offset: 0.,
            variables: Bounds::new(vec![0.; 4], vec![2.; 4]),
            kinds: vec![VariableKind::Continuous; 4],
            matrix: CsrMatrix::from_dense(
                3,
                4,
                &[19., 2., 12., 18., 1., 9., 5., 19., 4., 11., 14., 12.],
            )
            .unwrap(),
            rows: Bounds::new(vec![f64::NEG_INFINITY; 3], vec![25., 14., 21.]),
        })
        .unwrap();
        for (limit, expected) in [(None, Status::Optimal), (Some(5), Status::IterationLimit)] {
            let options = NativeOptions {
                iteration_limit: limit,
                ..Default::default()
            };
            let cancel = CancellationToken::default();
            let mut budget = Budget {
                settings: &options,
                cancel: &cancel,
                start: std::time::Instant::now(),
                pivots: 0,
            };
            let mut lp = Lp::new(&model, &[true; 3], &[true; 4], controls()).unwrap();
            lp.iteration_guard = 3;
            assert_eq!(
                lp.solve(&mut budget, true).unwrap(),
                Status::NumericalFailure
            );
            assert_eq!(budget.pivots, 4);
            assert_eq!(lp.retry_unweighted(&mut budget).unwrap(), expected);
            assert!(lp.controls.steepest_edge);
            assert_eq!(budget.pivots, limit.unwrap_or(7));
            if expected == Status::Optimal {
                assert!(
                    check::lp_residuals(&model, &lp.point(), &lp.duals(&model))
                        .unwrap()
                        .max()
                        < 1e-7
                );
            }
        }
    }

    /// The in-simplex cutoff may stop a warm node LP only with an outward-safe
    /// bound at or above the cutoff, never above the node's LP optimum, and
    /// never when the cutoff lies above that optimum. Both senses, an
    /// objective offset and narrowed node boxes are covered.
    #[test]
    fn verified_simplex_cutoff_is_a_safe_node_bound() {
        let mut state = 0x9e37_79b9_7f4a_7c15u64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        let settings = NativeOptions {
            dual_cutoff_interval: 1,
            ..Default::default()
        };
        let cancel = CancellationToken::default();
        let (mut cut, mut kept) = (0, 0);
        for case in 0..60usize {
            let (m, n) = (6 + case % 5, 10 + case % 7);
            let a: Vec<f64> = (0..m * n)
                .map(|_| {
                    let r = next();
                    if r % 3 == 0 {
                        ((r >> 8) % 9) as f64 - 4.
                    } else {
                        0.
                    }
                })
                .collect();
            let model = Model::new(ModelData {
                sense: if case % 2 == 0 {
                    Sense::Minimize
                } else {
                    Sense::Maximize
                },
                objective: (0..n).map(|_| ((next() >> 8) % 11) as f64 - 5.).collect(),
                objective_offset: 1.5,
                variables: Bounds::new(vec![0.; n], vec![3.; n]),
                kinds: vec![VariableKind::Continuous; n],
                matrix: CsrMatrix::from_dense(m, n, &a).unwrap(),
                rows: Bounds::new(vec![f64::NEG_INFINITY; m], vec![4.; m]),
            })
            .unwrap();
            // The node removes about half of the columns the root optimum
            // uses, so the warm dual simplex has to climb; x = 0 stays feasible.
            let (status, root) = solve(&model);
            assert_eq!(status, Status::Optimal);
            let mut node = model.variables().clone();
            for (j, x) in root.point().into_iter().enumerate() {
                if x > 1e-9 && next() % 2 == 0 {
                    node.upper[j] = 0.;
                }
            }
            let mut data = model.data().clone();
            data.variables = node.clone();
            let (status, reference) = solve(&Model::new(data).unwrap());
            if status != Status::Optimal {
                continue;
            }
            let value = |x: Vec<f64>| {
                crate::oriented(
                    &model,
                    model.objective_offset()
                        + model
                            .objective()
                            .iter()
                            .zip(&x)
                            .map(|(c, v)| c * v)
                            .sum::<f64>(),
                )
            };
            let z = value(reference.point());
            let tol = 1e-7 * (1. + z.abs());
            for upper in [z - 0.5, z - 1e-3, z + 1e-6, z + 0.5] {
                let (status, mut lp) = solve(&model);
                assert_eq!(status, Status::Optimal);
                lp.set_bounds(&node.lower, &node.upper).unwrap();
                let mut budget = Budget {
                    start: std::time::Instant::now(),
                    settings: &settings,
                    cancel: &cancel,
                    pivots: 0,
                };
                let (status, bound) = lp
                    .solve_verified_cutoff(&mut budget, &model, &node, upper, false)
                    .unwrap();
                if let Some(b) = bound {
                    assert!(
                        b >= upper && b <= z + tol,
                        "case {case}: {b} vs {upper}, {z}"
                    );
                    assert_eq!(status, Status::GapLimit);
                    cut += 1;
                } else {
                    assert_eq!(status, Status::Optimal, "case {case}");
                    assert!((value(lp.point()) - z).abs() <= tol, "case {case}");
                    kept += 1;
                }
                if upper > z + tol {
                    assert!(bound.is_none(), "case {case}: false cutoff");
                }
            }
        }
        assert!(
            cut > 10 && kept > 10,
            "{cut} cutoffs, {kept} complete solves"
        );
    }

    #[test]
    fn infeasible_rows_have_a_verified_farkas_combination() {
        let model = Model::new(ModelData {
            sense: Sense::Minimize,
            objective: vec![1.0, 1.0],
            objective_offset: 0.0,
            variables: Bounds::new(vec![0.0; 2], vec![1.0; 2]),
            kinds: vec![VariableKind::Continuous; 2],
            matrix: CsrMatrix::from_dense(2, 2, &[1.0, 1.0, 1.0, -1.0]).unwrap(),
            rows: Bounds::new(vec![2.5, f64::NEG_INFINITY], vec![f64::INFINITY, 5.0]),
        })
        .unwrap();
        let (status, lp) = solve(&model);
        assert_eq!(status, Status::Infeasible);
        assert!(lp.infeasibility_verified());
    }

    #[test]
    fn numeric_workers_preserve_dense_reduced_costs_prices_and_touched_order() {
        let m = 73usize;
        let n = 4097usize;
        let mut a = vec![0.; m * n];
        for i in 0..m {
            for j in 0..n {
                a[i * n + j] = if j == i {
                    256.
                } else if (i * 7 + j * 13) % 11 == 0 {
                    0.
                } else {
                    ((i * 37 + j * 19) % 17 + 1) as f64 / 128.
                };
            }
        }
        let model = Model::new(lp_ip_craft::ModelData {
            sense: Sense::Maximize,
            objective: (0..n).map(|j| (1 + j % 7) as f64).collect(),
            objective_offset: 0.,
            variables: lp_ip_craft::Bounds::new(vec![0.; n], vec![2.; n]),
            kinds: vec![lp_ip_craft::VariableKind::Continuous; n],
            matrix: lp_ip_craft::CsrMatrix::from_dense(m, n, &a).unwrap(),
            rows: lp_ip_craft::Bounds::new(vec![f64::NEG_INFINITY; m], vec![512.; m]),
        })
        .unwrap();
        let mut expected = None;
        for threads in [1, 2, 4, 8] {
            let mut c = controls();
            c.threads = threads;
            let mut lp = Lp::new(&model, &vec![true; m], &vec![true; n], c).unwrap();
            lp.state.fill(State::Lower);
            for i in 0..m {
                lp.basic[i] = i;
                lp.state[i] = State::Basic;
            }
            assert!(!lp.refactor().unwrap());
            lp.compute_dual();
            let d: Vec<_> = lp.d.iter().map(|v| v.to_bits()).collect();
            let mut prices = Vec::new();
            for row in [0, m / 2, m - 1] {
                lp.compute_row(row);
                prices.push((
                    lp.alpha.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
                    lp.touched.clone(),
                ));
            }
            assert_eq!(lp.stats.column_pricings, 3, "exercise dense column pricing");
            let actual = (d, prices);
            if let Some(e) = &expected {
                assert_eq!(&actual, e, "width{threads}");
            } else {
                expected = Some(actual);
            }
            // Reusing the same execution and factor with changed costs must be fresh.
            lp.cost[m] += 0.25;
            lp.compute_dual();
            assert_ne!(lp.d[m].to_bits(), expected.as_ref().unwrap().0[m]);
        }
    }
}