pounce-presolve 0.11.0

Algorithmic NLP preprocessing as a TNLP wrapper for POUNCE: bound tightening, redundant-constraint removal, LICQ degeneracy detection.
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
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
//! Algorithmic NLP preprocessing exposed as a composable TNLP wrapper.
//!
//! Tracks pounce issue #20.
//!
//! * **Phase 0** — scaffolding, options table, no-op identity path.
//! * **Phase 1** — Andersen-style bound tightening against linear rows.
//! * **Phase 2** — redundant linear-constraint removal: rows whose
//!   activity interval is implied by the (possibly Phase-1-tightened)
//!   variable box are dropped from the problem the solver sees, then
//!   reinstated with `λ=0` when forwarding `eval_h` / `finalize_solution`
//!   to the inner TNLP.
//!
//!   **Dual-attribution caveat (issue M24).** A row that was *itself* the
//!   reason a bound got tightened in Phase 1 — e.g. `x ≥ 2` tightening
//!   `x_l = 2` — then has an activity interval flush against its own
//!   bound, so Phase 2 sees it as redundant and drops it. If that bound is
//!   active at the solution the interior-point method reports the dual on
//!   the *variable bound* multiplier (`z_l`/`z_u`) against a bound that did
//!   not exist in the original problem, while the reinstated row keeps
//!   `λ = 0`. The primal point, objective, and KKT stationarity
//!   (`∇f − Jᵀλ − z_l + z_u = 0`) are all unaffected — only the *attribution*
//!   of the dual differs from a no-presolve solve (row multiplier vs. bound
//!   multiplier). A faithful fix would transfer the bound multiplier back to
//!   the row's `λ`, but that needs Phase-1 provenance (which row implied
//!   which bound) that is not currently tracked, and is ambiguous for
//!   multi-variable rows; it is left as future work. The behavior is pinned
//!   by `tests::dropped_row_dual_lands_on_bound_not_row` (M24).
//! * **Phase 3** — structural LICQ check on the surviving equality
//!   rows. Verdict is published via [`PresolveTnlp::licq_verdict`].
//! * **Phase 4** — bound-multiplier warm-start hints for variables
//!   whose bounds were tightened by Phase 1. Hints are emitted on
//!   `init_z` and exposed via [`PresolveTnlp::z_warm_starts`].
//! * **Phase 5** — sensitivity-aware passthrough: projects
//!   user-supplied constraint metadata and scaling through the row
//!   reduction on the way in, and expands outer→inner on the way out
//!   in `finalize_metadata`.
//! * **Phase 6** — linear-equality variable elimination
//!   (`presolve_linear_eq_reduction`, issue #487). The only phase that
//!   removes *columns*: singleton and two-variable linear equality rows
//!   determine variables, which are substituted away and recovered at
//!   `finalize_solution`. It lives in its own wrapper
//!   ([`linear_eq_elim::LinearEqElimTnlp`]) stacked **outside**
//!   [`PresolveTnlp`], so Phases 0–5 keep working in the variable space
//!   they were written against, and it is the outer layer that
//!   re-presents the reduced one. Off by default.

#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]

use std::cell::RefCell;
use std::rc::Rc;

use pounce_common::exception::SolverException;
use pounce_common::options_list::OptionsList;
use pounce_common::reg_options::RegisteredOptions;
use pounce_common::tolerance::is_negligible;
use pounce_common::types::{Index, Number, lower_bound_present, upper_bound_present};
use pounce_nlp::expression_provider::ExpressionProvider;
use pounce_nlp::tnlp::{
    BoundsInfo, IndexStyle, InfeasibilityProof, IpoptCq, IpoptData, IterStats, Linearity, MetaData,
    NlpInfo, ScalingRequest, Solution, SparsityRequest, StartingPoint, TNLP,
};

pub mod auxiliary;
pub mod block_solve;
pub mod bound_tighten;
pub mod btf;
pub mod components;
pub mod coupling;
pub mod diagnostics;
pub mod dulmage_mendelsohn;
pub mod fbbt;
pub mod incidence;
pub mod inequality_projection;
pub mod licq;
pub mod linear_eq_elim;
pub mod linear_eq_plan;
pub mod matching;
pub mod options;
pub mod reduction_frame;
pub mod redundant;
pub mod trivial_elim;

pub use block_solve::{
    BlockEquations, BlockSolveError, BlockSolveOptions, BlockSolveOutcome, BlockSolver,
    DampedNewtonSolver,
};
pub use bound_tighten::{INF_BOUND, LinearRow, TightenReport, tighten_bounds};
pub use btf::{BlockTriangularBlock, BlockTriangularForm};
pub use components::{SquareComponent, SquareComponents};
pub use coupling::{AuxiliaryCouplingClass, classify_block, objective_gradient_support};
pub use diagnostics::{AuxiliaryPreprocessingDiagnostics, AuxiliaryRejectionReason};
pub use dulmage_mendelsohn::{DMPart, DulmageMendelsohnPartition};
pub use incidence::{EqualityIncidence, InequalityIncidence, ProbeView};
pub use licq::{EqRow, LicqVerdict, licq_check};
pub use linear_eq_elim::{FullSolution, LinearEqElimTnlp, recover_dropped_multipliers};
pub use linear_eq_plan::{
    ElimStep, EliminationPlan, LinearEqElimReport, PlanConfig, PlanInput, VarRecovery, build_plan,
};
pub use options::{AuxiliaryCouplingPolicy, LicqAction, PresolveOptions, register_options};
pub use reduction_frame::{ReductionFrame, ReductionStack};
pub use redundant::find_redundant_rows;

/// Errors that can arise while building a presolved TNLP.
#[derive(Debug)]
pub enum PresolveError {
    OptionsError(SolverException),
}

impl std::fmt::Display for PresolveError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::OptionsError(e) => write!(f, "presolve options error: {e}"),
        }
    }
}

impl std::error::Error for PresolveError {}

impl From<SolverException> for PresolveError {
    fn from(e: SolverException) -> Self {
        Self::OptionsError(e)
    }
}

/// Stack Phase 6 on top of an already-built presolve wrapper, when the
/// option asks for it.
///
/// Phase 6 goes *outside*, not inside: it is the one pass that changes the
/// variable count, and Phases 0–5 are written against a fixed column
/// space. Putting it on top also means it sees the row set Phase 2 already
/// reduced, and its `finalize_solution` hands a full-length `x` back down
/// before `PresolveTnlp` lifts the row duals — so each layer only has to
/// undo its own reduction.
fn stack_linear_eq_elim(
    wrapped: Rc<RefCell<dyn TNLP>>,
    opts: PresolveOptions,
) -> Rc<RefCell<dyn TNLP>> {
    if !opts.linear_eq_reduction {
        return wrapped;
    }
    Rc::new(RefCell::new(LinearEqElimTnlp::new(wrapped, opts)))
}

/// Top-level entry: returns a TNLP wrapping `inner` with whatever
/// presolve passes the option table has enabled. When the master
/// switch is off, returns `inner` unchanged.
pub fn wrap_with_presolve(
    inner: Rc<RefCell<dyn TNLP>>,
    opts: PresolveOptions,
) -> Result<Rc<RefCell<dyn TNLP>>, PresolveError> {
    if !opts.enabled || inner.borrow().is_presolve_wrapper() {
        return Ok(inner);
    }
    let wrapped: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(PresolveTnlp::new(inner, opts)));
    Ok(stack_linear_eq_elim(wrapped, opts))
}

/// Same as [`wrap_with_presolve`] but also installs an
/// [`ExpressionProvider`] so passes like FBBT (issue #62) can see
/// constraint expression trees. Callers who have the concrete inner
/// TNLP type (`pounce-cli` with `NlTnlp`) should prefer this; the
/// plain `wrap_with_presolve` leaves `presolve_fbbt` as a silent
/// no-op.
pub fn wrap_with_presolve_provider(
    inner: Rc<RefCell<dyn TNLP>>,
    expr_provider: Rc<RefCell<dyn ExpressionProvider>>,
    opts: PresolveOptions,
) -> Result<Rc<RefCell<dyn TNLP>>, PresolveError> {
    if !opts.enabled || inner.borrow().is_presolve_wrapper() {
        return Ok(inner);
    }
    let wrapped: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(
        PresolveTnlp::with_expression_provider(inner, expr_provider, opts),
    ));
    Ok(stack_linear_eq_elim(wrapped, opts))
}

/// Convenience: read the `presolve_*` keys out of an `OptionsList`
/// and call [`wrap_with_presolve`].
pub fn wrap_from_options(
    inner: Rc<RefCell<dyn TNLP>>,
    options: &OptionsList,
) -> Result<Rc<RefCell<dyn TNLP>>, PresolveError> {
    let opts = PresolveOptions::from_options_list(options)?;
    wrap_with_presolve(inner, opts)
}

/// Which accepting test the witness-refutation gate uses to decide that a
/// sampled point satisfies a row.
///
/// The two forms exist because the question the witness answers is not always
/// the same question. Both are *accepting* tests, so both must fail closed —
/// when in doubt, accept the point, withdraw the verdict, keep the proof
/// unclaimed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WitnessRule {
    /// **Default, and the only rule for any path where the solve can run.**
    ///
    /// Accepts a row when the residual is negligible at the row's *live*
    /// magnitude through the clamped form `tol * max(scale, 1)` — i.e. exactly
    /// what the solver's own acceptance test would wave through. This is the
    /// #380 rule: never certify what the solver itself would accept as
    /// feasible, or the same model reports "proved infeasible" with presolve on
    /// and `Solve_Succeeded` with it off.
    #[default]
    SolverAcceptance,
    /// **Only for paths where the solve provably cannot run**, so no
    /// `Solve_Succeeded` counterfactual exists to contradict (today: the
    /// too-few-degrees-of-freedom gate, gh#391).
    ///
    /// Accepts a row when the residual is negligible relative to the row's
    /// **declared** magnitude, `max(|g_l|, |g_u|)` over its *finite* bounds,
    /// with no absolute clamp. Declared, not live: the live value moves with
    /// the sampled point, while the bounds are the magnitude the modeller wrote
    /// the row in — the same "declared, not live" pattern
    /// `fbbt_infeasibility_survives_margin` uses for its per-row margin.
    ///
    /// Why the clamp has to go here: `tol * max(scale, 1)` reinstates an
    /// absolute floor once the row's magnitude drops below 1, so multiplying
    /// every row of an infeasible model by `1e-12` — which changes the feasible
    /// set not at all — makes every point of the box "satisfy" every row and
    /// withdraws a scale-free bound-propagation proof. That is the whole of
    /// gh#391: `s*x == 0.2*s` with `s*x == 0.8*s` crosses by `0.6` at every `s`,
    /// yet the verdict flipped at `s <= ~3e-8`.
    ///
    /// Why it is still safe: the clamp's job is to not demand more precision
    /// than the solver promised, because a solver converges to *absolute*
    /// residuals. On this path the solver never produces a point at all, so
    /// there is no converged residual to be compatible with — the alternative
    /// to the proof is a structural error, not a solution.
    ///
    /// The `b = 0` hazard is handled explicitly and fails closed: a homogeneous
    /// row (`g_l = g_u = 0`, or a row with no finite bound at all) has no
    /// declared magnitude, which would make the relative test unsatisfiable by
    /// construction — `viol == scale` for any nonzero float noise — and a
    /// genuinely feasible point would fail to refute. Such a row keeps
    /// [`WitnessRule::SolverAcceptance`]'s clamped form, i.e. the absolute
    /// floor.
    DeclaredRowRelative,
}

/// Cached, reduced view of the problem after presolve passes have
/// run. Exposed for inspection from integration tests.
/// How far a model must be from satisfiable before an emptiness detection is
/// promoted from a *detection* to a *proof*.
///
/// The rule: **never certify what the solver itself would accept as feasible.**
/// POUNCE returns `Solve_Succeeded` for a violation up to its feasibility
/// tolerance `tol`, so certifying anything smaller makes the same model report
/// "proved infeasible" with presolve on and "solved" with it off — a
/// contradiction no caller can reconcile.
///
/// Presolve's internal emptiness tests are far tighter than this: bound
/// propagation uses a `1e-12` crossing margin and FBBT's tests are exact
/// (`is_empty`, `new_lo > new_hi` — no margin at all). Those are right for
/// deciding whether to keep propagating, and wrong for the word "proved".
///
/// Two models forced this. `x >= 0.1 + 0.2` with `x <= 0.3` is infeasible by
/// `5.5e-17` — pure binary-float noise — yet was reported proved infeasible.
/// And `x >= 1 + 1e-11` with `x <= 1` is solved to `Solve_Succeeded` on the
/// default path while presolve called it proved infeasible.
/// Try to *refute* a candidate infeasibility by finding a point that satisfies
/// every constraint. Returns `true` when a witness is found — the verdict must
/// then be withdrawn.
///
/// This is the check interval arithmetic cannot do for itself. FBBT and bound
/// propagation reason about *over-approximated ranges*; at extreme coefficient
/// scale those ranges lose the precision the conclusion rests on, and a
/// feasible model can be reported empty. Evaluating the real constraints at a
/// concrete point is exact by comparison — if the point satisfies them, the
/// region demonstrably is not empty, whatever the intervals concluded.
///
/// Measured on a 400-instance feasible-by-construction sweep, Pyomo's
/// `contrib.fbbt` — same tolerance idea, no refutation step — reports 57 false
/// positives where POUNCE reports 3. This gate is where the difference comes
/// from, and is the part worth keeping ahead of it.
///
/// Deliberately one-directional: it can only ever *withdraw* a verdict, never
/// create one, so a failed evaluation or an unsampled witness costs nothing but
/// a missed certification. It is also a single gate covering both certification
/// paths — the previous two safeguards each landed on one path and not its
/// twin, which is how a bound-propagation hole survived.
#[allow(clippy::too_many_arguments)]
fn witness_refutes_infeasibility(
    inner: &Rc<RefCell<dyn TNLP>>,
    n: usize,
    m_in: usize,
    x_l: &[Number],
    x_u: &[Number],
    g_l: &[Number],
    g_u: &[Number],
    tol: Number,
    rule: WitnessRule,
) -> bool {
    if m_in == 0 || n == 0 {
        return false;
    }
    let clamp = |v: Number, fallback: Number| -> Number {
        if v.is_finite() && v.abs() < crate::bound_tighten::INF_BOUND {
            v
        } else {
            fallback
        }
    };
    let lo: Vec<Number> = (0..n).map(|j| clamp(x_l[j], -1.0)).collect();
    let hi: Vec<Number> = (0..n).map(|j| clamp(x_u[j], 1.0)).collect();
    let mid: Vec<Number> = (0..n).map(|j| 0.5 * (lo[j] + hi[j])).collect();

    // The model's own starting point is the first candidate. It is a witness
    // the modeller supplied, and at extreme coefficient scale it is not
    // reproducible from the bounds: `0.5*(lo+hi)` and the modeller's
    // `lo + 0.5*(hi-lo)` differ by an ulp, and against a 1e30 coefficient that
    // ulp moves the row value by ~1e5 — enough to turn a satisfied row into a
    // violated one. Sampling geometry alone therefore missed witnesses that
    // `pounce check-x0` reports as exactly feasible.
    let mut x0 = vec![0.0; n];
    let mut z_l = vec![0.0; n];
    let mut z_u = vec![0.0; n];
    let mut lam = vec![0.0; m_in];
    let have_x0 = inner.borrow_mut().get_starting_point(StartingPoint {
        init_x: true,
        x: &mut x0,
        init_z: false,
        z_l: &mut z_l,
        z_u: &mut z_u,
        init_lambda: false,
        lambda: &mut lam,
    });

    let mut g = vec![0.0; m_in];
    let mut candidates: Vec<&Vec<Number>> = Vec::with_capacity(4);
    if have_x0 && x0.iter().all(|v| v.is_finite()) {
        candidates.push(&x0);
    }
    candidates.extend([&mid, &lo, &hi]);
    for x in candidates {
        if !inner.borrow_mut().eval_g(x, true, &mut g) {
            continue;
        }
        let feasible = (0..m_in).all(|i| {
            let v = g[i];
            if !v.is_finite() {
                return false;
            }
            // An absent bound is stored as the sentinel (`±INF_BOUND`), not as
            // an infinity, so every use of a bound has to ask whether it is
            // real — and the question is **directional**. A lower bound is
            // absent when it is at or below `-INF_BOUND`; an upper bound when
            // it is at or above `+INF_BOUND`. This is the convention
            // [`crate::bound_tighten`] already uses (`x_l[j] <= -INF_BOUND`,
            // `x_u[j] >= INF_BOUND`).
            //
            // gh #396 is what the symmetric magnitude test (`|b| < INF_BOUND`)
            // cost, and it went wrong in both directions at once on the same
            // row. Property-test seed 223 carries
            // `-1e30·x[0] <= -5.0000000000000007e20` over `x[0] ∈ [0, 1e-9]`,
            // with a starting point landing *exactly* on that upper bound:
            //
            //   * `g_l = -1e19` is the sentinel for an absent lower bound, but
            //     `viol` had no presence test at all, so it scored
            //     `g_l - v = 4.9e20` — a violation of a bound the row does not
            //     have, against a point whose true violation is zero.
            //   * `g_u = -5e20` is a genuine, finite upper bound, but
            //     `|−5e20| < 1e19` is false, so the magnitude test called it
            //     absent — discarding a real constraint.
            //
            // Either error alone sinks the witness. With no candidate able to
            // pass, presolve certified a *feasible* model infeasible and
            // reported `solve_result_num` 201, which asserts a proof.
            let lo_present = |b: Number| b.is_finite() && b > -crate::bound_tighten::INF_BOUND;
            let up_present = |b: Number| b.is_finite() && b < crate::bound_tighten::INF_BOUND;
            // Only *real* bounds inform the declared magnitude. The sentinel
            // would otherwise set the slack around 1e11 and make every row look
            // satisfied — which withdrew even correct verdicts.
            let declared = (if lo_present(g_l[i]) {
                g_l[i].abs()
            } else {
                0.0
            })
            .max(if up_present(g_u[i]) {
                g_u[i].abs()
            } else {
                0.0
            });
            let scale = v.abs().max(declared);
            let lo_viol = if lo_present(g_l[i]) { g_l[i] - v } else { 0.0 };
            let hi_viol = if up_present(g_u[i]) { v - g_u[i] } else { 0.0 };
            let viol = lo_viol.max(hi_viol).max(0.0);
            match rule {
                // Accepting direction, so the shared clamped form: never
                // stricter than the absolute `tol`.
                WitnessRule::SolverAcceptance => is_negligible(viol, scale, tol),
                // Pure relative against the *declared* magnitude — no clamp, so
                // the test moves with the row under scaling. A row with no
                // declared magnitude (homogeneous, or unbounded on both sides)
                // has nothing to be relative to and keeps the absolute floor,
                // which is the fail-closed direction here: it accepts the
                // point, and accepting withdraws the verdict.
                //
                // The directional presence tests above make "no declared
                // magnitude" mean what it says. Under the previous symmetric
                // test a row could have a perfectly real bound of `-5e20` and
                // still report `declared == 0`, dropping into the absolute
                // floor by accident rather than by the reasoning above.
                WitnessRule::DeclaredRowRelative if declared > 0.0 => {
                    viol.is_finite() && viol <= tol * declared
                }
                WitnessRule::DeclaredRowRelative => is_negligible(viol, scale, tol),
            }
        });
        if feasible {
            return true;
        }
    }
    false
}

/// Whether the model's numbers are representable enough to base an
/// infeasibility verdict on.
///
/// **Only the FBBT path consults this, deliberately.** Wiring the
/// bound-propagation path to it was tried and measured: every genuinely
/// infeasible model dropped from a certified verdict to the numerical one,
/// because POUNCE stores an unbounded constraint bound as the finite sentinel
/// `INF_BOUND` rather than `f64::INFINITY` — so `is_infinite()` is false, the
/// `< INF_BOUND` test fails on equality, and any model with a one-sided
/// constraint (nearly all of them) is rejected. Making the comparison inclusive
/// admits the sentinel, but then it also admits `1e300`: under POUNCE's own
/// convention `|v| >= INF_BOUND` *means* unbounded, so a bounds-magnitude test
/// cannot separate "no bound" from "absurd finite value". A guard that cannot
/// make that distinction should not be spread to a second path.
///
/// The overflow it does catch on the FBBT path comes from constraint
/// *coefficients*, not bounds; a check on the Jacobian magnitudes would be the
/// mechanism that generalises. See the commit history for the measured
/// alternatives (1e150 -> 99/400, 1e20 -> 37/400, sentinel-inclusive -> 37/400,
/// against a 3/400 baseline). Rejects NaN and finite magnitudes at or beyond the
/// unbounded sentinel, where interval arithmetic overflows; genuine infinities
/// stay admissible because they mean "no bound", not "a number".
fn certificate_data_is_admissible(
    x_l: &[Number],
    x_u: &[Number],
    g_l: &[Number],
    g_u: &[Number],
) -> bool {
    let sane = |v: &Number| {
        let v = *v;
        !v.is_nan() && (v.is_infinite() || v.abs() < crate::bound_tighten::INF_BOUND)
    };
    x_l.iter().all(sane) && x_u.iter().all(sane) && g_l.iter().all(sane) && g_u.iter().all(sane)
}

fn certify_margin(tol: Number) -> Number {
    // Guard against a degenerate or absurdly tight `tol`; below ~1e-12 the
    // margin would drop into the float-noise band the whole check exists to
    // exclude.
    tol.max(1e-12)
}

/// Whether some variable's crossed bounds are crossed by more than the solver
/// itself would accept as feasible — the condition for promoting a Phase-1
/// detection to a certified proof.
///
/// The scale is the crossed pair's own magnitude, through `is_negligible`'s
/// clamped accepting form — deliberately NOT the pure-relative proving form
/// (`is_significant`). The #380 rule binds here: a crossing so small that the
/// solver's acceptance test would wave a point through must never be certified,
/// or the same model reports "proved infeasible" with presolve on and
/// `Solve_Succeeded` with it off. The clamp hazard that rules the proving form
/// out for *row residuals* does not arise for bound crossings: row scaling
/// divides out of a propagated bound (`s*x >= 2*s` implies `x >= 2` at every
/// `s`), so crossings do not shrink in the down-scaled direction. What the
/// relative part fixes is the *up-scaled* model — a crossing of `6e-5` on
/// bounds near `3e11` is float noise (relative `2e-16`), and the absolute
/// margin used to certify it.
fn crossing_is_certifiable(x_l: &[Number], x_u: &[Number], tol: Number) -> bool {
    x_l.iter().zip(x_u).any(|(&l, &u)| {
        // Both sides present before a crossing counts (gh #402) — otherwise an
        // absent lower bound at the `-1e19` sentinel against a real upper bound
        // of `-5e20` reads as a `5e20` crossing, far too large for
        // `is_negligible` to dismiss, and certifies a feasible model infeasible.
        lower_bound_present(l)
            && upper_bound_present(u)
            && l > u
            && !is_negligible(l - u, l.abs().max(u.abs()), tol)
    })
}

/// Re-run FBBT with every constraint's bounds widened by that row's own
/// acceptance slack, `tol * max(|bound|, 1)` — the same clamped form
/// `is_negligible` uses. Returns `true` only if the problem is *still*
/// infeasible with that slack — i.e. the infeasibility is robust at the scale
/// the row is written in, not a hair's-breadth modelling artifact.
///
/// Per-row rather than one absolute margin: an absolute `1e-8` widening is
/// invisible on a row whose bounds sit near `5e13`, so an "infeasibility" of
/// `3e3` there (eleven relative digits — a violation `pounce verify` accepts)
/// would survive the probe and be certified, contradicting the verifier on the
/// same model.
///
/// Sound in the conservative direction: a false `false` merely withholds the
/// proof and leaves the previous behavior (let the IPM decide), while a false
/// `true` would be a wrong "proved infeasible" — so the test is written to fail
/// closed.
/// The acceptance slack for one row: `tol * max(|bound|, 1)` over the row's
/// *present* bounds.
///
/// Only a present bound carries magnitude information, and presence is
/// **directional** (gh #402). The symmetric `|b| < INF_BOUND` test this used to
/// run failed **open**: a row whose real bound is `-5e20` contributed `0.0`, so
/// the margin collapsed to `tol * 1.0` on a row written at `5e20` scale — the
/// infeasibility then survived an absurdly small widening and certified, which
/// is precisely the direction `fbbt_infeasibility_survives_margin` exists to
/// rule out. (The two `relaxed` maps in that function already used the
/// directional form; its halves disagreed.)
fn row_margin_for(g_l: Number, g_u: Number, tol: Number) -> Number {
    let lo_mag = if lower_bound_present(g_l) {
        g_l.abs()
    } else {
        0.0
    };
    let hi_mag = if upper_bound_present(g_u) {
        g_u.abs()
    } else {
        0.0
    };
    tol * lo_mag.max(hi_mag).max(1.0)
}

#[allow(clippy::too_many_arguments)]
fn fbbt_infeasibility_survives_margin(
    provider: &dyn ExpressionProvider,
    n: usize,
    m_in: usize,
    x_l: &[Number],
    x_u: &[Number],
    g_l: &[Number],
    g_u: &[Number],
    row_kept: &[bool],
    cfg: &crate::fbbt::FbbtConfig,
    tol: Number,
) -> bool {
    let row_margin = |i: usize| -> Number { row_margin_for(g_l[i], g_u[i], tol) };
    let g_l_relaxed: Vec<Number> = g_l
        .iter()
        .enumerate()
        .map(|(i, &v)| {
            if v <= -crate::bound_tighten::INF_BOUND {
                v
            } else {
                v - row_margin(i)
            }
        })
        .collect();
    let g_u_relaxed: Vec<Number> = g_u
        .iter()
        .enumerate()
        .map(|(i, &v)| {
            if v >= crate::bound_tighten::INF_BOUND {
                v
            } else {
                v + row_margin(i)
            }
        })
        .collect();
    // Overflow guard. Interval arithmetic on absurd-but-finite magnitudes
    // overflows to +/-inf, and `Interval::is_empty` treats a NaN endpoint as an
    // empty range — so `1e300 * 1e300` reads as "this constraint cannot be
    // satisfied" and would be certified as a *proof*. It is not: the model
    // `x in [-1e300, 1e300], 1e300*x >= 1e300` is plainly feasible (`x = 1`),
    // yet was reported proved infeasible while `presolve_fbbt=no` solved it.
    // Widening the bounds cannot expose this — an overflow is unaffected by a
    // 1e-9 relaxation — so the check has to be on the inputs.
    //
    // A genuine infinity is fine and common (`x >= 5` has `g_u = +inf`): those
    // are the INF sentinel and mean "unbounded". What cannot be trusted is a
    // *finite* magnitude at or beyond the sentinel, which is where the
    // arithmetic stops being representable.
    if !certificate_data_is_admissible(x_l, x_u, g_l, g_u) {
        return false;
    }
    let mut probe_x_l = x_l.to_vec();
    let mut probe_x_u = x_u.to_vec();
    let report = crate::fbbt::run_fbbt(
        provider,
        n,
        m_in,
        &mut probe_x_l,
        &mut probe_x_u,
        &g_l_relaxed,
        &g_u_relaxed,
        Some(row_kept),
        cfg,
    );
    report.infeasibility_witness.is_some()
}

pub struct CachedBounds {
    pub x_l: Vec<Number>,
    pub x_u: Vec<Number>,
    /// Reduced (post-row-drop) constraint lower bounds.
    pub g_l: Vec<Number>,
    /// Reduced constraint upper bounds.
    pub g_u: Vec<Number>,
}

/// TNLP wrapper that re-presents the inner problem after presolve.
pub struct PresolveTnlp {
    inner: Rc<RefCell<dyn TNLP>>,
    /// Optional structural-expression handle on the inner TNLP for
    /// passes (FBBT, issue #62) that need DAG-level access. Callers
    /// who know the concrete inner type (e.g. `pounce-cli` with
    /// `NlTnlp`) install this via
    /// [`Self::with_expression_provider`]. Callers without (e.g.
    /// callback-based bridges) leave it `None` and the expression-
    /// hungry passes silently become no-ops.
    expr_provider: Option<Rc<RefCell<dyn ExpressionProvider>>>,
    opts: PresolveOptions,

    /// Which accepting test the final witness-refutation gate uses. Left at
    /// [`WitnessRule::SolverAcceptance`] for every wrapper that is actually
    /// solved through; raised to [`WitnessRule::DeclaredRowRelative`] only by
    /// callers that have already established the solve cannot run (gh#391).
    /// Deliberately *not* a `PresolveOptions` field: it is a property of the
    /// call site, not a user-tunable knob, and no user should be able to switch
    /// a live solve onto the stricter rule.
    witness_rule: WitnessRule,

    /// `None` until init has run; afterwards `Some(state)`.
    state: Option<PresolveState>,

    /// Full-space `(x, lambda)` forwarded to the inner TNLP at the last
    /// `finalize_solution` — i.e. after row-drop multiplier recovery, in
    /// the original `.nl` row order (length `info_inner.m`). `None` until
    /// a solve finalizes. The CLI prefers this over its reduced-space
    /// `on_converged` / counting capture so the `.sol` / JSON dual block
    /// regains the original constraint count: the kept-row-space lambda
    /// the solver produces otherwise mis-aligns against the `.nl`'s `m`.
    finalized_full_solution: Option<(Vec<Number>, Vec<Number>)>,
}

struct PresolveState {
    info_inner: NlpInfo,
    info_outer: NlpInfo,
    bounds: CachedBounds,

    /// Maps outer (reduced) row index → inner row index. Length
    /// equals `info_outer.m`.
    rows_kept: Vec<usize>,

    /// For each outer nnz, the position in the inner nnz array.
    jac_kept_idx: Vec<usize>,
    /// Cached outer (reduced + renumbered) Jacobian sparsity, served
    /// on `eval_jac_g(Structure)`.
    jac_irow_outer: Vec<Index>,
    jac_jcol_outer: Vec<Index>,

    /// Phase 1 report.
    tighten_report: TightenReport,
    /// A proof that the feasible region is empty, when presolve derived one on
    /// an *un-clamped* box. `None` unless one of the four certifiable sites in
    /// `ensure_init` fired — in particular an infeasibility detected while a
    /// Phase-0 auxiliary elimination is in force is deliberately NOT recorded
    /// here, because a dropped row can fabricate one (the #53 / F6 hazard).
    /// Such a detection is re-checked on the rolled-back box first, and only
    /// the surviving result is certified.
    certified_infeasible: Option<InfeasibilityProof>,
    /// FBBT report (`None` when `presolve_fbbt` was off or the inner
    /// TNLP did not expose an `ExpressionProvider`).
    fbbt_report: Option<crate::fbbt::FbbtReport>,
    /// Number of rows dropped by Phase 2.
    n_dropped_rows: Index,
    /// Phase 3 verdict (`None` if the LICQ check was disabled).
    licq_verdict: Option<LicqVerdict>,
    /// Phase 4: warm-start values for `z_l` per variable. Entry is
    /// 0.0 where presolve did not tighten the lower bound, else
    /// `bound_mult_init_val`. Same length as `bounds.x_l`.
    z_l_warm: Vec<Number>,
    /// Phase 4: warm-start values for `z_u` per variable.
    z_u_warm: Vec<Number>,

    /// Scratch buffers reused across eval_* calls.
    scratch_g: Vec<Number>,
    scratch_jac: Vec<Number>,
    scratch_lambda: Vec<Number>,

    /// Phase 0 (issue #53) diagnostics. Always present; defaulted to
    /// zeros when the master switch is off.
    aux_diagnostics: AuxiliaryPreprocessingDiagnostics,
    /// Phase 0 postsolve stack. Empty until PR 7 wires real frames.
    #[allow(dead_code)]
    reduction_stack: ReductionStack,
}

impl PresolveTnlp {
    /// Build a presolve wrapper directly. Prefer
    /// [`wrap_with_presolve`] in production code; this constructor
    /// is exposed so integration tests can keep a typed handle for
    /// accessors like [`Self::licq_verdict`].
    pub fn new(inner: Rc<RefCell<dyn TNLP>>, opts: PresolveOptions) -> Self {
        Self {
            inner,
            expr_provider: None,
            opts,
            witness_rule: WitnessRule::default(),
            state: None,
            finalized_full_solution: None,
        }
    }

    /// Switch the final witness-refutation gate to
    /// [`WitnessRule::DeclaredRowRelative`].
    ///
    /// **Only legitimate when the caller has already established that the solve
    /// cannot run**, so the "never certify what the solver would accept"
    /// counterfactual has nothing to compare against. Today that is the
    /// too-few-degrees-of-freedom gate alone (gh#391). Calling this on a
    /// wrapper that will be solved through reintroduces the #380 defect: a
    /// small-magnitude model would report "proved infeasible" with presolve on
    /// and `Solve_Succeeded` with it off.
    pub fn probing_without_a_solve(mut self) -> Self {
        self.witness_rule = WitnessRule::DeclaredRowRelative;
        self
    }

    /// Build a presolve wrapper with an `ExpressionProvider` handle on
    /// the same inner TNLP. The two handles should reference the
    /// *same* object (typical pattern: clone an `Rc<RefCell<NlTnlp>>`
    /// twice, once as `dyn TNLP` and once as `dyn ExpressionProvider`).
    /// Required for `presolve_fbbt=yes` to fire — without a provider,
    /// FBBT silently becomes a no-op.
    pub fn with_expression_provider(
        inner: Rc<RefCell<dyn TNLP>>,
        expr_provider: Rc<RefCell<dyn ExpressionProvider>>,
        opts: PresolveOptions,
    ) -> Self {
        Self {
            inner,
            expr_provider: Some(expr_provider),
            opts,
            witness_rule: WitnessRule::default(),
            state: None,
            finalized_full_solution: None,
        }
    }

    /// FBBT report (`None` until init runs, or when FBBT was disabled
    /// or the inner TNLP did not expose an `ExpressionProvider`).
    pub fn fbbt_report(&self) -> Option<crate::fbbt::FbbtReport> {
        self.state.as_ref().and_then(|s| s.fbbt_report.clone())
    }

    /// Phase 1 report (zeroed until init has run).
    pub fn tighten_report(&self) -> TightenReport {
        self.state
            .as_ref()
            .map(|s| s.tighten_report.clone())
            .unwrap_or_default()
    }

    /// A proof that the feasible region is empty, if presolve derived one on
    /// an un-clamped box. `None` means "not proved", not "feasible".
    ///
    /// Distinct from `tighten_report().infeasible` /
    /// `fbbt_report().infeasibility_witness`, which are raw detections: those
    /// also fire for a contradiction manufactured by a Phase-0 auxiliary
    /// elimination, which is why they were never safe to act on. This returns
    /// only detections that survive on the original box.
    pub fn certified_infeasible(&self) -> Option<InfeasibilityProof> {
        self.state.as_ref().and_then(|s| s.certified_infeasible)
    }

    /// Number of constraint rows dropped by Phase 2 (0 if presolve
    /// has not yet run or no rows are redundant).
    pub fn n_dropped_rows(&self) -> Index {
        self.state.as_ref().map(|s| s.n_dropped_rows).unwrap_or(0)
    }

    /// The full-space `(x, lambda)` captured at the last
    /// `finalize_solution`, lifted back to the original `.nl` row space
    /// (length `info_inner.m`) with dropped-row multipliers recovered.
    /// `None` until a solve finalizes. The CLI consumes this so its
    /// `.sol` / JSON dual block carries the original constraint count
    /// rather than the reduced kept-row count. See the field docs.
    pub fn finalized_full_solution(&self) -> Option<(Vec<Number>, Vec<Number>)> {
        self.finalized_full_solution.clone()
    }

    /// Cached reduced bounds, if presolve has run.
    pub fn cached_bounds(&self) -> Option<&CachedBounds> {
        self.state.as_ref().map(|s| &s.bounds)
    }

    /// Phase 3 verdict — `Some` only if the LICQ check was enabled
    /// and presolve has run.
    pub fn licq_verdict(&self) -> Option<&LicqVerdict> {
        self.state.as_ref().and_then(|s| s.licq_verdict.as_ref())
    }

    /// Phase 4 warm-start hints `(z_l, z_u)`. Each entry is 0.0 if
    /// no hint is set for that variable, else the configured
    /// `bound_mult_init_val`. `None` until init has run.
    pub fn z_warm_starts(&self) -> Option<(&[Number], &[Number])> {
        self.state
            .as_ref()
            .map(|s| (&s.z_l_warm[..], &s.z_u_warm[..]))
    }

    /// Phase 0 (issue #53) summary. Returns a zero-valued struct
    /// until init has run; afterwards, populated by
    /// [`auxiliary::run_auxiliary_phase0`]. PR 1 always returns
    /// zeros even with the master switch on.
    pub fn auxiliary_diagnostics(&self) -> AuxiliaryPreprocessingDiagnostics {
        self.state
            .as_ref()
            .map(|s| s.aux_diagnostics.clone())
            .unwrap_or_default()
    }

    /// Lazy initialization: pull inner dims, bounds, linearity tags,
    /// Jacobian, and starting point; run Phase 1 + Phase 2 passes;
    /// cache everything needed to translate later eval_* calls.
    fn ensure_init(&mut self) -> Option<&PresolveState> {
        if self.state.is_some() {
            return self.state.as_ref();
        }

        let info_inner = self.inner.borrow_mut().get_nlp_info()?;
        let n = info_inner.n as usize;
        let m_in = info_inner.m as usize;
        let nnz_in = info_inner.nnz_jac_g as usize;

        // Inner bounds.
        let mut x_l = vec![0.0; n];
        let mut x_u = vec![0.0; n];
        let mut g_l_inner = vec![0.0; m_in];
        let mut g_u_inner = vec![0.0; m_in];
        {
            let mut inner = self.inner.borrow_mut();
            if !inner.get_bounds_info(BoundsInfo {
                x_l: &mut x_l,
                x_u: &mut x_u,
                g_l: &mut g_l_inner,
                g_u: &mut g_u_inner,
            }) {
                return None;
            }
        }

        // Jacobian sparsity.
        let mut jac_irow_inner = vec![0 as Index; nnz_in];
        let mut jac_jcol_inner = vec![0 as Index; nnz_in];
        if nnz_in > 0 {
            let mut inner = self.inner.borrow_mut();
            if !inner.eval_jac_g(
                None,
                false,
                SparsityRequest::Structure {
                    irow: &mut jac_irow_inner,
                    jcol: &mut jac_jcol_inner,
                },
            ) {
                return None;
            }
        }

        // Linearity tags (presolve is dormant without them).
        let mut linearity = vec![Linearity::NonLinear; m_in];
        let have_linearity = if m_in > 0 {
            self.inner
                .borrow_mut()
                .get_constraints_linearity(&mut linearity)
        } else {
            true
        };

        // Per-variable linearity (H11): lets Phase-0 objective-coupling
        // classification distinguish a genuinely objective-free variable from
        // one that is merely zero-gradient at the single probe point. The
        // objective-scoped query is preferred — it is exactly the set the
        // guard needs. The global tags are only a fallback: they are a
        // conservative superset (a variable nonlinear only in a *constraint*
        // is tagged NonLinear too), which keeps the guard sound but blocks
        // legitimate eliminations of objective-free blocks (the gas-network
        // case). Most TNLPs decline both (default `false`), in which case
        // Phase 0 falls back to the probe gradient alone.
        let mut var_linearity = vec![Linearity::NonLinear; n];
        let have_var_linearity = {
            let mut inner = self.inner.borrow_mut();
            inner.get_objective_variables_linearity(&mut var_linearity)
                || inner.get_variables_linearity(&mut var_linearity)
        };

        // Probe point for Jacobian values (linear rows have constant
        // Jacobians; this `x` is only needed because some inner
        // TNLPs assert on receipt).
        let mut x_probe = vec![0.0; n];
        let mut z_l_probe = vec![0.0; n];
        let mut z_u_probe = vec![0.0; n];
        let mut lambda_probe = vec![0.0; m_in];
        let started = self.inner.borrow_mut().get_starting_point(StartingPoint {
            init_x: true,
            x: &mut x_probe,
            init_z: false,
            z_l: &mut z_l_probe,
            z_u: &mut z_u_probe,
            init_lambda: false,
            lambda: &mut lambda_probe,
        });
        if !started {
            return None;
        }

        // Jacobian values at the probe.
        let mut jac_values_inner = vec![0.0; nnz_in];
        if nnz_in > 0 {
            let ok = self.inner.borrow_mut().eval_jac_g(
                Some(&x_probe),
                true,
                SparsityRequest::Values {
                    values: &mut jac_values_inner,
                },
            );
            if !ok {
                return None;
            }
        }

        // Build LinearRow list from the inner Jacobian + linearity.
        let one_based = matches!(info_inner.index_style, IndexStyle::Fortran);
        let mut by_row: Vec<Vec<(Index, Number)>> = vec![Vec::new(); m_in];
        for k in 0..nnz_in {
            let i = if one_based {
                (jac_irow_inner[k] - 1) as usize
            } else {
                jac_irow_inner[k] as usize
            };
            let j = if one_based {
                jac_jcol_inner[k] - 1
            } else {
                jac_jcol_inner[k]
            };
            if i < m_in && (j as usize) < n {
                by_row[i].push((j, jac_values_inner[k]));
            }
        }
        let linear_row_map: Vec<Option<LinearRow>> = (0..m_in)
            .map(|i| {
                if have_linearity && matches!(linearity[i], Linearity::Linear) {
                    Some(LinearRow {
                        entries: by_row[i].clone(),
                        lo: g_l_inner[i],
                        hi: g_u_inner[i],
                    })
                } else {
                    None
                }
            })
            .collect();
        // NOTE: `linear_rows` is materialised AFTER Phase 0 so it
        // can filter out rows Phase 0 dropped — propagating bounds
        // through aux-eliminated rows lets tighten_bounds derive
        // contradictions (see issue #53 PR review).

        // Snapshot inner bounds before Phase 1 mutates them; needed
        // for Phase 4 warm-start hints AND for rolling back Phase 0
        // if its clamps later prove infeasible against the kept
        // linear rows.
        let inner_x_l = x_l.clone();
        let inner_x_u = x_u.clone();

        // Phase 0 (issue #53): auxiliary-equality preprocessing.
        // PR 8 wires the real pipeline (incidence → matching → DM →
        // BTF → classify → linear block solve → frame). Variables it
        // fixes are clamped via x_l/x_u; rows it drops are recorded
        // in `row_kept_inner` so the existing remapping logic below
        // picks them up.
        let mut row_kept_inner: Vec<bool> = vec![true; m_in];
        let mut reduction_stack = ReductionStack::default();
        let aux_diagnostics = if self.opts.auxiliary && m_in > 0 {
            // Probe extra quantities Phase 0 needs.
            let mut g_at_probe = vec![0.0; m_in];
            let g_ok = self
                .inner
                .borrow_mut()
                .eval_g(&x_probe, true, &mut g_at_probe);
            if !g_ok {
                return None;
            }
            let mut grad_f_probe = vec![0.0; n];
            let grad_ok = self
                .inner
                .borrow_mut()
                .eval_grad_f(&x_probe, false, &mut grad_f_probe);
            if !grad_ok {
                return None;
            }
            // Plug everything into the orchestrator.
            let linearity_for_phase0: Vec<Linearity> = if have_linearity {
                linearity.clone()
            } else {
                vec![Linearity::NonLinear; m_in]
            };
            let probe_view = auxiliary::Phase0Probe {
                n_vars: n,
                n_rows: m_in,
                jac_irow: &jac_irow_inner,
                jac_jcol: &jac_jcol_inner,
                jac_values: &jac_values_inner,
                g_l: &g_l_inner,
                g_u: &g_u_inner,
                g_at_probe: &g_at_probe,
                linearity: &linearity_for_phase0,
                one_based,
                eq_tol: 1e-12,
                x_probe: &x_probe,
                grad_f: &grad_f_probe,
                var_linearity: if have_var_linearity {
                    Some(&var_linearity)
                } else {
                    None
                },
                x_l: &x_l,
                x_u: &x_u,
            };
            // Adapter: wrap `self.inner` so the orchestrator can
            // call eval_g / eval_jac_g for nonlinear blocks.
            struct TnlpCallbackAdapter {
                inner: Rc<RefCell<dyn TNLP>>,
            }
            impl auxiliary::Phase0TnlpCallback for TnlpCallbackAdapter {
                fn eval_g_full(&mut self, x: &[Number], g: &mut [Number]) -> bool {
                    self.inner.borrow_mut().eval_g(x, true, g)
                }
                fn eval_jac_g_values(&mut self, x: &[Number], values: &mut [Number]) -> bool {
                    self.inner.borrow_mut().eval_jac_g(
                        Some(x),
                        true,
                        SparsityRequest::Values { values },
                    )
                }
            }
            let mut adapter = TnlpCallbackAdapter {
                inner: Rc::clone(&self.inner),
            };
            let mut large_solver = block_solve::RelaxedNewtonSolver;
            let plan = auxiliary::run_auxiliary_phase0(
                &self.opts,
                &probe_view,
                Some(&mut adapter),
                Some(&mut large_solver),
            );
            if let Some(frame) = plan.frame {
                // Clamp fixed variables.
                for (k, &i) in frame.fixed_vars.iter().enumerate() {
                    x_l[i] = frame.fixed_values[k];
                    x_u[i] = frame.fixed_values[k];
                }
                // Drop dropped rows.
                for &r in &frame.dropped_rows {
                    row_kept_inner[r] = false;
                }
                reduction_stack.push(frame);
            }
            // When `presolve_auxiliary_diagnostics=yes`, emit the
            // summary through tracing (pounce#71).
            if self.opts.auxiliary_diagnostics {
                tracing::info!(target: "pounce::presolve", "{}", plan.diagnostics);
            }
            plan.diagnostics
        } else {
            AuxiliaryPreprocessingDiagnostics::default()
        };

        // Build `linear_rows` excluding rows Phase 0 dropped. This
        // is the headline fix from the #53 PR review: propagating
        // bounds through an aux-dropped row lets tighten_bounds
        // derive `x_l[j] > x_u[j]` for an aux-clamped variable and
        // then hand corrupted bounds to the IPM.
        let mut linear_rows: Vec<LinearRow> = linear_row_map
            .iter()
            .enumerate()
            .filter_map(|(i, r)| if row_kept_inner[i] { r.clone() } else { None })
            .collect();

        // Phase 1: bound tightening using linear rows.
        let mut tighten_report = TightenReport::default();
        // Set only where a contradiction is derived on an un-clamped box; see
        // the field doc on `PresolveState::certified_infeasible`.
        let mut certified_infeasible: Option<InfeasibilityProof> = None;
        if self.opts.bound_tightening && !linear_rows.is_empty() {
            tighten_report = tighten_bounds(
                &linear_rows,
                &mut x_l,
                &mut x_u,
                self.opts.max_passes,
                1e-12,
            );
        }

        // Defence in depth: if Phase 1 still flags infeasibility AND
        // Phase 0 made changes, those changes are presumed to blame
        // (aux solved a block to a point inconsistent with bounds
        // from kept rows). Roll back Phase 0 — restore bounds, undo
        // row drops, clear the reduction stack — and re-run Phase 1
        // on the un-filtered linear rows. Without this guard,
        // `report.infeasible` was previously never inspected and
        // corrupted bounds reached the IPM (#53 PR review).
        if tighten_report.infeasible && !reduction_stack.is_empty() {
            tracing::warn!(
                target: "pounce::presolve",
                "auxiliary-equality elimination produced bounds inconsistent \
                 with kept linear rows; rolling back the elimination for this solve."
            );
            x_l.copy_from_slice(&inner_x_l);
            x_u.copy_from_slice(&inner_x_u);
            for kept in row_kept_inner.iter_mut() {
                *kept = true;
            }
            reduction_stack = ReductionStack::default();
            // Re-run tighten on the unfiltered linear rows now that
            // the aux clamps are gone. Rebuild `linear_rows` to the
            // full set too, so Phase 2's redundancy mask stays aligned
            // with the now all-kept `row_kept_inner` (C1).
            let full_linear_rows: Vec<LinearRow> =
                linear_row_map.iter().filter_map(|r| r.clone()).collect();
            tighten_report = TightenReport::default();
            if self.opts.bound_tightening && !full_linear_rows.is_empty() {
                tighten_report = tighten_bounds(
                    &full_linear_rows,
                    &mut x_l,
                    &mut x_u,
                    self.opts.max_passes,
                    1e-12,
                );
            }
            linear_rows = full_linear_rows;
        }

        // M25: a *genuine* Phase-1 infeasibility (empty feasible box) must not
        // reach the IPM as crossed bounds `x_l > x_u`. `tighten_pass` returns
        // the moment it detects `x_l[j] > x_u[j]`, leaving those crossed
        // bounds in place; the rollback above only fires when Phase 0 made
        // changes (`!reduction_stack.is_empty()`), so an infeasibility found
        // with an empty reduction stack — or one that survives the rollback
        // re-tighten — would otherwise hand a degenerate box to the solver,
        // which reports an invalid-problem error instead of a clean
        // infeasibility verdict. Presolve has no channel to certify
        // infeasibility, so — mirroring the aux rollback above and the FBBT
        // handling below — restore the original inner box (always a valid box)
        // and let the IPM run on it and certify infeasibility itself. The
        // `tighten_report.infeasible` flag is preserved and surfaced via
        // `tighten_report()` for diagnostics.
        if tighten_report.infeasible {
            // Measure the crossing *before* the restore below overwrites it.
            let crossing = (0..n).map(|j| x_l[j] - x_u[j]).fold(0.0_f64, f64::max);
            // Reaching here implies the tightening ran on an un-clamped box:
            // the aux rollback above either did not fire (empty reduction
            // stack ⇒ Phase 0 changed nothing) or fired and recomputed
            // `tighten_report` on the restored box. Either way this is a
            // genuine contradiction in the user's model, not a presolve
            // artifact, so it is certifiable. The crossed bounds are still
            // discarded — a degenerate box must not reach the solver — but the
            // *verdict* now survives.
            // Phase 1 flags a crossing above its own `1e-12` test, which is
            // far below what the solver treats as feasible. Certify only a
            // crossing the solver's own acceptance would call a real violation
            // at that variable's scale (see `crossing_is_certifiable`), so a
            // model POUNCE would solve to `Solve_Succeeded` can never be
            // called proved infeasible.
            let robust = crossing_is_certifiable(&x_l, &x_u, certify_margin(self.opts.certify_tol));
            x_l.copy_from_slice(&inner_x_l);
            x_u.copy_from_slice(&inner_x_u);
            if robust {
                certified_infeasible = Some(InfeasibilityProof::BoundPropagation);
            }
            tracing::warn!(
                target: "pounce::presolve",
                crossing,
                certified = robust,
                "Phase 1 bound tightening found the feasible region empty; its \
                 crossed bounds are being discarded."
            );
        }

        // Phase 1 declares infeasibility only when the crossing exceeds its
        // `1e-12` margin, so a *sub-margin* crossing survives the block above:
        // `infeasible` is false, nothing is restored, and `x_l[j] > x_u[j]`
        // by a hair is handed to the solver, which rejects it as
        // `Invalid_Problem_Definition`. The model that surfaced this is
        // `x >= 0.1 + 0.2` with `x <= 0.3` — in binary floating point the two
        // differ by `5.5e-17`, so the box arrives crossed by that much and a
        // model POUNCE otherwise solves cleanly (`presolve=no` gives
        // `Solve_Succeeded`, the LP route gives "Optimal Solution Found")
        // failed with an invalid-problem error the moment presolve was on.
        //
        // Collapse those to a point. The crossing is below the margin at which
        // the tightening itself is willing to call the region empty, so the
        // honest reading is a single feasible value, not an empty set — and it
        // keeps every route's answer consistent.
        // The collapsed point must stay inside the *declared* box. The crossing
        // exists because tightening moved a bound past its partner, so the
        // midpoint of the crossed pair lies strictly outside the original range
        // — for `x >= 0.1 + 0.2`, `x <= 0.3` it lands on `0.30000000000000004`,
        // above the user's `x <= 0.3`. Returning that would silently violate a
        // declared bound, which is worse than the error it replaces and defeats
        // `honor_original_bounds`. Clamping to the original box keeps the
        // reported point admissible.
        //
        // Only *negligible* crossings collapse — `is_negligible` at the
        // crossed pair's own magnitude, the exact complement of
        // `crossing_is_certifiable`, so every crossing is either collapsed
        // here or certifiable there, never both. A crossing the solver itself
        // would call a real violation is not float noise; it is a
        // user-declared empty box (`x in [5, 3]`) on a variable no linear row
        // ever propagated into, which Phase 1 therefore never flagged.
        // Collapsing that would turn `Invalid_Problem_Definition` into
        // `Solve_Succeeded` at a point the model excludes — a wrong answer
        // replacing a correct error. Those stay crossed so the solver rejects
        // them exactly as it does with presolve off.
        let collapse_tol = certify_margin(self.opts.certify_tol);
        for j in 0..n {
            if x_l[j] > x_u[j]
                && is_negligible(
                    x_l[j] - x_u[j],
                    x_l[j].abs().max(x_u[j].abs()),
                    collapse_tol,
                )
            {
                let mid = (0.5 * (x_l[j] + x_u[j]))
                    .max(inner_x_l[j])
                    .min(inner_x_u[j]);
                x_l[j] = mid;
                x_u[j] = mid;
            }
        }

        // Phase 1b — FBBT (issue #62). Runs interval arithmetic over
        // each nonlinear constraint's expression DAG to tighten
        // variable bounds further. No-op when (a) `presolve_fbbt` is
        // off, (b) the inner TNLP did not supply an
        // `ExpressionProvider`, or (c) the problem has zero
        // constraints. Honors `fbbt_tol`, `fbbt_max_iter`, and
        // `fbbt_max_constraints`.
        let mut fbbt_report: Option<crate::fbbt::FbbtReport> = None;
        if self.opts.fbbt && m_in > 0 {
            if let Some(provider) = self.expr_provider.as_ref() {
                let cfg = crate::fbbt::FbbtConfig {
                    tol: self.opts.fbbt_tol,
                    max_iter: self.opts.fbbt_max_iter.max(1) as usize,
                    max_constraints: self.opts.fbbt_max_constraints.max(0) as usize,
                };
                // H12: snapshot the bounds before FBBT. The `FbbtReport`
                // contract states that on detected infeasibility the
                // variable bounds are "undefined and must not be trusted"
                // — FBBT may have partially tightened several variables
                // before a later constraint proved the box empty. Pass the
                // Phase-0 `row_kept_inner` mask so propagation skips any row
                // an auxiliary elimination dropped (over the aux-clamped box
                // a dropped row can fabricate a spurious infeasibility — the
                // same #53 hazard Phase 1 guards against with filtered rows).
                let fbbt_x_l_pre = x_l.clone();
                let fbbt_x_u_pre = x_u.clone();
                let provider_borrow = provider.borrow();
                let mut report = crate::fbbt::run_fbbt(
                    &*provider_borrow,
                    n,
                    m_in,
                    &mut x_l,
                    &mut x_u,
                    &g_l_inner,
                    &g_u_inner,
                    Some(&row_kept_inner),
                    &cfg,
                );
                drop(provider_borrow);
                if report.infeasibility_witness.is_some() && !reduction_stack.is_empty() {
                    // F6: an FBBT infeasibility found while a Phase-0
                    // auxiliary elimination is in force may be an *artifact*
                    // of that elimination — an aux clamp can make a kept
                    // *nonlinear* row infeasible over the clamped box even
                    // though the original problem is feasible. Restoring only
                    // the pre-FBBT box (the `else` branch below) leaves the
                    // aux clamps in place, so the IPM would then cleanly
                    // certify infeasibility of a problem presolve itself broke
                    // — a wrong "infeasible" verdict on a feasible original.
                    // Mirror the Phase-1 aux rollback (the `tighten_report`
                    // branch above): undo Phase 0 entirely — restore the inner
                    // box, re-keep every dropped row, clear the reduction
                    // stack, rebuild the full linear-row set — then re-run
                    // Phase 1 and FBBT on the un-clamped box. Only an
                    // infeasibility that *survives* on the un-clamped box is
                    // genuine; presolve still cannot certify it, so it then
                    // falls through to the same "discard FBBT bounds, let the
                    // IPM certify" handling.
                    tracing::warn!(
                        target: "pounce::presolve",
                        witness = report.infeasibility_witness,
                        "FBBT reported a constraint infeasibility while auxiliary \
                         elimination was active; rolling back the elimination and \
                         re-running FBBT on the un-clamped box to avoid certifying \
                         a presolve-induced infeasibility on a feasible original."
                    );
                    x_l.copy_from_slice(&inner_x_l);
                    x_u.copy_from_slice(&inner_x_u);
                    for kept in row_kept_inner.iter_mut() {
                        *kept = true;
                    }
                    reduction_stack = ReductionStack::default();
                    // Rebuild `linear_rows` to the full set so Phase 2's
                    // redundancy mask stays aligned with the now all-kept
                    // `row_kept_inner` (C1), mirroring the Phase-1 rollback.
                    let full_linear_rows: Vec<LinearRow> =
                        linear_row_map.iter().filter_map(|r| r.clone()).collect();
                    tighten_report = TightenReport::default();
                    if self.opts.bound_tightening && !full_linear_rows.is_empty() {
                        tighten_report = tighten_bounds(
                            &full_linear_rows,
                            &mut x_l,
                            &mut x_u,
                            self.opts.max_passes,
                            1e-12,
                        );
                    }
                    linear_rows = full_linear_rows;
                    // M25: a genuine Phase-1 infeasibility on the un-clamped
                    // box must not reach the IPM as crossed bounds.
                    if tighten_report.infeasible {
                        // Measure the crossing before the restore wipes it.
                        let crossing = (0..n).map(|j| x_l[j] - x_u[j]).fold(0.0_f64, f64::max);
                        // Derived on the rolled-back, un-clamped box, so the
                        // aux elimination cannot be to blame — certifiable when
                        // the crossing is real at the variable's own scale.
                        let robust = crossing_is_certifiable(
                            &x_l,
                            &x_u,
                            certify_margin(self.opts.certify_tol),
                        );
                        x_l.copy_from_slice(&inner_x_l);
                        x_u.copy_from_slice(&inner_x_u);
                        if robust {
                            certified_infeasible = Some(InfeasibilityProof::BoundPropagation);
                        }
                        tracing::warn!(
                            target: "pounce::presolve",
                            crossing,
                            certified = robust,
                            "Phase 1 bound tightening on the rolled-back (un-clamped) \
                             box found the feasible region empty; its crossed bounds \
                             are being discarded."
                        );
                    }
                    // Re-run FBBT on the un-clamped, all-kept box.
                    let rerun_x_l_pre = x_l.clone();
                    let rerun_x_u_pre = x_u.clone();
                    let provider_borrow = provider.borrow();
                    report = crate::fbbt::run_fbbt(
                        &*provider_borrow,
                        n,
                        m_in,
                        &mut x_l,
                        &mut x_u,
                        &g_l_inner,
                        &g_u_inner,
                        Some(&row_kept_inner),
                        &cfg,
                    );
                    drop(provider_borrow);
                    if let Some(witness) = report.infeasibility_witness {
                        // Survives without the aux clamp: a genuine
                        // infeasibility of the original problem, so it is
                        // certifiable *if* it is more than a hair's breadth —
                        // see `certify_margin`. FBBT's own bounds are
                        // still undefined per the `FbbtReport` contract and are
                        // discarded either way.
                        let provider_borrow = provider.borrow();
                        let robust = fbbt_infeasibility_survives_margin(
                            &*provider_borrow,
                            n,
                            m_in,
                            &inner_x_l,
                            &inner_x_u,
                            &g_l_inner,
                            &g_u_inner,
                            &row_kept_inner,
                            &cfg,
                            certify_margin(self.opts.certify_tol),
                        );
                        drop(provider_borrow);
                        if robust {
                            certified_infeasible =
                                Some(InfeasibilityProof::IntervalArithmetic { witness });
                        }
                        tracing::warn!(
                            target: "pounce::presolve",
                            witness,
                            certified = robust,
                            "FBBT still reports infeasibility on the un-clamped box; \
                             treating it as genuine."
                        );
                        x_l.copy_from_slice(&rerun_x_l_pre);
                        x_u.copy_from_slice(&rerun_x_u_pre);
                    }
                } else if let Some(witness) = report.infeasibility_witness {
                    // No aux elimination active (empty reduction stack): the
                    // witnessed infeasibility cannot be a Phase-0 artifact, so
                    // it is certifiable *if* it is more than a hair's breadth —
                    // see `certify_margin`. FBBT's tightened bounds are
                    // undefined per the `FbbtReport` contract and are discarded
                    // either way.
                    let provider_borrow = provider.borrow();
                    let robust = fbbt_infeasibility_survives_margin(
                        &*provider_borrow,
                        n,
                        m_in,
                        &inner_x_l,
                        &inner_x_u,
                        &g_l_inner,
                        &g_u_inner,
                        &row_kept_inner,
                        &cfg,
                        certify_margin(self.opts.certify_tol),
                    );
                    drop(provider_borrow);
                    if robust {
                        certified_infeasible =
                            Some(InfeasibilityProof::IntervalArithmetic { witness });
                    }
                    tracing::warn!(
                        target: "pounce::presolve",
                        witness,
                        certified = robust,
                        "FBBT reported a constraint's feasible range empty; its \
                         tightened bounds are undefined and are being discarded."
                    );
                    x_l.copy_from_slice(&fbbt_x_l_pre);
                    x_u.copy_from_slice(&fbbt_x_u_pre);
                }
                fbbt_report = Some(report);
            }
        }

        // Final admissibility gate for the infeasibility verdict, covering
        // BOTH certification paths in one place.
        //
        // Interval reasoning over-approximates; at extreme coefficient scale it
        // can report a feasible region empty. Before the verdict escapes, try
        // to refute it by evaluating the real constraints at concrete points in
        // the declared box. A witness means the region is demonstrably not
        // empty, whatever the intervals concluded.
        //
        // Placed here, once, rather than beside each detection: the two
        // previous safeguards were each added to one path and not its twin,
        // and a hole survived both times.
        //
        // Which accepting test decides "satisfies" is the call site's choice,
        // not an option — see `WitnessRule`. Every wrapper that is solved
        // through uses the solver's own acceptance; only a caller that has
        // established the solve cannot run may raise it to the declared,
        // scale-relative form.
        if certified_infeasible.is_some()
            && witness_refutes_infeasibility(
                &self.inner,
                n,
                m_in,
                &inner_x_l,
                &inner_x_u,
                &g_l_inner,
                &g_u_inner,
                self.opts.certify_tol,
                self.witness_rule,
            )
        {
            tracing::warn!(
                target: "pounce::presolve",
                "presolve flagged the feasible region empty, but a point in the \
                 declared box satisfies every constraint — withdrawing the \
                 verdict and letting the solver decide."
            );
            certified_infeasible = None;
        }

        // Phase 4: any variable whose lower (upper) bound moved
        // strictly inward is a candidate for a bound-multiplier warm
        // start. Zero entries leave that bound's multiplier on the
        // global default (`bound_mult_init_val` from upstream).
        let warm_tol: Number = 1e-12;
        let (z_l_warm, z_u_warm) = if self.opts.warm_z_bounds {
            let v0 = self.opts.bound_mult_init_val;
            let mut zl = vec![0.0; n];
            let mut zu = vec![0.0; n];
            for i in 0..n {
                if x_l[i] > inner_x_l[i] + warm_tol {
                    zl[i] = v0;
                }
                if x_u[i] < inner_x_u[i] - warm_tol {
                    zu[i] = v0;
                }
            }
            (zl, zu)
        } else {
            (vec![0.0; n], vec![0.0; n])
        };

        // Phase 2: detect redundant linear rows in the (possibly
        // tightened) box. Non-linear rows are never dropped. The
        // `row_kept_inner` mask was initialised above by Phase 0.
        let mut n_dropped_rows: Index = 0;
        if self.opts.redundant_constraint_removal {
            let redundant_mask = find_redundant_rows(&linear_rows, &x_l, &x_u, 1e-9);
            // `redundant_mask` aligns with the *kept* linear rows
            // (`linear_rows`); map it back onto inner rows, skipping
            // rows Phase 0 already dropped (C1).
            n_dropped_rows =
                apply_redundant_verdicts(&linear_row_map, &redundant_mask, &mut row_kept_inner);
        }

        // Phase 3: structural LICQ check on the kept equality rows.
        let licq_verdict = if self.opts.licq_check {
            let eq_tol: Number = 1e-12;
            let mut eq_rows: Vec<EqRow> = Vec::new();
            for (i, &kept) in row_kept_inner.iter().enumerate() {
                if !kept {
                    continue;
                }
                if (g_u_inner[i] - g_l_inner[i]).abs() > eq_tol {
                    continue;
                }
                use std::collections::BTreeSet;
                let mut cols: BTreeSet<Index> = BTreeSet::new();
                for &(j, v) in &by_row[i] {
                    if v != 0.0 {
                        cols.insert(j);
                    }
                }
                eq_rows.push(EqRow {
                    cols: cols.into_iter().collect(),
                });
            }
            Some(licq_check(&eq_rows, info_inner.n))
        } else {
            None
        };

        // Build outer row mapping.
        let mut rows_kept: Vec<usize> = Vec::with_capacity(m_in);
        let mut row_inner_to_outer = vec![usize::MAX; m_in];
        for (i, &kept) in row_kept_inner.iter().enumerate() {
            if kept {
                row_inner_to_outer[i] = rows_kept.len();
                rows_kept.push(i);
            }
        }
        let m_out = rows_kept.len();

        // Build outer Jacobian sparsity: keep entries whose row is
        // kept, renumber rows.
        let mut jac_kept_idx = Vec::new();
        let mut jac_irow_outer = Vec::new();
        let mut jac_jcol_outer = Vec::new();
        for k in 0..nnz_in {
            let i_inner = if one_based {
                (jac_irow_inner[k] - 1) as usize
            } else {
                jac_irow_inner[k] as usize
            };
            if i_inner >= m_in {
                continue;
            }
            if !row_kept_inner[i_inner] {
                continue;
            }
            let outer = row_inner_to_outer[i_inner];
            let outer_row_index = if one_based {
                (outer as Index) + 1
            } else {
                outer as Index
            };
            jac_irow_outer.push(outer_row_index);
            jac_jcol_outer.push(jac_jcol_inner[k]);
            jac_kept_idx.push(k);
        }
        let nnz_out = jac_kept_idx.len();

        // Reduced g_l, g_u in outer ordering.
        let g_l: Vec<Number> = rows_kept.iter().map(|&i| g_l_inner[i]).collect();
        let g_u: Vec<Number> = rows_kept.iter().map(|&i| g_u_inner[i]).collect();

        let info_outer = NlpInfo {
            n: info_inner.n,
            m: m_out as Index,
            nnz_jac_g: nnz_out as Index,
            // Linear rows contribute zero to the Hessian, so dropping
            // them does not change `nnz_h_lag`. We carry the inner
            // sparsity through unchanged.
            nnz_h_lag: info_inner.nnz_h_lag,
            index_style: info_inner.index_style,
        };

        self.state = Some(PresolveState {
            info_inner,
            info_outer,
            bounds: CachedBounds { x_l, x_u, g_l, g_u },
            rows_kept,
            jac_kept_idx,
            jac_irow_outer,
            jac_jcol_outer,
            tighten_report,
            certified_infeasible,
            fbbt_report,
            n_dropped_rows,
            licq_verdict,
            z_l_warm,
            z_u_warm,
            scratch_g: vec![0.0; m_in],
            scratch_jac: vec![0.0; nnz_in],
            scratch_lambda: vec![0.0; m_in],
            aux_diagnostics,
            reduction_stack,
        });
        self.state.as_ref()
    }
}

/// Map `find_redundant_rows`' verdict mask back onto `row_kept_inner`,
/// returning the number of rows newly dropped.
///
/// The mask is aligned to the **kept** linear rows in inner-row order
/// — i.e. it has exactly one entry per `(i)` where `linear_row_map[i]`
/// is `Some` **and** `row_kept_inner[i]` is still `true` (that is the
/// filter `linear_rows` was built with). The mapping iterator must
/// therefore advance only on rows that are both linear and still kept.
///
/// Regression guard for C1: the original loop advanced the mask on
/// every `Some` row regardless of `row_kept_inner`, so once Phase 0 had
/// dropped any linear row every later verdict landed on its
/// predecessor's row — silently deleting a binding constraint (and
/// keeping a redundant one).
fn apply_redundant_verdicts(
    linear_row_map: &[Option<LinearRow>],
    redundant_mask: &[bool],
    row_kept_inner: &mut [bool],
) -> Index {
    let mut mask = redundant_mask.iter();
    let mut n_dropped: Index = 0;
    for (i, lr) in linear_row_map.iter().enumerate() {
        if lr.is_some() && row_kept_inner[i] {
            if *mask.next().unwrap_or(&false) {
                row_kept_inner[i] = false;
                n_dropped += 1;
            }
        }
    }
    n_dropped
}

// Inside this impl every `.expect("inited")` is invariant-protected
// by the preceding `ensure_init` (which is the only way state ever
// becomes `Some`).
#[allow(clippy::expect_used)]
impl TNLP for PresolveTnlp {
    fn is_presolve_wrapper(&self) -> bool {
        true
    }

    fn presolve_infeasibility_proof(&self) -> Option<InfeasibilityProof> {
        self.certified_infeasible()
    }

    fn get_nlp_info(&mut self) -> Option<NlpInfo> {
        let s = self.ensure_init()?;
        Some(s.info_outer)
    }

    fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
        let Some(s) = self.ensure_init() else {
            return false;
        };
        b.x_l.copy_from_slice(&s.bounds.x_l);
        b.x_u.copy_from_slice(&s.bounds.x_u);
        b.g_l.copy_from_slice(&s.bounds.g_l);
        b.g_u.copy_from_slice(&s.bounds.g_u);
        true
    }

    fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
        // n is unchanged by presolve; lambda warm-start is masked to
        // kept rows only (caller already sized `sp.lambda` to m_out).
        let Some(_) = self.ensure_init() else {
            return false;
        };
        // For now, ask the inner TNLP for its starting point in full
        // and project lambda down. Most users don't warm-start
        // duals, so this hits the no-op path.
        let m_in = self.state.as_ref().expect("inited").info_inner.m as usize;
        let mut z_l_full = vec![0.0; sp.z_l.len()];
        let mut z_u_full = vec![0.0; sp.z_u.len()];
        let mut lambda_full = vec![0.0; m_in];
        let ok = self.inner.borrow_mut().get_starting_point(StartingPoint {
            init_x: sp.init_x,
            x: sp.x,
            init_z: sp.init_z,
            z_l: &mut z_l_full,
            z_u: &mut z_u_full,
            init_lambda: sp.init_lambda,
            lambda: &mut lambda_full,
        });
        if !ok {
            return false;
        }
        sp.z_l.copy_from_slice(&z_l_full);
        sp.z_u.copy_from_slice(&z_u_full);
        let s = self.state.as_ref().expect("inited");
        // Phase 4: overlay presolve hints onto any zero/unset
        // entries. User-supplied warm-start values always win.
        if sp.init_z && self.opts.warm_z_bounds {
            for (i, &hint) in s.z_l_warm.iter().enumerate() {
                if hint > 0.0 && sp.z_l[i] <= 0.0 {
                    sp.z_l[i] = hint;
                }
            }
            for (i, &hint) in s.z_u_warm.iter().enumerate() {
                if hint > 0.0 && sp.z_u[i] <= 0.0 {
                    sp.z_u[i] = hint;
                }
            }
        }
        for (outer, &i_inner) in s.rows_kept.iter().enumerate() {
            sp.lambda[outer] = lambda_full[i_inner];
        }
        true
    }

    fn eval_f(&mut self, x: &[Number], new_x: bool) -> Option<Number> {
        self.inner.borrow_mut().eval_f(x, new_x)
    }

    fn eval_grad_f(&mut self, x: &[Number], new_x: bool, grad_f: &mut [Number]) -> bool {
        self.inner.borrow_mut().eval_grad_f(x, new_x, grad_f)
    }

    fn eval_g(&mut self, x: &[Number], new_x: bool, g: &mut [Number]) -> bool {
        let Some(_) = self.ensure_init() else {
            return false;
        };
        let s = self.state.as_mut().expect("inited");
        if !self.inner.borrow_mut().eval_g(x, new_x, &mut s.scratch_g) {
            return false;
        }
        for (outer, &i_inner) in s.rows_kept.iter().enumerate() {
            g[outer] = s.scratch_g[i_inner];
        }
        true
    }

    fn eval_jac_g(&mut self, x: Option<&[Number]>, new_x: bool, mode: SparsityRequest<'_>) -> bool {
        let Some(_) = self.ensure_init() else {
            return false;
        };
        match mode {
            SparsityRequest::Structure { irow, jcol } => {
                let s = self.state.as_ref().expect("inited");
                irow.copy_from_slice(&s.jac_irow_outer);
                jcol.copy_from_slice(&s.jac_jcol_outer);
                true
            }
            SparsityRequest::Values { values } => {
                let s = self.state.as_mut().expect("inited");
                if !self.inner.borrow_mut().eval_jac_g(
                    x,
                    new_x,
                    SparsityRequest::Values {
                        values: &mut s.scratch_jac,
                    },
                ) {
                    return false;
                }
                for (outer_k, &inner_k) in s.jac_kept_idx.iter().enumerate() {
                    values[outer_k] = s.scratch_jac[inner_k];
                }
                true
            }
        }
    }

    fn eval_h(
        &mut self,
        x: Option<&[Number]>,
        new_x: bool,
        obj_factor: Number,
        lambda: Option<&[Number]>,
        new_lambda: bool,
        mode: SparsityRequest<'_>,
    ) -> bool {
        let Some(_) = self.ensure_init() else {
            return false;
        };
        // Hessian sparsity is untouched: linear rows (the only ones
        // we drop) contribute zero. Forward `lambda` after expanding
        // outer → inner with zeros at dropped rows.
        let lambda_full_opt = if let Some(lam) = lambda {
            let s = self.state.as_mut().expect("inited");
            for v in s.scratch_lambda.iter_mut() {
                *v = 0.0;
            }
            for (outer, &i_inner) in s.rows_kept.iter().enumerate() {
                s.scratch_lambda[i_inner] = lam[outer];
            }
            Some(&s.scratch_lambda[..])
        } else {
            None
        };
        // Re-borrow inner after dropping the state borrow.
        let lam_ref: Option<&[Number]> = lambda_full_opt;
        // SAFETY: `lam_ref` borrows from `self.state`'s scratch; the
        // call to `inner.borrow_mut()` does not touch `self.state`.
        self.inner
            .borrow_mut()
            .eval_h(x, new_x, obj_factor, lam_ref, new_lambda, mode)
    }

    fn finalize_solution(&mut self, sol: Solution<'_>, ip_data: &IpoptData, ip_cq: &IpoptCq) {
        let Some(_) = self.ensure_init() else {
            // Init failed earlier — best effort: just forward as-is.
            self.inner
                .borrow_mut()
                .finalize_solution(sol, ip_data, ip_cq);
            return;
        };
        // Reconstruct inner-sized g and lambda.
        let (g_full, mut lambda_full, n_inner, m_inner, nnz_inner, one_based) = {
            let s = self.state.as_mut().expect("inited");
            // Recompute g at sol.x — the solver gave us reduced g.
            let ok_g = self
                .inner
                .borrow_mut()
                .eval_g(sol.x, true, &mut s.scratch_g);
            if !ok_g {
                // L45: the final constraint re-eval failed, so `scratch_g` is
                // unreliable — it holds whatever the failing call left behind
                // (partial garbage, or a stale value from an earlier iterate).
                // Don't forward that. Rebuild g from the solver's own
                // (trustworthy) reduced `sol.g`, mapped back to the kept inner
                // rows exactly as the multiplier mapping below does; rows
                // dropped by presolve are left at 0 (no reliable value exists
                // for them once the re-eval has failed).
                for v in s.scratch_g.iter_mut() {
                    *v = 0.0;
                }
                for (outer, &i_inner) in s.rows_kept.iter().enumerate() {
                    if i_inner < s.scratch_g.len() && outer < sol.g.len() {
                        s.scratch_g[i_inner] = sol.g[outer];
                    }
                }
            }
            for v in s.scratch_lambda.iter_mut() {
                *v = 0.0;
            }
            for (outer, &i_inner) in s.rows_kept.iter().enumerate() {
                s.scratch_lambda[i_inner] = sol.lambda[outer];
            }
            (
                s.scratch_g.clone(),
                s.scratch_lambda.clone(),
                s.info_inner.n as usize,
                s.info_inner.m as usize,
                s.info_inner.nnz_jac_g as usize,
                matches!(s.info_inner.index_style, IndexStyle::Fortran),
            )
        };

        // Phase-0 (issue #53) multiplier recovery for dropped rows.
        // Walk the reduction stack top-down; for each frame, compute
        // the full-space ∇f and J at sol.x, then solve the k×k LU
        // system to recover λ for the frame's dropped rows. Splice
        // the result into `lambda_full` at the dropped indices.
        let frames: Vec<reduction_frame::ReductionFrame> = {
            let s = self.state.as_ref().expect("inited");
            s.reduction_stack.iter_top_down().cloned().collect()
        };
        // Bound multipliers forwarded to the inner finalize. At each frame's
        // Phase-0 aux-fixed variables these are zeroed once the variable's
        // dropped-row multipliers are recovered below:
        // `recover_dropped_multipliers` folds the entire stationarity residual
        // into λ under the documented assumption `z_l = z_u = 0` there, so
        // forwarding the IPM's clamp multipliers unchanged would double-count
        // that contribution and break `∇f − Jᵀλ − z_l + z_u = 0`.
        let mut z_l_full = sol.z_l.to_vec();
        let mut z_u_full = sol.z_u.to_vec();
        if !frames.is_empty() && m_inner > 0 {
            let mut grad_f = vec![0.0; n_inner];
            let ok_grad = self
                .inner
                .borrow_mut()
                .eval_grad_f(sol.x, true, &mut grad_f);
            // Sparsity + values for the full inner Jacobian.
            let mut jac_irow_inner = vec![0 as Index; nnz_inner];
            let mut jac_jcol_inner = vec![0 as Index; nnz_inner];
            let ok_struct = if nnz_inner > 0 {
                self.inner.borrow_mut().eval_jac_g(
                    None,
                    false,
                    SparsityRequest::Structure {
                        irow: &mut jac_irow_inner,
                        jcol: &mut jac_jcol_inner,
                    },
                )
            } else {
                true
            };
            let mut jac_values = vec![0.0; nnz_inner];
            let ok_vals = if nnz_inner > 0 {
                self.inner.borrow_mut().eval_jac_g(
                    Some(sol.x),
                    false,
                    SparsityRequest::Values {
                        values: &mut jac_values,
                    },
                )
            } else {
                true
            };
            if ok_grad && ok_struct && ok_vals {
                // `recover_dropped_multipliers` reads the Jacobian only at the
                // frames' fixed-var columns, so materialize just those columns
                // (the union across all frames) instead of the full
                // `m_inner × n_inner` dense block — O(m·k) rather than O(m·n),
                // where k = total distinct fixed vars is tiny next to n. The
                // old full densification cost ~80 GB at 100k×100k (issue M26).
                let mut orig_to_compact = vec![usize::MAX; n_inner];
                let mut n_cols = 0usize;
                for frame in &frames {
                    for &c in &frame.fixed_vars {
                        if c < n_inner && orig_to_compact[c] == usize::MAX {
                            orig_to_compact[c] = n_cols;
                            n_cols += 1;
                        }
                    }
                }
                let mut jac_cols = vec![0.0; m_inner * n_cols];
                for k in 0..nnz_inner {
                    let i = if one_based {
                        (jac_irow_inner[k] as isize - 1) as usize
                    } else {
                        jac_irow_inner[k] as usize
                    };
                    let j = if one_based {
                        (jac_jcol_inner[k] as isize - 1) as usize
                    } else {
                        jac_jcol_inner[k] as usize
                    };
                    if i < m_inner && j < n_inner {
                        let cc = orig_to_compact[j];
                        if cc != usize::MAX {
                            jac_cols[i * n_cols + cc] = jac_values[k];
                        }
                    }
                }
                for frame in &frames {
                    if let Ok(lam_dropped) = frame.recover_dropped_multipliers_cols(
                        &grad_f,
                        &jac_cols,
                        n_cols,
                        &orig_to_compact,
                        &lambda_full,
                    ) {
                        for (idx, &r) in frame.dropped_rows.iter().enumerate() {
                            lambda_full[r] = lam_dropped[idx];
                        }
                        // The recovered λ now carries this frame's fixed-var
                        // stationarity; drop the IPM's clamp multipliers there.
                        for &i in &frame.fixed_vars {
                            if i < z_l_full.len() {
                                z_l_full[i] = 0.0;
                            }
                            if i < z_u_full.len() {
                                z_u_full[i] = 0.0;
                            }
                        }
                    }
                }
            }
        }
        // Stash the full-space (x, lambda) the inner TNLP is about to
        // receive so the CLI can prefer it over its reduced-space
        // capture when sizing the `.sol` / JSON dual block.
        self.finalized_full_solution = Some((sol.x.to_vec(), lambda_full.clone()));
        self.inner.borrow_mut().finalize_solution(
            Solution {
                status: sol.status,
                x: sol.x,
                z_l: &z_l_full,
                z_u: &z_u_full,
                g: &g_full,
                lambda: &lambda_full,
                obj_value: sol.obj_value,
            },
            ip_data,
            ip_cq,
        );
    }

    fn get_var_con_metadata(&mut self, var: &mut MetaData, con: &mut MetaData) -> bool {
        let Some(_) = self.ensure_init() else {
            return false;
        };
        // Variable count is unchanged by presolve, so var metadata
        // flows through. Constraint metadata is per-inner-row; if we
        // dropped rows, subset the per-row vectors to kept rows.
        let mut inner_var = MetaData::default();
        let mut inner_con = MetaData::default();
        if !self
            .inner
            .borrow_mut()
            .get_var_con_metadata(&mut inner_var, &mut inner_con)
        {
            return false;
        }
        *var = inner_var;
        let s = self.state.as_ref().expect("inited");
        let m_in = s.info_inner.m as usize;
        *con = project_con_metadata(&inner_con, &s.rows_kept, m_in);
        true
    }

    fn get_scaling_parameters(&mut self, req: ScalingRequest<'_>) -> bool {
        let Some(_) = self.ensure_init() else {
            return false;
        };
        let s = self.state.as_ref().expect("inited");
        let m_in = s.info_inner.m as usize;
        // Allocate inner-sized g_scaling and forward.
        let mut inner_g = vec![1.0; m_in];
        let mut use_x = false;
        let mut use_g = false;
        let mut obj_scaling = 1.0;
        let inner_x_scaling_len = req.x_scaling.len();
        let mut inner_x = vec![1.0; inner_x_scaling_len];
        let ok = self
            .inner
            .borrow_mut()
            .get_scaling_parameters(ScalingRequest {
                obj_scaling: &mut obj_scaling,
                use_x_scaling: &mut use_x,
                x_scaling: &mut inner_x,
                use_g_scaling: &mut use_g,
                g_scaling: &mut inner_g,
            });
        if !ok {
            return false;
        }
        *req.obj_scaling = obj_scaling;
        *req.use_x_scaling = use_x;
        *req.use_g_scaling = use_g;
        req.x_scaling.copy_from_slice(&inner_x);
        for (outer, &i_inner) in s.rows_kept.iter().enumerate() {
            req.g_scaling[outer] = inner_g[i_inner];
        }
        true
    }

    fn get_variables_linearity(&mut self, types: &mut [Linearity]) -> bool {
        self.inner.borrow_mut().get_variables_linearity(types)
    }

    fn get_objective_variables_linearity(&mut self, types: &mut [Linearity]) -> bool {
        self.inner
            .borrow_mut()
            .get_objective_variables_linearity(types)
    }

    fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
        let Some(_) = self.ensure_init() else {
            return false;
        };
        let m_in = self.state.as_ref().expect("inited").info_inner.m as usize;
        let mut full = vec![Linearity::NonLinear; m_in];
        if !self.inner.borrow_mut().get_constraints_linearity(&mut full) {
            return false;
        }
        let s = self.state.as_ref().expect("inited");
        for (outer, &i_inner) in s.rows_kept.iter().enumerate() {
            types[outer] = full[i_inner];
        }
        true
    }

    fn get_number_of_nonlinear_variables(&mut self) -> Index {
        self.inner.borrow_mut().get_number_of_nonlinear_variables()
    }

    fn get_list_of_nonlinear_variables(&mut self, pos_nonlin_vars: &mut [Index]) -> bool {
        self.inner
            .borrow_mut()
            .get_list_of_nonlinear_variables(pos_nonlin_vars)
    }

    fn intermediate_callback(
        &mut self,
        stats: IterStats,
        ip_data: &IpoptData,
        ip_cq: &IpoptCq,
    ) -> bool {
        self.inner
            .borrow_mut()
            .intermediate_callback(stats, ip_data, ip_cq)
    }

    fn finalize_metadata(&mut self, var: &MetaData, con: &MetaData) {
        let Some(_) = self.ensure_init() else {
            self.inner.borrow_mut().finalize_metadata(var, con);
            return;
        };
        let s = self.state.as_ref().expect("inited");
        let m_in = s.info_inner.m as usize;
        let con_full = expand_con_metadata(con, &s.rows_kept, m_in);
        self.inner.borrow_mut().finalize_metadata(var, &con_full);
    }
}

/// Subset every per-row vector of `inner` to the rows in `rows_kept`.
///
/// Per-row-ness is inferred from `v.len() == m_in`, because `MetaData`
/// (mirroring upstream Ipopt's untyped `*MetaDataMapType`) carries no
/// per-key arity tag — so the length is the only signal available. By
/// the TNLP contract every vector in the *constraint* `MetaData` bucket
/// is per-constraint (length `m_in`), so this is exact for any
/// conforming inner TNLP (e.g. `nl_reader`'s per-row `con_names`).
///
/// L46 caveat: a vector that is semantically *global* yet happens to
/// have length `m_in` would be wrongly subset, and a genuinely per-row
/// vector whose length differs from `m_in` (a contract violation) is
/// passed through unchanged. Neither can be distinguished from the data
/// alone; fully resolving it needs an arity-aware metadata API. The
/// fast path `m_in == rows_kept.len()` (no rows dropped) is identity,
/// so the hazard only exists when presolve actually drops a row.
fn project_con_metadata(inner: &MetaData, rows_kept: &[usize], m_in: usize) -> MetaData {
    let mut out = MetaData::default();
    for (k, v) in &inner.strings {
        out.strings.insert(
            k.clone(),
            if v.len() == m_in {
                rows_kept.iter().map(|&i| v[i].clone()).collect()
            } else {
                v.clone()
            },
        );
    }
    for (k, v) in &inner.integers {
        out.integers.insert(
            k.clone(),
            if v.len() == m_in {
                rows_kept.iter().map(|&i| v[i]).collect()
            } else {
                v.clone()
            },
        );
    }
    for (k, v) in &inner.numerics {
        out.numerics.insert(
            k.clone(),
            if v.len() == m_in {
                rows_kept.iter().map(|&i| v[i]).collect()
            } else {
                v.clone()
            },
        );
    }
    out
}

/// Expand every per-(outer-row) vector back to `m_in` rows by
/// inserting empty / 0 / 0.0 defaults at dropped rows. The inverse of
/// [`project_con_metadata`]; per-row-ness is inferred from
/// `v.len() == m_out` and carries the same L46 caveat (see that
/// function): a coincidentally-`m_out`-length global vector is wrongly
/// expanded, inherent to the untyped `MetaData` API.
fn expand_con_metadata(outer: &MetaData, rows_kept: &[usize], m_in: usize) -> MetaData {
    let m_out = rows_kept.len();
    let mut full = MetaData::default();
    for (k, v) in &outer.strings {
        let mut buf: Vec<String> = vec![String::new(); m_in];
        if v.len() == m_out {
            for (outer_i, val) in v.iter().enumerate() {
                buf[rows_kept[outer_i]] = val.clone();
            }
            full.strings.insert(k.clone(), buf);
        } else {
            full.strings.insert(k.clone(), v.clone());
        }
    }
    for (k, v) in &outer.integers {
        let mut buf: Vec<Index> = vec![0; m_in];
        if v.len() == m_out {
            for (outer_i, &val) in v.iter().enumerate() {
                buf[rows_kept[outer_i]] = val;
            }
            full.integers.insert(k.clone(), buf);
        } else {
            full.integers.insert(k.clone(), v.clone());
        }
    }
    for (k, v) in &outer.numerics {
        let mut buf: Vec<Number> = vec![0.0; m_in];
        if v.len() == m_out {
            for (outer_i, &val) in v.iter().enumerate() {
                buf[rows_kept[outer_i]] = val;
            }
            full.numerics.insert(k.clone(), buf);
        } else {
            full.numerics.insert(k.clone(), v.clone());
        }
    }
    full
}

/// Re-export for callers that already imported
/// `pounce_presolve::register_options` directly.
pub fn register(reg: &RegisteredOptions) -> Result<(), SolverException> {
    register_options(reg)
}

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

    /// **gh #402.** A crossing between an absent bound and a real one past the
    /// *opposite* sentinel is not a crossing, and must never certify.
    ///
    /// The test was a bare `l > u`, so `x_l = -1e19` (absent) against
    /// `x_u = -5e20` (real) read as a `5e20` gap — far too large for
    /// `is_negligible` to dismiss — and certified a feasible model as *proved*
    /// infeasible, the strongest claim POUNCE makes.
    #[test]
    fn a_sentinel_against_a_real_bound_never_certifies_a_crossing() {
        let tol = 1e-8;
        assert!(
            !crossing_is_certifiable(&[-1e19], &[-5e20], tol),
            "`x <= -5e20` with no lower bound is feasible, not a crossed box"
        );
        assert!(
            !crossing_is_certifiable(&[5e20], &[1e19], tol),
            "`x >= 5e20` with no upper bound is feasible too"
        );
        // A genuine crossing between two present bounds still certifies.
        assert!(crossing_is_certifiable(&[5.0], &[3.0], tol));
        // And a sub-tolerance one still does not (the #380 rule).
        assert!(!crossing_is_certifiable(&[1.0 + 1e-13], &[1.0], tol));
    }

    /// **gh #402.** The acceptance slack must track the row's own scale, even
    /// when the row's real bound lies past the opposite sentinel.
    ///
    /// The old symmetric test contributed `0.0` for a bound of `-5e20`, so the
    /// margin collapsed to `tol * 1.0` — a widening of `1e-8` on a row written
    /// at `5e20`. Any infeasibility survives that, which is the fail-open
    /// direction this margin exists to prevent.
    #[test]
    fn the_row_margin_tracks_a_bound_past_the_opposite_sentinel() {
        let tol = 1e-8;
        // `g <= -5e20`, no lower bound. Magnitude is 5e20, not 1.
        let m = row_margin_for(-1e19, -5e20, tol);
        assert!(
            (m - tol * 5e20).abs() <= tol * 5e20 * 1e-12,
            "margin should be tol*5e20 = {}, got {m}",
            tol * 5e20
        );
        // Absent on both sides -> the floor of 1.
        assert_eq!(row_margin_for(-1e19, 1e19, tol), tol);
        // An ordinary two-sided row uses the larger magnitude.
        assert_eq!(row_margin_for(-2.0, 7.0, tol), tol * 7.0);
    }

    struct Probe;
    impl TNLP for Probe {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 1,
                m: 0,
                nnz_jac_g: 0,
                nnz_h_lag: 1,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, _b: BoundsInfo<'_>) -> bool {
            true
        }
        fn get_starting_point(&mut self, _sp: StartingPoint<'_>) -> bool {
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, _g: &mut [Number]) -> bool {
            true
        }
        fn eval_g(&mut self, _x: &[Number], _new_x: bool, _g: &mut [Number]) -> bool {
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            _mode: SparsityRequest<'_>,
        ) -> bool {
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    struct NoopProvider;
    impl ExpressionProvider for NoopProvider {}

    #[test]
    fn c1_redundancy_mask_realigned_after_phase0_drop() {
        // Regression for C1. `find_redundant_rows` returns a verdict
        // mask aligned to the *kept* linear rows (inner-row order).
        // When Phase 0 has dropped an earlier linear row, the mapping
        // back to inner rows must skip already-dropped rows; advancing
        // the mask iterator on them shifts every later verdict onto its
        // predecessor's row.
        let lr = |lo: Number| {
            Some(LinearRow {
                entries: vec![(0, 1.0)],
                lo,
                hi: lo,
            })
        };
        // Three linear rows; Phase 0 dropped inner row 0.
        let linear_row_map = vec![lr(0.0), lr(1.0), lr(2.0)];
        let row_kept = vec![false, true, true];
        // `find_redundant_rows` ran over the *kept* rows [row1, row2]
        // and flagged the SECOND kept row (inner row 2) redundant; the
        // first kept row (inner row 1) is binding.
        let mask = vec![false, true];

        // Correct mapping: only inner row 2 is dropped.
        let mut kept_new = row_kept.clone();
        let n = apply_redundant_verdicts(&linear_row_map, &mask, &mut kept_new);
        assert_eq!(
            kept_new,
            vec![false, true, false],
            "verdict must land on inner row 2, not its predecessor"
        );
        assert_eq!(n, 1);

        // Document the pre-fix misalignment this test guards against:
        // the old loop advanced the mask on every `Some` row regardless
        // of `row_kept_inner`, dropping inner row 1 (binding!) and
        // keeping inner row 2 (redundant) — a silent wrong answer.
        let mut buggy = row_kept.clone();
        let mut it = mask.iter();
        for (i, l) in linear_row_map.iter().enumerate() {
            if l.is_some() && *it.next().unwrap_or(&false) {
                buggy[i] = false;
            }
        }
        assert_eq!(buggy, vec![false, false, true]);
        assert_ne!(buggy, kept_new);
    }

    #[test]
    fn disabled_returns_inner_unchanged() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(Probe));
        let opts = PresolveOptions {
            enabled: false,
            ..PresolveOptions::defaults()
        };
        let wrapped = wrap_with_presolve(Rc::clone(&inner), opts).unwrap();
        assert!(Rc::ptr_eq(&inner, &wrapped));
    }

    #[test]
    fn enabled_wraps_and_forwards() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(Probe));
        let opts = PresolveOptions {
            enabled: true,
            ..PresolveOptions::defaults()
        };
        let wrapped = wrap_with_presolve(Rc::clone(&inner), opts).unwrap();
        assert!(!Rc::ptr_eq(&inner, &wrapped));
        let info = wrapped.borrow_mut().get_nlp_info().unwrap();
        assert_eq!(info.n, 1);
        assert_eq!(info.m, 0);
    }

    #[test]
    fn provider_wrapper_does_not_nest_an_existing_presolve_wrapper() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(Probe));
        let opts = PresolveOptions {
            enabled: true,
            ..PresolveOptions::defaults()
        };
        let manual = wrap_with_presolve(inner, opts.clone()).unwrap();
        let provider: Rc<RefCell<dyn ExpressionProvider>> = Rc::new(RefCell::new(NoopProvider));
        let wrapped = wrap_with_presolve_provider(manual.clone(), provider, opts).unwrap();

        assert!(Rc::ptr_eq(&manual, &wrapped));
    }

    #[test]
    fn register_options_roundtrip() {
        let reg = RegisteredOptions::default();
        register_options(&reg).unwrap();
        let opt = reg.get_option("presolve").expect("presolve registered");
        assert_eq!(opt.name, "presolve");
    }

    #[test]
    fn auxiliary_phase0_noop_when_disabled() {
        // Master switch off → Phase 0 returns zero diagnostics and
        // does not perturb the inner problem's dimensions.
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(Probe));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: false,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(info.n, 1);
        assert_eq!(info.m, 0);
        let diag = wrapped.auxiliary_diagnostics();
        assert_eq!(diag.blocks_eliminated, 0);
        assert_eq!(diag.vars_eliminated, 0);
        assert_eq!(diag.rows_eliminated, 0);
    }

    #[test]
    fn auxiliary_phase0_noop_when_enabled_no_algos_yet() {
        // For a 1-var, 0-row TNLP there are no candidate blocks; the
        // orchestrator skips its work regardless of master-switch state.
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(Probe));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_coupling: AuxiliaryCouplingPolicy::Aggressive,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(info.n, 1);
        assert_eq!(info.m, 0);
        let diag = wrapped.auxiliary_diagnostics();
        assert_eq!(diag.blocks_eliminated, 0);
        assert!(diag.rejection_reasons.is_empty());
    }

    /// 2-variable, 2-equality TNLP that PR 8's orchestrator should
    /// reduce: `x + y = 3, x - y = 1` → unique solution `(2, 1)`.
    /// Zero objective gradient → PureEquality, eligible under Safe.
    struct TwoVarSquareEq;
    impl TNLP for TwoVarSquareEq {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 2,
                m: 2,
                nnz_jac_g: 4,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            for v in b.x_l.iter_mut() {
                *v = -1e19;
            }
            for v in b.x_u.iter_mut() {
                *v = 1e19;
            }
            b.g_l[0] = 3.0;
            b.g_u[0] = 3.0;
            b.g_l[1] = 1.0;
            b.g_u[1] = 1.0;
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = 0.0;
                sp.x[1] = 0.0;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            for v in g.iter_mut() {
                *v = 0.0;
            }
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = x[0] + x[1];
            g[1] = x[0] - x[1];
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow.copy_from_slice(&[0, 0, 1, 1]);
                    jcol.copy_from_slice(&[0, 1, 0, 1]);
                }
                SparsityRequest::Values { values } => {
                    values.copy_from_slice(&[1.0, 1.0, 1.0, -1.0]);
                }
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::Linear;
            types[1] = Linearity::Linear;
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    #[test]
    fn phase0_via_tnlp_eliminates_square_block() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(TwoVarSquareEq));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_coupling: AuxiliaryCouplingPolicy::Safe,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        // Variable count unchanged (clamp, not reduce).
        assert_eq!(info.n, 2);
        // Both equality rows dropped.
        assert_eq!(info.m, 0);

        let diag = wrapped.auxiliary_diagnostics();
        assert_eq!(diag.blocks_eliminated, 1);
        assert_eq!(diag.vars_eliminated, 2);
        assert_eq!(diag.rows_eliminated, 2);

        let bounds = wrapped.cached_bounds().expect("inited");
        assert!((bounds.x_l[0] - 2.0).abs() < 1e-12);
        assert!((bounds.x_u[0] - 2.0).abs() < 1e-12);
        assert!((bounds.x_l[1] - 1.0).abs() < 1e-12);
        assert!((bounds.x_u[1] - 1.0).abs() < 1e-12);
    }

    /// [`TwoVarSquareEq`] with linearity tags layered on: the *global*
    /// tags report both variables `NonLinear` (as a TNLP whose equality
    /// rows are nonlinear would — the gas-network shape), while the
    /// objective-scoped tags, when offered, report both `Linear`
    /// (matching the zero objective gradient).
    struct SquareEqWithTags {
        inner: TwoVarSquareEq,
        offer_obj_tags: bool,
    }
    impl TNLP for SquareEqWithTags {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            self.inner.get_nlp_info()
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            self.inner.get_bounds_info(b)
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            self.inner.get_starting_point(sp)
        }
        fn eval_f(&mut self, x: &[Number], new_x: bool) -> Option<Number> {
            self.inner.eval_f(x, new_x)
        }
        fn eval_grad_f(&mut self, x: &[Number], new_x: bool, g: &mut [Number]) -> bool {
            self.inner.eval_grad_f(x, new_x, g)
        }
        fn eval_g(&mut self, x: &[Number], new_x: bool, g: &mut [Number]) -> bool {
            self.inner.eval_g(x, new_x, g)
        }
        fn eval_jac_g(
            &mut self,
            x: Option<&[Number]>,
            new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            self.inner.eval_jac_g(x, new_x, mode)
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            self.inner.get_constraints_linearity(types)
        }
        fn get_variables_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::NonLinear;
            types[1] = Linearity::NonLinear;
            true
        }
        fn get_objective_variables_linearity(&mut self, types: &mut [Linearity]) -> bool {
            if !self.offer_obj_tags {
                return false;
            }
            types[0] = Linearity::Linear;
            types[1] = Linearity::Linear;
            true
        }
        fn finalize_solution(&mut self, sol: Solution<'_>, d: &IpoptData, q: &IpoptCq) {
            self.inner.finalize_solution(sol, d, q)
        }
    }

    /// Regression for the gas-network CI failure: objective-scoped tags
    /// must take precedence over the global ones, so a variable that is
    /// nonlinear only in *constraints* does not poison `obj_support` and
    /// block a legitimate Phase-0 elimination. Pre-fix (global tags only)
    /// both variables were unioned into the objective support and the
    /// Safe policy kept both rows.
    #[test]
    fn phase0_objective_scoped_tags_dont_block_constraint_nonlinear_elimination() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(SquareEqWithTags {
            inner: TwoVarSquareEq,
            offer_obj_tags: true,
        }));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_coupling: AuxiliaryCouplingPolicy::Safe,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(
            info.m, 0,
            "objective-free block must still be eliminated when only the \
             global tags say NonLinear"
        );
        assert_eq!(wrapped.auxiliary_diagnostics().vars_eliminated, 2);
    }

    /// When the TNLP offers only the global tags, the fallback stays
    /// conservative: constraint nonlinearity is treated as possible
    /// objective coupling and the block is kept (sound, just suboptimal).
    #[test]
    fn phase0_global_tags_fallback_remains_conservative() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(SquareEqWithTags {
            inner: TwoVarSquareEq,
            offer_obj_tags: false,
        }));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_coupling: AuxiliaryCouplingPolicy::Safe,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(
            info.m, 2,
            "global-only tags fall back to the conservative union"
        );
        assert_eq!(wrapped.auxiliary_diagnostics().vars_eliminated, 0);
    }

    #[test]
    fn phase0_via_tnlp_disabled_is_pass_through() {
        // Same inner TNLP, but presolve_auxiliary=no. Orchestrator
        // is byte-identical to today; both rows remain.
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(TwoVarSquareEq));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: false,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(info.n, 2);
        assert_eq!(info.m, 2);
        let diag = wrapped.auxiliary_diagnostics();
        assert_eq!(diag.blocks_eliminated, 0);
    }

    /// Smoke test: turning on `presolve_auxiliary_diagnostics` still
    /// produces a correct elimination. We can't easily capture
    /// stderr from inside a #[test], but we can verify the option
    /// path doesn't break the orchestrator.
    #[test]
    fn phase0_via_tnlp_diagnostics_flag_does_not_break_solve() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(TwoVarSquareEq));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_diagnostics: true,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(info.m, 0);
        let diag = wrapped.auxiliary_diagnostics();
        assert_eq!(diag.blocks_eliminated, 1);
    }

    /// Regression for the #60 PR review blocker. The original
    /// `TwoVarSquareEq` TNLP, when wrapped with BOTH
    /// `presolve_auxiliary=yes` AND `presolve_bound_tightening=yes`
    /// (the new defaults), used to:
    ///   (1) let aux clamp x_l[0..2] = x_u[0..2] = solved values;
    ///   (2) let `tighten_bounds` re-propagate the (dropped)
    ///       equality rows over the clamped bounds, derive a
    ///       contradiction, and set `tighten_report.infeasible`;
    ///   (3) hand `x_l > x_u` to the IPM (because `infeasible` was
    ///       never inspected), crashing it with
    ///       `Invalid Problem Definition`.
    /// The fix: build `linear_rows` AFTER Phase 0, filtered by
    /// `row_kept_inner`, so dropped rows don't propagate. With this
    /// test we just confirm the wrapper init still succeeds and the
    /// final bounds remain self-consistent.
    #[test]
    fn phase0_via_tnlp_no_infeasible_with_default_bound_tightening() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(TwoVarSquareEq));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            // Both phases on — this is the combination that crashed
            // on `gaslib11_steady.nl` before the fix.
            bound_tightening: true,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(info.m, 0); // aux dropped both rows
        let bounds = wrapped.cached_bounds().expect("inited");
        // x_l ≤ x_u must hold for every variable.
        for i in 0..(info.n as usize) {
            assert!(
                bounds.x_l[i] <= bounds.x_u[i] + 1e-12,
                "x_l[{i}] = {} > x_u[{i}] = {}",
                bounds.x_l[i],
                bounds.x_u[i]
            );
        }
        // tighten_report must NOT have flagged infeasibility.
        let rpt = wrapped.tighten_report();
        assert!(!rpt.infeasible, "Phase 1 falsely flagged infeasibility");
    }

    /// Same model as [`TwoVarSquareEq`] but records the bound multipliers
    /// `z_l`/`z_u` that `finalize_solution` forwards to the inner TNLP, so a
    /// test can assert what the reported KKT point carries.
    struct RecordingTwoVar {
        rec: Rc<RefCell<Option<(Vec<Number>, Vec<Number>)>>>,
    }
    impl TNLP for RecordingTwoVar {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 2,
                m: 2,
                nnz_jac_g: 4,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            for v in b.x_l.iter_mut() {
                *v = -1e19;
            }
            for v in b.x_u.iter_mut() {
                *v = 1e19;
            }
            b.g_l[0] = 3.0;
            b.g_u[0] = 3.0;
            b.g_l[1] = 1.0;
            b.g_u[1] = 1.0;
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = 0.0;
                sp.x[1] = 0.0;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            for v in g.iter_mut() {
                *v = 0.0;
            }
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = x[0] + x[1];
            g[1] = x[0] - x[1];
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow.copy_from_slice(&[0, 0, 1, 1]);
                    jcol.copy_from_slice(&[0, 1, 0, 1]);
                }
                SparsityRequest::Values { values } => {
                    values.copy_from_slice(&[1.0, 1.0, 1.0, -1.0]);
                }
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::Linear;
            types[1] = Linearity::Linear;
            true
        }
        fn finalize_solution(&mut self, sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {
            *self.rec.borrow_mut() = Some((sol.z_l.to_vec(), sol.z_u.to_vec()));
        }
    }

    /// Regression for H10. Phase 0 clamps `x_l = x_u = v` at the two
    /// eliminated variables, so the IPM reports large bound multipliers
    /// there. `recover_dropped_multipliers` attributes the *whole*
    /// stationarity residual to the recovered row multipliers λ under the
    /// documented assumption `z_l = z_u = 0` at those variables; if
    /// `finalize_solution` forwards the clamp multipliers unchanged the
    /// contribution is double-counted and the reported point violates
    /// `∇f − Jᵀλ − z_l + z_u = 0`. The fix zeros `z_l`/`z_u` at every
    /// frame's `fixed_vars` once their λ has been recovered.
    #[test]
    fn phase0_finalize_zeroes_bound_multipliers_at_fixed_vars() {
        let rec = Rc::new(RefCell::new(None));
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(RecordingTwoVar {
            rec: Rc::clone(&rec),
        }));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_coupling: AuxiliaryCouplingPolicy::Safe,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(info.n, 2, "variable count unchanged (clamp, not reduce)");
        assert_eq!(info.m, 0, "both equality rows dropped by Phase 0");

        // The reduced solve returns the clamped point (2, 1); the IPM places
        // large bound multipliers on the now-fixed variables, and the reduced
        // problem has no rows (so empty g / lambda).
        let x = [2.0, 1.0];
        let z_l = [7.0, 0.0];
        let z_u = [0.0, 3.0];
        let g: [Number; 0] = [];
        let lambda: [Number; 0] = [];
        let sol = Solution {
            status: pounce_nlp::alg_types::SolverReturn::Success,
            x: &x,
            z_l: &z_l,
            z_u: &z_u,
            g: &g,
            lambda: &lambda,
            obj_value: 0.0,
        };
        wrapped.finalize_solution(sol, &IpoptData::default(), &IpoptCq::default());

        let (got_zl, got_zu) = rec.borrow().clone().expect("inner finalize ran");
        // fixed_vars = {0, 1}: both must be zeroed. Pre-fix the inner sees the
        // forwarded clamp multipliers [7,0] / [0,3] verbatim.
        assert_eq!(
            got_zl,
            vec![0.0, 0.0],
            "z_l must be zeroed at aux-fixed vars (H10)"
        );
        assert_eq!(
            got_zu,
            vec![0.0, 0.0],
            "z_u must be zeroed at aux-fixed vars (H10)"
        );
    }

    /// Same model as [`RecordingTwoVar`] but (a) records the `g` vector that
    /// `finalize_solution` forwards to the inner TNLP and (b) can be told to
    /// *fail* `eval_g` (returning `false` after scribbling a sentinel), so a
    /// test can check what happens when the final constraint re-eval fails.
    struct GFailRecordingVar {
        rec_g: Rc<RefCell<Option<Vec<Number>>>>,
        fail_g: Rc<RefCell<bool>>,
    }
    impl TNLP for GFailRecordingVar {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 2,
                m: 2,
                nnz_jac_g: 4,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            for v in b.x_l.iter_mut() {
                *v = -1e19;
            }
            for v in b.x_u.iter_mut() {
                *v = 1e19;
            }
            b.g_l[0] = 3.0;
            b.g_u[0] = 3.0;
            b.g_l[1] = 1.0;
            b.g_u[1] = 1.0;
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = 0.0;
                sp.x[1] = 0.0;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            for v in g.iter_mut() {
                *v = 0.0;
            }
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            if *self.fail_g.borrow() {
                // Simulate a failing evaluator that leaves garbage behind.
                for v in g.iter_mut() {
                    *v = 999.0;
                }
                return false;
            }
            g[0] = x[0] + x[1];
            g[1] = x[0] - x[1];
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow.copy_from_slice(&[0, 0, 1, 1]);
                    jcol.copy_from_slice(&[0, 1, 0, 1]);
                }
                SparsityRequest::Values { values } => {
                    values.copy_from_slice(&[1.0, 1.0, 1.0, -1.0]);
                }
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::Linear;
            types[1] = Linearity::Linear;
            true
        }
        fn finalize_solution(&mut self, sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {
            *self.rec_g.borrow_mut() = Some(sol.g.to_vec());
        }
    }

    /// L45: when the final constraint re-eval in `finalize_solution` fails,
    /// the forwarded `g` must NOT be the garbage/stale buffer the failing
    /// `eval_g` left behind. Both rows here are Phase-0 dropped (reduced
    /// `m = 0`, empty `sol.g`), so the trustworthy fallback yields all-zeros
    /// — never the `999.0` sentinel.
    #[test]
    fn finalize_does_not_forward_stale_g_when_eval_g_fails() {
        let rec_g = Rc::new(RefCell::new(None));
        let fail_g = Rc::new(RefCell::new(false));
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(GFailRecordingVar {
            rec_g: Rc::clone(&rec_g),
            fail_g: Rc::clone(&fail_g),
        }));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_coupling: AuxiliaryCouplingPolicy::Safe,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(info.m, 0, "both equality rows dropped by Phase 0");

        // Now make the final re-eval fail.
        *fail_g.borrow_mut() = true;
        let x = [2.0, 1.0];
        let z_l = [0.0, 0.0];
        let z_u = [0.0, 0.0];
        let g: [Number; 0] = [];
        let lambda: [Number; 0] = [];
        let sol = Solution {
            status: pounce_nlp::alg_types::SolverReturn::Success,
            x: &x,
            z_l: &z_l,
            z_u: &z_u,
            g: &g,
            lambda: &lambda,
            obj_value: 0.0,
        };
        wrapped.finalize_solution(sol, &IpoptData::default(), &IpoptCq::default());

        let got_g = rec_g.borrow().clone().expect("inner finalize ran");
        // Fail-first: pre-fix the ignored `eval_g` return forwards the
        // sentinel-filled `scratch_g` (`[999, 999]`) verbatim.
        assert_eq!(
            got_g,
            vec![0.0, 0.0],
            "failed eval_g must not forward stale/garbage constraint values",
        );
    }

    /// gh #396's shape, reduced to its essentials: one `<=`-only row whose
    /// genuine upper bound is *more negative* than the `-INF_BOUND` sentinel
    /// that stands in for its absent lower bound, and a starting point sitting
    /// exactly on that upper bound.
    ///
    /// `-1e30 · x <= -5e20` over `x ∈ [0, 1e-9]`, with `x0 = 5e-10`, so
    /// `g(x0) == g_u` exactly. True violation: zero.
    struct SentinelLowerBoundRow;
    impl TNLP for SentinelLowerBoundRow {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 1,
                m: 1,
                nnz_jac_g: 1,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            b.x_l[0] = 0.0;
            b.x_u[0] = 1e-9;
            b.g_l[0] = -1e19; // absent — the sentinel
            b.g_u[0] = -5e20; // real, and beyond the sentinel's magnitude
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = 5e-10;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = 0.0;
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = -1e30 * x[0];
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow[0] = 0;
                    jcol[0] = 0;
                }
                SparsityRequest::Values { values } => {
                    values[0] = -1e30;
                }
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::Linear;
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    /// **gh #396.** The absent-bound sentinel must not manufacture a violation,
    /// and a genuine bound beyond the sentinel's magnitude must not be
    /// discarded.
    ///
    /// Both errors landed on this one row pre-fix. `viol` had no presence test,
    /// so it scored `g_l - v = 4.9e20` against a lower bound the row does not
    /// have; and the magnitude test `|b| < INF_BOUND` called the row's *real*
    /// upper bound `-5e20` absent. Either alone sinks the witness, and with no
    /// candidate able to pass, presolve certified a feasible model infeasible
    /// with `solve_result_num` 201 — a claimed proof.
    #[test]
    fn absent_bound_sentinel_does_not_manufacture_a_violation() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(SentinelLowerBoundRow));
        assert!(
            witness_refutes_infeasibility(
                &inner,
                1,
                1,
                &[0.0],
                &[1e-9],
                &[-1e19],
                &[-5e20],
                1e-8,
                WitnessRule::SolverAcceptance,
            ),
            "x0 = 5e-10 puts the row exactly on its only real bound — that is a \
             witness, and the -1e19 sentinel standing in for the absent lower \
             bound must not turn it into a 4.9e20 violation"
        );
    }

    /// The other direction, and the reason the fix is a *directional* presence
    /// test rather than dropping the terms: a point that genuinely violates a
    /// real bound must still fail, so correct verdicts survive.
    ///
    /// Tightening the ceiling to `-5.1e20` over `x ∈ [4e-10, 5e-10]` puts every
    /// candidate — including `x0` — strictly above it, so there is genuinely no
    /// witness and the verdict must stand.
    ///
    /// This one does *not* reproduce #396: pre-fix it also returned `false`,
    /// via the phantom lower-bound violation rather than the real upper-bound
    /// one. It is here to pin the direction the fix could plausibly have broken
    /// — making `up_present` admit the bound must not make real violations
    /// invisible.
    #[test]
    fn a_real_bound_beyond_the_sentinel_still_blocks_the_witness() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(SentinelLowerBoundRow));
        assert!(
            !witness_refutes_infeasibility(
                &inner,
                1,
                1,
                &[4e-10],
                &[5e-10],
                &[-1e19],
                &[-5.1e20],
                1e-8,
                WitnessRule::SolverAcceptance,
            ),
            "no point in [4e-10, 5e-10] satisfies -1e30*x <= -5.1e20, so there \
             is no witness — a real bound of magnitude 5.1e20 must not be \
             discarded as the infinity sentinel"
        );
    }

    /// Single-variable `min x` with one linear row `x ≥ 2` (M24). Phase 1
    /// tightens `x_l = 2` from the row; Phase 2 then sees the row's activity
    /// `[2, 10] ⊆ [2, +∞)` and drops it as redundant.
    struct MinXWithLowerRow;
    impl TNLP for MinXWithLowerRow {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 1,
                m: 1,
                nnz_jac_g: 1,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            b.x_l[0] = 0.0;
            b.x_u[0] = 10.0;
            b.g_l[0] = 2.0; // x ≥ 2
            b.g_u[0] = 1e19;
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = 5.0;
            }
            true
        }
        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
            Some(x[0])
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = 1.0;
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = x[0];
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow[0] = 0;
                    jcol[0] = 0;
                }
                SparsityRequest::Values { values } => {
                    values[0] = 1.0;
                }
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::Linear;
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    /// Characterizes the M24 dual-attribution behavior (see the module-level
    /// "Dual-attribution caveat"). A redundant row that *implied* a now-active
    /// bound is dropped; the dual lands on the variable-bound multiplier
    /// (`z_l`) rather than the row's `λ`, which stays 0. The primal point and
    /// KKT stationarity are intact — only the attribution differs from a
    /// no-presolve solve. Pins the current behavior so a future provenance-
    /// based dual-transfer fix has an explicit target (the `λ == 0` assertion
    /// is what such a fix would flip to `λ == z_l`).
    #[test]
    fn dropped_row_dual_lands_on_bound_not_row() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(MinXWithLowerRow));
        let opts = PresolveOptions {
            enabled: true,
            bound_tightening: true,
            redundant_constraint_removal: true,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let info = wrapped.get_nlp_info().expect("init ok");

        // Phase 1 tightened the bound from the row; Phase 2 dropped the row.
        assert_eq!(
            wrapped.n_dropped_rows(),
            1,
            "the `x ≥ 2` row must be dropped"
        );
        assert_eq!(info.m, 0, "reduced problem has no rows");
        let b = wrapped.cached_bounds().expect("inited");
        assert!(
            (b.x_l[0] - 2.0).abs() < 1e-12,
            "x_l tightened to 2 by the row, got {}",
            b.x_l[0]
        );

        // Reduced solve at the optimum x=2: the bound `x ≥ 2` (which presolve
        // created — the original lower bound was 0) is active, so the IPM puts
        // the dual on z_l. ∇f = 1, so stationarity ∇f − z_l = 0 ⇒ z_l = 1.
        let x = [2.0];
        let z_l = [1.0];
        let z_u = [0.0];
        let g: [Number; 0] = [];
        let lambda: [Number; 0] = [];
        let sol = Solution {
            status: pounce_nlp::alg_types::SolverReturn::Success,
            x: &x,
            z_l: &z_l,
            z_u: &z_u,
            g: &g,
            lambda: &lambda,
            obj_value: 2.0,
        };
        wrapped.finalize_solution(sol, &IpoptData::default(), &IpoptCq::default());
        let (xf, lamf) = wrapped.finalized_full_solution().expect("finalized");

        // Primal is correct.
        assert!((xf[0] - 2.0).abs() < 1e-12, "primal x = 2");
        // M24: the reinstated row keeps λ = 0 — the dual is *not* transferred
        // back from the bound multiplier. (A dual-transfer fix would make this
        // `≈ z_l = 1`.)
        assert_eq!(lamf.len(), 1, "full-space lambda regains the original row");
        assert!(
            lamf[0].abs() < 1e-12,
            "M24: dropped-row λ stays 0 (dual sits on z_l instead), got {}",
            lamf[0]
        );
        // KKT stationarity ∇f − Jᵀλ − z_l + z_u = 0 still holds with the dual
        // on z_l (1 − 1·0 − 1 + 0 = 0): the certificate is valid, only the
        // attribution differs.
        let grad_f = 1.0;
        let jac = 1.0; // ∂g0/∂x
        let stat = grad_f - jac * lamf[0] - z_l[0] + z_u[0];
        assert!(stat.abs() < 1e-12, "KKT stationarity residual {stat}");
    }

    /// M25 scratch: one variable, box `x ∈ [0, 10]`, two contradictory linear
    /// rows `x ≥ 5` and `x ≤ 3`. Phase 1 tightens `x_l = 5`, `x_u = 3` and
    /// flags infeasible. Auxiliary is off, so the reduction stack is empty and
    /// the rollback guard does NOT fire.
    struct TwoContradictoryRows;
    impl TNLP for TwoContradictoryRows {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 1,
                m: 2,
                nnz_jac_g: 2,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            b.x_l[0] = 0.0;
            b.x_u[0] = 10.0;
            b.g_l[0] = 5.0; // x ≥ 5
            b.g_u[0] = 1e19;
            b.g_l[1] = -1e19; // x ≤ 3
            b.g_u[1] = 3.0;
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = 4.0;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = 0.0;
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = x[0];
            g[1] = x[0];
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow.copy_from_slice(&[0, 1]);
                    jcol.copy_from_slice(&[0, 0]);
                }
                SparsityRequest::Values { values } => {
                    values.copy_from_slice(&[1.0, 1.0]);
                }
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::Linear;
            types[1] = Linearity::Linear;
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    /// Regression for M25. A genuine Phase-1 infeasibility found with an empty
    /// reduction stack (auxiliary off, so the aux rollback guard never fires)
    /// must NOT hand crossed bounds `x_l > x_u` to the IPM — that triggers an
    /// invalid-problem failure instead of a clean infeasibility verdict.
    /// Presolve restores the original box and lets the IPM certify
    /// infeasibility itself; the `infeasible` flag is still surfaced for
    /// diagnostics.
    #[test]
    fn phase1_infeasible_restores_valid_box_for_ipm() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(TwoContradictoryRows));
        let opts = PresolveOptions {
            enabled: true,
            bound_tightening: true,
            auxiliary: false,
            ..PresolveOptions::defaults()
        };
        let mut wrapped = PresolveTnlp::new(Rc::clone(&inner), opts);
        let _info = wrapped.get_nlp_info().expect("init ok");

        // The infeasibility is still detected and surfaced for diagnostics.
        assert!(
            wrapped.tighten_report().infeasible,
            "Phase 1 must still flag the empty feasible region"
        );

        // ...and, with no Phase-0 elimination in force, it is a genuine
        // contradiction in the model rather than a presolve artifact, so it is
        // certified. This is what lets the solver report "proved infeasible"
        // instead of re-deriving a weaker numerical verdict.
        assert_eq!(
            wrapped.certified_infeasible(),
            Some(InfeasibilityProof::BoundPropagation),
            "a Phase-1 contradiction on an un-clamped box must be certified"
        );

        // But the box handed to the IPM is the original, valid box — not the
        // crossed `[5, 3]` Phase 1 derived.
        let b = wrapped.cached_bounds().expect("inited");
        assert!(
            b.x_l[0] <= b.x_u[0] + 1e-12,
            "M25: bounds handed to IPM must be valid, got x_l={} > x_u={}",
            b.x_l[0],
            b.x_u[0]
        );
        assert!(
            (b.x_l[0] - 0.0).abs() < 1e-12 && (b.x_u[0] - 10.0).abs() < 1e-12,
            "box restored to the original [0, 10], got [{}, {}]",
            b.x_l[0],
            b.x_u[0]
        );
    }

    /// 1-variable, 2-constraint TNLP that drives FBBT into a partial
    /// tightening followed by a genuine infeasibility. Both constraints are
    /// `g = x` (default `NonLinear` linearity, so they are FBBT-handled, not
    /// turned into linear rows Phase 1 would catch first). Row 0 demands
    /// `x ∈ [0.3, 0.7]` (tightens the box `x ∈ [0, 1]`); row 1 demands
    /// `x = 5` (infeasible). FBBT applies row 0, then row 1 flags the box
    /// empty — leaving the bounds in the partially-tightened `[0.3, 0.7]`
    /// state the `FbbtReport` contract says must not be trusted.
    struct FbbtPartialThenInfeasible;
    impl TNLP for FbbtPartialThenInfeasible {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 1,
                m: 2,
                nnz_jac_g: 2,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            b.x_l[0] = 0.0;
            b.x_u[0] = 1.0;
            b.g_l[0] = 0.3;
            b.g_u[0] = 0.7;
            b.g_l[1] = 5.0;
            b.g_u[1] = 5.0;
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = 0.5;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = 0.0;
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = x[0];
            g[1] = x[0];
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow.copy_from_slice(&[0, 1]);
                    jcol.copy_from_slice(&[0, 0]);
                }
                SparsityRequest::Values { values } => {
                    values.copy_from_slice(&[1.0, 1.0]);
                }
            }
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    /// Returns the tape `x` (i.e. `Var(0)`) for both constraints.
    struct VarTapeProvider;
    impl ExpressionProvider for VarTapeProvider {
        fn constraint_expression(
            &self,
            i: usize,
        ) -> Option<pounce_nlp::expression_provider::FbbtTape> {
            use pounce_nlp::expression_provider::{FbbtOp, FbbtTape};
            if i < 2 {
                Some(FbbtTape {
                    ops: vec![FbbtOp::Var(0)],
                })
            } else {
                None
            }
        }
    }

    /// H12: when FBBT detects a genuine infeasibility, the partially
    /// tightened (and per its own contract "undefined") bounds must NOT
    /// reach the reduced problem. Presolve has no infeasibility channel, so
    /// it discards FBBT's bounds and lets the IPM run on the pre-FBBT box —
    /// here the original `[0, 1]`, never the corrupted `[0.3, 0.7]`.
    #[test]
    fn fbbt_infeasibility_discards_corrupted_bounds() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(FbbtPartialThenInfeasible));
        let provider: Rc<RefCell<dyn ExpressionProvider>> = Rc::new(RefCell::new(VarTapeProvider));
        let opts = PresolveOptions {
            enabled: true,
            fbbt: true,
            ..PresolveOptions::defaults()
        };
        let mut wrapped =
            PresolveTnlp::with_expression_provider(Rc::clone(&inner), Rc::clone(&provider), opts);
        let info = wrapped.get_nlp_info().expect("init ok");
        assert_eq!(info.n, 1);
        assert_eq!(info.m, 2, "nonlinear rows are not dropped by presolve");

        // FBBT must have reached the infeasible row.
        let rpt = wrapped.fbbt_report().expect("fbbt ran");
        // No Phase-0 elimination is in force here, so the witness cannot be an
        // artifact — it is certified, and carries the witnessing row.
        assert_eq!(
            wrapped.certified_infeasible(),
            Some(InfeasibilityProof::IntervalArithmetic { witness: 1 }),
            "an FBBT witness on an un-clamped box must be certified"
        );
        assert_eq!(
            rpt.infeasibility_witness,
            Some(1),
            "row 1 (`x = 5`) is the infeasibility witness"
        );

        // ...but its corrupted tightening is discarded: the reduced box is
        // the original [0, 1], not the partial [0.3, 0.7] FBBT left behind.
        let mut x_l = vec![0.0; info.n as usize];
        let mut x_u = vec![0.0; info.n as usize];
        let mut g_l = vec![0.0; info.m as usize];
        let mut g_u = vec![0.0; info.m as usize];
        assert!(wrapped.get_bounds_info(BoundsInfo {
            x_l: &mut x_l,
            x_u: &mut x_u,
            g_l: &mut g_l,
            g_u: &mut g_u,
        }));
        assert_eq!(
            (x_l[0], x_u[0]),
            (0.0, 1.0),
            "FBBT's undefined-on-infeasibility bounds must not reach the IPM (H12)"
        );
    }

    /// 3-variable, 3-row TNLP that pits a Phase-0 auxiliary clamp against a
    /// kept nonlinear row. Rows 0/1 are a square LINEAR equality block
    /// (`x0 + x1 = 3`, `x0 - x1 = 1` → `(x0, x1) = (2, 1)`) that Phase 0
    /// eliminates, clamping `x0 = 2`. Row 2 is tagged `NonLinear` (so it is
    /// FBBT-handled, never turned into a linear row Phase 1 would catch) and
    /// reads `x0 + x2 = 20` with `x2 ∈ [0, 1]`. Over the *aux-clamped* box
    /// `x0 ∈ [2, 2]` FBBT sees `x0 + x2 ∈ [2, 3]`, disjoint from the required
    /// `20`, and witnesses infeasibility on row 2 — an infeasibility that
    /// exists ONLY because the aux clamp pinned `x0`. On the un-clamped box
    /// `x0` is free and FBBT tightens it to `[19, 20]` with no witness.
    struct AuxClampBreaksKeptNonlinearRow;
    impl TNLP for AuxClampBreaksKeptNonlinearRow {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 3,
                m: 3,
                nnz_jac_g: 6,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            b.x_l[0] = -1e19;
            b.x_u[0] = 1e19;
            b.x_l[1] = -1e19;
            b.x_u[1] = 1e19;
            b.x_l[2] = 0.0;
            b.x_u[2] = 1.0;
            b.g_l[0] = 3.0;
            b.g_u[0] = 3.0;
            b.g_l[1] = 1.0;
            b.g_u[1] = 1.0;
            b.g_l[2] = 20.0;
            b.g_u[2] = 20.0;
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = 0.0;
                sp.x[1] = 0.0;
                sp.x[2] = 0.0;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            for v in g.iter_mut() {
                *v = 0.0;
            }
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = x[0] + x[1];
            g[1] = x[0] - x[1];
            g[2] = x[0] + x[2];
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow.copy_from_slice(&[0, 0, 1, 1, 2, 2]);
                    jcol.copy_from_slice(&[0, 1, 0, 1, 0, 2]);
                }
                SparsityRequest::Values { values } => {
                    values.copy_from_slice(&[1.0, 1.0, 1.0, -1.0, 1.0, 1.0]);
                }
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::Linear;
            types[1] = Linearity::Linear;
            // Tagged NonLinear so it is FBBT-handled, not a Phase-1 linear row.
            types[2] = Linearity::NonLinear;
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    /// Supplies the FBBT tape `x0 + x2` for row 2 only (rows 0/1 are linear
    /// and need no tape).
    struct AuxBreakProvider;
    impl ExpressionProvider for AuxBreakProvider {
        fn constraint_expression(
            &self,
            i: usize,
        ) -> Option<pounce_nlp::expression_provider::FbbtTape> {
            use pounce_nlp::expression_provider::{FbbtOp, FbbtTape};
            if i == 2 {
                Some(FbbtTape {
                    ops: vec![FbbtOp::Var(0), FbbtOp::Var(2), FbbtOp::Add(0, 1)],
                })
            } else {
                None
            }
        }
    }

    /// Regression for F6 (follow-up to H12). An FBBT infeasibility witnessed
    /// while a Phase-0 auxiliary elimination is in force must roll back that
    /// elimination and re-run FBBT on the un-clamped box — mirroring the
    /// Phase-1 aux rollback (#53). Restoring only the pre-FBBT box leaves the
    /// aux clamps in place, handing the IPM a reduced problem whose
    /// infeasibility is a presolve artifact (here `x0` pinned to 2 makes the
    /// kept row `x0 + x2 = 20` infeasible). After the rollback the dropped
    /// rows are restored, FBBT finds no infeasibility on the free box, and the
    /// solver sees the full original problem.
    #[test]
    fn fbbt_infeasibility_with_aux_clamp_rolls_back_phase0() {
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(AuxClampBreaksKeptNonlinearRow));
        let provider: Rc<RefCell<dyn ExpressionProvider>> = Rc::new(RefCell::new(AuxBreakProvider));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_coupling: AuxiliaryCouplingPolicy::Safe,
            bound_tightening: true,
            fbbt: true,
            ..PresolveOptions::defaults()
        };
        let mut wrapped =
            PresolveTnlp::with_expression_provider(Rc::clone(&inner), Rc::clone(&provider), opts);
        let info = wrapped.get_nlp_info().expect("init ok");

        // Confirm the scenario actually fired: Phase 0 eliminated the 2×2
        // linear block (clamping x0, x1). Without this the test would pass
        // vacuously.
        assert_eq!(
            wrapped.auxiliary_diagnostics().vars_eliminated,
            2,
            "Phase 0 must have clamped the linear block — otherwise the \
             rollback path is never exercised"
        );

        // The headline fix: the elimination is rolled back, so every dropped
        // row is restored. Without the rollback Phase 0's two dropped rows
        // would leave `m == 1`.
        assert_eq!(
            info.m, 3,
            "FBBT infeasibility under an aux clamp must roll Phase 0 back, \
             restoring the dropped rows (got m={})",
            info.m
        );

        // FBBT, re-run on the un-clamped box, finds no infeasibility: the
        // witness was an artifact of the aux clamp.
        let rpt = wrapped.fbbt_report().expect("fbbt ran");
        assert!(
            rpt.infeasibility_witness.is_none(),
            "FBBT must not witness infeasibility on the un-clamped box, got {:?}",
            rpt.infeasibility_witness
        );

        // The soundness property for the certification channel, on the one
        // scenario that can break it: this model *is feasible*, and the only
        // infeasibility ever seen was manufactured by Phase 0's own clamp.
        // Certifying it would make POUNCE report "proved infeasible" for a
        // problem that has solutions — strictly worse than the numerical
        // verdict this replaces. The proof must be withheld.
        assert_eq!(
            wrapped.certified_infeasible(),
            None,
            "a presolve-manufactured infeasibility must never be certified — \
             this model is feasible"
        );

        // x0 is no longer pinned to the aux value 2; FBBT over `x0 + x2 = 20`
        // with `x2 ∈ [0, 1]` tightens it to `[19, 20]`. Bounds stay valid.
        let mut x_l = vec![0.0; info.n as usize];
        let mut x_u = vec![0.0; info.n as usize];
        let mut g_l = vec![0.0; info.m as usize];
        let mut g_u = vec![0.0; info.m as usize];
        assert!(wrapped.get_bounds_info(BoundsInfo {
            x_l: &mut x_l,
            x_u: &mut x_u,
            g_l: &mut g_l,
            g_u: &mut g_u,
        }));
        for i in 0..(info.n as usize) {
            assert!(
                x_l[i] <= x_u[i] + 1e-12,
                "bounds handed to IPM must be valid: x_l[{i}]={} > x_u[{i}]={}",
                x_l[i],
                x_u[i]
            );
        }
        assert!(
            x_l[0] > 2.0 + 1e-6,
            "x0 must no longer be clamped to the aux value 2 (got x_l[0]={})",
            x_l[0]
        );
    }

    /// 2-variable, 2-row TNLP whose ORIGINAL problem is FEASIBLE (at
    /// `(x, y) = (2, 1)`) but where Phase-0's nonlinear block solve picks the
    /// WRONG root of a multi-root block. Row 0 is the 1×1 nonlinear block
    /// `x² = 4` (roots ±2); the starting point `x = -1` drives the damped
    /// Newton to the root `x = -2`. Row 1 is the kept row `x + y = 3` with
    /// `y ∈ [0, 2]` — tagged `NonLinear` so it is FBBT-handled (a `Linear`
    /// tag would let Phase 1 catch the clamp first and exercise the Phase-1
    /// rollback instead of the F6 FBBT rollback under test). Under the clamp
    /// `x = -2` the kept row needs `y = 5 > 2`: infeasible. At the OTHER root
    /// `x = +2` it needs `y = 1 ∈ [0, 2]`: feasible. So FBBT's witness is
    /// purely a Phase-0 artifact of the wrong root, on a feasible original.
    ///
    /// Phase-0 mechanics that make the scenario fire: DM matches row 0 to
    /// `x` (its only column) and row 1 to `y`; BTF solves the block
    /// `{row 0, x}` first (Newton from the probe `x = -1` → `-2`, inside
    /// `x ∈ [-10, 10]`, residual 0, accepted and clamped) and then rejects
    /// the block `{row 1, y}` as `OutOfBounds` (`y = 3 − (−2) = 5 ∉ [0, 2]`),
    /// which keeps row 1 visible to FBBT.
    struct WrongRootClampBreaksFeasibleOriginal;
    impl TNLP for WrongRootClampBreaksFeasibleOriginal {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 2,
                m: 2,
                nnz_jac_g: 3,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            b.x_l[0] = -10.0;
            b.x_u[0] = 10.0;
            b.x_l[1] = 0.0;
            b.x_u[1] = 2.0;
            b.g_l[0] = 4.0;
            b.g_u[0] = 4.0;
            b.g_l[1] = 3.0;
            b.g_u[1] = 3.0;
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                // The probe seeds the block Newton: from -1 it converges to
                // the wrong root -2 (a start of +1 would find +2 and the
                // scenario would not fire).
                sp.x[0] = -1.0;
                sp.x[1] = 0.0;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            for v in g.iter_mut() {
                *v = 0.0;
            }
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = x[0] * x[0];
            g[1] = x[0] + x[1];
            true
        }
        fn eval_jac_g(
            &mut self,
            x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    irow.copy_from_slice(&[0, 1, 1]);
                    jcol.copy_from_slice(&[0, 0, 1]);
                }
                SparsityRequest::Values { values } => {
                    // ∂(x²)/∂x = 2x — genuinely point-dependent so the block
                    // Newton sees the true (sign-carrying) derivative at each
                    // iterate. Values requests always carry `Some(x)` here
                    // (probe fetch and Phase-0 callback both pass it).
                    let x0 = x.map(|x| x[0]).unwrap_or(-1.0);
                    values.copy_from_slice(&[2.0 * x0, 1.0, 1.0]);
                }
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types[0] = Linearity::NonLinear;
            // Tagged NonLinear so it is FBBT-handled, not a Phase-1 linear row.
            types[1] = Linearity::NonLinear;
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    /// Supplies the FBBT tape `x + y` for the kept row 1 only (row 0 is the
    /// eliminated block; it needs no tape for this scenario).
    struct WrongRootKeptRowProvider;
    impl ExpressionProvider for WrongRootKeptRowProvider {
        fn constraint_expression(
            &self,
            i: usize,
        ) -> Option<pounce_nlp::expression_provider::FbbtTape> {
            use pounce_nlp::expression_provider::{FbbtOp, FbbtTape};
            if i == 1 {
                Some(FbbtTape {
                    ops: vec![FbbtOp::Var(0), FbbtOp::Var(1), FbbtOp::Add(0, 1)],
                })
            } else {
                None
            }
        }
    }

    /// F6's headline failure mode, end to end: a FEASIBLE original problem
    /// must not be declared infeasible because Phase 0 clamped a multi-root
    /// nonlinear block at the wrong root. The companion test above
    /// (`fbbt_infeasibility_with_aux_clamp_rolls_back_phase0`) exercises the
    /// rollback *mechanism* but its original model is itself infeasible; here
    /// the original is feasible at `(2, 1)`, Newton lands on `x = -2`
    /// (breaking the kept row `x + y = 3`, `y ∈ [0, 2]`), FBBT witnesses the
    /// artifact infeasibility, and the rollback must rescue the solve: full
    /// row set restored, clamp gone, FBBT witness-free on the re-run — so the
    /// IPM receives the feasible full problem instead of a wrong "infeasible"
    /// verdict.
    #[test]
    fn fbbt_rollback_rescues_feasible_original_from_wrong_root_clamp() {
        let inner: Rc<RefCell<dyn TNLP>> =
            Rc::new(RefCell::new(WrongRootClampBreaksFeasibleOriginal));
        let provider: Rc<RefCell<dyn ExpressionProvider>> =
            Rc::new(RefCell::new(WrongRootKeptRowProvider));
        let opts = PresolveOptions {
            enabled: true,
            auxiliary: true,
            auxiliary_coupling: AuxiliaryCouplingPolicy::Safe,
            bound_tightening: true,
            fbbt: true,
            ..PresolveOptions::defaults()
        };
        let mut wrapped =
            PresolveTnlp::with_expression_provider(Rc::clone(&inner), Rc::clone(&provider), opts);
        let info = wrapped.get_nlp_info().expect("init ok");

        // Pre-rollback, the scenario must actually have fired: Phase 0
        // eliminated the 1×1 block, clamping x at a Newton root. Without
        // this the test passes vacuously (diagnostics survive the rollback).
        assert_eq!(
            wrapped.auxiliary_diagnostics().vars_eliminated,
            1,
            "Phase 0 must have solved and clamped the x² = 4 block — \
             otherwise the wrong-root path is never exercised"
        );

        // The rollback restored the full model. `m == 2` proves both halves:
        // (a) FBBT witnessed the artifact infeasibility (no witness → no
        // rollback → row 0 stays dropped → m == 1), and (b) that witness can
        // only arise from the wrong root (-2): at +2 the kept row is
        // satisfiable with y = 1 ∈ [0, 2] and FBBT finds nothing.
        assert_eq!(
            info.m, 2,
            "wrong-root clamp on a feasible original must trigger the F6 \
             rollback and restore the dropped block row (got m={})",
            info.m
        );

        // The re-run on the un-clamped box is witness-free: the original is
        // feasible, so nothing survives the rollback.
        let rpt = wrapped.fbbt_report().expect("fbbt ran");
        assert!(
            rpt.infeasibility_witness.is_none(),
            "feasible original: FBBT must not witness infeasibility after \
             the rollback, got {:?}",
            rpt.infeasibility_witness
        );

        // The box handed to the IPM is valid, the wrong-root clamp is gone,
        // and the feasible point (x, y) = (2, 1) is still inside it.
        let mut x_l = vec![0.0; info.n as usize];
        let mut x_u = vec![0.0; info.n as usize];
        let mut g_l = vec![0.0; info.m as usize];
        let mut g_u = vec![0.0; info.m as usize];
        assert!(wrapped.get_bounds_info(BoundsInfo {
            x_l: &mut x_l,
            x_u: &mut x_u,
            g_l: &mut g_l,
            g_u: &mut g_u,
        }));
        for i in 0..(info.n as usize) {
            assert!(
                x_l[i] <= x_u[i] + 1e-12,
                "bounds handed to IPM must be valid: x_l[{i}]={} > x_u[{i}]={}",
                x_l[i],
                x_u[i]
            );
        }
        assert!(
            x_u[0] - x_l[0] > 1e-6,
            "x must no longer be clamped (got [{}, {}])",
            x_l[0],
            x_u[0]
        );
        assert!(
            x_l[0] <= 2.0 + 1e-9 && 2.0 <= x_u[0] + 1e-9,
            "the feasible root x = 2 must survive in the IPM's box, got \
             [{}, {}]",
            x_l[0],
            x_u[0]
        );
        assert!(
            x_l[1] <= 1.0 + 1e-9 && 1.0 <= x_u[1] + 1e-9,
            "the feasible y = 1 must survive in the IPM's box, got [{}, {}]",
            x_l[1],
            x_u[1]
        );
    }

    /// L46: under a row drop, a genuinely per-constraint metadata vector
    /// (length `m_in`) must be subset to the kept rows, and the inverse
    /// `expand` must restore it (dropped rows defaulted). This is the
    /// canonical, contract-conforming case — the only one any real inner
    /// TNLP produces (e.g. `nl_reader`'s per-row `con_names`).
    #[test]
    fn con_metadata_per_row_vector_round_trips_under_row_drop() {
        let m_in = 3;
        let rows_kept = vec![0usize, 2]; // row 1 dropped by presolve
        let mut inner = MetaData::default();
        inner.strings.insert(
            "names".to_string(),
            vec!["c0".to_string(), "c1".to_string(), "c2".to_string()],
        );
        inner.integers.insert("flags".to_string(), vec![10, 11, 12]);
        inner
            .numerics
            .insert("weights".to_string(), vec![1.0, 2.0, 3.0]);

        let reduced = project_con_metadata(&inner, &rows_kept, m_in);
        assert_eq!(
            reduced.strings["names"],
            vec!["c0".to_string(), "c2".to_string()]
        );
        assert_eq!(reduced.integers["flags"], vec![10, 12]);
        assert_eq!(reduced.numerics["weights"], vec![1.0, 3.0]);

        // finalize_metadata's inverse: reduced (m_out=2) back to m_in=3.
        let restored = expand_con_metadata(&reduced, &rows_kept, m_in);
        assert_eq!(
            restored.strings["names"],
            vec!["c0".to_string(), String::new(), "c2".to_string()]
        );
        assert_eq!(restored.integers["flags"], vec![10, 0, 12]);
        assert_eq!(restored.numerics["weights"], vec![1.0, 0.0, 3.0]);
    }

    /// L46 hazard, characterized: a *global* metadata vector that happens
    /// to have length `m_in` is indistinguishable from a per-row vector
    /// (the untyped `MetaData` API carries no arity tag), so projection
    /// silently subsets it. This pins the known-imperfect behavior so a
    /// future arity-aware fix has a regression anchor; the value pounce
    /// ships today is unaffected because no real inner TNLP emits a
    /// coincidentally-`m_in`-length global constraint vector.
    #[test]
    fn con_metadata_length_heuristic_misfires_on_coincidental_global() {
        let m_in = 3;
        let rows_kept = vec![0usize, 2]; // a row is dropped, so projection is non-identity
        let mut inner = MetaData::default();
        // Semantically global (e.g. a 3-entry config tuple) that just
        // happens to be length 3 == m_in.
        inner
            .integers
            .insert("global_triple".to_string(), vec![100, 200, 300]);

        let reduced = project_con_metadata(&inner, &rows_kept, m_in);
        // Wrongly treated as per-row and subset to [100, 300]; the
        // faithful value would be the untouched [100, 200, 300].
        assert_eq!(
            reduced.integers["global_triple"],
            vec![100, 300],
            "documents the L46 length-heuristic misfire on a coincidental global vector"
        );

        // A global vector whose length differs from m_in is correctly
        // passed through untouched (the heuristic only misfires on the
        // exact-length coincidence).
        let mut inner2 = MetaData::default();
        inner2
            .numerics
            .insert("two_globals".to_string(), vec![1.5, 2.5]);
        let reduced2 = project_con_metadata(&inner2, &rows_kept, m_in);
        assert_eq!(reduced2.numerics["two_globals"], vec![1.5, 2.5]);
    }

    /// gh#391 scratch. One variable in `[0, 1]`, `m` rows evaluated as
    /// `coeff[i] * x + offset[i]` against per-row declared bounds — enough to
    /// drive `witness_refutes_infeasibility` directly and compare the two
    /// [`WitnessRule`] forms on the same numbers.
    struct WitnessProbeRows {
        coeff: Vec<Number>,
        offset: Vec<Number>,
        g_l: Vec<Number>,
        g_u: Vec<Number>,
        x0: Number,
    }

    impl TNLP for WitnessProbeRows {
        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
            Some(NlpInfo {
                n: 1,
                m: self.coeff.len() as Index,
                nnz_jac_g: self.coeff.len() as Index,
                nnz_h_lag: 0,
                index_style: IndexStyle::C,
            })
        }
        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
            b.x_l[0] = 0.0;
            b.x_u[0] = 1.0;
            b.g_l.copy_from_slice(&self.g_l);
            b.g_u.copy_from_slice(&self.g_u);
            true
        }
        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
            if sp.init_x {
                sp.x[0] = self.x0;
            }
            true
        }
        fn eval_f(&mut self, _x: &[Number], _new_x: bool) -> Option<Number> {
            Some(0.0)
        }
        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            g[0] = 0.0;
            true
        }
        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
            for ((out, &c), &o) in g.iter_mut().zip(&self.coeff).zip(&self.offset) {
                *out = c * x[0] + o;
            }
            true
        }
        fn eval_jac_g(
            &mut self,
            _x: Option<&[Number]>,
            _new_x: bool,
            mode: SparsityRequest<'_>,
        ) -> bool {
            match mode {
                SparsityRequest::Structure { irow, jcol } => {
                    for (i, r) in irow.iter_mut().enumerate() {
                        *r = i as Index;
                    }
                    jcol.fill(0);
                }
                SparsityRequest::Values { values } => values.copy_from_slice(&self.coeff),
            }
            true
        }
        fn get_constraints_linearity(&mut self, types: &mut [Linearity]) -> bool {
            types.fill(Linearity::Linear);
            true
        }
        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
    }

    fn refutes(model: WitnessProbeRows, rule: WitnessRule) -> bool {
        let (g_l, g_u) = (model.g_l.clone(), model.g_u.clone());
        let m = g_l.len();
        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(model));
        witness_refutes_infeasibility(&inner, 1, m, &[0.0], &[1.0], &g_l, &g_u, 1e-8, rule)
    }

    /// The gh#391 mechanism in one assertion pair, on identical numbers.
    ///
    /// `s*x == 0.2*s` with `s*x == 0.8*s` over `x ∈ [0, 1]` is empty at every
    /// `s > 0` — the crossing is `0.6` regardless. At `s = 1e-12` the clamped
    /// accepting form reinstates the absolute floor (`tol * max(scale, 1)` =
    /// `1e-8`), every point of the box "satisfies" both rows, and the witness
    /// withdraws a scale-free proof. Measured against the row's declared
    /// magnitude with no clamp, the same point violates by `0.6` relative and
    /// refutes nothing.
    #[test]
    fn down_scaled_rows_only_defeat_the_clamped_witness_form() {
        let model = |_s: Number| WitnessProbeRows {
            coeff: vec![1e-12, 1e-12],
            offset: vec![0.0, 0.0],
            g_l: vec![0.2e-12, 0.8e-12],
            g_u: vec![0.2e-12, 0.8e-12],
            x0: 0.5,
        };
        assert!(
            refutes(model(1e-12), WitnessRule::SolverAcceptance),
            "the clamped form accepts every point of the box at this row scale \
             — this is the behavior gh#391 is about, pinned so the contrast \
             below stays meaningful"
        );
        assert!(
            !refutes(model(1e-12), WitnessRule::DeclaredRowRelative),
            "0.6 of the row's own declared magnitude is a violation at every \
             scale; the strict rule must not withdraw the proof"
        );
    }

    /// The same rows at unit scale: both forms agree, which is the point —
    /// the strict rule changes nothing where the clamp was never active.
    #[test]
    fn unit_scale_rows_refute_under_neither_form() {
        let model = || WitnessProbeRows {
            coeff: vec![1.0, 1.0],
            offset: vec![0.0, 0.0],
            g_l: vec![0.2, 0.8],
            g_u: vec![0.2, 0.8],
            x0: 0.5,
        };
        assert!(!refutes(model(), WitnessRule::SolverAcceptance));
        assert!(!refutes(model(), WitnessRule::DeclaredRowRelative));
    }

    /// The hazard the strict rule has to handle explicitly: a *homogeneous* row
    /// (`g_l = g_u = 0`) has no declared magnitude, so a pure relative test
    /// would be unsatisfiable by construction — the violation *is* the scale,
    /// and any float-noise residual reads as a full-magnitude violation. Such a
    /// row keeps the absolute floor, so a genuinely feasible point still
    /// refutes and the proof is still withheld. Fail closed.
    #[test]
    fn homogeneous_row_keeps_the_absolute_floor_under_the_strict_rule() {
        // `x - 0.5 == 0` evaluated at the modeller's `x0 = 0.5`, off by an ulp
        // of noise. Feasible; the witness must say so under both rules.
        let noisy = || WitnessProbeRows {
            coeff: vec![1.0],
            offset: vec![-0.5 + 1e-16],
            g_l: vec![0.0],
            g_u: vec![0.0],
            x0: 0.5,
        };
        assert!(refutes(noisy(), WitnessRule::SolverAcceptance));
        assert!(
            refutes(noisy(), WitnessRule::DeclaredRowRelative),
            "a homogeneous row has nothing to be relative to; float noise on it \
             must not be promoted to a violation"
        );

        // A real violation on a homogeneous row still refutes nothing: the
        // fallback is the absolute floor, not blanket acceptance.
        let violated = || WitnessProbeRows {
            coeff: vec![1.0],
            offset: vec![0.6],
            g_l: vec![0.0],
            g_u: vec![0.0],
            x0: 0.5,
        };
        assert!(!refutes(violated(), WitnessRule::SolverAcceptance));
        assert!(!refutes(violated(), WitnessRule::DeclaredRowRelative));
    }

    /// The strict rule is relative, not absolute: on a row declared near `1e30`
    /// a residual of `1e5` is fifteen relative digits of agreement and still
    /// refutes. This is the extreme-coefficient class the witness gate exists
    /// for, and it must survive the rule change.
    #[test]
    fn strict_rule_still_refutes_at_extreme_row_magnitude() {
        let model = || WitnessProbeRows {
            coeff: vec![2e30],
            offset: vec![1e5],
            g_l: vec![1e30],
            g_u: vec![1e30],
            x0: 0.5,
        };
        assert!(refutes(model(), WitnessRule::SolverAcceptance));
        assert!(refutes(model(), WitnessRule::DeclaredRowRelative));
    }

    /// End-to-end through the wrapper: the rule is a property of the call site,
    /// so a default wrapper (one that would be solved through) keeps the #380
    /// behavior at sub-tolerance row scale, and only a caller that has
    /// established the solve cannot run gets the proof.
    #[test]
    fn probing_without_a_solve_certifies_where_the_default_wrapper_withholds() {
        let opts = PresolveOptions {
            enabled: true,
            bound_tightening: true,
            auxiliary: false,
            ..PresolveOptions::defaults()
        };
        let model = || WitnessProbeRows {
            coeff: vec![1e-12, 1e-12],
            offset: vec![0.0, 0.0],
            g_l: vec![0.2e-12, 0.8e-12],
            g_u: vec![0.2e-12, 0.8e-12],
            x0: 0.5,
        };

        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(model()));
        let mut solved_through = PresolveTnlp::new(inner, opts);
        solved_through.get_nlp_info().expect("init ok");
        assert!(
            solved_through.tighten_report().infeasible,
            "bound propagation sees the contradiction at every scale"
        );
        assert_eq!(
            solved_through.certified_infeasible(),
            None,
            "#380: a wrapper that will be solved through must not claim a proof \
             the solver's own acceptance test would contradict"
        );

        let inner: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(model()));
        let mut probe = PresolveTnlp::new(inner, opts).probing_without_a_solve();
        probe.get_nlp_info().expect("init ok");
        assert_eq!(
            probe.certified_infeasible(),
            Some(InfeasibilityProof::BoundPropagation),
            "gh#391: with no solve to contradict, the scale-free crossing is a \
             proof at every row scale"
        );
    }
}