RustedSciThe 0.4.20

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
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
//! Orchestration layer over generated chunk functions.
//!
//! This module is the bridge between:
//! - low-level generated chunk functions of shape `fn(&[f64], &mut [f64])`,
//! - and solver-facing residual / Jacobian evaluators.
//!
//! Current scope:
//! - sequential orchestration,
//! - parallel orchestration with deterministic chunk joining,
//! - no bundle loading yet.
//!
//! Chunk size matters a lot for runtime performance.
//!
//! Very small chunks are easy to parallelize, but they can still be slow in
//! practice because the runtime spends too much time scheduling work instead of
//! evaluating math. For large residual/Jacobian problems it is usually better
//! to use fewer, heavier chunks:
//! - each chunk does more useful arithmetic,
//! - there are fewer rayon tasks to spawn,
//! - chunk-local CSE has more expressions to reuse,
//! - memory locality is usually better.
//!
//! In other words, parallel work should be coarse enough to amortize runtime
//! overhead, but not so coarse that only one or two workers do all the work.
//! A practical rule of thumb is:
//! - start with several chunks per worker thread,
//! - then increase chunk size for large systems until scheduling overhead stops
//!   dominating,
//! - keep sequential execution available for small systems where parallelism is
//!   more expensive than the math itself.
//!
//! The goal is to replace ad-hoc manual harness code with production-shaped
//! execution objects while keeping the implementation simple and race-free.
//!
//! Planned next steps:
//! - lower-allocation parallel execution into disjoint output slices,
//! - integration with generated-module loading / bundle lifecycle,
//! - orchestration helpers specialized for residual and sparse Jacobian tasks.

use crate::somelinalg::banded::banded_assembly::BandedAssembly;
use crate::symbolic::codegen::codegen_runtime_api::{
    BandedJacobianRuntimePlan, DenseJacobianRuntimePlan, ResidualChunkingStrategy,
    ResidualRuntimePlan, SparseJacobianRuntimePlan,
    recommended_residual_chunking_for_auto_parallelism,
    recommended_row_chunking_for_auto_parallelism,
};
use crate::symbolic::codegen::codegen_tasks::{SparseChunkingStrategy, SparseExprEntry};
use faer::sparse::SparseColMat;
use nalgebra::DMatrix;
use rayon::{join, scope};
use std::ops::Range;
use std::sync::OnceLock;
use std::time::Instant;

// Runtime parallelism must be chosen from measured scheduling overhead rather
// than from one developer machine.  The unit-cost estimate is intentionally
// small and conservative: if the generated scalar operations are heavier than
// this, Auto will become more willing to parallelize on that workload after the
// join-overhead calibration moves the threshold down.
const DEFAULT_ESTIMATED_UNIT_COST_NS: f64 = 5.0;
const DEFAULT_PARALLEL_OVERHEAD_SAFETY_FACTOR: f64 = 2.0;

/// Cached process-local measurement of raw rayon join overhead on the current machine.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RayonOverheadBaseline {
    /// Number of rayon workers visible to the current process.
    pub workers: usize,
    /// Median overhead of a two-way `rayon::join` with no-op closures.
    pub join2_ns: f64,
    /// Median overhead of a four-way nested `rayon::join` tree with no-op closures.
    pub join4_ns: f64,
}

/// Auto-tuned runtime recommendation for parallel executor configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutoParallelRecommendation {
    /// Whether runtime parallel execution is expected to amortize scheduling cost.
    pub should_parallelize: bool,
    /// Recommended grouped residual job count.
    pub residual_jobs: usize,
    /// Recommended grouped sparse-Jacobian job count.
    pub sparse_jobs: usize,
    /// Minimum useful work per parallel job derived from the measured machine overhead.
    pub min_work_per_job: usize,
    /// Number of workers observed during calibration.
    pub workers: usize,
    /// Residual callback workload diagnostics.
    pub residual_stage: AutoParallelStagePlan,
    /// Sparse/Banded Jacobian callback workload diagnostics.
    pub sparse_stage: AutoParallelStagePlan,
}

/// Why `Auto` accepted or rejected parallel execution for one callback stage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoParallelDecisionReason {
    /// There is no work for this callback stage.
    NoWork,
    /// The generated artifact has only one chunk or the current machine can use
    /// only one useful grouped job, so there is nothing meaningful to schedule.
    SingleChunkOrJob,
    /// The whole stage is too small to amortize measured rayon scheduling cost.
    TotalWorkTooSmall,
    /// Grouped jobs would be too light.
    WorkPerJobTooSmall,
    /// Individual generated chunks would be too light; this is the usual sign
    /// of over-fragmented generated code.
    WorkPerChunkTooSmall,
    /// The stage is large and coarse enough to run in parallel.
    ParallelCandidate,
}

impl AutoParallelDecisionReason {
    /// Short stable label for logs and story-table diagnostics.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::NoWork => "no_work",
            Self::SingleChunkOrJob => "single_chunk_or_job",
            Self::TotalWorkTooSmall => "total_work_too_small",
            Self::WorkPerJobTooSmall => "work_per_job_too_small",
            Self::WorkPerChunkTooSmall => "work_per_chunk_too_small",
            Self::ParallelCandidate => "parallel_candidate",
        }
    }
}

/// Per-stage workload diagnostics used by the `Auto` execution policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutoParallelStagePlan {
    /// Total scalar outputs/values represented by this stage.
    pub total_work: usize,
    /// Number of generated chunks available before grouped runtime scheduling.
    pub chunk_count: usize,
    /// Number of grouped runtime jobs selected for this stage.
    pub jobs: usize,
    /// Integer work per grouped runtime job.
    pub work_per_job: usize,
    /// Integer work per generated chunk.
    pub work_per_chunk: usize,
    /// Minimum useful work per job derived from measured machine overhead.
    pub min_work_per_job: usize,
    /// Decision reason for this stage.
    pub reason: AutoParallelDecisionReason,
}

/// High-level machine-aware execution mode chosen by the `Auto` parallel policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoExecutionMode {
    /// Keep runtime execution sequential because the measured machine overhead
    /// is expected to dominate the available work.
    Sequential,
    /// Use runtime parallel execution with the recommended grouped jobs.
    Parallel,
}

/// Full machine-aware recommendation for sparse residual/Jacobian runtime work.
///
/// This is the production-shaped contract for `Auto`:
/// - whether execution should stay sequential or go parallel,
/// - how residuals should be chunked if a new compiled artifact is generated,
/// - how sparse Jacobian values should be chunked,
/// - and which grouped runtime job counts should be used if the problem is
///   already compiled and only runtime binding is being selected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SparseAutoParallelPlan {
    /// Final high-level execution decision.
    pub execution_mode: AutoExecutionMode,
    /// Recommended residual chunking for future code generation.
    pub residual_chunking: ResidualChunkingStrategy,
    /// Recommended sparse-Jacobian chunking for future code generation.
    pub sparse_chunking: SparseChunkingStrategy,
    /// Runtime grouped-job recommendation for already prepared/compiled plans.
    pub executor_config: Option<ParallelExecutorConfig>,
    /// Minimum useful work per job derived from the measured machine overhead.
    pub min_work_per_job: usize,
    /// Number of workers observed during calibration.
    pub workers: usize,
    /// Residual callback workload diagnostics.
    pub residual_stage: AutoParallelStagePlan,
    /// Sparse/Banded Jacobian callback workload diagnostics.
    pub sparse_stage: AutoParallelStagePlan,
}

fn measure_rayon_overhead_baseline() -> RayonOverheadBaseline {
    const ITERS: usize = 10_000;
    const SAMPLES: usize = 7;

    let median_per_iter = |timings: Vec<f64>| -> f64 {
        let mut sorted = timings;
        sorted.sort_by(|lhs, rhs| lhs.partial_cmp(rhs).unwrap_or(std::cmp::Ordering::Equal));
        sorted[sorted.len() / 2]
    };

    let seq_samples: Vec<f64> = (0..SAMPLES)
        .map(|_| {
            let start = Instant::now();
            for _ in 0..ITERS {
                std::hint::black_box(0u64);
            }
            start.elapsed().as_secs_f64() * 1e9 / ITERS as f64
        })
        .collect();

    let join2_samples: Vec<f64> = (0..SAMPLES)
        .map(|_| {
            let start = Instant::now();
            for _ in 0..ITERS {
                join(|| std::hint::black_box(0u64), || std::hint::black_box(0u64));
            }
            start.elapsed().as_secs_f64() * 1e9 / ITERS as f64
        })
        .collect();

    let join4_samples: Vec<f64> = (0..SAMPLES)
        .map(|_| {
            let start = Instant::now();
            for _ in 0..ITERS {
                join(
                    || join(|| std::hint::black_box(0u64), || std::hint::black_box(0u64)),
                    || join(|| std::hint::black_box(0u64), || std::hint::black_box(0u64)),
                );
            }
            start.elapsed().as_secs_f64() * 1e9 / ITERS as f64
        })
        .collect();

    let seq_ns = median_per_iter(seq_samples);
    let join2_ns = (median_per_iter(join2_samples) - seq_ns).max(0.0);
    let join4_ns = (median_per_iter(join4_samples) - seq_ns).max(join2_ns);

    RayonOverheadBaseline {
        workers: rayon::current_num_threads().max(1),
        join2_ns,
        join4_ns,
    }
}

/// Returns a cached measurement of raw rayon join overhead for the current process.
pub fn rayon_overhead_baseline() -> RayonOverheadBaseline {
    static BASELINE: OnceLock<RayonOverheadBaseline> = OnceLock::new();
    *BASELINE.get_or_init(measure_rayon_overhead_baseline)
}

fn min_work_per_job_from_baseline(baseline: RayonOverheadBaseline) -> usize {
    ((baseline.join4_ns * DEFAULT_PARALLEL_OVERHEAD_SAFETY_FACTOR / DEFAULT_ESTIMATED_UNIT_COST_NS)
        .ceil() as usize)
        .max(1)
}

/// Returns the calibrated minimum useful work for one parallel runtime job.
///
/// This is shared with the IVP callback dispatcher so `Auto` uses the same
/// machine-local calibration as generated BVP/AOT plans instead of carrying a
/// second fixed worker threshold.
pub fn machine_min_work_per_parallel_job() -> usize {
    min_work_per_job_from_baseline(rayon_overhead_baseline())
}

fn work_per_group(total_work: usize, group_count: usize) -> usize {
    if group_count == 0 {
        0
    } else {
        total_work / group_count
    }
}

fn auto_parallel_fallback_for_workload(
    total_work: usize,
    chunk_count: usize,
    job_count: usize,
) -> bool {
    if job_count <= 1 || chunk_count <= 1 {
        return true;
    }

    let min_work_per_job = min_work_per_job_from_baseline(rayon_overhead_baseline());
    let min_total_work = min_work_per_job.saturating_mul(2);

    total_work < min_total_work
        || work_per_group(total_work, job_count) < min_work_per_job
        || work_per_group(total_work, chunk_count) < min_work_per_job
}

fn auto_parallel_stage_plan(
    total_work: usize,
    chunk_count: usize,
    job_count: usize,
    min_work_per_job: usize,
) -> AutoParallelStagePlan {
    let work_per_job = work_per_group(total_work, job_count);
    let work_per_chunk = work_per_group(total_work, chunk_count);
    let min_total_work = min_work_per_job.saturating_mul(2);
    let reason = if total_work == 0 {
        AutoParallelDecisionReason::NoWork
    } else if job_count <= 1 || chunk_count <= 1 {
        AutoParallelDecisionReason::SingleChunkOrJob
    } else if total_work < min_total_work {
        AutoParallelDecisionReason::TotalWorkTooSmall
    } else if work_per_job < min_work_per_job {
        AutoParallelDecisionReason::WorkPerJobTooSmall
    } else if work_per_chunk < min_work_per_job {
        AutoParallelDecisionReason::WorkPerChunkTooSmall
    } else {
        AutoParallelDecisionReason::ParallelCandidate
    };

    AutoParallelStagePlan {
        total_work,
        chunk_count,
        jobs: job_count,
        work_per_job,
        work_per_chunk,
        min_work_per_job,
        reason,
    }
}

fn recommended_job_count_for_workload(
    total_work: usize,
    chunk_count: usize,
    min_work_per_job: usize,
    workers: usize,
) -> usize {
    if chunk_count <= 1 || total_work < min_work_per_job.saturating_mul(2) {
        return 1;
    }

    let max_useful_jobs = (total_work / min_work_per_job).max(1);
    workers.min(chunk_count).min(max_useful_jobs).max(1)
}

/// Recommends whether runtime execution should stay sequential or go parallel,
/// and, if parallel, how many grouped residual/sparse jobs should be prepared.
pub fn auto_parallel_recommendation(
    residual_work: usize,
    residual_chunk_count: usize,
    sparse_work: usize,
    sparse_chunk_count: usize,
) -> AutoParallelRecommendation {
    let baseline = rayon_overhead_baseline();
    let min_work_per_job = min_work_per_job_from_baseline(baseline);
    let residual_jobs = recommended_job_count_for_workload(
        residual_work,
        residual_chunk_count,
        min_work_per_job,
        baseline.workers,
    );
    let sparse_jobs = recommended_job_count_for_workload(
        sparse_work,
        sparse_chunk_count,
        min_work_per_job,
        baseline.workers,
    );
    let residual_stage = auto_parallel_stage_plan(
        residual_work,
        residual_chunk_count,
        residual_jobs,
        min_work_per_job,
    );
    let sparse_stage = auto_parallel_stage_plan(
        sparse_work,
        sparse_chunk_count,
        sparse_jobs,
        min_work_per_job,
    );

    AutoParallelRecommendation {
        should_parallelize: matches!(
            residual_stage.reason,
            AutoParallelDecisionReason::ParallelCandidate
        ) || matches!(
            sparse_stage.reason,
            AutoParallelDecisionReason::ParallelCandidate
        ),
        residual_jobs,
        sparse_jobs,
        min_work_per_job,
        workers: baseline.workers,
        residual_stage,
        sparse_stage,
    }
}

/// Builds a machine-aware parallel config for compiled/runtime execution.
///
/// Returns `None` when the current machine and workload suggest that the
/// sequential path is still cheaper than runtime parallelization.
pub fn auto_parallel_executor_config(
    residual_work: usize,
    residual_chunk_count: usize,
    sparse_work: usize,
    sparse_chunk_count: usize,
) -> Option<ParallelExecutorConfig> {
    let recommendation = auto_parallel_recommendation(
        residual_work,
        residual_chunk_count,
        sparse_work,
        sparse_chunk_count,
    );
    if !recommendation.should_parallelize {
        return None;
    }

    Some(ParallelExecutorConfig {
        jobs_per_worker: 1,
        max_residual_jobs: Some(recommendation.residual_jobs.max(1)),
        max_sparse_jobs: Some(recommendation.sparse_jobs.max(1)),
        fallback_policy: ParallelFallbackPolicy::Never,
    })
}

fn residual_chunk_count(total_outputs: usize, strategy: ResidualChunkingStrategy) -> usize {
    match strategy {
        ResidualChunkingStrategy::Whole => usize::from(total_outputs > 0),
        ResidualChunkingStrategy::ByTargetChunkCount { target_chunks } => total_outputs
            .max(1)
            .div_ceil(total_outputs.max(1).div_ceil(target_chunks).max(1)),
        ResidualChunkingStrategy::ByOutputCount {
            max_outputs_per_chunk,
        } => total_outputs.max(1).div_ceil(max_outputs_per_chunk.max(1)),
    }
}

fn sparse_chunk_count(total_rows: usize, strategy: SparseChunkingStrategy) -> usize {
    match strategy {
        SparseChunkingStrategy::Whole => usize::from(total_rows > 0),
        SparseChunkingStrategy::ByTargetChunkCount { target_chunks } => total_rows
            .max(1)
            .div_ceil(total_rows.max(1).div_ceil(target_chunks).max(1)),
        SparseChunkingStrategy::ByNonZeroCount { .. } => 1,
        SparseChunkingStrategy::ByRowCount { rows_per_chunk } => {
            total_rows.max(1).div_ceil(rows_per_chunk.max(1))
        }
    }
}

/// Builds a complete `Auto` recommendation for sparse residual/Jacobian work.
///
/// This helper combines three inputs:
/// - measured machine-specific rayon overhead,
/// - coarse problem-size characteristics,
/// - and conservative per-worker chunking heuristics.
///
/// The returned plan can be used in two different scenarios:
/// - generation time: use `residual_chunking` / `sparse_chunking`;
/// - runtime binding of an already compiled artifact: use `executor_config`.
pub fn recommended_sparse_auto_parallel_plan(
    residual_work: usize,
    sparse_rows: usize,
    sparse_work: usize,
) -> SparseAutoParallelPlan {
    let baseline = rayon_overhead_baseline();
    let min_work_per_job = min_work_per_job_from_baseline(baseline);

    if residual_work == 0 || sparse_rows == 0 || sparse_work == 0 {
        let residual_stage = auto_parallel_stage_plan(residual_work, 0, 1, min_work_per_job);
        let sparse_stage = auto_parallel_stage_plan(sparse_work, 0, 1, min_work_per_job);
        return SparseAutoParallelPlan {
            execution_mode: AutoExecutionMode::Sequential,
            residual_chunking: ResidualChunkingStrategy::Whole,
            sparse_chunking: SparseChunkingStrategy::Whole,
            executor_config: None,
            min_work_per_job,
            workers: baseline.workers,
            residual_stage,
            sparse_stage,
        };
    }

    let residual_chunking = recommended_residual_chunking_for_auto_parallelism(residual_work);
    let sparse_chunking = recommended_row_chunking_for_auto_parallelism(sparse_rows);
    let recommendation = auto_parallel_recommendation(
        residual_work,
        residual_chunk_count(residual_work, residual_chunking),
        sparse_work,
        sparse_chunk_count(sparse_rows, sparse_chunking),
    );

    if !recommendation.should_parallelize {
        return SparseAutoParallelPlan {
            execution_mode: AutoExecutionMode::Sequential,
            residual_chunking: ResidualChunkingStrategy::Whole,
            sparse_chunking: SparseChunkingStrategy::Whole,
            executor_config: None,
            min_work_per_job: recommendation.min_work_per_job,
            workers: recommendation.workers,
            residual_stage: recommendation.residual_stage,
            sparse_stage: recommendation.sparse_stage,
        };
    }

    SparseAutoParallelPlan {
        execution_mode: AutoExecutionMode::Parallel,
        residual_chunking,
        sparse_chunking,
        executor_config: Some(ParallelExecutorConfig {
            jobs_per_worker: 1,
            max_residual_jobs: Some(recommendation.residual_jobs.max(1)),
            max_sparse_jobs: Some(recommendation.sparse_jobs.max(1)),
            fallback_policy: ParallelFallbackPolicy::Never,
        }),
        min_work_per_job: recommendation.min_work_per_job,
        workers: recommendation.workers,
        residual_stage: recommendation.residual_stage,
        sparse_stage: recommendation.sparse_stage,
    }
}

fn contiguous_job_ranges(len: usize, max_jobs: usize) -> Vec<Range<usize>> {
    if len == 0 {
        return Vec::new();
    }

    let target_jobs = len.min(max_jobs.max(1));
    let items_per_job = len.div_ceil(target_jobs);
    let mut ranges = Vec::with_capacity(target_jobs);
    let mut start = 0usize;

    while start < len {
        let end = (start + items_per_job).min(len);
        ranges.push(start..end);
        start = end;
    }

    ranges
}

fn borrowed_sparse_entries(
    owned_entries: &[(usize, usize, crate::symbolic::symbolic_engine::Expr)],
) -> Vec<SparseExprEntry<'_>> {
    owned_entries
        .iter()
        .map(|(row, col, expr)| SparseExprEntry {
            row: *row,
            col: *col,
            expr,
        })
        .collect()
}

fn contiguous_weighted_job_ranges(weights: &[usize], max_jobs: usize) -> Vec<Range<usize>> {
    if weights.is_empty() {
        return Vec::new();
    }

    let len = weights.len();
    let target_jobs = len.min(max_jobs.max(1));
    if target_jobs == 1 {
        return vec![0..len];
    }

    let normalized_weights: Vec<usize> = weights.iter().map(|weight| (*weight).max(1)).collect();
    let total_weight: usize = normalized_weights.iter().sum();
    if total_weight == 0 {
        return contiguous_job_ranges(len, target_jobs);
    }

    let mut prefix = Vec::with_capacity(len + 1);
    prefix.push(0usize);
    for weight in &normalized_weights {
        let next = prefix.last().copied().unwrap_or(0) + *weight;
        prefix.push(next);
    }

    let mut ranges = Vec::with_capacity(target_jobs);
    let mut start = 0usize;

    for job_index in 1..target_jobs {
        let min_end = start + 1;
        let max_end = len - (target_jobs - job_index);
        let target_prefix = total_weight.saturating_mul(job_index).div_ceil(target_jobs);

        let mut end = min_end;
        while end < max_end && prefix[end] < target_prefix {
            end += 1;
        }

        ranges.push(start..end);
        start = end;
    }

    ranges.push(start..len);
    ranges
}

/// Signature shared by generated chunk functions emitted by the current AOT
/// pipeline.
pub type GeneratedChunkFn = fn(&[f64], &mut [f64]);

/// Policy that decides when a parallel executor should fall back to the
/// sequential path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParallelFallbackPolicy {
    /// Use built-in heuristics tuned for the current implementation.
    Auto,
    /// Never fall back automatically. This is mainly useful for experiments
    /// and benchmarking the true parallel path.
    Never,
    /// Fall back when the total residual output count or sparse nnz count is
    /// below the user-provided thresholds.
    Thresholds {
        min_residual_outputs: usize,
        min_sparse_values: usize,
    },
}

impl Default for ParallelFallbackPolicy {
    fn default() -> Self {
        Self::Auto
    }
}

/// User-tunable configuration for runtime parallel executors.
///
/// The defaults keep the current production-oriented heuristics, but callers
/// can override them if they want to:
/// - force the true parallel path for benchmarking,
/// - lower or raise fallback thresholds for a specific workload,
/// - or choose how many grouped jobs are created relative to rayon workers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParallelExecutorConfig {
    /// How many grouped jobs to prepare per rayon worker thread.
    pub jobs_per_worker: usize,
    /// Optional explicit residual job count override used instead of the
    /// worker-based heuristic.
    pub max_residual_jobs: Option<usize>,
    /// Optional explicit sparse Jacobian job count override used instead of the
    /// worker-based heuristic.
    pub max_sparse_jobs: Option<usize>,
    /// Sequential fallback policy.
    pub fallback_policy: ParallelFallbackPolicy,
}

impl Default for ParallelExecutorConfig {
    fn default() -> Self {
        Self {
            jobs_per_worker: 1,
            max_residual_jobs: None,
            max_sparse_jobs: None,
            fallback_policy: ParallelFallbackPolicy::Auto,
        }
    }
}

impl ParallelExecutorConfig {
    fn worker_jobs(self) -> usize {
        let workers = rayon::current_num_threads().max(1);
        workers.saturating_mul(self.jobs_per_worker.max(1))
    }

    fn residual_jobs(self) -> usize {
        self.max_residual_jobs
            .unwrap_or_else(|| self.worker_jobs())
            .max(1)
    }

    fn sparse_jobs(self) -> usize {
        self.max_sparse_jobs
            .unwrap_or_else(|| self.worker_jobs())
            .max(1)
    }

    fn residual_fallback(self, output_len: usize, chunk_count: usize, job_count: usize) -> bool {
        if job_count <= 1 {
            return true;
        }

        match self.fallback_policy {
            ParallelFallbackPolicy::Never => false,
            ParallelFallbackPolicy::Auto => {
                auto_parallel_fallback_for_workload(output_len, chunk_count, job_count)
            }
            ParallelFallbackPolicy::Thresholds {
                min_residual_outputs,
                ..
            } => output_len < min_residual_outputs,
        }
    }

    fn sparse_fallback(self, nnz: usize, chunk_count: usize, job_count: usize) -> bool {
        if job_count <= 1 {
            return true;
        }

        match self.fallback_policy {
            ParallelFallbackPolicy::Never => false,
            ParallelFallbackPolicy::Auto => {
                auto_parallel_fallback_for_workload(nnz, chunk_count, job_count)
            }
            ParallelFallbackPolicy::Thresholds {
                min_sparse_values, ..
            } => nnz < min_sparse_values,
        }
    }
}

/// Binding between one residual chunk plan and one generated function.
#[derive(Clone, Copy, Debug)]
pub struct ResidualChunkBinding<'a> {
    pub fn_name: &'a str,
    pub output_offset: usize,
    pub output_len: usize,
    pub eval: GeneratedChunkFn,
}

/// Binding between one sparse Jacobian-values chunk plan and one generated
/// function.
#[derive(Clone, Copy, Debug)]
pub struct SparseJacobianChunkBinding<'a> {
    pub fn_name: &'a str,
    pub value_offset: usize,
    pub value_len: usize,
    pub eval: GeneratedChunkFn,
}

/// Binding between one banded Jacobian-values chunk plan and one generated
/// function.
#[derive(Clone, Copy, Debug)]
pub struct BandedJacobianChunkBinding<'a> {
    pub fn_name: &'a str,
    pub value_offset: usize,
    pub value_len: usize,
    pub eval: GeneratedChunkFn,
}

/// Binding between one dense Jacobian chunk plan and one generated function.
#[derive(Clone, Copy, Debug)]
pub struct DenseJacobianChunkBinding<'a> {
    pub fn_name: &'a str,
    pub value_offset: usize,
    pub value_len: usize,
    pub eval: GeneratedChunkFn,
}

/// Sequential executor for residual chunks.
///
/// This is intentionally the simplest production-shaped execution object:
/// - generated chunks are called in order,
/// - each chunk writes into its own output slice,
/// - there is no shared mutable state between chunks beyond the caller-owned
///   residual buffer.
pub struct SequentialResidualExecutor<'a> {
    plan: &'a ResidualRuntimePlan<'a>,
    chunks: Vec<ResidualChunkBinding<'a>>,
}

impl<'a> SequentialResidualExecutor<'a> {
    /// Creates a sequential residual executor.
    pub fn new(plan: &'a ResidualRuntimePlan<'a>, chunks: Vec<ResidualChunkBinding<'a>>) -> Self {
        assert_eq!(
            plan.chunks.len(),
            chunks.len(),
            "residual chunk binding count must match runtime plan"
        );

        for (planned, bound) in plan.chunks.iter().zip(chunks.iter()) {
            assert_eq!(
                planned.output_offset, bound.output_offset,
                "residual chunk output offset mismatch for {}",
                bound.fn_name
            );
            assert_eq!(
                planned.residuals.len(),
                bound.output_len,
                "residual chunk output length mismatch for {}",
                bound.fn_name
            );
        }

        Self { plan, chunks }
    }

    /// Evaluates all residual chunks into a caller-provided output slice.
    pub fn eval_into(&self, args: &[f64], out: &mut [f64]) {
        assert!(
            out.len() >= self.plan.output_len,
            "expected at least {} residual output slots, got {}",
            self.plan.output_len,
            out.len()
        );

        for chunk in &self.chunks {
            let start = chunk.output_offset;
            let end = start + chunk.output_len;
            (chunk.eval)(args, &mut out[start..end]);
        }
    }

    /// Evaluates all residual chunks and returns the full residual vector.
    pub fn eval(&self, args: &[f64]) -> Vec<f64> {
        let mut out = vec![0.0; self.plan.output_len];
        self.eval_into(args, &mut out);
        out
    }
}

/// Sequential executor for sparse Jacobian value chunks.
///
/// It computes the explicit sparse values in global solver order and can
/// assemble the final `SparseColMat` using the structure stored in the runtime
/// plan.
pub struct SequentialSparseJacobianExecutor<'a> {
    plan: &'a SparseJacobianRuntimePlan<'a>,
    chunks: Vec<SparseJacobianChunkBinding<'a>>,
}

impl<'a> SequentialSparseJacobianExecutor<'a> {
    /// Creates a sequential sparse Jacobian executor.
    pub fn new(
        plan: &'a SparseJacobianRuntimePlan<'a>,
        chunks: Vec<SparseJacobianChunkBinding<'a>>,
    ) -> Self {
        assert_eq!(
            plan.chunks.len(),
            chunks.len(),
            "sparse Jacobian chunk binding count must match runtime plan"
        );

        for (planned, bound) in plan.chunks.iter().zip(chunks.iter()) {
            assert_eq!(
                planned.value_offset, bound.value_offset,
                "sparse Jacobian chunk value offset mismatch for {}",
                bound.fn_name
            );
            assert_eq!(
                planned.entries.len(),
                bound.value_len,
                "sparse Jacobian chunk length mismatch for {}",
                bound.fn_name
            );
        }

        Self { plan, chunks }
    }

    /// Evaluates all sparse Jacobian chunks into a caller-provided values
    /// buffer following the global explicit entry order.
    pub fn eval_values_into(&self, args: &[f64], values_out: &mut [f64]) {
        assert!(
            values_out.len() >= self.plan.nnz(),
            "expected at least {} Jacobian value slots, got {}",
            self.plan.nnz(),
            values_out.len()
        );

        for chunk in &self.chunks {
            let start = chunk.value_offset;
            let end = start + chunk.value_len;
            (chunk.eval)(args, &mut values_out[start..end]);
        }
    }

    /// Evaluates all sparse Jacobian chunks and returns explicit non-zero
    /// values in global solver order.
    pub fn eval_values(&self, args: &[f64]) -> Vec<f64> {
        let mut values = vec![0.0; self.plan.nnz()];
        self.eval_values_into(args, &mut values);
        values
    }

    /// Evaluates all sparse Jacobian chunks and assembles the final
    /// `SparseColMat`.
    pub fn eval_sparse_col_mat(&self, args: &[f64]) -> SparseColMat<usize, f64> {
        let values = self.eval_values(args);
        self.plan.assemble_sparse_col_mat(values.as_slice())
    }
}

/// Sequential executor for banded Jacobian value chunks.
///
/// It computes the banded values in the global diagonal-major order and can
/// assemble the final native `BandedAssembly` using the structure stored in
/// the runtime plan.
pub struct SequentialBandedJacobianExecutor<'a> {
    plan: &'a BandedJacobianRuntimePlan<'a>,
    chunks: Vec<BandedJacobianChunkBinding<'a>>,
}

impl<'a> SequentialBandedJacobianExecutor<'a> {
    /// Creates a sequential banded Jacobian executor.
    pub fn new(
        plan: &'a BandedJacobianRuntimePlan<'a>,
        chunks: Vec<BandedJacobianChunkBinding<'a>>,
    ) -> Self {
        assert_eq!(
            plan.chunks.len(),
            chunks.len(),
            "banded Jacobian chunk binding count must match runtime plan"
        );

        for (planned, bound) in plan.chunks.iter().zip(chunks.iter()) {
            assert_eq!(
                planned.value_offset, bound.value_offset,
                "banded Jacobian chunk value offset mismatch for {}",
                bound.fn_name
            );
            assert_eq!(
                planned.entries.len(),
                bound.value_len,
                "banded Jacobian chunk length mismatch for {}",
                bound.fn_name
            );
        }

        Self { plan, chunks }
    }

    /// Evaluates all banded Jacobian chunks into a caller-provided values
    /// buffer.
    pub fn eval_values_into(&self, args: &[f64], values_out: &mut [f64]) {
        assert!(
            values_out.len() >= self.plan.nnz(),
            "expected at least {} banded Jacobian value slots, got {}",
            self.plan.nnz(),
            values_out.len()
        );

        for chunk in &self.chunks {
            let start = chunk.value_offset;
            let end = start + chunk.value_len;
            (chunk.eval)(args, &mut values_out[start..end]);
        }
    }

    /// Evaluates all banded Jacobian chunks and returns explicit values in
    /// diagonal-major order.
    pub fn eval_values(&self, args: &[f64]) -> Vec<f64> {
        let mut values = vec![0.0; self.plan.nnz()];
        self.eval_values_into(args, &mut values);
        values
    }

    /// Evaluates all banded Jacobian chunks and assembles the final native
    /// `BandedAssembly`.
    pub fn eval_banded_assembly(&self, args: &[f64]) -> BandedAssembly {
        let values = self.eval_values(args);
        self.plan.assemble_banded_assembly(values.as_slice())
    }
}

/// Sequential executor for dense Jacobian row chunks.
///
/// Dense Jacobian chunks write row-major values into disjoint slices of a
/// caller-provided flat output buffer and can then be assembled into a
/// `nalgebra::DMatrix`.
pub struct SequentialDenseJacobianExecutor<'a> {
    plan: &'a DenseJacobianRuntimePlan<'a>,
    chunks: Vec<DenseJacobianChunkBinding<'a>>,
}

impl<'a> SequentialDenseJacobianExecutor<'a> {
    /// Creates a sequential dense Jacobian executor.
    pub fn new(
        plan: &'a DenseJacobianRuntimePlan<'a>,
        chunks: Vec<DenseJacobianChunkBinding<'a>>,
    ) -> Self {
        assert_eq!(
            plan.chunks.len(),
            chunks.len(),
            "dense Jacobian chunk binding count must match runtime plan"
        );

        for (planned, bound) in plan.chunks.iter().zip(chunks.iter()) {
            assert_eq!(
                planned.value_offset, bound.value_offset,
                "dense Jacobian chunk value offset mismatch for {}",
                bound.fn_name
            );
            assert_eq!(
                planned.value_range().len(),
                bound.value_len,
                "dense Jacobian chunk length mismatch for {}",
                bound.fn_name
            );
        }

        Self { plan, chunks }
    }

    /// Evaluates all dense Jacobian chunks into a caller-provided flat
    /// row-major output buffer.
    pub fn eval_values_into(&self, args: &[f64], values_out: &mut [f64]) {
        assert!(
            values_out.len() >= self.plan.len(),
            "expected at least {} dense Jacobian value slots, got {}",
            self.plan.len(),
            values_out.len()
        );

        for chunk in &self.chunks {
            let start = chunk.value_offset;
            let end = start + chunk.value_len;
            (chunk.eval)(args, &mut values_out[start..end]);
        }
    }

    /// Evaluates all dense Jacobian chunks and returns row-major values.
    pub fn eval_values(&self, args: &[f64]) -> Vec<f64> {
        let mut values = vec![0.0; self.plan.len()];
        self.eval_values_into(args, &mut values);
        values
    }

    /// Evaluates all dense Jacobian chunks and assembles the final matrix.
    pub fn eval_dense_matrix(&self, args: &[f64]) -> DMatrix<f64> {
        let values = self.eval_values(args);
        self.plan.assemble_dense_matrix(values.as_slice())
    }
}

/// Parallel executor for dense Jacobian row chunks.
///
/// Dense Jacobian chunks write row-major values into disjoint slices of one
/// flat output buffer and can then be assembled into a `DMatrix<f64>`.
pub struct ParallelDenseJacobianExecutor<'a> {
    plan: &'a DenseJacobianRuntimePlan<'a>,
    chunks: Vec<DenseJacobianChunkBinding<'a>>,
    job_ranges: Vec<Range<usize>>,
    job_value_ranges: Vec<Range<usize>>,
    use_sequential_fallback: bool,
    config: ParallelExecutorConfig,
}

impl<'a> ParallelDenseJacobianExecutor<'a> {
    pub fn new(
        plan: &'a DenseJacobianRuntimePlan<'a>,
        chunks: Vec<DenseJacobianChunkBinding<'a>>,
    ) -> Self {
        Self::with_config(plan, chunks, ParallelExecutorConfig::default())
    }

    pub fn with_config(
        plan: &'a DenseJacobianRuntimePlan<'a>,
        chunks: Vec<DenseJacobianChunkBinding<'a>>,
        config: ParallelExecutorConfig,
    ) -> Self {
        let sequential = SequentialDenseJacobianExecutor::new(plan, chunks);
        Self::assert_non_overlapping_value_layout(&sequential.chunks, sequential.plan.len());
        let worker_jobs = config.sparse_jobs();
        let chunk_weights: Vec<usize> = sequential
            .chunks
            .iter()
            .map(|chunk| chunk.value_len)
            .collect();
        let job_ranges = contiguous_weighted_job_ranges(chunk_weights.as_slice(), worker_jobs);
        let job_value_ranges = job_ranges
            .iter()
            .map(|chunk_range| {
                let first = &sequential.chunks[chunk_range.start];
                let last = &sequential.chunks[chunk_range.end - 1];
                first.value_offset..(last.value_offset + last.value_len)
            })
            .collect();
        let use_sequential_fallback = config.sparse_fallback(
            sequential.plan.len(),
            sequential.chunks.len(),
            job_ranges.len(),
        );

        Self {
            plan: sequential.plan,
            chunks: sequential.chunks,
            job_ranges,
            job_value_ranges,
            use_sequential_fallback,
            config,
        }
    }

    fn assert_non_overlapping_value_layout(chunks: &[DenseJacobianChunkBinding<'_>], len: usize) {
        let mut expected_offset = 0usize;
        for chunk in chunks {
            assert_eq!(
                chunk.value_offset, expected_offset,
                "parallel dense Jacobian chunks must form a contiguous, non-overlapping layout"
            );
            expected_offset += chunk.value_len;
        }
        assert_eq!(
            expected_offset, len,
            "parallel dense Jacobian chunk layout must cover all dense values"
        );
    }

    pub fn eval_values_into(&self, args: &[f64], values_out: &mut [f64]) {
        assert!(
            values_out.len() >= self.plan.len(),
            "expected at least {} dense Jacobian value slots, got {}",
            self.plan.len(),
            values_out.len()
        );

        if self.use_sequential_fallback {
            for chunk in &self.chunks {
                let start = chunk.value_offset;
                let end = start + chunk.value_len;
                (chunk.eval)(args, &mut values_out[start..end]);
            }
            return;
        }

        match self.job_ranges.len() {
            2 => self.eval_two_jobs_with_join(args, values_out),
            4 => self.eval_four_jobs_with_join(args, values_out),
            _ => self.eval_many_jobs_with_join_tree(args, values_out),
        }
    }

    pub fn eval_values(&self, args: &[f64]) -> Vec<f64> {
        let mut values = vec![0.0; self.plan.len()];
        self.eval_values_into(args, &mut values);
        values
    }

    pub fn eval_dense_matrix(&self, args: &[f64]) -> DMatrix<f64> {
        let values = self.eval_values(args);
        self.plan.assemble_dense_matrix(values.as_slice())
    }

    pub fn uses_sequential_fallback(&self) -> bool {
        self.use_sequential_fallback
    }

    pub fn job_count(&self) -> usize {
        self.job_ranges.len()
    }

    pub fn chunk_count(&self) -> usize {
        self.chunks.len()
    }

    pub fn work_per_job(&self) -> usize {
        work_per_group(self.plan.len(), self.job_count())
    }

    pub fn work_per_chunk(&self) -> usize {
        work_per_group(self.plan.len(), self.chunk_count())
    }

    pub fn min_work_per_parallel_job(&self) -> usize {
        min_work_per_job_from_baseline(rayon_overhead_baseline())
    }

    pub fn config(&self) -> ParallelExecutorConfig {
        self.config
    }

    fn eval_job_into(
        &self,
        args: &[f64],
        job_index: usize,
        values_out: &mut [f64],
        base_offset: usize,
    ) {
        let chunk_range = self.job_ranges[job_index].clone();
        for chunk in &self.chunks[chunk_range] {
            let start = chunk.value_offset - base_offset;
            let end = start + chunk.value_len;
            (chunk.eval)(args, &mut values_out[start..end]);
        }
    }

    fn eval_two_jobs_with_join(&self, args: &[f64], values_out: &mut [f64]) {
        let left_range = self.job_value_ranges[0].clone();
        let right_range = self.job_value_ranges[1].clone();
        let split_at = right_range.start;
        let (left_out, right_out) = values_out.split_at_mut(split_at);
        join(
            || self.eval_job_into(args, 0, left_out, left_range.start),
            || self.eval_job_into(args, 1, right_out, right_range.start),
        );
    }

    fn eval_many_jobs_with_scope(&self, args: &[f64], values_out: &mut [f64]) {
        let values_ptr = values_out.as_mut_ptr() as usize;
        scope(|scope| {
            for job_range in &self.job_ranges {
                let args = args;
                let job_range = job_range.clone();
                let chunks = &self.chunks;
                scope.spawn(move |_| {
                    for chunk in &chunks[job_range] {
                        let slice_ptr = (values_ptr as *mut f64).wrapping_add(chunk.value_offset);
                        // SAFETY:
                        // - layout contiguity/non-overlap is validated in `new()`,
                        // - each job processes a disjoint contiguous chunk group,
                        // - therefore each inner chunk still writes to a unique value range,
                        // - `values_out` lives for the duration of this scope.
                        let out_slice =
                            unsafe { std::slice::from_raw_parts_mut(slice_ptr, chunk.value_len) };
                        (chunk.eval)(args, out_slice);
                    }
                });
            }
        });
    }
    fn eval_four_jobs_with_join(&self, args: &[f64], values_out: &mut [f64]) {
        let r0 = self.job_value_ranges[0].clone();
        let r1 = self.job_value_ranges[1].clone();
        let r2 = self.job_value_ranges[2].clone();
        let r3 = self.job_value_ranges[3].clone();

        let (left_half, right_half) = values_out.split_at_mut(r2.start);
        let (left0, left1) = left_half.split_at_mut(r1.start - r0.start);
        let (right0, right1) = right_half.split_at_mut(r3.start - r2.start);

        join(
            || {
                join(
                    || self.eval_job_into(args, 0, left0, r0.start),
                    || self.eval_job_into(args, 1, left1, r1.start),
                );
            },
            || {
                join(
                    || self.eval_job_into(args, 2, right0, r2.start),
                    || self.eval_job_into(args, 3, right1, r3.start),
                );
            },
        );
    }

    fn eval_many_jobs_with_join_tree(&self, args: &[f64], values_out: &mut [f64]) {
        self.eval_job_range_recursive(args, 0, self.job_ranges.len(), values_out, 0);
    }

    fn eval_job_range_recursive(
        &self,
        args: &[f64],
        job_start: usize,
        job_end: usize,
        values_out: &mut [f64],
        base_offset: usize,
    ) {
        match job_end - job_start {
            0 => {}
            1 => self.eval_job_into(args, job_start, values_out, base_offset),
            _ => {
                let mid = job_start + (job_end - job_start) / 2;
                let right_range = self.job_value_ranges[mid].clone();
                let split_at = right_range.start - base_offset;
                let (left_out, right_out) = values_out.split_at_mut(split_at);
                join(
                    || self.eval_job_range_recursive(args, job_start, mid, left_out, base_offset),
                    || {
                        self.eval_job_range_recursive(
                            args,
                            mid,
                            job_end,
                            right_out,
                            right_range.start,
                        )
                    },
                );
            }
        }
    }
}

/// Parallel executor for residual chunks.
///
/// Jobs write directly into disjoint slices of one caller-owned residual
/// buffer. This keeps the deterministic chunk order while avoiding the
/// temporary-buffer/copy-back pattern that was too expensive for hot callbacks.
pub struct ParallelResidualExecutor<'a> {
    plan: &'a ResidualRuntimePlan<'a>,
    chunks: Vec<ResidualChunkBinding<'a>>,
    job_ranges: Vec<Range<usize>>,
    job_output_ranges: Vec<Range<usize>>,
    use_sequential_fallback: bool,
    config: ParallelExecutorConfig,
}

impl<'a> ParallelResidualExecutor<'a> {
    pub fn new(plan: &'a ResidualRuntimePlan<'a>, chunks: Vec<ResidualChunkBinding<'a>>) -> Self {
        Self::with_config(plan, chunks, ParallelExecutorConfig::default())
    }

    pub fn with_config(
        plan: &'a ResidualRuntimePlan<'a>,
        chunks: Vec<ResidualChunkBinding<'a>>,
        config: ParallelExecutorConfig,
    ) -> Self {
        let sequential = SequentialResidualExecutor::new(plan, chunks);
        Self::assert_non_overlapping_residual_layout(
            &sequential.chunks,
            sequential.plan.output_len,
        );
        let worker_jobs = config.residual_jobs();
        let chunk_weights: Vec<usize> = sequential
            .chunks
            .iter()
            .map(|chunk| chunk.output_len)
            .collect();
        let job_ranges = contiguous_weighted_job_ranges(chunk_weights.as_slice(), worker_jobs);
        let job_output_ranges = job_ranges
            .iter()
            .map(|chunk_range| {
                let first = &sequential.chunks[chunk_range.start];
                let last = &sequential.chunks[chunk_range.end - 1];
                first.output_offset..(last.output_offset + last.output_len)
            })
            .collect();
        let use_sequential_fallback = config.residual_fallback(
            sequential.plan.output_len,
            sequential.chunks.len(),
            job_ranges.len(),
        );
        Self {
            plan: sequential.plan,
            chunks: sequential.chunks,
            job_ranges,
            job_output_ranges,
            use_sequential_fallback,
            config,
        }
    }

    fn assert_non_overlapping_residual_layout(
        chunks: &[ResidualChunkBinding<'_>],
        output_len: usize,
    ) {
        let mut expected_offset = 0usize;
        for chunk in chunks {
            assert_eq!(
                chunk.output_offset, expected_offset,
                "parallel residual chunks must form a contiguous, non-overlapping layout"
            );
            expected_offset += chunk.output_len;
        }
        assert_eq!(
            expected_offset, output_len,
            "parallel residual chunk layout must cover the full output"
        );
    }

    pub fn eval_into(&self, args: &[f64], out: &mut [f64]) {
        assert!(
            out.len() >= self.plan.output_len,
            "expected at least {} residual output slots, got {}",
            self.plan.output_len,
            out.len()
        );

        if self.use_sequential_fallback {
            for chunk in &self.chunks {
                let start = chunk.output_offset;
                let end = start + chunk.output_len;
                (chunk.eval)(args, &mut out[start..end]);
            }
            return;
        }

        match self.job_ranges.len() {
            2 => self.eval_two_jobs_with_join(args, out),
            4 => self.eval_four_jobs_with_join(args, out),
            _ => self.eval_many_jobs_with_join_tree(args, out),
        }
    }

    pub fn eval(&self, args: &[f64]) -> Vec<f64> {
        let mut out = vec![0.0; self.plan.output_len];
        self.eval_into(args, &mut out);
        out
    }

    /// Returns `true` when this executor intentionally uses the sequential
    /// path because the current workload is too small to amortize parallel
    /// scheduling overhead.
    pub fn uses_sequential_fallback(&self) -> bool {
        self.use_sequential_fallback
    }

    /// Returns the number of grouped worker jobs prepared for parallel
    /// execution.
    pub fn job_count(&self) -> usize {
        self.job_ranges.len()
    }

    pub fn chunk_count(&self) -> usize {
        self.chunks.len()
    }

    pub fn work_per_job(&self) -> usize {
        work_per_group(self.plan.output_len, self.job_count())
    }

    pub fn work_per_chunk(&self) -> usize {
        work_per_group(self.plan.output_len, self.chunk_count())
    }

    pub fn min_work_per_parallel_job(&self) -> usize {
        min_work_per_job_from_baseline(rayon_overhead_baseline())
    }

    /// Returns the effective configuration used by this executor.
    pub fn config(&self) -> ParallelExecutorConfig {
        self.config
    }

    fn eval_job_into(&self, args: &[f64], job_index: usize, out: &mut [f64], base_offset: usize) {
        let chunk_range = self.job_ranges[job_index].clone();
        for chunk in &self.chunks[chunk_range] {
            let start = chunk.output_offset - base_offset;
            let end = start + chunk.output_len;
            (chunk.eval)(args, &mut out[start..end]);
        }
    }

    fn eval_two_jobs_with_join(&self, args: &[f64], out: &mut [f64]) {
        let left_range = self.job_output_ranges[0].clone();
        let right_range = self.job_output_ranges[1].clone();
        let split_at = right_range.start;
        let (left_out, right_out) = out.split_at_mut(split_at);
        join(
            || self.eval_job_into(args, 0, left_out, left_range.start),
            || self.eval_job_into(args, 1, right_out, right_range.start),
        );
    }

    fn eval_four_jobs_with_join(&self, args: &[f64], out: &mut [f64]) {
        let r0 = self.job_output_ranges[0].clone();
        let r1 = self.job_output_ranges[1].clone();
        let r2 = self.job_output_ranges[2].clone();
        let r3 = self.job_output_ranges[3].clone();

        let (left_half, right_half) = out.split_at_mut(r2.start);
        let (left0, left1) = left_half.split_at_mut(r1.start - r0.start);
        let (right0, right1) = right_half.split_at_mut(r3.start - r2.start);

        join(
            || {
                join(
                    || self.eval_job_into(args, 0, left0, r0.start),
                    || self.eval_job_into(args, 1, left1, r1.start),
                );
            },
            || {
                join(
                    || self.eval_job_into(args, 2, right0, r2.start),
                    || self.eval_job_into(args, 3, right1, r3.start),
                );
            },
        );
    }

    fn eval_many_jobs_with_join_tree(&self, args: &[f64], out: &mut [f64]) {
        self.eval_job_range_recursive(args, 0, self.job_ranges.len(), out, 0);
    }

    fn eval_job_range_recursive(
        &self,
        args: &[f64],
        job_start: usize,
        job_end: usize,
        out: &mut [f64],
        base_offset: usize,
    ) {
        match job_end - job_start {
            0 => {}
            1 => self.eval_job_into(args, job_start, out, base_offset),
            _ => {
                let mid = job_start + (job_end - job_start) / 2;
                let right_range = self.job_output_ranges[mid].clone();
                let split_at = right_range.start - base_offset;
                let (left_out, right_out) = out.split_at_mut(split_at);
                join(
                    || self.eval_job_range_recursive(args, job_start, mid, left_out, base_offset),
                    || {
                        self.eval_job_range_recursive(
                            args,
                            mid,
                            job_end,
                            right_out,
                            right_range.start,
                        )
                    },
                );
            }
        }
    }
}

/// Parallel executor for sparse Jacobian value chunks.
///
/// Jobs write directly into disjoint slices of the explicit sparse-values
/// buffer, preserving global sparse ordering without a merge step.
pub struct ParallelSparseJacobianExecutor<'a> {
    plan: &'a SparseJacobianRuntimePlan<'a>,
    chunks: Vec<SparseJacobianChunkBinding<'a>>,
    job_ranges: Vec<Range<usize>>,
    job_value_ranges: Vec<Range<usize>>,
    use_sequential_fallback: bool,
    config: ParallelExecutorConfig,
}

impl<'a> ParallelSparseJacobianExecutor<'a> {
    pub fn new(
        plan: &'a SparseJacobianRuntimePlan<'a>,
        chunks: Vec<SparseJacobianChunkBinding<'a>>,
    ) -> Self {
        Self::with_config(plan, chunks, ParallelExecutorConfig::default())
    }

    pub fn with_config(
        plan: &'a SparseJacobianRuntimePlan<'a>,
        chunks: Vec<SparseJacobianChunkBinding<'a>>,
        config: ParallelExecutorConfig,
    ) -> Self {
        let sequential = SequentialSparseJacobianExecutor::new(plan, chunks);
        Self::assert_non_overlapping_value_layout(&sequential.chunks, sequential.plan.nnz());
        let worker_jobs = config.sparse_jobs();
        let chunk_weights: Vec<usize> = sequential
            .chunks
            .iter()
            .map(|chunk| chunk.value_len)
            .collect();
        let job_ranges = contiguous_weighted_job_ranges(chunk_weights.as_slice(), worker_jobs);
        let job_value_ranges = job_ranges
            .iter()
            .map(|chunk_range| {
                let first = &sequential.chunks[chunk_range.start];
                let last = &sequential.chunks[chunk_range.end - 1];
                first.value_offset..(last.value_offset + last.value_len)
            })
            .collect();
        let use_sequential_fallback = config.sparse_fallback(
            sequential.plan.nnz(),
            sequential.chunks.len(),
            job_ranges.len(),
        );
        Self {
            plan: sequential.plan,
            chunks: sequential.chunks,
            job_ranges,
            job_value_ranges,
            use_sequential_fallback,
            config,
        }
    }

    fn assert_non_overlapping_value_layout(chunks: &[SparseJacobianChunkBinding<'_>], nnz: usize) {
        let mut expected_offset = 0usize;
        for chunk in chunks {
            assert_eq!(
                chunk.value_offset, expected_offset,
                "parallel sparse Jacobian chunks must form a contiguous, non-overlapping layout"
            );
            expected_offset += chunk.value_len;
        }
        assert_eq!(
            expected_offset, nnz,
            "parallel sparse Jacobian chunk layout must cover all explicit values"
        );
    }

    pub fn eval_values_into(&self, args: &[f64], values_out: &mut [f64]) {
        assert!(
            values_out.len() >= self.plan.nnz(),
            "expected at least {} Jacobian value slots, got {}",
            self.plan.nnz(),
            values_out.len()
        );

        if self.use_sequential_fallback {
            for chunk in &self.chunks {
                let start = chunk.value_offset;
                let end = start + chunk.value_len;
                (chunk.eval)(args, &mut values_out[start..end]);
            }
            return;
        }

        match self.job_ranges.len() {
            2 => self.eval_two_jobs_with_join(args, values_out),
            4 => self.eval_four_jobs_with_join(args, values_out),
            _ => self.eval_many_jobs_with_join_tree(args, values_out),
        }
    }

    pub fn eval_values(&self, args: &[f64]) -> Vec<f64> {
        let mut values = vec![0.0; self.plan.nnz()];
        self.eval_values_into(args, &mut values);
        values
    }

    pub fn eval_sparse_col_mat(&self, args: &[f64]) -> SparseColMat<usize, f64> {
        let values = self.eval_values(args);
        self.plan.assemble_sparse_col_mat(values.as_slice())
    }

    /// Returns `true` when this executor intentionally uses the sequential
    /// path because the current workload is too small to amortize parallel
    /// scheduling overhead.
    pub fn uses_sequential_fallback(&self) -> bool {
        self.use_sequential_fallback
    }

    /// Returns the number of grouped worker jobs prepared for parallel
    /// execution.
    pub fn job_count(&self) -> usize {
        self.job_ranges.len()
    }

    pub fn chunk_count(&self) -> usize {
        self.chunks.len()
    }

    pub fn work_per_job(&self) -> usize {
        work_per_group(self.plan.nnz(), self.job_count())
    }

    pub fn work_per_chunk(&self) -> usize {
        work_per_group(self.plan.nnz(), self.chunk_count())
    }

    pub fn min_work_per_parallel_job(&self) -> usize {
        min_work_per_job_from_baseline(rayon_overhead_baseline())
    }

    /// Returns the effective configuration used by this executor.
    pub fn config(&self) -> ParallelExecutorConfig {
        self.config
    }

    fn eval_job_into(
        &self,
        args: &[f64],
        job_index: usize,
        values_out: &mut [f64],
        base_offset: usize,
    ) {
        let chunk_range = self.job_ranges[job_index].clone();
        for chunk in &self.chunks[chunk_range] {
            let start = chunk.value_offset - base_offset;
            let end = start + chunk.value_len;
            (chunk.eval)(args, &mut values_out[start..end]);
        }
    }

    fn eval_two_jobs_with_join(&self, args: &[f64], values_out: &mut [f64]) {
        let left_range = self.job_value_ranges[0].clone();
        let right_range = self.job_value_ranges[1].clone();
        let split_at = right_range.start;
        let (left_out, right_out) = values_out.split_at_mut(split_at);
        join(
            || self.eval_job_into(args, 0, left_out, left_range.start),
            || self.eval_job_into(args, 1, right_out, right_range.start),
        );
    }

    fn eval_four_jobs_with_join(&self, args: &[f64], values_out: &mut [f64]) {
        let r0 = self.job_value_ranges[0].clone();
        let r1 = self.job_value_ranges[1].clone();
        let r2 = self.job_value_ranges[2].clone();
        let r3 = self.job_value_ranges[3].clone();

        let (left_half, right_half) = values_out.split_at_mut(r2.start);
        let (left0, left1) = left_half.split_at_mut(r1.start - r0.start);
        let (right0, right1) = right_half.split_at_mut(r3.start - r2.start);

        join(
            || {
                join(
                    || self.eval_job_into(args, 0, left0, r0.start),
                    || self.eval_job_into(args, 1, left1, r1.start),
                );
            },
            || {
                join(
                    || self.eval_job_into(args, 2, right0, r2.start),
                    || self.eval_job_into(args, 3, right1, r3.start),
                );
            },
        );
    }

    fn eval_many_jobs_with_join_tree(&self, args: &[f64], values_out: &mut [f64]) {
        self.eval_job_range_recursive(args, 0, self.job_ranges.len(), values_out, 0);
    }

    fn eval_job_range_recursive(
        &self,
        args: &[f64],
        job_start: usize,
        job_end: usize,
        values_out: &mut [f64],
        base_offset: usize,
    ) {
        match job_end - job_start {
            0 => {}
            1 => self.eval_job_into(args, job_start, values_out, base_offset),
            _ => {
                let mid = job_start + (job_end - job_start) / 2;
                let right_range = self.job_value_ranges[mid].clone();
                let split_at = right_range.start - base_offset;
                let (left_out, right_out) = values_out.split_at_mut(split_at);
                join(
                    || self.eval_job_range_recursive(args, job_start, mid, left_out, base_offset),
                    || {
                        self.eval_job_range_recursive(
                            args,
                            mid,
                            job_end,
                            right_out,
                            right_range.start,
                        )
                    },
                );
            }
        }
    }
}

/// Parallel executor for banded Jacobian value chunks.
///
/// This mirrors the sparse-value executor, but the final assembly target is a
/// native `BandedAssembly` instead of a sparse triplet matrix.
pub struct ParallelBandedJacobianExecutor<'a> {
    plan: &'a BandedJacobianRuntimePlan<'a>,
    chunks: Vec<BandedJacobianChunkBinding<'a>>,
    job_ranges: Vec<Range<usize>>,
    job_value_ranges: Vec<Range<usize>>,
    use_sequential_fallback: bool,
    config: ParallelExecutorConfig,
}

impl<'a> ParallelBandedJacobianExecutor<'a> {
    pub fn new(
        plan: &'a BandedJacobianRuntimePlan<'a>,
        chunks: Vec<BandedJacobianChunkBinding<'a>>,
    ) -> Self {
        Self::with_config(plan, chunks, ParallelExecutorConfig::default())
    }

    pub fn with_config(
        plan: &'a BandedJacobianRuntimePlan<'a>,
        chunks: Vec<BandedJacobianChunkBinding<'a>>,
        config: ParallelExecutorConfig,
    ) -> Self {
        let sequential = SequentialBandedJacobianExecutor::new(plan, chunks);
        Self::assert_non_overlapping_value_layout(&sequential.chunks, sequential.plan.nnz());
        let worker_jobs = config.sparse_jobs();
        let chunk_weights: Vec<usize> = sequential
            .chunks
            .iter()
            .map(|chunk| chunk.value_len)
            .collect();
        let job_ranges = contiguous_weighted_job_ranges(chunk_weights.as_slice(), worker_jobs);
        let job_value_ranges = job_ranges
            .iter()
            .map(|chunk_range| {
                let first = &sequential.chunks[chunk_range.start];
                let last = &sequential.chunks[chunk_range.end - 1];
                first.value_offset..(last.value_offset + last.value_len)
            })
            .collect();
        let use_sequential_fallback = config.sparse_fallback(
            sequential.plan.nnz(),
            sequential.chunks.len(),
            job_ranges.len(),
        );
        Self {
            plan: sequential.plan,
            chunks: sequential.chunks,
            job_ranges,
            job_value_ranges,
            use_sequential_fallback,
            config,
        }
    }

    fn assert_non_overlapping_value_layout(chunks: &[BandedJacobianChunkBinding<'_>], nnz: usize) {
        let mut expected_offset = 0usize;
        for chunk in chunks {
            assert_eq!(
                chunk.value_offset, expected_offset,
                "parallel banded Jacobian chunks must form a contiguous, non-overlapping layout"
            );
            expected_offset += chunk.value_len;
        }
        assert_eq!(
            expected_offset, nnz,
            "parallel banded Jacobian chunk layout must cover all explicit values"
        );
    }

    pub fn eval_values_into(&self, args: &[f64], values_out: &mut [f64]) {
        assert!(
            values_out.len() >= self.plan.nnz(),
            "expected at least {} banded Jacobian value slots, got {}",
            self.plan.nnz(),
            values_out.len()
        );

        if self.use_sequential_fallback {
            for chunk in &self.chunks {
                let start = chunk.value_offset;
                let end = start + chunk.value_len;
                (chunk.eval)(args, &mut values_out[start..end]);
            }
            return;
        }

        match self.job_ranges.len() {
            2 => self.eval_two_jobs_with_join(args, values_out),
            4 => self.eval_four_jobs_with_join(args, values_out),
            _ => self.eval_many_jobs_with_join_tree(args, values_out),
        }
    }

    pub fn eval_values(&self, args: &[f64]) -> Vec<f64> {
        let mut values = vec![0.0; self.plan.nnz()];
        self.eval_values_into(args, &mut values);
        values
    }

    pub fn eval_banded_assembly(&self, args: &[f64]) -> BandedAssembly {
        let values = self.eval_values(args);
        self.plan.assemble_banded_assembly(values.as_slice())
    }

    pub fn uses_sequential_fallback(&self) -> bool {
        self.use_sequential_fallback
    }

    pub fn job_count(&self) -> usize {
        self.job_ranges.len()
    }

    pub fn chunk_count(&self) -> usize {
        self.chunks.len()
    }

    pub fn work_per_job(&self) -> usize {
        work_per_group(self.plan.nnz(), self.job_count())
    }

    pub fn work_per_chunk(&self) -> usize {
        work_per_group(self.plan.nnz(), self.chunk_count())
    }

    pub fn min_work_per_parallel_job(&self) -> usize {
        min_work_per_job_from_baseline(rayon_overhead_baseline())
    }

    pub fn config(&self) -> ParallelExecutorConfig {
        self.config
    }

    fn eval_job_into(
        &self,
        args: &[f64],
        job_index: usize,
        values_out: &mut [f64],
        base_offset: usize,
    ) {
        let chunk_range = self.job_ranges[job_index].clone();
        for chunk in &self.chunks[chunk_range] {
            let start = chunk.value_offset - base_offset;
            let end = start + chunk.value_len;
            (chunk.eval)(args, &mut values_out[start..end]);
        }
    }

    fn eval_two_jobs_with_join(&self, args: &[f64], values_out: &mut [f64]) {
        let left_range = self.job_value_ranges[0].clone();
        let right_range = self.job_value_ranges[1].clone();
        let split_at = right_range.start;
        let (left_out, right_out) = values_out.split_at_mut(split_at);
        join(
            || self.eval_job_into(args, 0, left_out, left_range.start),
            || self.eval_job_into(args, 1, right_out, right_range.start),
        );
    }

    fn eval_four_jobs_with_join(&self, args: &[f64], values_out: &mut [f64]) {
        let r0 = self.job_value_ranges[0].clone();
        let r1 = self.job_value_ranges[1].clone();
        let r2 = self.job_value_ranges[2].clone();
        let r3 = self.job_value_ranges[3].clone();

        let (left_half, right_half) = values_out.split_at_mut(r2.start);
        let (left0, left1) = left_half.split_at_mut(r1.start - r0.start);
        let (right0, right1) = right_half.split_at_mut(r3.start - r2.start);

        join(
            || {
                join(
                    || self.eval_job_into(args, 0, left0, r0.start),
                    || self.eval_job_into(args, 1, left1, r1.start),
                );
            },
            || {
                join(
                    || self.eval_job_into(args, 2, right0, r2.start),
                    || self.eval_job_into(args, 3, right1, r3.start),
                );
            },
        );
    }

    fn eval_many_jobs_with_join_tree(&self, args: &[f64], values_out: &mut [f64]) {
        self.eval_job_range_recursive(args, 0, self.job_ranges.len(), values_out, 0);
    }

    fn eval_job_range_recursive(
        &self,
        args: &[f64],
        job_start: usize,
        job_end: usize,
        values_out: &mut [f64],
        base_offset: usize,
    ) {
        match job_end - job_start {
            0 => {}
            1 => self.eval_job_into(args, job_start, values_out, base_offset),
            _ => {
                let mid = job_start + (job_end - job_start) / 2;
                let right_range = self.job_value_ranges[mid].clone();
                let split_at = right_range.start - base_offset;
                let (left_out, right_out) = values_out.split_at_mut(split_at);
                join(
                    || self.eval_job_range_recursive(args, job_start, mid, left_out, base_offset),
                    || {
                        self.eval_job_range_recursive(
                            args,
                            mid,
                            job_end,
                            right_out,
                            right_range.start,
                        )
                    },
                );
            }
        }
    }
}
//===================================================================================
// TESTS
//=====================================================================================
#[cfg(test)]
mod tests {
    use super::{
        AutoExecutionMode, BandedJacobianChunkBinding, DenseJacobianChunkBinding, GeneratedChunkFn,
        ParallelBandedJacobianExecutor, ParallelDenseJacobianExecutor, ParallelExecutorConfig,
        ParallelFallbackPolicy, ParallelResidualExecutor, ParallelSparseJacobianExecutor,
        ResidualChunkBinding, SequentialBandedJacobianExecutor, SequentialDenseJacobianExecutor,
        SequentialResidualExecutor, SequentialSparseJacobianExecutor, SparseJacobianChunkBinding,
        auto_parallel_executor_config, auto_parallel_fallback_for_workload,
        borrowed_sparse_entries, min_work_per_job_from_baseline, rayon_overhead_baseline,
        recommended_sparse_auto_parallel_plan, work_per_group,
    };
    use crate::somelinalg::banded::banded_assembly::BandedAssembly;
    use crate::symbolic::codegen::codegen_runtime_api::{
        BandedJacobianRuntimePlan, DenseJacobianChunkingStrategy, ResidualChunkingStrategy,
        RuntimeArguments,
    };
    use crate::symbolic::codegen::codegen_tasks::{
        BandedChunkingStrategy, BandedExprEntry, BandedJacobianTask, JacobianTask, ResidualTask,
        SparseChunkingStrategy, SparseJacobianTask,
    };
    use crate::symbolic::codegen::testing_fixtures::test_codegen_generated_bvp_fixtures::generated_bvp_fixture;
    use crate::symbolic::symbolic_engine::Expr;
    use crate::symbolic::symbolic_functions_BVP::Jacobian;
    use std::collections::HashMap;

    fn build_real_bvp_damp1_case(n_steps: usize) -> Jacobian {
        let eq1 = Expr::parse_expression("y-z");
        let eq2 = Expr::parse_expression("-z^3");
        let eq_system = vec![eq1, eq2];
        let values = vec!["z".to_string(), "y".to_string()];

        let mut border_conditions = HashMap::new();
        border_conditions.insert("z".to_string(), vec![(0usize, 1.0f64)]);
        border_conditions.insert("y".to_string(), vec![(1usize, 1.0f64)]);

        let mut jac = Jacobian::new();
        jac.discretization_system_BVP_par(
            eq_system,
            values,
            "x".to_string(),
            0.0,
            Some(n_steps),
            None,
            None,
            border_conditions,
            None,
            None,
            "forward".to_string(),
        );
        jac.calc_jacobian_parallel_smart_optimized();
        jac
    }

    fn bind_residual_fixture_chunks<'a>(
        plan: &'a crate::symbolic::codegen::codegen_runtime_api::ResidualRuntimePlan<'a>,
    ) -> Vec<ResidualChunkBinding<'a>> {
        let chunk_fns: [GeneratedChunkFn; 2] = [
            generated_bvp_fixture::fixture_bvp_residual_chunk_0,
            generated_bvp_fixture::fixture_bvp_residual_chunk_1,
        ];

        plan.chunks
            .iter()
            .zip(chunk_fns)
            .map(|(chunk, eval)| ResidualChunkBinding {
                fn_name: chunk.fn_name.as_str(),
                output_offset: chunk.output_offset,
                output_len: chunk.residuals.len(),
                eval,
            })
            .collect()
    }

    fn bind_sparse_fixture_chunks<'a>(
        plan: &'a crate::symbolic::codegen::codegen_runtime_api::SparseJacobianRuntimePlan<'a>,
    ) -> Vec<SparseJacobianChunkBinding<'a>> {
        let chunk_fns: [GeneratedChunkFn; 16] = [
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_0,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_1,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_2,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_3,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_4,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_5,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_6,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_7,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_8,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_9,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_10,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_11,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_12,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_13,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_14,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_15,
        ];

        plan.chunks
            .iter()
            .zip(chunk_fns)
            .map(|(chunk, eval)| SparseJacobianChunkBinding {
                fn_name: chunk.fn_name.as_str(),
                value_offset: chunk.value_offset,
                value_len: chunk.entries.len(),
                eval,
            })
            .collect()
    }

    fn dense_chunk_0(args: &[f64], out: &mut [f64]) {
        out[0] = args[0] + 1.0;
        out[1] = args[1];
        out[2] = 2.0;
        out[3] = args[0] * args[1];
    }

    fn dense_chunk_1(args: &[f64], out: &mut [f64]) {
        out[0] = args[0] - args[1];
        out[1] = 3.0;
    }

    fn bind_dense_fixture_chunks<'a>(
        plan: &'a crate::symbolic::codegen::codegen_runtime_api::DenseJacobianRuntimePlan<'a>,
    ) -> Vec<DenseJacobianChunkBinding<'a>> {
        let chunk_fns: [GeneratedChunkFn; 2] = [dense_chunk_0, dense_chunk_1];

        plan.chunks
            .iter()
            .zip(chunk_fns)
            .map(|(chunk, eval)| DenseJacobianChunkBinding {
                fn_name: chunk.fn_name.as_str(),
                value_offset: chunk.value_offset,
                value_len: chunk.value_range().len(),
                eval,
            })
            .collect()
    }

    fn banded_chunk_0(args: &[f64], out: &mut [f64]) {
        out[0] = args[0] + 1.0;
        out[1] = args[1] + 2.0;
    }

    fn banded_chunk_1(args: &[f64], out: &mut [f64]) {
        out[0] = args[0] * args[1];
        out[1] = args[0] - args[1];
    }

    fn bind_banded_fixture_chunks<'a>(
        plan: &'a BandedJacobianRuntimePlan<'a>,
    ) -> Vec<BandedJacobianChunkBinding<'a>> {
        let chunk_fns: [GeneratedChunkFn; 2] = [banded_chunk_0, banded_chunk_1];

        plan.chunks
            .iter()
            .zip(chunk_fns)
            .map(|(chunk, eval)| BandedJacobianChunkBinding {
                fn_name: chunk.fn_name.as_str(),
                value_offset: chunk.value_offset,
                value_len: chunk.entries.len(),
                eval,
            })
            .collect()
    }

    fn banded_diagonals_snapshot(assembly: &BandedAssembly) -> Vec<(isize, Vec<f64>)> {
        (-(assembly.kl() as isize)..=(assembly.ku() as isize))
            .map(|offset| {
                (
                    offset,
                    assembly
                        .diag(offset)
                        .expect("requested diagonal must exist")
                        .to_vec(),
                )
            })
            .collect()
    }

    #[test]
    fn sequential_dense_jacobian_executor_assembles_dense_matrix() {
        let jacobian = vec![
            vec![Expr::parse_expression("x + 1"), Expr::parse_expression("y")],
            vec![Expr::parse_expression("2"), Expr::parse_expression("x*y")],
            vec![Expr::parse_expression("x - y"), Expr::parse_expression("3")],
        ];
        let task = JacobianTask {
            fn_name: "fixture_dense_jacobian",
            jacobian: &jacobian,
            variables: &["x", "y"],
            params: None,
        };
        let runtime_plan =
            task.runtime_plan(DenseJacobianChunkingStrategy::ByRowCount { rows_per_chunk: 2 });
        let executor = SequentialDenseJacobianExecutor::new(
            &runtime_plan,
            bind_dense_fixture_chunks(&runtime_plan),
        );

        let matrix = executor.eval_dense_matrix(&[2.0, 5.0]);

        assert_eq!(matrix.nrows(), 3);
        assert_eq!(matrix.ncols(), 2);
        assert_eq!(matrix[(0, 0)], 3.0);
        assert_eq!(matrix[(0, 1)], 5.0);
        assert_eq!(matrix[(1, 0)], 2.0);
        assert_eq!(matrix[(1, 1)], 10.0);
        assert_eq!(matrix[(2, 0)], -3.0);
        assert_eq!(matrix[(2, 1)], 3.0);
    }

    #[test]
    fn parallel_dense_jacobian_executor_matches_sequential_executor() {
        let jacobian = vec![
            vec![Expr::parse_expression("x + 1"), Expr::parse_expression("y")],
            vec![Expr::parse_expression("2"), Expr::parse_expression("x*y")],
            vec![Expr::parse_expression("x - y"), Expr::parse_expression("3")],
        ];
        let task = JacobianTask {
            fn_name: "fixture_dense_jacobian",
            jacobian: &jacobian,
            variables: &["x", "y"],
            params: None,
        };
        let runtime_plan =
            task.runtime_plan(DenseJacobianChunkingStrategy::ByRowCount { rows_per_chunk: 2 });
        let bindings = bind_dense_fixture_chunks(&runtime_plan);
        let sequential = SequentialDenseJacobianExecutor::new(&runtime_plan, bindings.clone());
        let parallel = ParallelDenseJacobianExecutor::with_config(
            &runtime_plan,
            bindings,
            ParallelExecutorConfig {
                jobs_per_worker: 1,
                max_residual_jobs: None,
                max_sparse_jobs: Some(2),
                fallback_policy: ParallelFallbackPolicy::Never,
            },
        );

        assert_eq!(
            parallel.eval_dense_matrix(&[2.0, 5.0]),
            sequential.eval_dense_matrix(&[2.0, 5.0])
        );
    }

    #[test]
    fn sequential_banded_jacobian_executor_assembles_expected_native_storage() {
        let expressions = vec![
            Expr::parse_expression("x + 1"),
            Expr::parse_expression("y + 2"),
            Expr::parse_expression("x * y"),
            Expr::parse_expression("x - y"),
        ];
        let entries = vec![
            BandedExprEntry {
                row: 1,
                col: 0,
                diag_offset: -1,
                diag_position: 0,
                expr: &expressions[2],
            },
            BandedExprEntry {
                row: 2,
                col: 1,
                diag_offset: -1,
                diag_position: 1,
                expr: &expressions[3],
            },
            BandedExprEntry {
                row: 0,
                col: 0,
                diag_offset: 0,
                diag_position: 0,
                expr: &expressions[0],
            },
            BandedExprEntry {
                row: 1,
                col: 1,
                diag_offset: 0,
                diag_position: 1,
                expr: &expressions[1],
            },
        ];
        let task = BandedJacobianTask {
            fn_name: "fixture_banded_jacobian",
            shape: (3, 3),
            kl: 1,
            ku: 0,
            compact: false,
            entries: &entries,
            variables: &["x", "y"],
            params: None,
        };
        let runtime_plan = task.runtime_plan(BandedChunkingStrategy::ByDiagonalCount {
            diagonals_per_chunk: 1,
        });
        let executor = SequentialBandedJacobianExecutor::new(
            &runtime_plan,
            bind_banded_fixture_chunks(&runtime_plan),
        );

        let values = executor.eval_values(&[2.0, 5.0]);
        let assembly = executor.eval_banded_assembly(&[2.0, 5.0]);
        let expected_values = vec![3.0, 7.0, 10.0, -3.0];
        let expected = runtime_plan.assemble_banded_assembly(&expected_values);

        assert_eq!(values, expected_values);
        assert_eq!(
            banded_diagonals_snapshot(&assembly),
            banded_diagonals_snapshot(&expected)
        );
    }

    #[test]
    fn parallel_banded_jacobian_executor_matches_sequential_executor() {
        let expressions = vec![
            Expr::parse_expression("x + 1"),
            Expr::parse_expression("y + 2"),
            Expr::parse_expression("x * y"),
            Expr::parse_expression("x - y"),
        ];
        let entries = vec![
            BandedExprEntry {
                row: 1,
                col: 0,
                diag_offset: -1,
                diag_position: 0,
                expr: &expressions[2],
            },
            BandedExprEntry {
                row: 2,
                col: 1,
                diag_offset: -1,
                diag_position: 1,
                expr: &expressions[3],
            },
            BandedExprEntry {
                row: 0,
                col: 0,
                diag_offset: 0,
                diag_position: 0,
                expr: &expressions[0],
            },
            BandedExprEntry {
                row: 1,
                col: 1,
                diag_offset: 0,
                diag_position: 1,
                expr: &expressions[1],
            },
        ];
        let task = BandedJacobianTask {
            fn_name: "fixture_banded_jacobian",
            shape: (3, 3),
            kl: 1,
            ku: 0,
            compact: false,
            entries: &entries,
            variables: &["x", "y"],
            params: None,
        };
        let runtime_plan = task.runtime_plan(BandedChunkingStrategy::ByDiagonalCount {
            diagonals_per_chunk: 1,
        });
        let bindings = bind_banded_fixture_chunks(&runtime_plan);
        let sequential = SequentialBandedJacobianExecutor::new(&runtime_plan, bindings.clone());
        let parallel = ParallelBandedJacobianExecutor::with_config(
            &runtime_plan,
            bindings,
            ParallelExecutorConfig {
                jobs_per_worker: 1,
                max_residual_jobs: None,
                max_sparse_jobs: Some(2),
                fallback_policy: ParallelFallbackPolicy::Never,
            },
        );

        assert_eq!(
            parallel.eval_values(&[2.0, 5.0]),
            sequential.eval_values(&[2.0, 5.0])
        );
        assert_eq!(
            banded_diagonals_snapshot(&parallel.eval_banded_assembly(&[2.0, 5.0])),
            banded_diagonals_snapshot(&sequential.eval_banded_assembly(&[2.0, 5.0]))
        );
        assert!(!parallel.uses_sequential_fallback());
    }

    #[test]
    fn sequential_residual_executor_matches_manual_fixture_collection() {
        let residuals = vec![
            Expr::parse_expression("y0 - y1 - 1"),
            Expr::parse_expression("-y0 + y2 - 1"),
            Expr::parse_expression("-y1^3 - y2 + y4"),
            Expr::parse_expression("-y3 + y5 - y2"),
            Expr::parse_expression("-y3^3 - y4 + y6"),
            Expr::parse_expression("-y5 + y7 - y4"),
            Expr::parse_expression("-y5^3 - y6 + y8"),
            Expr::parse_expression("-y7 + y9 - y6"),
            Expr::parse_expression("-y7^3 - y8 + y10"),
            Expr::parse_expression("-y9 + y11 - y8"),
            Expr::parse_expression("-y9^3 - y10 + y12"),
            Expr::parse_expression("-y11 + y13 - y10"),
            Expr::parse_expression("-y11^3 - y12 + y14"),
            Expr::parse_expression("-y13 + y15 - y12"),
            Expr::parse_expression("-y13^3 - y14 + 1"),
            Expr::parse_expression("-y15 + 1 - y14"),
        ];
        let variables = [
            "y0", "y1", "y2", "y3", "y4", "y5", "y6", "y7", "y8", "y9", "y10", "y11", "y12", "y13",
            "y14", "y15",
        ];
        let task = ResidualTask {
            fn_name: "fixture_bvp_residual",
            residuals: &residuals,
            variables: &variables,
            params: None,
        };
        let runtime_plan = task.runtime_plan(ResidualChunkingStrategy::ByOutputCount {
            max_outputs_per_chunk: 8,
        });
        let executor = SequentialResidualExecutor::new(
            &runtime_plan,
            bind_residual_fixture_chunks(&runtime_plan),
        );

        let flat_args = RuntimeArguments::new(
            &(0..16)
                .map(|index| 0.2 + index as f64 * 0.01)
                .collect::<Vec<_>>(),
            None,
        )
        .flatten();

        let actual = executor.eval(flat_args.as_slice());

        let mut expected = vec![0.0; 16];
        generated_bvp_fixture::fixture_bvp_residual_chunk_0(
            flat_args.as_slice(),
            &mut expected[0..8],
        );
        generated_bvp_fixture::fixture_bvp_residual_chunk_1(
            flat_args.as_slice(),
            &mut expected[8..16],
        );

        assert_eq!(actual, expected);
    }

    #[test]
    fn sequential_sparse_executor_matches_manual_fixture_collection() {
        let jac = build_real_bvp_damp1_case(8);
        let variable_names_owned = jac.variable_string.clone();
        let variables: Vec<&str> = variable_names_owned
            .iter()
            .map(|name| name.as_str())
            .collect();
        let entries_owned = jac.symbolic_jacobian_sparse_entries_owned();
        let entries = borrowed_sparse_entries(&entries_owned);
        let task = SparseJacobianTask {
            fn_name: "fixture_bvp_sparse_values",
            shape: (jac.vector_of_functions.len(), jac.vector_of_variables.len()),
            entries: &entries,
            variables: &variables,
            params: None,
        };
        let runtime_plan =
            task.runtime_plan(SparseChunkingStrategy::ByRowCount { rows_per_chunk: 1 });
        let executor = SequentialSparseJacobianExecutor::new(
            &runtime_plan,
            bind_sparse_fixture_chunks(&runtime_plan),
        );

        let flat_args = RuntimeArguments::new(
            &(0..16)
                .map(|index| 0.2 + index as f64 * 0.01)
                .collect::<Vec<_>>(),
            None,
        )
        .flatten();

        let actual = executor.eval_values(flat_args.as_slice());

        let mut expected = Vec::new();
        let chunk_fns: [GeneratedChunkFn; 16] = [
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_0,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_1,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_2,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_3,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_4,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_5,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_6,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_7,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_8,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_9,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_10,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_11,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_12,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_13,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_14,
            generated_bvp_fixture::fixture_bvp_sparse_values_chunk_15,
        ];
        let chunk_sizes = [2usize, 2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2];
        for (chunk_fn, chunk_size) in chunk_fns.into_iter().zip(chunk_sizes) {
            let mut chunk_out = vec![0.0; chunk_size];
            chunk_fn(flat_args.as_slice(), &mut chunk_out);
            expected.extend(chunk_out);
        }

        assert_eq!(actual, expected);
    }

    #[test]
    fn parallel_residual_executor_matches_sequential_executor() {
        let residuals = vec![
            Expr::parse_expression("y0 - y1 - 1"),
            Expr::parse_expression("-y0 + y2 - 1"),
            Expr::parse_expression("-y1^3 - y2 + y4"),
            Expr::parse_expression("-y3 + y5 - y2"),
            Expr::parse_expression("-y3^3 - y4 + y6"),
            Expr::parse_expression("-y5 + y7 - y4"),
            Expr::parse_expression("-y5^3 - y6 + y8"),
            Expr::parse_expression("-y7 + y9 - y6"),
            Expr::parse_expression("-y7^3 - y8 + y10"),
            Expr::parse_expression("-y9 + y11 - y8"),
            Expr::parse_expression("-y9^3 - y10 + y12"),
            Expr::parse_expression("-y11 + y13 - y10"),
            Expr::parse_expression("-y11^3 - y12 + y14"),
            Expr::parse_expression("-y13 + y15 - y12"),
            Expr::parse_expression("-y13^3 - y14 + 1"),
            Expr::parse_expression("-y15 + 1 - y14"),
        ];
        let variables = [
            "y0", "y1", "y2", "y3", "y4", "y5", "y6", "y7", "y8", "y9", "y10", "y11", "y12", "y13",
            "y14", "y15",
        ];
        let task = ResidualTask {
            fn_name: "fixture_bvp_residual",
            residuals: &residuals,
            variables: &variables,
            params: None,
        };
        let runtime_plan = task.runtime_plan(ResidualChunkingStrategy::ByOutputCount {
            max_outputs_per_chunk: 8,
        });
        let bindings = bind_residual_fixture_chunks(&runtime_plan);
        let sequential = SequentialResidualExecutor::new(&runtime_plan, bindings.clone());
        let parallel = ParallelResidualExecutor::new(&runtime_plan, bindings);

        let flat_args = RuntimeArguments::new(
            &(0..16)
                .map(|index| 0.2 + index as f64 * 0.01)
                .collect::<Vec<_>>(),
            None,
        )
        .flatten();

        assert_eq!(
            parallel.eval(flat_args.as_slice()),
            sequential.eval(flat_args.as_slice())
        );
    }

    #[test]
    fn parallel_sparse_executor_matches_sequential_executor() {
        let jac = build_real_bvp_damp1_case(8);
        let variable_names_owned = jac.variable_string.clone();
        let variables: Vec<&str> = variable_names_owned
            .iter()
            .map(|name| name.as_str())
            .collect();
        let entries_owned = jac.symbolic_jacobian_sparse_entries_owned();
        let entries = borrowed_sparse_entries(&entries_owned);
        let task = SparseJacobianTask {
            fn_name: "fixture_bvp_sparse_values",
            shape: (jac.vector_of_functions.len(), jac.vector_of_variables.len()),
            entries: &entries,
            variables: &variables,
            params: None,
        };
        let runtime_plan =
            task.runtime_plan(SparseChunkingStrategy::ByRowCount { rows_per_chunk: 1 });
        let bindings = bind_sparse_fixture_chunks(&runtime_plan);
        let sequential = SequentialSparseJacobianExecutor::new(&runtime_plan, bindings.clone());
        let parallel = ParallelSparseJacobianExecutor::new(&runtime_plan, bindings);

        let flat_args = RuntimeArguments::new(
            &(0..16)
                .map(|index| 0.2 + index as f64 * 0.01)
                .collect::<Vec<_>>(),
            None,
        )
        .flatten();

        assert_eq!(
            parallel.eval_values(flat_args.as_slice()),
            sequential.eval_values(flat_args.as_slice())
        );
    }

    #[test]
    fn parallel_residual_executor_allows_disabling_fallback() {
        let residuals = vec![
            Expr::parse_expression("y0 - y1 - 1"),
            Expr::parse_expression("-y0 + y2 - 1"),
            Expr::parse_expression("-y1^3 - y2 + y4"),
            Expr::parse_expression("-y3 + y5 - y2"),
            Expr::parse_expression("-y3^3 - y4 + y6"),
            Expr::parse_expression("-y5 + y7 - y4"),
            Expr::parse_expression("-y5^3 - y6 + y8"),
            Expr::parse_expression("-y7 + y9 - y6"),
            Expr::parse_expression("-y7^3 - y8 + y10"),
            Expr::parse_expression("-y9 + y11 - y8"),
            Expr::parse_expression("-y9^3 - y10 + y12"),
            Expr::parse_expression("-y11 + y13 - y10"),
            Expr::parse_expression("-y11^3 - y12 + y14"),
            Expr::parse_expression("-y13 + y15 - y12"),
            Expr::parse_expression("-y13^3 - y14 + 1"),
            Expr::parse_expression("-y15 + 1 - y14"),
        ];
        let variables = [
            "y0", "y1", "y2", "y3", "y4", "y5", "y6", "y7", "y8", "y9", "y10", "y11", "y12", "y13",
            "y14", "y15",
        ];
        let task = ResidualTask {
            fn_name: "fixture_bvp_residual",
            residuals: &residuals,
            variables: &variables,
            params: None,
        };
        let runtime_plan = task.runtime_plan(ResidualChunkingStrategy::ByOutputCount {
            max_outputs_per_chunk: 8,
        });
        let parallel = ParallelResidualExecutor::with_config(
            &runtime_plan,
            bind_residual_fixture_chunks(&runtime_plan),
            ParallelExecutorConfig {
                jobs_per_worker: 1,
                max_residual_jobs: None,
                max_sparse_jobs: None,
                fallback_policy: ParallelFallbackPolicy::Never,
            },
        );
        let flat_args = RuntimeArguments::new(
            &(0..16)
                .map(|index| 0.2 + index as f64 * 0.01)
                .collect::<Vec<_>>(),
            None,
        )
        .flatten();

        let out = parallel.eval(flat_args.as_slice());
        assert_eq!(out.len(), runtime_plan.output_len);
        assert!(!parallel.uses_sequential_fallback());
    }

    #[test]
    fn parallel_sparse_executor_allows_custom_thresholds() {
        let jac = build_real_bvp_damp1_case(8);
        let variable_names_owned = jac.variable_string.clone();
        let variables: Vec<&str> = variable_names_owned
            .iter()
            .map(|name| name.as_str())
            .collect();
        let entries_owned = jac.symbolic_jacobian_sparse_entries_owned();
        let entries = borrowed_sparse_entries(&entries_owned);
        let task = SparseJacobianTask {
            fn_name: "fixture_bvp_sparse_values",
            shape: (jac.vector_of_functions.len(), jac.vector_of_variables.len()),
            entries: &entries,
            variables: &variables,
            params: None,
        };
        let runtime_plan =
            task.runtime_plan(SparseChunkingStrategy::ByRowCount { rows_per_chunk: 1 });
        let parallel = ParallelSparseJacobianExecutor::with_config(
            &runtime_plan,
            bind_sparse_fixture_chunks(&runtime_plan),
            ParallelExecutorConfig {
                jobs_per_worker: 1,
                max_residual_jobs: None,
                max_sparse_jobs: None,
                fallback_policy: ParallelFallbackPolicy::Thresholds {
                    min_residual_outputs: usize::MAX,
                    min_sparse_values: 0,
                },
            },
        );
        let flat_args = RuntimeArguments::new(
            &(0..16)
                .map(|index| 0.2 + index as f64 * 0.01)
                .collect::<Vec<_>>(),
            None,
        )
        .flatten();

        let values = parallel.eval_values(flat_args.as_slice());
        assert_eq!(values.len(), runtime_plan.nnz());
        assert!(!parallel.uses_sequential_fallback());
    }

    #[test]
    fn sparse_auto_parallel_plan_stays_sequential_for_tiny_workloads() {
        let plan = recommended_sparse_auto_parallel_plan(16, 16, 32);

        assert_eq!(plan.execution_mode, AutoExecutionMode::Sequential);
        assert_eq!(plan.residual_chunking, ResidualChunkingStrategy::Whole);
        assert_eq!(plan.sparse_chunking, SparseChunkingStrategy::Whole);
        assert!(plan.executor_config.is_none());
        assert!(plan.min_work_per_job >= 1);
        assert!(plan.workers >= 1);
    }

    #[test]
    fn auto_parallel_executor_config_refuses_tiny_workloads() {
        let min_work = min_work_per_job_from_baseline(rayon_overhead_baseline());
        let tiny_work = min_work.saturating_sub(1).max(1);
        let chunk_count = 4;

        assert!(
            auto_parallel_fallback_for_workload(tiny_work, chunk_count, chunk_count),
            "tiny workloads should stay sequential"
        );
        assert!(
            auto_parallel_executor_config(tiny_work, chunk_count, tiny_work, chunk_count).is_none(),
            "Auto executor config should be absent for workloads too small to amortize parallel scheduling"
        );
    }

    #[test]
    fn sparse_auto_parallel_plan_exposes_parallel_shape_for_large_workloads() {
        let baseline = rayon_overhead_baseline();
        let min_work = min_work_per_job_from_baseline(baseline);
        let rows = min_work
            .saturating_mul(baseline.workers.max(2))
            .saturating_mul(4)
            .max(1536);
        let plan = recommended_sparse_auto_parallel_plan(rows, rows, rows.saturating_mul(4));

        assert!(plan.min_work_per_job >= 1);
        assert!(plan.workers >= 1);
        if plan.workers == 1 {
            assert_eq!(plan.execution_mode, AutoExecutionMode::Sequential);
            assert!(plan.executor_config.is_none());
            return;
        }

        assert_eq!(plan.execution_mode, AutoExecutionMode::Parallel);
        assert!(matches!(
            plan.residual_chunking,
            ResidualChunkingStrategy::ByOutputCount { .. }
        ));
        assert!(matches!(
            plan.sparse_chunking,
            SparseChunkingStrategy::ByRowCount { .. }
        ));
        let config = plan
            .executor_config
            .expect("large sparse workloads should produce runtime parallel config");
        assert_eq!(config.jobs_per_worker, 1);
        assert!(config.max_residual_jobs.unwrap_or(0) >= 1);
        assert!(config.max_sparse_jobs.unwrap_or(0) >= 2);
        assert_eq!(config.fallback_policy, ParallelFallbackPolicy::Never);
    }

    #[test]
    fn auto_fallback_rejects_overfragmented_medium_chunks() {
        let min_work = min_work_per_job_from_baseline(rayon_overhead_baseline());
        let total_work = min_work.saturating_mul(8);
        let chunk_count = 16;
        let job_count = 4;

        assert!(
            work_per_group(total_work, job_count) >= min_work,
            "test setup should have enough work per job"
        );
        assert!(
            work_per_group(total_work, chunk_count) < min_work,
            "test setup should expose too little work per chunk"
        );
        assert!(
            auto_parallel_fallback_for_workload(total_work, chunk_count, job_count),
            "Auto should stay sequential when chunks are too fine-grained even if grouped jobs look large enough"
        );
    }

    #[test]
    fn auto_fallback_allows_coarse_large_chunks() {
        let min_work = min_work_per_job_from_baseline(rayon_overhead_baseline());
        let total_work = min_work.saturating_mul(16);
        let chunk_count = 4;
        let job_count = 4;

        assert!(
            work_per_group(total_work, job_count) >= min_work,
            "test setup should have enough work per job"
        );
        assert!(
            work_per_group(total_work, chunk_count) >= min_work,
            "test setup should have enough work per chunk"
        );
        assert!(
            !auto_parallel_fallback_for_workload(total_work, chunk_count, job_count),
            "Auto should permit parallel execution when both jobs and chunks are coarse enough"
        );
    }
}