RustedSciThe 0.4.16

Rust framework for symbolic and numerical computing:BVP ( Newton-Raphson frozen/damped/with collocations ), IVP( BDF, Radau, Backward Euler, LSODE, LSODA, RK45, DoPri), nonlinear equations ( Levenberg, Gavin) and more
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
//! Symbolic frontend for nonlinear systems.
//!
//! This module owns the symbolic side of `Nonlinear_systems` and turns raw
//! equations into one prepared residual/Jacobian provider for the solver
//! engine.
//!
//! The current architecture is intentionally layered:
//! - user code builds one [`SymbolicNonlinearProblem`] from equations plus
//!   [`SymbolicProblemOptions`],
//! - this module prepares one backend that implements the local
//!   residual/Jacobian contract,
//! - solver code later sees only [`NonlinearProblem`] and
//!   [`JacobianProvider`] and does not need to know whether evaluation comes
//!   from `lambdify` or from a linked compiled AOT module.
//!
//! Backend scenarios:
//! - `Lambdify` stays on the existing symbolic Jacobian + lambdify path,
//! - `Aot` is reached through
//!   [`crate::numerical::Nonlinear_systems::symbolic_backend`], which selects,
//!   resolves, and links a compiled dense backend before this module adapts it
//!   to the same solver-facing contract.
//!
//! This makes `Nonlinear_systems` follow the same direction as the newer BVP
//! stack: contracts and prepared bridges are explicit, while generic AOT
//! lifecycle details stay outside the solver engine itself.

use crate::numerical::Nonlinear_systems::error::SolveError;
use crate::numerical::Nonlinear_systems::problem::{JacobianProvider, NonlinearProblem};
use crate::numerical::Nonlinear_systems::symbolic_backend::{
    SelectedSymbolicNonlinearBackendKind, SymbolicBackendSelectionPolicy,
    select_symbolic_nonlinear_backend,
};
use crate::numerical::Nonlinear_systems::symbolic_legacy::LegacyLambdifySymbolicBackend;
use crate::symbolic::codegen::codegen_aot_resolution::AotResolver;
use crate::symbolic::codegen::codegen_aot_runtime_link::{
    LinkedDenseAotBackend, resolve_linked_dense_backend,
};
use crate::symbolic::codegen::codegen_manifest::PreparedProblemManifest;
use crate::symbolic::codegen::codegen_provider_api::{
    BackendKind, MatrixBackend, PreparedDenseProblem,
};
use crate::symbolic::codegen::codegen_runtime_api::{
    DenseJacobianChunkingStrategy, ResidualChunkingStrategy,
};
use crate::symbolic::codegen::codegen_tasks::{JacobianTask, ResidualTask};
use crate::symbolic::symbolic_engine::Expr;
use nalgebra::{DMatrix, DVector};
use std::cell::RefCell;
use std::time::{Duration, Instant};

/// Backend used to turn symbolic equations into callable residual/Jacobian evaluators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SymbolicBackendKind {
    /// Compile symbolic expressions into in-process lambdified closures.
    #[default]
    Lambdify,
    /// Reserve a slot for the future AOT-generated backend path.
    Aot,
}

impl SymbolicBackendKind {
    /// Returns a stable short name used in logs and diagnostics.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Lambdify => "lambdify",
            Self::Aot => "aot",
        }
    }
}

/// Lifecycle policy requested for an optional generated artifact.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SymbolicArtifactPolicy {
    /// No generated artifact was requested by the direct Lambdify API.
    #[default]
    NotRequested,
    /// Use an artifact when one is already available, otherwise use Lambdify.
    UseIfAvailable,
    /// Fail unless a compatible prebuilt artifact is available.
    RequirePrebuilt,
    /// Build an artifact when the compatible artifact is missing.
    BuildIfMissing,
    /// Always execute a fresh artifact build.
    RebuildAlways,
}

impl SymbolicArtifactPolicy {
    /// Returns the stable label used by diagnostics and story tables.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NotRequested => "not-requested",
            Self::UseIfAvailable => "use-if-available",
            Self::RequirePrebuilt => "require-prebuilt",
            Self::BuildIfMissing => "build-if-missing",
            Self::RebuildAlways => "rebuild-always",
        }
    }
}

fn artifact_policy_for_backend_selection(
    policy: SymbolicBackendSelectionPolicy,
) -> SymbolicArtifactPolicy {
    match policy {
        SymbolicBackendSelectionPolicy::LambdifyOnly => SymbolicArtifactPolicy::NotRequested,
        SymbolicBackendSelectionPolicy::AotOnly => SymbolicArtifactPolicy::RequirePrebuilt,
        SymbolicBackendSelectionPolicy::PreferAotThenLambdify => {
            SymbolicArtifactPolicy::UseIfAvailable
        }
    }
}

/// Action taken with the generated artifact during preparation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SymbolicArtifactAction {
    /// The direct Lambdify API did not request an artifact.
    #[default]
    NotApplicable,
    /// A compatible artifact was reused without a new build.
    Reused,
    /// A new artifact was built and registered.
    Built,
    /// A requested artifact was unavailable and the policy fell back to Lambdify.
    FallbackToLambdify,
}

/// Preparation/build telemetry shared by direct Lambdify and generated AOT
/// entry points.
///
/// Build-related fields are optional by design: `None` means that the stage
/// was not part of this lifecycle call. This keeps an unavailable metric
/// distinct from a measured zero-duration stage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SymbolicPreparationReport {
    /// Effective callable backend after preparation and selection.
    pub effective_backend: SymbolicBackendKind,
    /// Artifact policy requested by the caller.
    pub artifact_policy: SymbolicArtifactPolicy,
    /// Action taken for the generated artifact, if applicable.
    pub artifact_action: SymbolicArtifactAction,
    /// Manifest-derived artifact identity, when an AOT plan was prepared.
    pub artifact_key: Option<String>,
    /// End-to-end preparation time, excluding later numerical solves.
    pub preparation_duration: Duration,
    /// Time spent in the AOT materialize/build/register stage performed by
    /// this call. `None` also covers a request satisfied by another process.
    pub build_duration: Option<Duration>,
    /// Number of generated residual jobs/chunks, when an AOT plan exists.
    pub generated_residual_jobs: Option<usize>,
    /// Number of generated Jacobian jobs/chunks, when an AOT plan exists.
    pub generated_jacobian_jobs: Option<usize>,
}

impl SymbolicPreparationReport {
    fn direct_lambdify(duration: Duration, backend: SymbolicBackendKind) -> Self {
        Self {
            effective_backend: backend,
            artifact_policy: SymbolicArtifactPolicy::NotRequested,
            artifact_action: SymbolicArtifactAction::NotApplicable,
            artifact_key: None,
            preparation_duration: duration,
            build_duration: None,
            generated_residual_jobs: None,
            generated_jacobian_jobs: None,
        }
    }
}

/// High-level symbolic backend selection for nonlinear systems.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SymbolicBackendConfig {
    /// Backend used to prepare the symbolic residual/Jacobian provider.
    pub kind: SymbolicBackendKind,
}

/// Runtime policy for evaluating prepared Lambdify callbacks.
///
/// `Sequential` is the conservative default for small systems. `Parallel`
/// uses the already-known evaluator layout and activates only when the
/// selected Jacobian/residual work is at least `min_work`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LambdifyExecutionPolicy {
    /// Evaluate callbacks on the calling thread.
    Sequential,
    /// Evaluate independent callback outputs with Rayon when work is large enough.
    Parallel {
        /// Minimum number of evaluator slots required to use parallel execution.
        min_work: usize,
    },
}

impl Default for LambdifyExecutionPolicy {
    fn default() -> Self {
        Self::Sequential
    }
}

impl SymbolicBackendConfig {
    /// Uses the existing lambdify-based symbolic backend.
    pub fn lambdify() -> Self {
        Self {
            kind: SymbolicBackendKind::Lambdify,
        }
    }

    /// Requests the future AOT symbolic backend.
    pub fn aot() -> Self {
        Self {
            kind: SymbolicBackendKind::Aot,
        }
    }
}

/// Stable, ordered names of the numeric parameters of a nonlinear system.
///
/// The order is part of the evaluation contract: parameter values are passed
/// to Lambdify/AOT backends in this order, before the unknown vector.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NonlinearParameterSchema {
    names: Vec<String>,
}

impl NonlinearParameterSchema {
    /// Creates a validated parameter schema and preserves the supplied order.
    pub fn new(names: Vec<String>) -> Result<Self, SolveError> {
        for (index, name) in names.iter().enumerate() {
            if name.trim().is_empty() {
                return Err(SolveError::InvalidParameterSchema(format!(
                    "parameter name at index {index} is empty"
                )));
            }
            if name.trim() != name {
                return Err(SolveError::InvalidParameterSchema(format!(
                    "parameter name '{name}' contains surrounding whitespace"
                )));
            }
            if names[..index].iter().any(|previous| previous == name) {
                return Err(SolveError::InvalidParameterSchema(format!(
                    "duplicate parameter name '{name}'"
                )));
            }
        }
        Ok(Self { names })
    }

    /// Returns the number of declared parameters.
    pub fn len(&self) -> usize {
        self.names.len()
    }

    /// Returns true when the schema has no names.
    pub fn is_empty(&self) -> bool {
        self.names.is_empty()
    }

    /// Returns parameter names in their stable evaluation order.
    pub fn names(&self) -> &[String] {
        &self.names
    }

    /// Returns the stable index of a named parameter.
    pub fn index_of(&self, name: &str) -> Option<usize> {
        self.names.iter().position(|candidate| candidate == name)
    }

    /// Consumes the schema and returns its ordered names.
    pub fn into_names(self) -> Vec<String> {
        self.names
    }
}

/// Validated numeric values bound to a NonlinearParameterSchema.
#[derive(Debug, Clone, PartialEq)]
pub struct NonlinearParameterValues {
    schema: NonlinearParameterSchema,
    values: DVector<f64>,
}

impl NonlinearParameterValues {
    /// Validates values against the schema without modifying an existing bind.
    pub fn new(
        schema: &NonlinearParameterSchema,
        values: DVector<f64>,
    ) -> Result<Self, SolveError> {
        if schema.len() != values.len() {
            return Err(SolveError::DimensionMismatch {
                expected: schema.len(),
                actual: values.len(),
                context: "nonlinear parameter values",
            });
        }
        for (index, value) in values.iter().copied().enumerate() {
            if !value.is_finite() {
                return Err(SolveError::NonFiniteParameterValue { index, value });
            }
        }
        Ok(Self {
            schema: schema.clone(),
            values,
        })
    }

    /// Returns the ordered schema this binding was validated against.
    pub fn schema(&self) -> &NonlinearParameterSchema {
        &self.schema
    }

    /// Returns the validated values in schema order.
    pub fn as_vector(&self) -> &DVector<f64> {
        &self.values
    }

    /// Returns one value by its stable parameter index.
    pub fn get(&self, index: usize) -> Option<f64> {
        self.values.get(index).copied()
    }

    /// Consumes the binding and returns its numeric vector.
    pub fn into_vector(self) -> DVector<f64> {
        self.values
    }
}

fn validate_variable_names(names: &[String]) -> Result<(), SolveError> {
    for (index, name) in names.iter().enumerate() {
        if name.trim().is_empty() {
            return Err(SolveError::InvalidVariableSchema(format!(
                "variable name at index {index} is empty"
            )));
        }
        if name.trim() != name {
            return Err(SolveError::InvalidVariableSchema(format!(
                "variable name '{name}' contains surrounding whitespace"
            )));
        }
        if names[..index].iter().any(|previous| previous == name) {
            return Err(SolveError::InvalidVariableSchema(format!(
                "duplicate variable name '{name}'"
            )));
        }
    }
    Ok(())
}

/// User-facing setup object for symbolic nonlinear problems.
///
/// This keeps symbolic problem construction on one layer:
/// equations are provided separately, while variables, optional parameters,
/// parameter values, and backend choice are grouped into one options object.
#[derive(Debug, Clone, Default)]
pub struct SymbolicProblemOptions {
    /// Explicit variable ordering.
    pub variables: Option<Vec<String>>,
    /// Optional symbolic parameter names.
    pub equation_parameters: Option<Vec<String>>,
    /// Optional parameter values used during evaluation.
    pub equation_parameter_values: Option<DVector<f64>>,
    /// Backend used to prepare the symbolic provider.
    pub backend_config: SymbolicBackendConfig,
    /// Runtime execution policy for the prepared Lambdify backend.
    pub lambdify_execution_policy: LambdifyExecutionPolicy,
}

impl SymbolicProblemOptions {
    /// Creates a default symbolic problem setup that uses the lambdify backend.
    pub fn new() -> Self {
        Self::default()
    }

    /// Installs an explicit variable ordering.
    pub fn with_variables(mut self, variables: Vec<String>) -> Self {
        self.variables = Some(variables);
        self
    }

    /// Installs symbolic parameter names.
    pub fn with_equation_parameters(mut self, parameters: Vec<String>) -> Self {
        self.equation_parameters = Some(parameters);
        self
    }

    /// Installs parameter values used when evaluating the symbolic system.
    pub fn with_equation_parameter_values(mut self, values: DVector<f64>) -> Self {
        self.equation_parameter_values = Some(values);
        self
    }

    /// Overrides the symbolic backend preparation mode.
    pub fn with_backend_config(mut self, backend_config: SymbolicBackendConfig) -> Self {
        self.backend_config = backend_config;
        self
    }

    /// Selects sequential or thresholded parallel Lambdify evaluation.
    pub fn with_lambdify_execution_policy(mut self, policy: LambdifyExecutionPolicy) -> Self {
        self.lambdify_execution_policy = policy;
        self
    }

    /// Convenience preset for the existing lambdify backend.
    pub fn with_lambdify_backend(self) -> Self {
        self.with_backend_config(SymbolicBackendConfig::lambdify())
    }

    /// Convenience preset for the future AOT backend.
    pub fn with_aot_backend(self) -> Self {
        self.with_backend_config(SymbolicBackendConfig::aot())
    }
}

/// AOT preparation settings for dense nonlinear symbolic problems.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SymbolicDenseAotOptions {
    /// Residual chunking used by the dense nonlinear residual plan.
    pub residual_strategy: ResidualChunkingStrategy,
    /// Jacobian row chunking used by the dense nonlinear Jacobian plan.
    pub jacobian_strategy: DenseJacobianChunkingStrategy,
}

impl Default for SymbolicDenseAotOptions {
    fn default() -> Self {
        Self {
            residual_strategy: ResidualChunkingStrategy::Whole,
            jacobian_strategy: DenseJacobianChunkingStrategy::Whole,
        }
    }
}

/// Dense nonlinear prepared AOT bridge built from symbolic equations.
///
/// This is the dense nonlinear-system analogue of the BVP prepared AOT bridge:
/// it carries runtime plans and exposes a manifest-friendly prepared dense
/// problem that can later be handed to the generic AOT lifecycle.
#[derive(Debug, Clone)]
pub struct PreparedSymbolicNonlinearAotProblem<'a> {
    equations: &'a [Expr],
    symbolic_jacobian: &'a [Vec<Expr>],
    variable_refs: Vec<&'a str>,
    parameter_refs: Option<Vec<&'a str>>,
    flattened_input_names: Vec<&'a str>,
    residual_fn_name: String,
    jacobian_fn_name: String,
    residual_strategy: ResidualChunkingStrategy,
    jacobian_strategy: DenseJacobianChunkingStrategy,
}

impl<'a> PreparedSymbolicNonlinearAotProblem<'a> {
    /// Builds the residual runtime plan consumed by the generic AOT pipeline.
    ///
    /// The plan borrows the symbolic equations and the already-fixed flattened
    /// input order stored by this bridge.
    fn residual_runtime_plan(
        &self,
    ) -> crate::symbolic::codegen::codegen_runtime_api::ResidualRuntimePlan<'_> {
        ResidualTask {
            fn_name: self.residual_fn_name.as_str(),
            residuals: self.equations,
            variables: &self.variable_refs,
            params: self.parameter_refs.as_deref(),
        }
        .runtime_plan(self.residual_strategy)
    }

    fn jacobian_runtime_plan(
        &self,
    ) -> crate::symbolic::codegen::codegen_runtime_api::DenseJacobianRuntimePlan<'_> {
        // The dense runtime plan keeps exactly the same flattened input order
        // contract as the residual plan, so codegen/build layers can treat both
        // outputs as one prepared problem.
        JacobianTask {
            fn_name: self.jacobian_fn_name.as_str(),
            jacobian: self.symbolic_jacobian,
            variables: &self.variable_refs,
            params: self.parameter_refs.as_deref(),
        }
        .runtime_plan(self.jacobian_strategy)
    }

    /// Returns the underlying generic prepared dense problem.
    pub fn as_prepared_problem(&self) -> PreparedDenseProblem<'_> {
        PreparedDenseProblem::new(
            BackendKind::Aot,
            MatrixBackend::Dense,
            self.residual_runtime_plan(),
            self.jacobian_runtime_plan(),
        )
    }

    /// Returns the flattened input names shared by residual and Jacobian plans.
    pub fn flattened_input_names(&self) -> &[&'a str] {
        &self.flattened_input_names
    }

    /// Returns the residual length.
    pub fn residual_len(&self) -> usize {
        self.equations.len()
    }

    /// Returns the dense Jacobian shape `(rows, cols)`.
    pub fn jacobian_shape(&self) -> (usize, usize) {
        (
            self.symbolic_jacobian.len(),
            self.symbolic_jacobian.first().map_or(0, |row| row.len()),
        )
    }

    /// Returns an owned manifest for the prepared dense AOT problem.
    pub fn manifest(&self) -> PreparedProblemManifest {
        PreparedProblemManifest::from(&self.as_prepared_problem())
    }

    /// Returns the stable manifest-derived problem key used by registry layers.
    pub fn problem_key(&self) -> String {
        self.manifest().problem_key()
    }
}

/// Solver-facing contract implemented by symbolic nonlinear backends.
///
/// The nonlinear engine should not care whether residuals and Jacobians come from
/// the legacy lambdify path or, later, from generated AOT code. This trait keeps
/// that contract explicit.
pub(crate) trait SymbolicEvaluationBackend: Send + Sync {
    /// Returns the backend kind that produced this provider.
    fn kind(&self) -> SymbolicBackendKind;

    /// Returns symbolic Jacobian metadata when the backend owns it.
    ///
    /// Generated backends do not need to retain symbolic expressions, so the
    /// default is `None`.
    fn symbolic_jacobian(&self) -> Option<&[Vec<Expr>]> {
        None
    }

    /// Returns the configured Lambdify execution policy, if applicable.
    fn lambdify_execution_policy(&self) -> Option<LambdifyExecutionPolicy> {
        None
    }

    /// Returns whether residual output can be written without a temporary.
    fn supports_residual_into(&self) -> bool {
        false
    }

    /// Returns whether Jacobian output can be written into caller-owned storage.
    fn supports_jacobian_into(&self) -> bool {
        false
    }

    /// Evaluates the residual vector at `x`.
    fn residual(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
    ) -> Result<DVector<f64>, SolveError>;

    /// Evaluates a residual into caller-owned storage.
    ///
    /// The default preserves the owned-returning backend contract. A backend
    /// with a native `*_into` evaluator may override this to avoid a temporary
    /// vector allocation.
    fn residual_into(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
        out: &mut DVector<f64>,
    ) -> Result<(), SolveError> {
        let residual =
            self.residual(x, equation_parameters, equation_parameter_values, variables)?;
        if residual.len() != out.len() {
            return Err(SolveError::DimensionMismatch {
                expected: variables.len(),
                actual: residual.len(),
                context: "symbolic residual evaluation",
            });
        }
        out.copy_from(&residual);
        Ok(())
    }

    /// Evaluates a Jacobian into caller-owned storage.
    fn jacobian_into(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
        out: &mut DMatrix<f64>,
    ) -> Result<(), SolveError> {
        let jacobian =
            self.jacobian(x, equation_parameters, equation_parameter_values, variables)?;
        if jacobian.nrows() != out.nrows() || jacobian.ncols() != out.ncols() {
            return Err(SolveError::InvalidConfig(format!(
                "Jacobian evaluation returned {}x{}, expected {}x{}",
                jacobian.nrows(),
                jacobian.ncols(),
                out.nrows(),
                out.ncols()
            )));
        }
        out.copy_from(&jacobian);
        Ok(())
    }

    /// Evaluates the Jacobian matrix at `x`.
    fn jacobian(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
    ) -> Result<DMatrix<f64>, SolveError>;
}

/// Concrete backend implementation that uses a linked compiled dense AOT backend.
struct CompiledDenseAotSymbolicBackend {
    /// Process-local linked compiled backend entry.
    linked: LinkedDenseAotBackend,
    /// Ordered symbolic variable names used by the nonlinear problem.
    variables: Vec<String>,
    /// Optional symbolic parameter names used to assemble flattened AOT inputs.
    equation_parameters: Option<Vec<String>>,
}

thread_local! {
    /// Reusable flattened input for one compiled callback on the current thread.
    ///
    /// Generated callbacks intentionally keep a single contiguous ABI. Reusing
    /// this buffer avoids rebuilding `[parameters..., variables...]` on every
    /// AOT residual/Jacobian call without introducing a mutex into the hot path.
    static COMPILED_AOT_ARGS: RefCell<Vec<f64>> = const { RefCell::new(Vec::new()) };
    /// Row-major Jacobian scratch used when adapting generated output to nalgebra.
    static COMPILED_AOT_JACOBIAN: RefCell<Vec<f64>> = const { RefCell::new(Vec::new()) };
}

/// Copies a generated row-major Jacobian into nalgebra's column-major storage.
///
/// The generated ABI is intentionally row-major because it is shared by the
/// C, Zig, Rust, BVP, and IVP integrations. Keeping the conversion here avoids
/// changing that public ABI. Traversing column segments inside small tiles
/// makes writes contiguous in the destination while keeping the source
/// working set cache-friendly.
pub(crate) fn copy_row_major_jacobian_into_column_major(
    row_major: &[f64],
    column_major: &mut [f64],
    rows: usize,
    cols: usize,
) {
    const TILE: usize = 32;
    debug_assert_eq!(row_major.len(), rows * cols);
    debug_assert_eq!(column_major.len(), rows * cols);

    for col_start in (0..cols).step_by(TILE) {
        let col_end = (col_start + TILE).min(cols);
        for row_start in (0..rows).step_by(TILE) {
            let row_end = (row_start + TILE).min(rows);
            for col in col_start..col_end {
                let destination_start = col * rows;
                for row in row_start..row_end {
                    column_major[destination_start + row] = row_major[row * cols + col];
                }
            }
        }
    }
}

impl CompiledDenseAotSymbolicBackend {
    /// Builds a compiled dense backend from a linked runtime entry.
    fn new(
        linked: LinkedDenseAotBackend,
        variables: &[String],
        equation_parameters: Option<&[String]>,
    ) -> Self {
        Self {
            linked,
            variables: variables.to_vec(),
            equation_parameters: equation_parameters.map(|params| params.to_vec()),
        }
    }

    /// Validates the input metadata shared by residual and Jacobian callbacks.
    fn validate_input(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
    ) -> Result<(), SolveError> {
        if x.len() != variables.len() {
            return Err(SolveError::DimensionMismatch {
                expected: variables.len(),
                actual: x.len(),
                context: "compiled symbolic residual input",
            });
        }

        if variables != self.variables.as_slice() {
            return Err(SolveError::InvalidConfig(
                "compiled nonlinear AOT backend was prepared for a different variable ordering"
                    .to_string(),
            ));
        }

        if equation_parameters != self.equation_parameters.as_deref() {
            return Err(SolveError::InvalidConfig(
                "compiled nonlinear AOT backend was prepared for a different parameter schema"
                    .to_string(),
            ));
        }

        if let Some(parameters) = &self.equation_parameters {
            let values = equation_parameter_values.ok_or_else(|| {
                SolveError::InvalidConfig(
                    "compiled nonlinear AOT backend requires parameter values".to_string(),
                )
            })?;
            if values.len() != parameters.len() {
                return Err(SolveError::DimensionMismatch {
                    expected: parameters.len(),
                    actual: values.len(),
                    context: "compiled symbolic parameter values",
                });
            }
        }
        Ok(())
    }

    /// Runs one generated callback with a reusable flattened input buffer.
    fn with_flattened_args<T>(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
        callback: impl FnOnce(&[f64]) -> Result<T, SolveError>,
    ) -> Result<T, SolveError> {
        self.validate_input(x, equation_parameters, equation_parameter_values, variables)?;
        COMPILED_AOT_ARGS.with(|scratch| {
            let mut args = scratch.borrow_mut();
            args.clear();
            if let Some(values) = equation_parameter_values {
                args.extend(values.iter().copied());
            }
            args.extend(x.iter().copied());
            callback(args.as_slice())
        })
    }
}

impl SymbolicEvaluationBackend for CompiledDenseAotSymbolicBackend {
    fn kind(&self) -> SymbolicBackendKind {
        SymbolicBackendKind::Aot
    }

    fn supports_residual_into(&self) -> bool {
        true
    }

    fn residual(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
    ) -> Result<DVector<f64>, SolveError> {
        self.with_flattened_args(
            x,
            equation_parameters,
            equation_parameter_values,
            variables,
            |args| {
                let mut out = vec![0.0; self.linked.residual_len];
                (self.linked.residual_eval)(args, &mut out);
                if out.iter().any(|value| !value.is_finite()) {
                    return Err(SolveError::ResidualEvaluation(
                        "compiled nonlinear AOT residual returned NaN or Inf".to_string(),
                    ));
                }
                Ok(DVector::from_vec(out))
            },
        )
    }

    fn residual_into(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
        out: &mut DVector<f64>,
    ) -> Result<(), SolveError> {
        self.with_flattened_args(
            x,
            equation_parameters,
            equation_parameter_values,
            variables,
            |args| {
                if out.len() != self.linked.residual_len {
                    return Err(SolveError::DimensionMismatch {
                        expected: self.linked.residual_len,
                        actual: out.len(),
                        context: "compiled symbolic residual output",
                    });
                }
                (self.linked.residual_eval)(args, out.as_mut_slice());
                if out.iter().any(|value| !value.is_finite()) {
                    return Err(SolveError::ResidualEvaluation(
                        "compiled nonlinear AOT residual returned NaN or Inf".to_string(),
                    ));
                }
                Ok(())
            },
        )
    }

    fn supports_jacobian_into(&self) -> bool {
        true
    }

    fn jacobian(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
    ) -> Result<DMatrix<f64>, SolveError> {
        self.with_flattened_args(
            x,
            equation_parameters,
            equation_parameter_values,
            variables,
            |args| {
                let mut out = vec![0.0; self.linked.shape.0 * self.linked.shape.1];
                (self.linked.jacobian_eval)(args, &mut out);
                if out.iter().any(|value| !value.is_finite()) {
                    return Err(SolveError::JacobianEvaluation(
                        "compiled nonlinear AOT jacobian returned NaN or Inf".to_string(),
                    ));
                }
                Ok(DMatrix::from_row_slice(
                    self.linked.shape.0,
                    self.linked.shape.1,
                    &out,
                ))
            },
        )
    }

    fn jacobian_into(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
        out: &mut DMatrix<f64>,
    ) -> Result<(), SolveError> {
        let (rows, cols) = self.linked.shape;
        if out.nrows() != rows || out.ncols() != cols {
            return Err(SolveError::InvalidConfig(format!(
                "Jacobian evaluation returned {}x{}, expected {}x{}",
                rows,
                cols,
                out.nrows(),
                out.ncols()
            )));
        }
        self.with_flattened_args(
            x,
            equation_parameters,
            equation_parameter_values,
            variables,
            |args| {
                COMPILED_AOT_JACOBIAN.with(|scratch| {
                    let mut row_major = scratch.borrow_mut();
                    row_major.resize(rows * cols, 0.0);
                    row_major.fill(0.0);
                    (self.linked.jacobian_eval)(args, row_major.as_mut_slice());
                    if row_major.iter().any(|value| !value.is_finite()) {
                        return Err(SolveError::JacobianEvaluation(
                            "compiled nonlinear AOT jacobian returned NaN or Inf".to_string(),
                        ));
                    }
                    copy_row_major_jacobian_into_column_major(
                        &row_major,
                        out.as_mut_slice(),
                        rows,
                        cols,
                    );
                    Ok(())
                })
            },
        )
    }
}

/// Prepared callable backend for a symbolic nonlinear system.
///
/// This mirrors the newer BVP architecture: symbolic equations are first normalized
/// into a backend configuration, then materialized into a prepared provider that the
/// generic solver engine can evaluate without knowing whether the backend came from
/// `lambdify` or, later, from AOT code generation.
struct PreparedSymbolicBackend {
    /// Solver-facing backend contract.
    backend: Box<dyn SymbolicEvaluationBackend>,
}

impl PreparedSymbolicBackend {
    /// Builds a prepared backend from symbolic equations and backend config.
    fn from_expressions(
        equations: &[Expr],
        variables: &[String],
        equation_parameters: Option<&[String]>,
        execution_policy: LambdifyExecutionPolicy,
        config: &SymbolicBackendConfig,
    ) -> Result<Self, SolveError> {
        match config.kind {
            SymbolicBackendKind::Lambdify => Ok(Self {
                backend: Box::new(LegacyLambdifySymbolicBackend::from_expressions(
                    equations,
                    variables,
                    equation_parameters,
                    execution_policy,
                )?),
            }),
            SymbolicBackendKind::Aot => Err(SolveError::InvalidConfig(
                "symbolic nonlinear AOT backend is not wired yet; use SymbolicBackendKind::Lambdify for now".to_string(),
            )),
        }
    }

    /// Returns the prepared backend kind.
    fn kind(&self) -> SymbolicBackendKind {
        self.backend.kind()
    }

    /// Returns whether the selected backend supports direct residual output.
    fn supports_residual_into(&self) -> bool {
        self.backend.supports_residual_into()
    }

    /// Returns whether the prepared backend can fill Jacobian storage directly.
    fn supports_jacobian_into(&self) -> bool {
        self.backend.supports_jacobian_into()
    }

    /// Returns symbolic Jacobian metadata retained by the prepared backend.
    fn symbolic_jacobian(&self) -> Option<&[Vec<Expr>]> {
        self.backend.symbolic_jacobian()
    }

    /// Returns the configured Lambdify execution policy, if applicable.
    fn lambdify_execution_policy(&self) -> Option<LambdifyExecutionPolicy> {
        self.backend.lambdify_execution_policy()
    }

    /// Builds a prepared compiled dense AOT backend from a linked runtime entry.
    ///
    /// By the time this constructor is called, backend selection, artifact
    /// resolution, and process-local runtime linking have already been done by
    /// outer layers. This method only adapts the linked callbacks to the local
    /// solver-facing backend contract.
    fn from_linked_dense(
        linked: LinkedDenseAotBackend,
        variables: &[String],
        equation_parameters: Option<&[String]>,
    ) -> Self {
        Self {
            backend: Box::new(CompiledDenseAotSymbolicBackend::new(
                linked,
                variables,
                equation_parameters,
            )),
        }
    }

    /// Evaluates the residual vector using the prepared backend.
    fn residual(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
    ) -> Result<DVector<f64>, SolveError> {
        self.backend
            .residual(x, equation_parameters, equation_parameter_values, variables)
    }

    /// Evaluates the Jacobian matrix using the prepared backend.
    fn jacobian(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
    ) -> Result<DMatrix<f64>, SolveError> {
        self.backend
            .jacobian(x, equation_parameters, equation_parameter_values, variables)
    }

    /// Evaluates a residual into reusable caller-owned storage.
    fn residual_into(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
        out: &mut DVector<f64>,
    ) -> Result<(), SolveError> {
        self.backend.residual_into(
            x,
            equation_parameters,
            equation_parameter_values,
            variables,
            out,
        )
    }

    /// Evaluates a Jacobian into reusable caller-owned storage.
    fn jacobian_into(
        &self,
        x: &DVector<f64>,
        equation_parameters: Option<&[String]>,
        equation_parameter_values: Option<&DVector<f64>>,
        variables: &[String],
        out: &mut DMatrix<f64>,
    ) -> Result<(), SolveError> {
        self.backend.jacobian_into(
            x,
            equation_parameters,
            equation_parameter_values,
            variables,
            out,
        )
    }
}

/// Adapter that exposes symbolic equations through the generic problem traits.
pub struct SymbolicNonlinearProblem {
    /// Backend configuration used to prepare the symbolic provider.
    backend_config: SymbolicBackendConfig,
    /// Prepared symbolic residual/Jacobian backend.
    backend: PreparedSymbolicBackend,
    /// Original symbolic equations.
    equations: Vec<Expr>,
    /// Dense symbolic Jacobian kept for future AOT preparation and diagnostics.
    symbolic_jacobian: Vec<Vec<Expr>>,
    /// Ordered list of variables.
    variables: Vec<String>,
    /// Optional stable symbolic parameter schema.
    parameter_schema: Option<NonlinearParameterSchema>,
    /// Optional validated parameter values used during evaluation.
    parameter_values: Option<NonlinearParameterValues>,
    /// Immutable preparation telemetry retained for later story/report use.
    preparation_report: SymbolicPreparationReport,
}

/// Immutable prepared symbolic nonlinear problem.
///
/// Preparation owns the equations, symbolic Jacobian, variable order, and
/// callable backend. Runtime parameter values are deliberately not mutable
/// state here; use [`PreparedSymbolicNonlinearProblem::bind`] to create a
/// solver-facing bound view.
pub struct PreparedSymbolicNonlinearProblem {
    problem: SymbolicNonlinearProblem,
}

/// Parameter-bound view of a prepared symbolic nonlinear problem.
///
/// The view borrows the prepared backend and owns only validated numeric
/// parameter values, so changing parameters does not repeat symbolic
/// differentiation, lambdification, AOT selection, or artifact preparation.
pub struct BoundSymbolicNonlinearProblem<'a> {
    prepared: &'a PreparedSymbolicNonlinearProblem,
    parameter_values: Option<NonlinearParameterValues>,
}

impl PreparedSymbolicNonlinearProblem {
    /// Wraps an already prepared compatibility problem without rebuilding it.
    ///
    /// This is useful when a higher-level lifecycle API has already selected
    /// and prepared an AOT backend and the caller wants the immutable
    /// prepared/bound interface afterward.
    pub fn from_problem(problem: SymbolicNonlinearProblem) -> Self {
        Self { problem }
    }

    /// Returns the immutable preparation/build report for this provider.
    pub fn preparation_report(&self) -> &SymbolicPreparationReport {
        self.problem.preparation_report()
    }

    /// Prepares a symbolic problem once from parsed expressions.
    pub fn from_expressions(
        equations: Vec<Expr>,
        options: SymbolicProblemOptions,
    ) -> Result<Self, SolveError> {
        Ok(Self {
            problem: SymbolicNonlinearProblem::from_expressions_with_options(equations, options)?,
        })
    }

    /// Prepares a symbolic problem once from equation strings.
    pub fn from_strings(
        equations: Vec<String>,
        options: SymbolicProblemOptions,
    ) -> Result<Self, SolveError> {
        Ok(Self {
            problem: SymbolicNonlinearProblem::from_strings_with_options(equations, options)?,
        })
    }

    /// Prepares a symbolic problem through the explicit Lambdify/AOT selector.
    pub fn from_expressions_with_backend_selection(
        equations: Vec<Expr>,
        options: SymbolicProblemOptions,
        policy: SymbolicBackendSelectionPolicy,
        resolver: Option<&AotResolver>,
        aot_options: SymbolicDenseAotOptions,
    ) -> Result<Self, SolveError> {
        Ok(Self {
            problem: SymbolicNonlinearProblem::from_expressions_with_backend_selection(
                equations,
                options,
                policy,
                resolver,
                aot_options,
            )?,
        })
    }

    /// String-based backend-selection constructor for the prepared lifecycle.
    pub fn from_strings_with_backend_selection(
        equations: Vec<String>,
        options: SymbolicProblemOptions,
        policy: SymbolicBackendSelectionPolicy,
        resolver: Option<&AotResolver>,
        aot_options: SymbolicDenseAotOptions,
    ) -> Result<Self, SolveError> {
        Ok(Self {
            problem: SymbolicNonlinearProblem::from_strings_with_backend_selection(
                equations,
                options,
                policy,
                resolver,
                aot_options,
            )?,
        })
    }

    /// Returns the prepared solver-facing problem for compatibility adapters.
    pub fn as_problem(&self) -> &SymbolicNonlinearProblem {
        &self.problem
    }

    /// Consumes the prepared object and returns its compatibility problem.
    pub fn into_problem(self) -> SymbolicNonlinearProblem {
        self.problem
    }

    /// Returns the ordered variable names.
    pub fn variables(&self) -> &[String] {
        self.problem.variables()
    }

    /// Returns the declared parameter schema, if any.
    pub fn parameter_schema(&self) -> Option<&NonlinearParameterSchema> {
        self.problem.parameter_schema()
    }

    /// Returns the effective backend selected during preparation.
    pub fn backend_kind(&self) -> SymbolicBackendKind {
        self.problem.backend_kind()
    }

    /// Returns the prepared Lambdify execution policy, if Lambdify is active.
    pub fn lambdify_execution_policy(&self) -> Option<LambdifyExecutionPolicy> {
        self.problem.lambdify_execution_policy()
    }

    /// Builds an AOT manifest view without changing the prepared backend.
    pub fn prepare_dense_aot_problem(
        &self,
        options: SymbolicDenseAotOptions,
    ) -> PreparedSymbolicNonlinearAotProblem<'_> {
        self.problem.prepare_dense_aot_problem(options)
    }

    /// Creates a bound view after verifying that the binding belongs to this schema.
    pub fn bind(
        &self,
        parameter_values: NonlinearParameterValues,
    ) -> Result<BoundSymbolicNonlinearProblem<'_>, SolveError> {
        let schema = self.parameter_schema().ok_or_else(|| {
            SolveError::ParameterSchemaMismatch(
                "cannot bind values because the prepared problem has no parameter schema"
                    .to_string(),
            )
        })?;
        if parameter_values.schema() != schema {
            return Err(SolveError::ParameterSchemaMismatch(
                "parameter values were created for a different ordered schema".to_string(),
            ));
        }
        Ok(BoundSymbolicNonlinearProblem {
            prepared: self,
            parameter_values: Some(parameter_values),
        })
    }

    /// Validates raw values against the prepared schema and creates a bound view.
    pub fn bind_values(
        &self,
        values: DVector<f64>,
    ) -> Result<BoundSymbolicNonlinearProblem<'_>, SolveError> {
        let schema = self.parameter_schema().ok_or_else(|| {
            SolveError::ParameterSchemaMismatch(
                "cannot bind values because the prepared problem has no parameter schema"
                    .to_string(),
            )
        })?;
        self.bind(NonlinearParameterValues::new(schema, values)?)
    }

    /// Creates a bound view for a non-parameterized prepared problem.
    pub fn bind_without_parameters(&self) -> Result<BoundSymbolicNonlinearProblem<'_>, SolveError> {
        if self.parameter_schema().is_some() {
            return Err(SolveError::ParameterSchemaMismatch(
                "the prepared problem declares parameters; bind their values explicitly"
                    .to_string(),
            ));
        }
        Ok(BoundSymbolicNonlinearProblem {
            prepared: self,
            parameter_values: None,
        })
    }

    /// Reuses values supplied through `SymbolicProblemOptions`, if present.
    pub fn bind_initial(&self) -> Result<BoundSymbolicNonlinearProblem<'_>, SolveError> {
        match self.problem.parameter_values.clone() {
            Some(values) => self.bind(values),
            None => self.bind_without_parameters(),
        }
    }
}

impl<'a> BoundSymbolicNonlinearProblem<'a> {
    /// Returns the immutable prepared object behind this binding.
    pub fn prepared(&self) -> &'a PreparedSymbolicNonlinearProblem {
        self.prepared
    }

    /// Returns the currently bound parameter values, if any.
    pub fn parameter_values(&self) -> Option<&DVector<f64>> {
        self.parameter_values
            .as_ref()
            .map(NonlinearParameterValues::as_vector)
    }
}

impl SymbolicNonlinearProblem {
    /// Builds a symbolic problem from parsed expressions.
    pub fn from_expressions(
        equations: Vec<Expr>,
        variables: Option<Vec<String>>,
        equation_parameters: Option<Vec<String>>,
        equation_parameter_values: Option<DVector<f64>>,
    ) -> Result<Self, SolveError> {
        Self::from_expressions_with_backend(
            equations,
            variables,
            equation_parameters,
            equation_parameter_values,
            SymbolicBackendConfig::default(),
        )
    }

    /// Builds a symbolic problem from parsed expressions and grouped symbolic options.
    pub fn from_expressions_with_options(
        equations: Vec<Expr>,
        options: SymbolicProblemOptions,
    ) -> Result<Self, SolveError> {
        Self::from_expressions_with_backend_and_policy(
            equations,
            options.variables,
            options.equation_parameters,
            options.equation_parameter_values,
            options.lambdify_execution_policy,
            options.backend_config,
        )
    }

    /// Builds a symbolic problem through the explicit backend-selection layer.
    ///
    /// This is the nonlinear dense analogue of the newer BVP path:
    /// the symbolic problem is first prepared in a backend-agnostic form, then
    /// the requested backend policy decides whether the callable provider should
    /// use lambdify or a linked compiled dense AOT backend.
    pub fn from_expressions_with_backend_selection(
        equations: Vec<Expr>,
        options: SymbolicProblemOptions,
        policy: SymbolicBackendSelectionPolicy,
        resolver: Option<&AotResolver>,
        aot_options: SymbolicDenseAotOptions,
    ) -> Result<Self, SolveError> {
        let preparation_started = Instant::now();
        let mut problem = Self::from_expressions_with_backend_and_policy(
            equations,
            options.variables,
            options.equation_parameters,
            options.equation_parameter_values,
            options.lambdify_execution_policy,
            SymbolicBackendConfig::lambdify(),
        )?;

        let selected = select_symbolic_nonlinear_backend(&problem, policy, resolver, aot_options);
        match selected.effective_backend {
            SelectedSymbolicNonlinearBackendKind::Lambdify => {
                problem.preparation_report.artifact_policy =
                    artifact_policy_for_backend_selection(policy);
                if policy == SymbolicBackendSelectionPolicy::PreferAotThenLambdify {
                    problem.preparation_report.artifact_action =
                        SymbolicArtifactAction::FallbackToLambdify;
                }
                problem.preparation_report.preparation_duration = preparation_started.elapsed();
                Ok(problem)
            }
            SelectedSymbolicNonlinearBackendKind::AotCompiled => {
                let prepared_key = selected
                    .prepared_aot_problem
                    .as_ref()
                    .map(PreparedSymbolicNonlinearAotProblem::problem_key)
                    .ok_or_else(|| {
                        SolveError::InvalidConfig(
                        "compiled nonlinear AOT selection did not include prepared problem data"
                            .to_string(),
                    )
                    })?;
                let Some(linked) = resolve_linked_dense_backend(&prepared_key) else {
                    return Err(SolveError::CompiledAotRuntimeUnavailable(format!(
                        "no linked dense nonlinear AOT runtime registered for problem key {}",
                        prepared_key
                    )));
                };
                let prepared_manifest = selected
                    .prepared_aot_problem
                    .as_ref()
                    .expect("prepared AOT key was just validated")
                    .manifest();
                drop(selected);
                problem.backend_config = SymbolicBackendConfig::aot();
                problem.backend = PreparedSymbolicBackend::from_linked_dense(
                    linked,
                    &problem.variables,
                    problem
                        .parameter_schema
                        .as_ref()
                        .map(|schema| schema.names()),
                );
                problem.preparation_report.artifact_policy =
                    artifact_policy_for_backend_selection(policy);
                problem.preparation_report.artifact_action = SymbolicArtifactAction::Reused;
                problem.preparation_report.artifact_key = Some(prepared_key);
                problem.preparation_report.generated_residual_jobs =
                    Some(prepared_manifest.functions.residual_chunks.len());
                problem.preparation_report.generated_jacobian_jobs =
                    Some(prepared_manifest.functions.jacobian_chunks.len());
                problem.preparation_report.effective_backend = SymbolicBackendKind::Aot;
                problem.preparation_report.preparation_duration = preparation_started.elapsed();
                Ok(problem)
            }
            SelectedSymbolicNonlinearBackendKind::AotRegisteredButNotBuilt => {
                Err(SolveError::InvalidConfig(
                    "dense nonlinear AOT backend is registered but not built".to_string(),
                ))
            }
            SelectedSymbolicNonlinearBackendKind::AotMissing => Err(SolveError::InvalidConfig(
                "dense nonlinear AOT backend was requested but no artifact was found".to_string(),
            )),
        }
    }

    /// Builds a symbolic problem from parsed expressions and explicit backend config.
    pub fn from_expressions_with_backend(
        equations: Vec<Expr>,
        variables: Option<Vec<String>>,
        equation_parameters: Option<Vec<String>>,
        equation_parameter_values: Option<DVector<f64>>,
        backend_config: SymbolicBackendConfig,
    ) -> Result<Self, SolveError> {
        Self::from_expressions_with_backend_and_policy(
            equations,
            variables,
            equation_parameters,
            equation_parameter_values,
            LambdifyExecutionPolicy::default(),
            backend_config,
        )
    }

    /// Builds a symbolic problem with an explicit prepared Lambdify execution policy.
    fn from_expressions_with_backend_and_policy(
        equations: Vec<Expr>,
        variables: Option<Vec<String>>,
        equation_parameters: Option<Vec<String>>,
        equation_parameter_values: Option<DVector<f64>>,
        lambdify_execution_policy: LambdifyExecutionPolicy,
        backend_config: SymbolicBackendConfig,
    ) -> Result<Self, SolveError> {
        let preparation_started = Instant::now();
        if equations.is_empty() {
            return Err(SolveError::InvalidConfig(
                "equation system must not be empty".to_string(),
            ));
        }

        let parameter_schema = equation_parameters
            .map(NonlinearParameterSchema::new)
            .transpose()?;

        let variables = match variables {
            Some(variables) => variables,
            None => {
                let mut args = equations
                    .iter()
                    .flat_map(|expr| expr.all_arguments_are_variables())
                    .collect::<Vec<_>>();
                args.sort();
                args.dedup();
                if let Some(schema) = &parameter_schema {
                    args.retain(|name| schema.index_of(name).is_none());
                }
                args
            }
        };

        validate_variable_names(&variables)?;
        if variables.is_empty() {
            return Err(SolveError::InvalidConfig(
                "failed to infer variables from symbolic equations".to_string(),
            ));
        }
        if variables.len() != equations.len() {
            return Err(SolveError::DimensionMismatch {
                expected: equations.len(),
                actual: variables.len(),
                context: "symbolic variables vs equations",
            });
        }

        if let Some(schema) = &parameter_schema {
            if let Some(variable) = variables
                .iter()
                .find(|variable| schema.index_of(variable).is_some())
            {
                return Err(SolveError::InvalidParameterSchema(format!(
                    "parameter name '{variable}' is also declared as a variable"
                )));
            }
        }

        let declared_names = variables
            .iter()
            .cloned()
            .chain(
                parameter_schema
                    .as_ref()
                    .into_iter()
                    .flat_map(|schema| schema.names().iter().cloned()),
            )
            .collect::<std::collections::HashSet<_>>();
        for (equation_index, equation) in equations.iter().enumerate() {
            if let Some(name) = equation
                .all_arguments_are_variables()
                .into_iter()
                .find(|name| !declared_names.contains(name))
            {
                return Err(SolveError::UndeclaredSymbol {
                    equation_index,
                    name,
                });
            }
        }

        let parameter_values = match (parameter_schema.as_ref(), equation_parameter_values) {
            (Some(schema), Some(values)) => Some(NonlinearParameterValues::new(schema, values)?),
            (Some(_), None) => None,
            (None, Some(_)) => {
                return Err(SolveError::InvalidParameterSchema(
                    "parameter values were supplied without parameter names".to_string(),
                ));
            }
            (None, None) => None,
        };
        let parameter_names = parameter_schema.as_ref().map(|schema| schema.names());

        let backend = PreparedSymbolicBackend::from_expressions(
            &equations,
            &variables,
            parameter_names,
            lambdify_execution_policy,
            &backend_config,
        )?;
        let symbolic_jacobian = backend
            .symbolic_jacobian()
            .map_or_else(Vec::new, <[Vec<Expr>]>::to_vec);
        let prepared_backend_kind = backend.kind();

        Ok(Self {
            backend_config,
            backend,
            equations,
            symbolic_jacobian,
            variables,
            parameter_schema,
            parameter_values,
            preparation_report: SymbolicPreparationReport::direct_lambdify(
                preparation_started.elapsed(),
                prepared_backend_kind,
            ),
        })
    }

    /// Builds a symbolic problem from equation strings.
    pub fn from_strings(
        equations: Vec<String>,
        variables: Option<Vec<String>>,
        equation_parameters: Option<Vec<String>>,
        equation_parameter_values: Option<DVector<f64>>,
    ) -> Result<Self, SolveError> {
        Self::from_strings_with_backend(
            equations,
            variables,
            equation_parameters,
            equation_parameter_values,
            SymbolicBackendConfig::default(),
        )
    }

    /// Builds a symbolic problem from equation strings and grouped symbolic options.
    pub fn from_strings_with_options(
        equations: Vec<String>,
        options: SymbolicProblemOptions,
    ) -> Result<Self, SolveError> {
        let expressions = equations
            .iter()
            .map(|equation| Expr::parse_expression(equation))
            .collect::<Vec<_>>();
        Self::from_expressions_with_options(expressions, options)
    }

    /// Builds a symbolic problem from equation strings through explicit backend selection.
    pub fn from_strings_with_backend_selection(
        equations: Vec<String>,
        options: SymbolicProblemOptions,
        policy: SymbolicBackendSelectionPolicy,
        resolver: Option<&AotResolver>,
        aot_options: SymbolicDenseAotOptions,
    ) -> Result<Self, SolveError> {
        let expressions = equations
            .iter()
            .map(|equation| Expr::parse_expression(equation))
            .collect::<Vec<_>>();
        Self::from_expressions_with_backend_selection(
            expressions,
            options,
            policy,
            resolver,
            aot_options,
        )
    }

    /// Builds a symbolic problem from equation strings and explicit backend config.
    pub fn from_strings_with_backend(
        equations: Vec<String>,
        variables: Option<Vec<String>>,
        equation_parameters: Option<Vec<String>>,
        equation_parameter_values: Option<DVector<f64>>,
        backend_config: SymbolicBackendConfig,
    ) -> Result<Self, SolveError> {
        let expressions = equations
            .iter()
            .map(|equation| Expr::parse_expression(equation))
            .collect::<Vec<_>>();
        Self::from_expressions_with_backend(
            expressions,
            variables,
            equation_parameters,
            equation_parameter_values,
            backend_config,
        )
    }

    /// Returns the variable names used by the symbolic system.
    pub fn variables(&self) -> &[String] {
        &self.variables
    }

    /// Returns the original symbolic equations.
    pub fn equations(&self) -> &[Expr] {
        &self.equations
    }

    /// Returns the symbolic dense Jacobian retained by the symbolic layer.
    pub fn symbolic_jacobian(&self) -> &[Vec<Expr>] {
        &self.symbolic_jacobian
    }

    /// Returns the symbolic backend configuration used to prepare the problem.
    pub fn backend_config(&self) -> &SymbolicBackendConfig {
        &self.backend_config
    }

    /// Returns immutable preparation/build telemetry for this symbolic provider.
    pub fn preparation_report(&self) -> &SymbolicPreparationReport {
        &self.preparation_report
    }

    /// Replaces preparation telemetry when an outer lifecycle wrapper adds
    /// backend-selection or artifact-build stages to the original report.
    pub(crate) fn replace_preparation_report(&mut self, report: SymbolicPreparationReport) {
        self.preparation_report = report;
    }

    /// Returns the effective prepared backend kind.
    pub fn backend_kind(&self) -> SymbolicBackendKind {
        self.backend.kind()
    }

    /// Returns the configured Lambdify execution policy, if Lambdify is active.
    pub fn lambdify_execution_policy(&self) -> Option<LambdifyExecutionPolicy> {
        self.backend.lambdify_execution_policy()
    }

    /// Builds a dense AOT-ready prepared problem from the symbolic nonlinear system.
    ///
    /// This is the narrow bridge from the nonlinear symbolic frontend into the
    /// generic codegen lifecycle. The returned value fixes:
    /// - parameter-first flattened input order,
    /// - symbolic residual and dense Jacobian sources,
    /// - runtime chunking choices for both outputs,
    /// - manifest-ready metadata such as function names and problem key.
    pub fn prepare_dense_aot_problem(
        &self,
        options: SymbolicDenseAotOptions,
    ) -> PreparedSymbolicNonlinearAotProblem<'_> {
        let variable_refs = self
            .variables
            .iter()
            .map(|name| name.as_str())
            .collect::<Vec<_>>();
        let parameter_refs = self.parameter_schema.as_ref().map(|schema| {
            schema
                .names()
                .iter()
                .map(|name| name.as_str())
                .collect::<Vec<_>>()
        });
        let mut flattened_input_names = Vec::new();
        if let Some(params) = &parameter_refs {
            flattened_input_names.extend(params.iter().copied());
        }
        flattened_input_names.extend(variable_refs.iter().copied());

        PreparedSymbolicNonlinearAotProblem {
            equations: &self.equations,
            symbolic_jacobian: &self.symbolic_jacobian,
            variable_refs,
            parameter_refs,
            flattened_input_names,
            residual_fn_name: "eval_nonlinear_residual".to_string(),
            jacobian_fn_name: "eval_nonlinear_jacobian".to_string(),
            residual_strategy: options.residual_strategy,
            jacobian_strategy: options.jacobian_strategy,
        }
    }

    /// Updates parameter values for parameterized equations.
    pub fn set_parameter_values(&mut self, values: DVector<f64>) -> Result<(), SolveError> {
        let schema = self.parameter_schema.as_ref().ok_or_else(|| {
            SolveError::InvalidParameterSchema(
                "cannot set parameter values because no parameter schema was declared".to_string(),
            )
        })?;
        let validated = NonlinearParameterValues::new(schema, values)?;
        self.parameter_values = Some(validated);
        Ok(())
    }

    /// Returns the ordered symbolic parameter schema, when one was declared.
    pub fn parameter_schema(&self) -> Option<&NonlinearParameterSchema> {
        self.parameter_schema.as_ref()
    }

    /// Returns the currently bound parameter values, when available.
    pub fn parameter_values(&self) -> Option<&DVector<f64>> {
        self.parameter_values
            .as_ref()
            .map(NonlinearParameterValues::as_vector)
    }

    /// Shared implementation of residual evaluation.
    fn residual_impl(&self, x: &DVector<f64>) -> Result<DVector<f64>, SolveError> {
        self.residual_impl_with_parameter_values(
            x,
            self.parameter_values
                .as_ref()
                .map(NonlinearParameterValues::as_vector),
        )
    }

    /// Evaluates the residual with an explicit immutable parameter binding.
    fn residual_impl_with_parameter_values(
        &self,
        x: &DVector<f64>,
        parameter_values: Option<&DVector<f64>>,
    ) -> Result<DVector<f64>, SolveError> {
        self.backend.residual(
            x,
            self.parameter_schema.as_ref().map(|schema| schema.names()),
            parameter_values,
            &self.variables,
        )
    }

    /// Shared implementation of Jacobian evaluation.
    fn jacobian_impl(&self, x: &DVector<f64>) -> Result<DMatrix<f64>, SolveError> {
        self.jacobian_impl_with_parameter_values(
            x,
            self.parameter_values
                .as_ref()
                .map(NonlinearParameterValues::as_vector),
        )
    }

    /// Evaluates the Jacobian with an explicit immutable parameter binding.
    fn jacobian_impl_with_parameter_values(
        &self,
        x: &DVector<f64>,
        parameter_values: Option<&DVector<f64>>,
    ) -> Result<DMatrix<f64>, SolveError> {
        self.backend.jacobian(
            x,
            self.parameter_schema.as_ref().map(|schema| schema.names()),
            parameter_values,
            &self.variables,
        )
    }
}

impl NonlinearProblem for SymbolicNonlinearProblem {
    /// Returns the number of unknowns in the symbolic system.
    fn dimension(&self) -> usize {
        self.variables.len()
    }

    /// Returns whether the selected symbolic backend can fill residual storage.
    fn supports_residual_into(&self) -> bool {
        self.backend.supports_residual_into()
    }

    /// Evaluates the symbolic residual vector.
    fn residual(&self, x: &DVector<f64>) -> Result<DVector<f64>, SolveError> {
        self.residual_impl(x)
    }

    /// Evaluates the symbolic residual into reusable storage.
    fn residual_into(&self, x: &DVector<f64>, out: &mut DVector<f64>) -> Result<(), SolveError> {
        self.backend.residual_into(
            x,
            self.parameter_schema.as_ref().map(|schema| schema.names()),
            self.parameter_values
                .as_ref()
                .map(NonlinearParameterValues::as_vector),
            &self.variables,
            out,
        )
    }
}

impl JacobianProvider for SymbolicNonlinearProblem {
    /// Evaluates the symbolic Jacobian matrix.
    fn jacobian(&self, x: &DVector<f64>) -> Result<DMatrix<f64>, SolveError> {
        self.jacobian_impl(x)
    }

    /// Returns whether the Lambdify backend can fill Jacobian storage directly.
    fn supports_jacobian_into(&self) -> bool {
        self.backend.supports_jacobian_into()
    }

    /// Evaluates the symbolic Jacobian into reusable storage.
    fn jacobian_into(&self, x: &DVector<f64>, out: &mut DMatrix<f64>) -> Result<(), SolveError> {
        self.backend.jacobian_into(
            x,
            self.parameter_schema.as_ref().map(|schema| schema.names()),
            self.parameter_values
                .as_ref()
                .map(NonlinearParameterValues::as_vector),
            &self.variables,
            out,
        )
    }
}

impl<'a> NonlinearProblem for BoundSymbolicNonlinearProblem<'a> {
    /// Returns the number of unknowns in the prepared symbolic system.
    fn dimension(&self) -> usize {
        self.prepared.problem.dimension()
    }

    /// Returns whether the prepared symbolic backend can fill residual storage.
    fn supports_residual_into(&self) -> bool {
        self.prepared.problem.backend.supports_residual_into()
    }

    /// Evaluates the residual using this view's immutable parameter binding.
    fn residual(&self, x: &DVector<f64>) -> Result<DVector<f64>, SolveError> {
        self.prepared
            .problem
            .residual_impl_with_parameter_values(x, self.parameter_values())
    }

    /// Evaluates the bound symbolic residual into reusable storage.
    fn residual_into(&self, x: &DVector<f64>, out: &mut DVector<f64>) -> Result<(), SolveError> {
        self.prepared.problem.backend.residual_into(
            x,
            self.prepared
                .problem
                .parameter_schema
                .as_ref()
                .map(|schema| schema.names()),
            self.parameter_values(),
            &self.prepared.problem.variables,
            out,
        )
    }
}

impl<'a> JacobianProvider for BoundSymbolicNonlinearProblem<'a> {
    /// Evaluates the Jacobian using this view's immutable parameter binding.
    fn jacobian(&self, x: &DVector<f64>) -> Result<DMatrix<f64>, SolveError> {
        self.prepared
            .problem
            .jacobian_impl_with_parameter_values(x, self.parameter_values())
    }

    /// Returns whether the bound Lambdify backend can fill Jacobian storage directly.
    fn supports_jacobian_into(&self) -> bool {
        self.prepared.problem.backend.supports_jacobian_into()
    }

    /// Evaluates the bound symbolic Jacobian into reusable storage.
    fn jacobian_into(&self, x: &DVector<f64>, out: &mut DMatrix<f64>) -> Result<(), SolveError> {
        self.prepared.problem.backend.jacobian_into(
            x,
            self.prepared
                .problem
                .parameter_schema
                .as_ref()
                .map(|schema| schema.names()),
            self.parameter_values(),
            &self.prepared.problem.variables,
            out,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::numerical::Nonlinear_systems::LM_Nielsen::NielsenLevenbergMarquardtMethod;
    use crate::numerical::Nonlinear_systems::LM_vanilla::LevenbergMarquardtMethod;
    use crate::numerical::Nonlinear_systems::NR_damped::DampedNewtonMethod;
    use crate::numerical::Nonlinear_systems::engine::{NewtonMethod, SolveOptions, SolverEngine};
    use crate::numerical::Nonlinear_systems::problem::Bounds;
    use crate::numerical::Nonlinear_systems::trust_region::*;
    use crate::symbolic::codegen::codegen_aot_resolution::AotResolver;
    use approx::assert_relative_eq;
    use std::collections::HashMap;
    use std::f64;

    fn elementary_problem() -> SymbolicNonlinearProblem {
        SymbolicNonlinearProblem::from_strings(
            vec!["x^2+y^2-10".to_string(), "x-y-4".to_string()],
            Some(vec!["x".to_string(), "y".to_string()]),
            None,
            None,
        )
        .expect("symbolic problem should build")
    }

    fn elementary_problem_with_options() -> SymbolicNonlinearProblem {
        SymbolicNonlinearProblem::from_strings_with_options(
            vec!["x^2+y^2-10".to_string(), "x-y-4".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_lambdify_backend(),
        )
        .expect("symbolic problem should build")
    }

    fn solve_elementary_with_bounds<M>(method: M) -> DVector<f64>
    where
        M: crate::numerical::Nonlinear_systems::engine::NonlinearMethod,
    {
        let options = SolveOptions {
            bounds: Some(Bounds::new(vec![(-10.0, 10.0), (-10.0, 10.0)]).expect("bounds")),
            ..SolveOptions::default()
        };
        SolverEngine::new(method, options)
            .solve(&elementary_problem(), DVector::from_vec(vec![1.0, 1.0]))
            .expect("solve should succeed")
            .x
    }

    fn chemistry_problem(dgm: f64) -> (SymbolicNonlinearProblem, Vec<String>) {
        let symbolic = Expr::Symbols("N0, N1, N2, Np, Lambda0, Lambda1");
        let d_g0 = Expr::Const(-450.0e3);
        let d_g1 = Expr::Const(-150.0e3);
        let d_g2 = Expr::Const(-50e3);
        let d_gm = Expr::Const(dgm);
        let n0 = symbolic[0].clone();
        let n1 = symbolic[1].clone();
        let n2 = symbolic[2].clone();
        let np = symbolic[3].clone();
        let lambda0 = symbolic[4].clone();
        let lambda1 = symbolic[5].clone();
        let rt = Expr::Const(8.314) * Expr::Const(273.15);

        let eq_mu = vec![
            lambda0.clone()
                + Expr::Const(2.0) * lambda1.clone()
                + (d_g0.clone() + rt.clone() * Expr::ln(n0.clone() / np.clone())) / d_gm.clone(),
            lambda0
                + lambda1.clone()
                + (d_g1 + rt.clone() * Expr::ln(n1.clone() / np.clone())) / d_gm.clone(),
            Expr::Const(2.0) * lambda1 + (d_g2 + rt * Expr::ln(n2.clone() / np.clone())) / d_gm,
        ];
        let eq_sum = vec![n0.clone() + n1.clone() + n2.clone() - np.clone()];
        let eq_comp = vec![
            n0.clone() + n1.clone() - Expr::Const(0.999),
            Expr::Const(2.0) * n0 + n1 + Expr::Const(2.0) * n2 - Expr::Const(1.501),
        ];

        let mut system = Vec::new();
        system.extend(eq_mu);
        system.extend(eq_sum);
        system.extend(eq_comp);
        let variables = symbolic.iter().map(|x| x.to_string()).collect::<Vec<_>>();
        (
            SymbolicNonlinearProblem::from_expressions(system, Some(variables.clone()), None, None)
                .expect("chemistry problem should build"),
            variables,
        )
    }

    fn assert_chemistry_constraints(solution: &DVector<f64>, variables: &[String], tol: f64) {
        let map = variables
            .iter()
            .zip(solution.iter())
            .map(|(k, v)| (k.clone(), *v))
            .collect::<HashMap<String, f64>>();
        let n0 = map["N0"];
        let n1 = map["N1"];
        let n2 = map["N2"];
        let np = map["Np"];
        assert!((n0 + n1 - 0.999).abs() < tol);
        assert!((n0 + n1 + n2 - np).abs() < tol);
        assert!((2.0 * n0 + n1 + 2.0 * n2 - 1.501).abs() < tol);
    }

    #[test]
    fn symbolic_problem_solves_from_expressions() {
        let problem = elementary_problem();
        let result = SolverEngine::new(
            crate::numerical::Nonlinear_systems::engine::NewtonMethod,
            SolveOptions::default(),
        )
        .solve(&problem, DVector::from_vec(vec![1.0, 1.0]))
        .expect("solve should succeed");
        assert_relative_eq!(result.x[0], 3.0, epsilon = 1e-8);
        assert_relative_eq!(result.x[1], -1.0, epsilon = 1e-8);
    }

    #[test]
    fn symbolic_problem_options_builds_problem_through_preferred_path() {
        let problem = elementary_problem_with_options();
        let result = SolverEngine::new(
            crate::numerical::Nonlinear_systems::engine::NewtonMethod,
            SolveOptions::default(),
        )
        .solve(&problem, DVector::from_vec(vec![1.0, 1.0]))
        .expect("solve should succeed");
        assert_relative_eq!(result.x[0], 3.0, epsilon = 1e-8);
        assert_relative_eq!(result.x[1], -1.0, epsilon = 1e-8);
    }

    #[test]
    fn prepared_problem_binds_independent_parameter_views() {
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            vec!["a*x-2".to_string(), "y-1".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string()]),
        )
        .expect("prepared problem should build");

        let first = prepared
            .bind_values(DVector::from_vec(vec![2.0]))
            .expect("first binding should validate");
        let second = prepared
            .bind_values(DVector::from_vec(vec![4.0]))
            .expect("second binding should validate");
        let x0 = DVector::from_vec(vec![0.0, 0.0]);

        let first_residual = first.residual(&x0).expect("first residual");
        let second_residual = second.residual(&x0).expect("second residual");
        assert_relative_eq!(first_residual[0], -2.0, epsilon = 1e-12);
        assert_relative_eq!(second_residual[0], -2.0, epsilon = 1e-12);
        assert_relative_eq!(
            first.jacobian(&x0).expect("first jacobian")[(0, 0)],
            2.0,
            epsilon = 1e-12
        );
        assert_relative_eq!(
            second.jacobian(&x0).expect("second jacobian")[(0, 0)],
            4.0,
            epsilon = 1e-12
        );
        assert_eq!(prepared.backend_kind(), SymbolicBackendKind::Lambdify);
        assert_eq!(first.prepared().variables(), &["x", "y"]);
    }

    #[test]
    fn lambdify_into_evaluations_match_owned_values_and_reuse_buffers() {
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            vec!["a*x^2+y-3".to_string(), "x-y".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string()]),
        )
        .expect("parameterized Lambdify problem should build");
        let bound = prepared
            .bind_values(DVector::from_vec(vec![2.0]))
            .expect("parameter binding should validate");
        let x = DVector::from_vec(vec![1.25, 0.75]);

        assert!(bound.supports_residual_into());
        assert!(bound.supports_jacobian_into());

        let expected_residual = bound.residual(&x).expect("owned residual");
        let expected_jacobian = bound.jacobian(&x).expect("owned Jacobian");
        let mut residual = DVector::zeros(2);
        let residual_ptr = residual.as_slice().as_ptr();
        let mut jacobian = DMatrix::zeros(2, 2);
        let jacobian_ptr = jacobian.as_slice().as_ptr();

        bound
            .residual_into(&x, &mut residual)
            .expect("residual_into should succeed");
        bound
            .jacobian_into(&x, &mut jacobian)
            .expect("jacobian_into should succeed");

        assert_eq!(residual, expected_residual);
        assert_eq!(jacobian, expected_jacobian);
        assert_eq!(residual.as_slice().as_ptr(), residual_ptr);
        assert_eq!(jacobian.as_slice().as_ptr(), jacobian_ptr);

        let second_x = DVector::from_vec(vec![0.5, -0.25]);
        bound
            .residual_into(&second_x, &mut residual)
            .expect("second residual_into should succeed");
        bound
            .jacobian_into(&second_x, &mut jacobian)
            .expect("second jacobian_into should succeed");
        assert_eq!(residual.as_slice().as_ptr(), residual_ptr);
        assert_eq!(jacobian.as_slice().as_ptr(), jacobian_ptr);
    }

    #[test]
    fn parameterized_lambdify_reuses_input_workspace_capacity() {
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            vec!["a*x^2+y-3".to_string(), "x-y".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string()]),
        )
        .expect("parameterized Lambdify problem should build");
        let bound = prepared
            .bind_values(DVector::from_vec(vec![2.0]))
            .expect("parameter binding should validate");
        let x = DVector::from_vec(vec![1.25, 0.75]);
        let mut residual = DVector::zeros(2);
        let mut jacobian = DMatrix::zeros(2, 2);

        bound
            .residual_into(&x, &mut residual)
            .expect("first parameterized residual should evaluate");
        bound
            .jacobian_into(&x, &mut jacobian)
            .expect("first parameterized Jacobian should evaluate");
        let first_capacity =
            crate::numerical::Nonlinear_systems::symbolic_legacy::lambdify_input_workspace_capacity(
            );

        for _ in 0..8 {
            bound
                .residual_into(&x, &mut residual)
                .expect("repeated parameterized residual should evaluate");
            bound
                .jacobian_into(&x, &mut jacobian)
                .expect("repeated parameterized Jacobian should evaluate");
        }

        let final_capacity =
            crate::numerical::Nonlinear_systems::symbolic_legacy::lambdify_input_workspace_capacity(
            );
        assert!(first_capacity >= 3);
        assert_eq!(final_capacity, first_capacity);
    }

    #[test]
    fn unparameterized_lambdify_into_evaluations_use_the_variable_schema() {
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            vec!["x^2+y".to_string(), "x-y".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_lambdify_backend(),
        )
        .expect("unparameterized Lambdify problem should build");
        let bound = prepared
            .bind_without_parameters()
            .expect("unparameterized problem should bind");
        let x = DVector::from_vec(vec![2.0, 0.5]);
        let mut residual = DVector::zeros(2);
        let mut jacobian = DMatrix::zeros(2, 2);

        bound
            .residual_into(&x, &mut residual)
            .expect("residual_into should succeed");
        bound
            .jacobian_into(&x, &mut jacobian)
            .expect("jacobian_into should succeed");

        assert_eq!(residual.as_slice(), &[4.5, 1.5]);
        assert_eq!(
            jacobian,
            DMatrix::from_row_slice(2, 2, &[4.0, 1.0, 1.0, -1.0])
        );
    }

    #[test]
    fn row_major_jacobian_adapter_preserves_rectangular_layout() {
        let row_major = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let mut column_major = vec![0.0; row_major.len()];
        copy_row_major_jacobian_into_column_major(&row_major, &mut column_major, 2, 3);

        assert_eq!(
            DMatrix::from_column_slice(2, 3, &column_major),
            DMatrix::from_row_slice(2, 3, &row_major)
        );
    }

    #[test]
    fn parallel_lambdify_matches_sequential_sparse_jacobian() {
        let variables = (0..8).map(|index| format!("x{index}")).collect::<Vec<_>>();
        let equations = (0..8)
            .map(|index| {
                let next = (index + 1) % 8;
                format!("a*x{index}^2+x{next}-1")
            })
            .collect::<Vec<_>>();
        let base_options = SymbolicProblemOptions::new()
            .with_variables(variables)
            .with_equation_parameters(vec!["a".to_string()]);
        let sequential = PreparedSymbolicNonlinearProblem::from_strings(
            equations.clone(),
            base_options
                .clone()
                .with_lambdify_execution_policy(LambdifyExecutionPolicy::Sequential),
        )
        .expect("sequential Lambdify problem should build");
        let parallel = PreparedSymbolicNonlinearProblem::from_strings(
            equations,
            base_options
                .with_lambdify_execution_policy(LambdifyExecutionPolicy::Parallel { min_work: 1 }),
        )
        .expect("parallel Lambdify problem should build");
        let sequential = sequential
            .bind_values(DVector::from_vec(vec![2.0]))
            .expect("sequential parameter binding should succeed");
        let parallel = parallel
            .bind_values(DVector::from_vec(vec![2.0]))
            .expect("parallel parameter binding should succeed");
        let x = DVector::from_iterator(8, (0..8).map(|index| 0.2 + index as f64 * 0.03));

        assert_eq!(
            sequential.prepared().lambdify_execution_policy(),
            Some(LambdifyExecutionPolicy::Sequential)
        );
        assert_eq!(
            parallel.prepared().lambdify_execution_policy(),
            Some(LambdifyExecutionPolicy::Parallel { min_work: 1 })
        );
        assert_eq!(
            sequential.residual(&x).expect("sequential residual"),
            parallel.residual(&x).expect("parallel residual")
        );
        assert_eq!(
            sequential.jacobian(&x).expect("sequential Jacobian"),
            parallel.jacobian(&x).expect("parallel Jacobian")
        );

        let mut sequential_jacobian = DMatrix::zeros(8, 8);
        let mut parallel_jacobian = DMatrix::zeros(8, 8);
        sequential
            .jacobian_into(&x, &mut sequential_jacobian)
            .expect("sequential Jacobian into");
        parallel
            .jacobian_into(&x, &mut parallel_jacobian)
            .expect("parallel Jacobian into");
        assert_eq!(sequential_jacobian, parallel_jacobian);
    }

    #[test]
    fn large_sparse_parallel_lambdify_is_deterministic_and_thread_safe() {
        const DIMENSION: usize = 64;
        let variables = (0..DIMENSION)
            .map(|index| format!("x{index}"))
            .collect::<Vec<_>>();
        let equations = (0..DIMENSION)
            .map(|index| {
                let current = format!("x{index}");
                let mut equation = format!("a*({current}^2-{:.17})", 1.0 + index as f64 * 0.01);
                if index > 0 {
                    equation.push_str(&format!("+0.08*x{}", index - 1));
                }
                if index + 1 < DIMENSION {
                    equation.push_str(&format!("+0.08*x{}", index + 1));
                }
                equation
            })
            .collect::<Vec<_>>();
        let options = |policy| {
            SymbolicProblemOptions::new()
                .with_variables(variables.clone())
                .with_equation_parameters(vec!["a".to_string()])
                .with_lambdify_execution_policy(policy)
        };
        let sequential_prepared = PreparedSymbolicNonlinearProblem::from_strings(
            equations.clone(),
            options(LambdifyExecutionPolicy::Sequential),
        )
        .expect("large sequential Lambdify problem should build");
        let sequential = sequential_prepared
            .bind_values(DVector::from_vec(vec![1.25]))
            .expect("large sequential binding should succeed");
        let parallel_prepared = std::sync::Arc::new(
            PreparedSymbolicNonlinearProblem::from_strings(
                equations.clone(),
                options(LambdifyExecutionPolicy::Parallel { min_work: 1 }),
            )
            .expect("large parallel Lambdify problem should build"),
        );
        let parallel = parallel_prepared
            .bind_values(DVector::from_vec(vec![1.25]))
            .expect("large parallel binding should succeed");
        let fallback_prepared = PreparedSymbolicNonlinearProblem::from_strings(
            equations,
            options(LambdifyExecutionPolicy::Parallel {
                min_work: usize::MAX,
            }),
        )
        .expect("threshold fallback problem should build");
        let fallback = fallback_prepared
            .bind_values(DVector::from_vec(vec![1.25]))
            .expect("threshold fallback binding should succeed");
        let point = DVector::from_iterator(
            DIMENSION,
            (0..DIMENSION).map(|index| 0.7 + index as f64 * 0.002),
        );
        let expected_residual = sequential.residual(&point).expect("sequential residual");
        let expected_jacobian = sequential.jacobian(&point).expect("sequential Jacobian");

        assert_eq!(
            parallel.residual(&point).expect("parallel residual"),
            expected_residual
        );
        let parallel_jacobian = parallel.jacobian(&point).expect("parallel Jacobian");
        assert_eq!(parallel_jacobian, expected_jacobian);
        assert_eq!(
            fallback.jacobian(&point).expect("fallback Jacobian"),
            expected_jacobian
        );
        for row in 0..DIMENSION {
            for column in 0..DIMENSION {
                if row.abs_diff(column) > 1 {
                    assert_eq!(parallel_jacobian[(row, column)], 0.0);
                }
            }
        }

        let mut repeated_jacobian = DMatrix::zeros(DIMENSION, DIMENSION);
        for _ in 0..4 {
            parallel
                .jacobian_into(&point, &mut repeated_jacobian)
                .expect("repeated parallel Jacobian");
            assert_eq!(repeated_jacobian, expected_jacobian);
        }

        std::thread::scope(|scope| {
            let handles = (0..4).map(|_| {
                let prepared = std::sync::Arc::clone(&parallel_prepared);
                let point = point.clone();
                scope.spawn(move || {
                    let bound = prepared
                        .bind_values(DVector::from_vec(vec![1.25]))
                        .expect("concurrent binding should succeed");
                    let mut residual = DVector::zeros(DIMENSION);
                    let mut jacobian = DMatrix::zeros(DIMENSION, DIMENSION);
                    bound
                        .residual_into(&point, &mut residual)
                        .expect("concurrent residual should succeed");
                    bound
                        .jacobian_into(&point, &mut jacobian)
                        .expect("concurrent Jacobian should succeed");
                    (residual, jacobian)
                })
            });
            for handle in handles {
                let (residual, jacobian) = handle.join().expect("concurrent worker should finish");
                assert_eq!(residual, expected_residual);
                assert_eq!(jacobian, expected_jacobian);
            }
        });
    }

    #[test]
    fn prepared_parallel_lambdify_matches_legacy_callback_values() {
        const DIMENSION: usize = 16;
        let variables = (0..DIMENSION)
            .map(|index| format!("x{index}"))
            .collect::<Vec<_>>();
        let equations = (0..DIMENSION)
            .map(|index| {
                let mut equation = format!("x{index}^2-1.0");
                if index > 0 {
                    equation.push_str(&format!("+0.08*x{}", index - 1));
                }
                if index + 1 < DIMENSION {
                    equation.push_str(&format!("+0.08*x{}", index + 1));
                }
                equation
            })
            .collect::<Vec<_>>();
        let expressions = equations
            .iter()
            .map(|equation| Expr::parse_expression(equation))
            .collect::<Vec<_>>();
        let mut legacy = crate::symbolic::symbolic_functions::Jacobian::new();
        legacy.set_vector_of_functions(expressions);
        legacy.set_variables(variables.iter().map(String::as_str).collect());
        legacy.calc_jacobian();
        legacy.lambdify_vector_funvector_DVector();
        legacy.lambdify_jacobian_DMatrix_parallel();

        let prepared_problem = PreparedSymbolicNonlinearProblem::from_strings(
            equations,
            SymbolicProblemOptions::new()
                .with_variables(variables)
                .with_lambdify_execution_policy(LambdifyExecutionPolicy::Parallel { min_work: 1 }),
        )
        .expect("prepared parity problem should build");
        let prepared = prepared_problem
            .bind_without_parameters()
            .expect("prepared parity problem should bind");
        let point = DVector::from_iterator(
            DIMENSION,
            (0..DIMENSION).map(|index| 0.75 + index as f64 * 0.01),
        );

        assert_eq!(
            prepared.residual(&point).expect("prepared residual"),
            (legacy.lambdified_function_DVector)(&point)
        );
        assert_eq!(
            prepared.jacobian(&point).expect("prepared Jacobian"),
            (legacy.lambdified_jacobian_DMatrix)(&point)
        );
    }

    #[test]
    fn parallel_lambdify_preserves_non_finite_error_semantics() {
        for policy in [
            LambdifyExecutionPolicy::Sequential,
            LambdifyExecutionPolicy::Parallel { min_work: 1 },
        ] {
            let prepared = PreparedSymbolicNonlinearProblem::from_strings(
                vec!["1/x".to_string()],
                SymbolicProblemOptions::new()
                    .with_variables(vec!["x".to_string()])
                    .with_lambdify_execution_policy(policy),
            )
            .expect("non-finite policy problem should build");
            let problem = prepared
                .bind_without_parameters()
                .expect("non-finite policy problem should bind");
            let zero = DVector::from_vec(vec![0.0]);

            assert!(matches!(
                problem.residual(&zero),
                Err(SolveError::ResidualEvaluation(_))
            ));
            assert!(matches!(
                problem.jacobian(&zero),
                Err(SolveError::JacobianEvaluation(_))
            ));
        }
    }

    #[test]
    fn parallel_lambdify_handles_empty_jacobian_columns() {
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            vec!["x0^2-1".to_string(), "2*x0+3".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x0".to_string(), "x1".to_string()])
                .with_lambdify_execution_policy(LambdifyExecutionPolicy::Parallel { min_work: 1 }),
        )
        .expect("empty-column problem should build");
        let problem = prepared
            .bind_without_parameters()
            .expect("empty-column problem should bind");
        let point = DVector::from_vec(vec![2.0, 7.0]);
        let jacobian = problem.jacobian(&point).expect("empty-column Jacobian");

        assert_eq!(
            jacobian,
            DMatrix::from_row_slice(2, 2, &[4.0, 0.0, 2.0, 0.0])
        );
        assert_eq!(
            problem.residual(&point).expect("empty-column residual")[1],
            7.0
        );

        let threshold_prepared = PreparedSymbolicNonlinearProblem::from_strings(
            vec!["0.00000000000001*x0".to_string(), "x0".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x0".to_string(), "x1".to_string()])
                .with_lambdify_execution_policy(LambdifyExecutionPolicy::Parallel { min_work: 1 }),
        )
        .expect("threshold problem should build");
        let threshold_problem = threshold_prepared
            .bind_without_parameters()
            .expect("threshold problem should bind");
        let threshold_jacobian = threshold_problem
            .jacobian(&point)
            .expect("threshold Jacobian");
        assert_eq!(
            threshold_jacobian,
            DMatrix::from_row_slice(2, 2, &[0.0, 0.0, 1.0, 0.0])
        );
    }

    #[test]
    fn parallel_lambdify_large_corpus_matches_sequential() {
        const DIMENSION: usize = 32;
        let variables = (0..DIMENSION)
            .map(|index| format!("x{index}"))
            .collect::<Vec<_>>();
        let targets = [
            (0..DIMENSION)
                .map(|index| 1.0 + index as f64 * 0.01)
                .collect::<Vec<_>>(),
            (0..DIMENSION)
                .map(|index| 0.2 + index as f64 * 0.001)
                .collect::<Vec<_>>(),
            (0..DIMENSION)
                .map(|index| 0.5 + index as f64 * 0.003)
                .collect::<Vec<_>>(),
        ];
        let equations_for = |corpus: usize| {
            (0..DIMENSION)
                .map(|index| {
                    let target = &targets[corpus];
                    let variable = format!("x{index}");
                    let mut equation = match corpus {
                        0 => format!("({variable}^2-{:.17})", target[index] * target[index]),
                        1 => {
                            let h2 = 1.0 / ((DIMENSION + 1) * (DIMENSION + 1)) as f64;
                            format!(
                                "2*({variable}-{:.17})+{h2:.17}*(exp({variable})-exp({:.17}))",
                                target[index], target[index]
                            )
                        }
                        _ => format!("({variable}^2-{:.17})", target[index] * target[index]),
                    };
                    let offsets = match corpus {
                        2 => (1..=5).collect::<Vec<_>>(),
                        _ => vec![1],
                    };
                    for offset in offsets {
                        let coefficient = match corpus {
                            0 => 0.08,
                            1 => -1.0,
                            _ => 0.01 / offset as f64,
                        };
                        if index >= offset {
                            equation.push_str(&format!(
                                "{coefficient:+.17}*(x{}-{:.17})",
                                index - offset,
                                target[index - offset]
                            ));
                        }
                        if index + offset < DIMENSION {
                            equation.push_str(&format!(
                                "{coefficient:+.17}*(x{}-{:.17})",
                                index + offset,
                                target[index + offset]
                            ));
                        }
                    }
                    equation
                })
                .collect::<Vec<_>>()
        };

        for corpus in 0..3 {
            let equations = equations_for(corpus);
            let sequential_prepared = PreparedSymbolicNonlinearProblem::from_strings(
                equations.clone(),
                SymbolicProblemOptions::new()
                    .with_variables(variables.clone())
                    .with_lambdify_execution_policy(LambdifyExecutionPolicy::Sequential),
            )
            .expect("corpus sequential problem should build");
            let parallel_prepared = PreparedSymbolicNonlinearProblem::from_strings(
                equations,
                SymbolicProblemOptions::new()
                    .with_variables(variables.clone())
                    .with_lambdify_execution_policy(LambdifyExecutionPolicy::Parallel {
                        min_work: 1,
                    }),
            )
            .expect("corpus parallel problem should build");
            let sequential = sequential_prepared
                .bind_without_parameters()
                .expect("corpus sequential problem should bind");
            let parallel = parallel_prepared
                .bind_without_parameters()
                .expect("corpus parallel problem should bind");
            let point = DVector::from_iterator(
                DIMENSION,
                targets[corpus].iter().copied().map(|value| value * 0.8),
            );
            assert_eq!(
                parallel.residual(&point).expect("corpus parallel residual"),
                sequential
                    .residual(&point)
                    .expect("corpus sequential residual")
            );
            assert_eq!(
                parallel.jacobian(&point).expect("corpus parallel Jacobian"),
                sequential
                    .jacobian(&point)
                    .expect("corpus sequential Jacobian")
            );
        }
    }

    #[test]
    fn prepared_lambdify_can_be_shared_by_independent_bound_views() {
        fn assert_send_sync<T: Send + Sync>() {}

        assert_send_sync::<PreparedSymbolicNonlinearProblem>();
        assert_send_sync::<BoundSymbolicNonlinearProblem<'static>>();

        let prepared = std::sync::Arc::new(
            PreparedSymbolicNonlinearProblem::from_strings(
                vec!["a*x-2".to_string(), "y-1".to_string()],
                SymbolicProblemOptions::new()
                    .with_variables(vec!["x".to_string(), "y".to_string()])
                    .with_equation_parameters(vec!["a".to_string()]),
            )
            .expect("shared Lambdify problem should build"),
        );

        std::thread::scope(|scope| {
            let handles = [2.0, 4.0].into_iter().map(|parameter| {
                let prepared = std::sync::Arc::clone(&prepared);
                scope.spawn(move || {
                    let bound = prepared
                        .bind_values(DVector::from_vec(vec![parameter]))
                        .expect("thread-local parameter binding should validate");
                    let x = DVector::from_vec(vec![0.5, 1.0]);
                    let residual = bound.residual(&x).expect("thread-local residual");
                    let jacobian = bound.jacobian(&x).expect("thread-local Jacobian");
                    (parameter, residual, jacobian)
                })
            });

            for handle in handles {
                let (parameter, residual, jacobian) = handle.join().expect("worker should finish");
                assert_eq!(residual[0], parameter * 0.5 - 2.0);
                assert_eq!(residual[1], 0.0);
                assert_eq!(jacobian[(0, 0)], parameter);
                assert_eq!(jacobian[(1, 1)], 1.0);
            }
        });
    }

    #[test]
    fn prepared_bound_views_can_solve_without_mutating_preparation() {
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            vec!["a*x-2".to_string(), "y-1".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string()]),
        )
        .expect("prepared problem should build");
        let options = SolveOptions {
            tolerance: 1e-12,
            ..SolveOptions::default()
        };

        let first = prepared
            .bind_values(DVector::from_vec(vec![2.0]))
            .expect("first binding should validate");
        let first_result = SolverEngine::new(NewtonMethod, options.clone())
            .solve(&first, DVector::from_vec(vec![0.0, 0.0]))
            .expect("first bound solve should succeed");
        assert_relative_eq!(first_result.x[0], 1.0, epsilon = 1e-10);
        assert_relative_eq!(first_result.x[1], 1.0, epsilon = 1e-10);

        let second = prepared
            .bind_values(DVector::from_vec(vec![4.0]))
            .expect("second binding should validate");
        let second_result = SolverEngine::new(NewtonMethod, options)
            .solve(&second, DVector::from_vec(vec![0.0, 0.0]))
            .expect("second bound solve should succeed");
        assert_relative_eq!(second_result.x[0], 0.5, epsilon = 1e-10);
        assert_relative_eq!(second_result.x[1], 1.0, epsilon = 1e-10);
        assert!(prepared.as_problem().parameter_values().is_none());
    }

    #[test]
    fn prepared_binding_rejects_wrong_schema_and_missing_values() {
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            vec!["a*x-1".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string()])
                .with_equation_parameters(vec!["a".to_string()]),
        )
        .expect("prepared problem should build");
        let other_schema = NonlinearParameterSchema::new(vec!["b".to_string()])
            .expect("other schema should build");
        let other_values =
            NonlinearParameterValues::new(&other_schema, DVector::from_vec(vec![2.0]))
                .expect("other values should validate");

        assert!(matches!(
            prepared.bind(other_values),
            Err(SolveError::ParameterSchemaMismatch(_))
        ));
        assert!(matches!(
            prepared.bind_without_parameters(),
            Err(SolveError::ParameterSchemaMismatch(_))
        ));
    }

    #[test]
    fn prepared_backend_selection_preserves_bind_then_solve_contract() {
        let resolver =
            AotResolver::new(crate::symbolic::codegen::codegen_aot_registry::AotRegistry::new());
        let prepared = PreparedSymbolicNonlinearProblem::from_strings_with_backend_selection(
            vec!["a*x-1".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string()])
                .with_equation_parameters(vec!["a".to_string()]),
            SymbolicBackendSelectionPolicy::PreferAotThenLambdify,
            Some(&resolver),
            SymbolicDenseAotOptions::default(),
        )
        .expect("prepared backend selection should fall back cleanly");
        let bound = prepared
            .bind_values(DVector::from_vec(vec![2.0]))
            .expect("binding should validate");

        let residual = bound
            .residual(&DVector::from_vec(vec![0.5]))
            .expect("bound residual should evaluate");
        assert_relative_eq!(residual[0], 0.0, epsilon = 1e-12);
        assert_eq!(prepared.backend_kind(), SymbolicBackendKind::Lambdify);
    }

    #[test]
    fn legacy_symbolic_constructor_matches_typed_options_route() {
        let equations = vec!["a*x+y-3".to_string(), "x-y".to_string()];
        let variables = vec!["x".to_string(), "y".to_string()];
        let parameters = vec!["a".to_string()];
        let values = DVector::from_vec(vec![2.0]);

        let legacy = SymbolicNonlinearProblem::from_strings(
            equations.clone(),
            Some(variables.clone()),
            Some(parameters.clone()),
            Some(values.clone()),
        )
        .expect("legacy constructor should remain usable");
        let typed = SymbolicNonlinearProblem::from_strings_with_options(
            equations,
            SymbolicProblemOptions::new()
                .with_variables(variables)
                .with_equation_parameters(parameters)
                .with_equation_parameter_values(values),
        )
        .expect("typed options constructor should succeed");

        let point = DVector::from_vec(vec![1.25, 0.75]);
        assert_eq!(legacy.backend_kind(), typed.backend_kind());
        assert_eq!(legacy.variables(), typed.variables());
        assert_eq!(legacy.parameter_schema(), typed.parameter_schema());
        assert_eq!(legacy.parameter_values(), typed.parameter_values());
        assert_relative_eq!(
            legacy.residual(&point).expect("legacy residual").as_slice(),
            typed.residual(&point).expect("typed residual").as_slice(),
            epsilon = 1e-12
        );
        assert_relative_eq!(
            legacy.jacobian(&point).expect("legacy Jacobian"),
            typed.jacobian(&point).expect("typed Jacobian"),
            epsilon = 1e-12
        );
    }

    #[test]
    fn symbolic_problem_uses_lambdify_backend_by_default() {
        let problem = elementary_problem();
        assert_eq!(problem.backend_kind(), SymbolicBackendKind::Lambdify);
        assert_eq!(problem.backend_config(), &SymbolicBackendConfig::lambdify());
    }

    #[test]
    fn symbolic_problem_rejects_unwired_aot_backend_for_now() {
        let result = SymbolicNonlinearProblem::from_strings_with_backend(
            vec!["x^2+y^2-10".to_string(), "x-y-4".to_string()],
            Some(vec!["x".to_string(), "y".to_string()]),
            None,
            None,
            SymbolicBackendConfig::aot(),
        );

        match result {
            Err(SolveError::InvalidConfig(message)) => {
                assert!(message.contains("AOT backend"));
            }
            Err(other) => panic!("expected InvalidConfig, got {other:?}"),
            Ok(_) => panic!("AOT backend is not wired yet"),
        }
    }

    #[test]
    fn symbolic_problem_with_parameters_keeps_backend_and_evaluates() {
        let symbolic = Expr::Symbols("x, y, a");
        let x = symbolic[0].clone();
        let y = symbolic[1].clone();
        let a = symbolic[2].clone();
        let problem = SymbolicNonlinearProblem::from_expressions_with_options(
            vec![a.clone() * x.clone() + y.clone() - Expr::Const(3.0), x - y],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string()])
                .with_equation_parameter_values(DVector::from_vec(vec![2.0])),
        )
        .expect("parameterized symbolic problem should build");

        assert_eq!(problem.backend_kind(), SymbolicBackendKind::Lambdify);

        let x0 = DVector::from_vec(vec![1.0, 1.0]);
        let residual = problem.residual(&x0).expect("residual");
        let jacobian = problem.jacobian(&x0).expect("jacobian");

        assert_relative_eq!(residual[0], 0.0, epsilon = 1e-12);
        assert_relative_eq!(residual[1], 0.0, epsilon = 1e-12);
        assert_relative_eq!(jacobian[(0, 0)], 2.0, epsilon = 1e-12);
        assert_relative_eq!(jacobian[(0, 1)], 1.0, epsilon = 1e-12);
        assert_relative_eq!(jacobian[(1, 0)], 1.0, epsilon = 1e-12);
        assert_relative_eq!(jacobian[(1, 1)], -1.0, epsilon = 1e-12);
    }

    #[test]
    fn parameter_schema_preserves_order_and_supports_index_lookup() {
        let schema = NonlinearParameterSchema::new(vec!["beta".to_string(), "alpha".to_string()])
            .expect("schema");

        assert_eq!(schema.names(), ["beta", "alpha"]);
        assert_eq!(schema.index_of("beta"), Some(0));
        assert_eq!(schema.index_of("alpha"), Some(1));
        assert_eq!(schema.index_of("gamma"), None);

        let values = NonlinearParameterValues::new(&schema, DVector::from_vec(vec![2.5, -4.0]))
            .expect("values");
        assert_eq!(values.get(0), Some(2.5));
        assert_eq!(values.get(1), Some(-4.0));
    }

    #[test]
    fn parameter_update_changes_residual_and_jacobian_without_rebuilding() {
        let mut problem = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["a*x+y-3".to_string(), "x-y".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string()])
                .with_equation_parameter_values(DVector::from_vec(vec![2.0])),
        )
        .expect("parameterized problem");
        let x = DVector::from_vec(vec![1.0, 1.0]);

        let first_residual = problem.residual(&x).expect("first residual");
        let first_jacobian = problem.jacobian(&x).expect("first jacobian");
        assert_relative_eq!(first_residual[0], 0.0, epsilon = 1e-12);
        assert_relative_eq!(first_jacobian[(0, 0)], 2.0, epsilon = 1e-12);

        let schema_before = problem.parameter_schema().cloned().expect("schema");
        let symbolic_jacobian_before = problem.symbolic_jacobian().to_vec();
        let prepared_before = problem.prepare_dense_aot_problem(SymbolicDenseAotOptions::default());
        let artifact_key_before = prepared_before.problem_key().to_string();
        let input_names_before = prepared_before.manifest().io.input_names.clone();

        problem
            .set_parameter_values(DVector::from_vec(vec![4.0]))
            .expect("parameter update");
        let second_residual = problem.residual(&x).expect("second residual");
        let second_jacobian = problem.jacobian(&x).expect("second jacobian");

        assert_relative_eq!(second_residual[0], 2.0, epsilon = 1e-12);
        assert_relative_eq!(second_jacobian[(0, 0)], 4.0, epsilon = 1e-12);
        assert_eq!(problem.parameter_schema(), Some(&schema_before));
        assert_eq!(
            problem.symbolic_jacobian(),
            symbolic_jacobian_before.as_slice()
        );
        assert_eq!(
            problem.parameter_values().expect("bound values").as_slice(),
            &[4.0]
        );

        let prepared_after = problem.prepare_dense_aot_problem(SymbolicDenseAotOptions::default());
        assert_eq!(prepared_after.problem_key(), artifact_key_before);
        assert_eq!(prepared_after.manifest().io.input_names, input_names_before);
    }

    #[test]
    fn invalid_parameter_update_is_atomic_and_rejects_non_finite_values() {
        let mut problem = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["a*x+y-3".to_string(), "x-y".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string()])
                .with_equation_parameter_values(DVector::from_vec(vec![2.0])),
        )
        .expect("parameterized problem");

        let dimension_error = problem
            .set_parameter_values(DVector::from_vec(vec![1.0, 2.0]))
            .expect_err("wrong parameter length");
        assert!(matches!(
            dimension_error,
            SolveError::DimensionMismatch {
                context: "nonlinear parameter values",
                ..
            }
        ));
        assert_eq!(
            problem.parameter_values().expect("old values").as_slice(),
            &[2.0]
        );

        let finite_error = problem
            .set_parameter_values(DVector::from_vec(vec![f64::NAN]))
            .expect_err("non-finite parameter");
        assert!(matches!(
            finite_error,
            SolveError::NonFiniteParameterValue { index: 0, .. }
        ));
        assert_eq!(
            problem.parameter_values().expect("old values").as_slice(),
            &[2.0]
        );
    }

    #[test]
    fn parameter_schema_is_required_for_parameter_values_and_validated_at_build() {
        let duplicate = NonlinearParameterSchema::new(vec!["a".to_string(), "a".to_string()])
            .expect_err("duplicate schema should fail");
        assert!(matches!(duplicate, SolveError::InvalidParameterSchema(_)));

        let collision = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["a".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["a".to_string()])
                .with_equation_parameters(vec!["a".to_string()])
                .with_equation_parameter_values(DVector::from_vec(vec![1.0])),
        )
        .err()
        .expect("variable/parameter collision should fail");
        assert!(matches!(collision, SolveError::InvalidParameterSchema(_)));

        let no_schema = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["x".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string()])
                .with_equation_parameter_values(DVector::from_vec(vec![1.0])),
        )
        .err()
        .expect("values without schema should fail");
        assert!(matches!(no_schema, SolveError::InvalidParameterSchema(_)));

        let mut unbound = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["a*x".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string()])
                .with_equation_parameters(vec!["a".to_string()]),
        )
        .expect("a parameterized problem may be prepared before binding");
        let unbound_error = unbound
            .residual(&DVector::from_vec(vec![2.0]))
            .expect_err("unbound parameters must not use a non-parameter closure");
        assert!(matches!(
            unbound_error,
            SolveError::InvalidParameterSchema(_)
        ));

        let undeclared = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["x+q".to_string()],
            SymbolicProblemOptions::new().with_variables(vec!["x".to_string()]),
        )
        .err()
        .expect("undeclared symbols should fail validation");
        assert!(matches!(
            undeclared,
            SolveError::UndeclaredSymbol {
                equation_index: 0,
                name
            } if name == "q"
        ));

        let duplicate_variables = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["x".to_string(), "x".to_string()],
            SymbolicProblemOptions::new().with_variables(vec!["x".to_string(), "x".to_string()]),
        )
        .err()
        .expect("duplicate variables should fail validation");
        assert!(matches!(
            duplicate_variables,
            SolveError::InvalidVariableSchema(_)
        ));

        let empty_variable = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["x".to_string()],
            SymbolicProblemOptions::new().with_variables(vec![" ".to_string()]),
        )
        .err()
        .expect("empty variables should fail validation");
        assert!(matches!(
            empty_variable,
            SolveError::InvalidVariableSchema(_)
        ));
    }

    #[test]
    fn parameters_are_excluded_when_variables_are_inferred() {
        let problem = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["a*x+y-3".to_string(), "x-y".to_string()],
            SymbolicProblemOptions::new()
                .with_equation_parameters(vec!["a".to_string()])
                .with_equation_parameter_values(DVector::from_vec(vec![2.0])),
        )
        .expect("parameterized problem with inferred variables");

        assert_eq!(problem.variables(), ["x", "y"]);
        assert_eq!(
            problem
                .residual(&DVector::from_vec(vec![1.0, 1.0]))
                .expect("residual")[0],
            0.0
        );
    }

    fn central_difference_jacobian(
        problem: &SymbolicNonlinearProblem,
        x: &DVector<f64>,
        step: f64,
    ) -> DMatrix<f64> {
        let baseline = problem.dimension();
        let mut jacobian = DMatrix::zeros(baseline, baseline);
        for column in 0..baseline {
            let mut plus = x.clone();
            let mut minus = x.clone();
            plus[column] += step;
            minus[column] -= step;
            let f_plus = problem.residual(&plus).expect("plus residual");
            let f_minus = problem.residual(&minus).expect("minus residual");
            for row in 0..baseline {
                jacobian[(row, column)] = (f_plus[row] - f_minus[row]) / (2.0 * step);
            }
        }
        jacobian
    }

    #[test]
    fn symbolic_jacobian_matches_central_difference_for_multiple_parameter_scales() {
        let mut problem = SymbolicNonlinearProblem::from_strings_with_options(
            vec!["a*sin(x)+exp(b*y)-c".to_string(), "x*y+a*x^2-b".to_string()],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string(), "b".to_string(), "c".to_string()])
                .with_equation_parameter_values(DVector::from_vec(vec![1.3, -0.4, 0.7])),
        )
        .expect("parameterized nonlinear problem");

        let cases = [
            (DVector::from_vec(vec![0.2, -0.3]), 1e-6),
            (DVector::from_vec(vec![0.01, -0.0002]), 1e-6),
        ];
        let parameter_sets = [
            DVector::from_vec(vec![1.3, -0.4, 0.7]),
            DVector::from_vec(vec![1e-3, 2e3, 0.5]),
        ];

        for ((x, step), parameters) in cases.into_iter().zip(parameter_sets) {
            problem
                .set_parameter_values(parameters)
                .expect("parameter update");
            let symbolic = problem.jacobian(&x).expect("symbolic jacobian");
            let finite_difference = central_difference_jacobian(&problem, &x, step);
            for row in 0..symbolic.nrows() {
                for column in 0..symbolic.ncols() {
                    let difference =
                        (symbolic[(row, column)] - finite_difference[(row, column)]).abs();
                    let scale = 1.0
                        + symbolic[(row, column)].abs()
                        + finite_difference[(row, column)].abs();
                    assert!(
                        difference <= 2e-5 * scale,
                        "Jacobian mismatch at ({row}, {column}): symbolic={} finite_difference={} diff={difference}",
                        symbolic[(row, column)],
                        finite_difference[(row, column)]
                    );
                }
            }
        }
    }

    #[test]
    fn symbolic_problem_prepares_dense_aot_bridge_with_variable_input_order() {
        let problem = elementary_problem_with_options();
        let prepared = problem.prepare_dense_aot_problem(SymbolicDenseAotOptions::default());

        assert_eq!(prepared.flattened_input_names(), &["x", "y"]);
        assert_eq!(prepared.residual_len(), 2);
        assert_eq!(prepared.jacobian_shape(), (2, 2));
        assert_eq!(
            prepared.as_prepared_problem().backend_kind,
            BackendKind::Aot
        );
        assert_eq!(
            prepared.as_prepared_problem().matrix_backend,
            MatrixBackend::Dense
        );
    }

    #[test]
    fn symbolic_problem_prepares_dense_aot_bridge_with_parameter_first_order() {
        let symbolic = Expr::Symbols("x, y, a");
        let x = symbolic[0].clone();
        let y = symbolic[1].clone();
        let a = symbolic[2].clone();
        let problem = SymbolicNonlinearProblem::from_expressions_with_options(
            vec![a.clone() * x.clone() + y.clone() - Expr::Const(3.0), x - y],
            SymbolicProblemOptions::new()
                .with_variables(vec!["x".to_string(), "y".to_string()])
                .with_equation_parameters(vec!["a".to_string()])
                .with_equation_parameter_values(DVector::from_vec(vec![2.0])),
        )
        .expect("parameterized symbolic problem should build");

        let prepared = problem.prepare_dense_aot_problem(SymbolicDenseAotOptions::default());
        assert_eq!(prepared.flattened_input_names(), &["a", "x", "y"]);
        assert!(!prepared.problem_key().is_empty());
        assert_eq!(prepared.manifest().io.input_names, vec!["a", "x", "y"]);
    }

    #[test]
    fn symbolic_problem_solves_from_strings() {
        let result = SolverEngine::new(
            crate::numerical::Nonlinear_systems::engine::NewtonMethod,
            SolveOptions::default(),
        )
        .solve(&elementary_problem(), DVector::from_vec(vec![1.0, 1.0]))
        .expect("solve should succeed");
        assert_relative_eq!(result.x[0], 3.0, epsilon = 1e-8);
        assert_relative_eq!(result.x[1], -1.0, epsilon = 1e-8);
    }

    #[test]
    fn various_nonlinear_equations_simple() {
        let problem = SymbolicNonlinearProblem::from_strings(
            vec!["x+y-100".to_string(), "1/x - 1/y - 1/200".to_string()],
            Some(vec!["x".to_string(), "y".to_string()]),
            None,
            None,
        )
        .expect("problem should build");
        let result = SolverEngine::new(
            crate::numerical::Nonlinear_systems::engine::NewtonMethod,
            SolveOptions::default(),
        )
        .solve(&problem, DVector::from_vec(vec![1.0, 1.0]))
        .expect("solve should succeed");
        let x = -50.0 * (f64::sqrt(17.0) - 5.0);
        let y = 50.0 * (f64::sqrt(17.0) - 3.0);
        assert_relative_eq!(result.x[0], x, epsilon = 1e-3);
        assert_relative_eq!(result.x[1], y, epsilon = 1e-3);
    }

    #[test]
    fn symbolic_damped_method_respects_bounds() {
        let solution = solve_elementary_with_bounds(DampedNewtonMethod::default());
        assert_relative_eq!(solution[0], 3.0, epsilon = 1e-6);
        assert_relative_eq!(solution[1], -1.0, epsilon = 1e-6);
    }

    #[test]
    fn symbolic_lm_method_solves_elementary_problem() {
        let solution = solve_elementary_with_bounds(LevenbergMarquardtMethod::default());
        assert_relative_eq!(solution[0], 3.0, epsilon = 1e-6);
        assert_relative_eq!(solution[1], -1.0, epsilon = 1e-6);
    }

    #[test]
    fn symbolic_trust_region_method_solves_elementary_problem() {
        let solution = solve_elementary_with_bounds(TrustRegionMethod::default());
        assert_relative_eq!(solution[0], 3.0, epsilon = 1e-6);
        assert_relative_eq!(solution[1], -1.0, epsilon = 1e-6);
    }

    #[test]
    fn chemistry_problem_solves_with_lm() {
        let (problem, variables) = chemistry_problem(8.314 * 450e4);
        let bounds = Bounds::new(vec![
            (1e-40, 2.0),
            (1e-40, 2.0),
            (1e-40, 2.0),
            (1e-40, 10.0),
            (-1e-1, 1e-2),
            (-1e-1, 1e-2),
        ])
        .expect("bounds");
        let options = SolveOptions {
            tolerance: 2.0e-3,
            max_iterations: 130,
            bounds: Some(bounds),
            ..SolveOptions::default()
        };
        let method = LevenbergMarquardtMethod {
            increase_factor: 11.0,
            decrease_factor: 9.0,
            ..LevenbergMarquardtMethod::default()
        };
        let result = SolverEngine::new(method, options)
            .solve(
                &problem,
                DVector::from_vec(vec![0.9, 0.9, 0.9, 0.6, 0.0, 0.0]),
            )
            .expect("solve should succeed");
        assert_chemistry_constraints(&result.x, &variables, 8e-3);
    }

    #[test]
    fn chemistry_problem_solves_with_nielsen_lm() {
        let (problem, variables) = chemistry_problem(8.314 * 60e5);
        let bounds = Bounds::new(vec![
            (1e-40, 2.0),
            (1e-40, 2.0),
            (1e-40, 2.0),
            (1e-40, 10.0),
            (-10000.0, 1e6),
            (-100000.0, 1e6),
        ])
        .expect("bounds");
        let options = SolveOptions {
            tolerance: 2.0e-3,
            max_iterations: 130,
            bounds: Some(bounds),
            ..SolveOptions::default()
        };
        let result = SolverEngine::new(NielsenLevenbergMarquardtMethod::default(), options)
            .solve(
                &problem,
                DVector::from_vec(vec![0.9, 0.9, 0.9, 0.6, 0.0, 0.0]),
            )
            .expect("solve should succeed");
        assert_chemistry_constraints(&result.x, &variables, 8e-3);
    }
}