dijkstra3d-core 0.1.0

Voxel-grid Dijkstra and rolling-ball invalidation, ported from seung-lab/dijkstra3d and seung-lab/kimimaro
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
//! Single-source single-target shortest path.
//!
//! Upstream reference: `dijkstra3d.hpp::dijkstra3d` and `bidirectional_dijkstra3d`.

use crate::connectivity_graph::ConnectivityGraph;
use crate::neighborhood::{neighborhood_masks, neighborhood_offsets};
use crate::perf_pool::resolve_batch_pool;
use crate::queue::binary_heap::BinaryHeapQueue;
use crate::queue::bucket::BucketQueue;
use crate::queue::PriorityQueue;
use crate::voxel::{Anisotropy, ToF32Fast, ToU64Fast, VolumeShape, VoxelSource};
use crate::{Connectivity, Dijkstra3dError, Result};
use num_traits::ToPrimitive;
use rayon::prelude::*;

/// Run a batch fan-out `f` on the pool selected by `threads`
/// ([`resolve_batch_pool`]): the global rayon pool by default, or an opt-in
/// P-core-pinned pool for `Some(n > 0)`. See [`crate::perf_pool`].
fn run_batch_on_pool<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> R {
    match resolve_batch_pool(threads) {
        Some(pool) => pool.install(f),
        None => f(),
    }
}

/// Search mode for `dijkstra`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Unidirectional,

    Bidirectional,

    Compass,
}

/// Configuration shared by single-target searches.
#[derive(Debug, Clone, Copy)]
pub struct DijkstraConfig {
    pub connectivity: Connectivity,

    pub anisotropy: Anisotropy,

    pub mode: Mode,
}

impl Default for DijkstraConfig {
    fn default() -> Self {
        Self {
            connectivity: Connectivity::TwentySix,
            anisotropy: Anisotropy::default(),
            mode: Mode::Unidirectional,
        }
    }
}

/// Compute a path from `source` to `target` through the cost field.
///
/// Unidirectional and bidirectional modes return a shortest path. Compass mode
/// uses an unscaled Euclidean heuristic that is not generally admissible for
/// weighted fields, so it may return a higher-cost path.
pub fn dijkstra<V>(
    field: &V,
    source: u64,
    target: u64,
    cfg: DijkstraConfig,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>>
where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if target >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: total,
        });
    }
    if source == target {
        return Ok(vec![source]);
    }

    match cfg.mode {
        Mode::Unidirectional => dijkstra_unidirectional(field, source, target, cfg, graph),
        Mode::Bidirectional => dijkstra_bidirectional(field, source, target, cfg, graph),
        Mode::Compass => dijkstra_compass(field, source, target, cfg, graph),
    }
}

/// Standard unidirectional Dijkstra.
fn dijkstra_unidirectional<V>(
    field: &V,
    source: u64,
    target: u64,
    cfg: DijkstraConfig,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>>
where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    // Shortest-path state.
    let mut distances = vec![f32::INFINITY; total as usize];
    let mut parents = vec![0u64; total as usize];
    distances[source as usize] = 0.0;

    let mut queue = BinaryHeapQueue::<f32, u64>::new();
    queue.push(0.0, source);

    // Precompute neighbor metadata once.
    let sx = shape.sx as i64;
    let sxy = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx, sxy);
    let masks = neighborhood_masks();
    // let weights = neighborhood_weights(cfg.anisotropy);
    let neighbor_count = cfg.connectivity.count();

    // Precompute coordinates and bounds-per-axis to avoid wraparound bugs that
    // a pure linear-index bounds check would miss. The upstream uses a similar
    // per-axis check via integer division; the explicit form documents why
    // anisotropy-edge bugs surface in tests.
    let sx_u = shape.sx;
    let sy_u = shape.sy;
    let sz_u = shape.sz;

    while let Some((dist, loc)) = queue.pop() {
        // Lazy deletion.
        if dist > distances[loc as usize] {
            continue;
        }
        // Early termination.
        if loc == target {
            return Ok(reconstruct_path(&parents, source, target));
        }

        let (lx, ly, lz) = shape.coords(loc);

        for i in 0..neighbor_count {
            let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];

            // Per-axis bounds check using signed coordinates. This catches
            // wraparound: e.g. stepping +x from x=sx-1 would otherwise look
            // like a valid linear index pointing into the next y row.
            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0
                || nx >= sx_u as i64
                || ny < 0
                || ny >= sy_u as i64
                || nz < 0
                || nz >= sz_u as i64
            {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;

            // Voxel connectivity graph: skip forbidden directions.
            if let Some(ref g) = graph {
                if !g.allows(loc, masks[i]) {
                    continue;
                }
            }

            // Edge cost: field[neighbor] * geometric step length.
            let neighbor_cost = field.get(neighbor)?;
            let neighbor_cost_f32 = neighbor_cost.to_f32().ok_or(Dijkstra3dError::OutOfBounds {
                idx: neighbor,
                volume_size: total,
            })?;
            let new_dist = distances[loc as usize] + neighbor_cost_f32;

            if new_dist < distances[neighbor as usize] {
                distances[neighbor as usize] = new_dist;
                parents[neighbor as usize] = loc + 1; // +1 sentinel encoding
                queue.push(new_dist, neighbor);
            }
        }
    }

    Err(Dijkstra3dError::Unreachable)
}

/// Reconstruct the path from `source` to `target` using the parent array.
///
/// Parents use the +1 sentinel encoding: `parents[i] = parent_idx + 1`, with
/// `0` meaning unreached.
fn reconstruct_path(parents: &[u64], source: u64, target: u64) -> Vec<u64> {
    let mut path = vec![target];
    let mut current = target;
    while current != source {
        let parent = parents[current as usize];
        if parent == 0 {
            break;
        }
        current = parent - 1;
        path.push(current);
    }
    path.reverse();
    path
}

/// Bidirectional Dijkstra: simultaneous expansion from source and target.
fn dijkstra_bidirectional<V>(
    field: &V,
    source: u64,
    target: u64,
    cfg: DijkstraConfig,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>>
where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    // Cost-correction term used at the meeting check.
    let field_tgt_f32 = field
        .get(target)?
        .to_f32()
        .ok_or(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: total,
        })?;

    // Forward search rooted at source.
    let mut dist_fwd = vec![f32::INFINITY; total as usize];
    let mut parents_fwd = vec![0u64; total as usize];
    dist_fwd[source as usize] = 0.0;
    let mut queue_fwd = BinaryHeapQueue::<f32, u64>::new();
    queue_fwd.push(0.0, source);

    // Backward search rooted at target.
    let mut dist_bwd = vec![f32::INFINITY; total as usize];
    let mut parents_bwd = vec![0u64; total as usize];
    dist_bwd[target as usize] = 0.0;
    let mut queue_bwd = BinaryHeapQueue::<f32, u64>::new();
    queue_bwd.push(0.0, target);

    // Best meeting cost (corrected) and its meeting voxel.
    let mut best_cost = f32::INFINITY;
    let mut final_loc: Option<u64> = None;

    // Precompute neighbor metadata.
    let sx = shape.sx as i64;
    let sxy = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx, sxy);
    let masks = neighborhood_masks();
    let neighbor_count = cfg.connectivity.count();
    let sx_u = shape.sx;
    let sy_u = shape.sy;
    let sz_u = shape.sz;

    // Optimal bidirectional termination
    let mut forward = false;
    loop {
        let kf = match queue_fwd.peek() {
            Some((k, _)) => k,
            None => break,
        };
        let kb = match queue_bwd.peek() {
            Some((k, _)) => k,
            None => break,
        };
        if kf + kb >= best_cost {
            break;
        }

        forward = !forward;
        let (dist, loc) = if forward {
            queue_fwd.pop().unwrap()
        } else {
            queue_bwd.pop().unwrap()
        };
        let loc_us = loc as usize;

        // Lazy deletion on the active side.
        if forward {
            if dist > dist_fwd[loc_us] {
                continue;
            }
        } else if dist > dist_bwd[loc_us] {
            continue;
        }

        // Meeting check at settle.
        if (forward && dist_bwd[loc_us].is_finite()) || (!forward && dist_fwd[loc_us].is_finite()) {
            let field_loc_f32 = field
                .get(loc)?
                .to_f32()
                .ok_or(Dijkstra3dError::OutOfBounds {
                    idx: loc,
                    volume_size: total,
                })?;
            let cost = dist_fwd[loc_us] + dist_bwd[loc_us] + field_tgt_f32 - field_loc_f32;
            if cost < best_cost {
                best_cost = cost;
                final_loc = Some(loc);
            }
        }

        let (lx, ly, lz) = shape.coords(loc);
        for i in 0..neighbor_count {
            let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];
            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0
                || nx >= sx_u as i64
                || ny < 0
                || ny >= sy_u as i64
                || nz < 0
                || nz >= sz_u as i64
            {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;

            if let Some(ref g) = graph {
                if !g.allows(loc, masks[i]) {
                    continue;
                }
            }

            let neighbor_cost = field.get(neighbor)?;
            let neighbor_cost_f32 = neighbor_cost.to_f32().ok_or(Dijkstra3dError::OutOfBounds {
                idx: neighbor,
                volume_size: total,
            })?;

            if forward {
                let new_dist = dist_fwd[loc_us] + neighbor_cost_f32;
                if new_dist < dist_fwd[neighbor as usize] {
                    dist_fwd[neighbor as usize] = new_dist;
                    parents_fwd[neighbor as usize] = loc + 1;
                    queue_fwd.push(new_dist, neighbor);
                    if dist_bwd[neighbor as usize].is_finite() {
                        let cost = new_dist + dist_bwd[neighbor as usize] + field_tgt_f32
                            - neighbor_cost_f32;
                        if cost < best_cost {
                            best_cost = cost;
                            final_loc = Some(neighbor);
                        }
                    }
                }
            } else {
                let new_dist = dist_bwd[loc_us] + neighbor_cost_f32;
                if new_dist < dist_bwd[neighbor as usize] {
                    dist_bwd[neighbor as usize] = new_dist;
                    parents_bwd[neighbor as usize] = loc + 1;
                    queue_bwd.push(new_dist, neighbor);
                    if dist_fwd[neighbor as usize].is_finite() {
                        let cost = dist_fwd[neighbor as usize] + new_dist + field_tgt_f32
                            - neighbor_cost_f32;
                        if cost < best_cost {
                            best_cost = cost;
                            final_loc = Some(neighbor);
                        }
                    }
                }
            }
        }
    }

    // Reconstruct path. Upstream walks both halves outward from final_loc to
    // their respective search roots, reverses the forward half, and splices.
    //
    //   path_fwd (rooted at source)  : final_loc -> ... -> source
    //   path_rev (rooted at target)  : final_loc -> ... -> target
    if let Some(meet) = final_loc {
        let fwd = reconstruct_path(&parents_fwd, source, meet);

        let bwd = reconstruct_path(&parents_bwd, target, meet);

        let mut path = fwd;
        path.extend(bwd.iter().rev().skip(1).copied());
        Ok(path)
    } else {
        Err(Dijkstra3dError::Unreachable)
    }
}

/// Compass mode (A*): Dijkstra with Euclidean heuristic to target.
fn dijkstra_compass<V>(
    field: &V,
    source: u64,
    target: u64,
    cfg: DijkstraConfig,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>>
where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    let mut distances = vec![f32::INFINITY; total as usize];
    let mut parents = vec![0u64; total as usize];
    distances[source as usize] = 0.0;

    let mut queue = BinaryHeapQueue::<f32, u64>::new();

    // Compute heuristic for source
    let (tx, ty, tz) = shape.coords(target);
    let (sx_coord, sy_coord, sz_coord) = shape.coords(source);
    let h_source = euclidean_heuristic(sx_coord, sy_coord, sz_coord, tx, ty, tz, cfg.anisotropy);
    queue.push(h_source, source);

    let sx = shape.sx as i64;
    let sxy = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx, sxy);
    let masks = neighborhood_masks();
    let neighbor_count = cfg.connectivity.count();
    let sx_u = shape.sx;
    let sy_u = shape.sy;
    let sz_u = shape.sz;

    while let Some((_, loc)) = queue.pop() {
        // Queue order uses f = g + h, while stale-entry detection uses g.
        let current_g = distances[loc as usize];

        if loc == target {
            return Ok(reconstruct_path(&parents, source, target));
        }

        let (lx, ly, lz) = shape.coords(loc);

        for i in 0..neighbor_count {
            let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];
            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0
                || nx >= sx_u as i64
                || ny < 0
                || ny >= sy_u as i64
                || nz < 0
                || nz >= sz_u as i64
            {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;

            if let Some(ref g) = graph {
                if !g.allows(loc, masks[i]) {
                    continue;
                }
            }

            let neighbor_cost = field.get(neighbor)?;
            let neighbor_cost_f32 = neighbor_cost.to_f32().ok_or(Dijkstra3dError::OutOfBounds {
                idx: neighbor,
                volume_size: total,
            })?;
            let new_g = current_g + neighbor_cost_f32;

            if new_g < distances[neighbor as usize] {
                distances[neighbor as usize] = new_g;
                parents[neighbor as usize] = loc + 1;

                // Compute heuristic for neighbor
                let (nx_u, ny_u, nz_u) = shape.coords(neighbor);
                let h = euclidean_heuristic(nx_u, ny_u, nz_u, tx, ty, tz, cfg.anisotropy);
                let f = new_g + h;

                queue.push(f, neighbor);
            }
        }
    }

    Err(Dijkstra3dError::Unreachable)
}

/// Euclidean distance used to order the Compass frontier.
///
/// This value is not generally an admissible lower bound for the entered-voxel
/// cost model, particularly with diagonal connectivity or weights below the
/// corresponding geometric step length.
fn euclidean_heuristic(
    x: u64,
    y: u64,
    z: u64,
    tx: u64,
    ty: u64,
    tz: u64,
    aniso: Anisotropy,
) -> f32 {
    let (wx, wy, wz) = (aniso.wx, aniso.wy, aniso.wz);
    let dx = (x as f32 - tx as f32) * wx;
    let dy = (y as f32 - ty as f32) * wy;
    let dz = (z as f32 - tz as f32) * wz;
    (dx * dx + dy * dy + dz * dz).sqrt()
}

/// Empirically-tuned informativeness threshold for the compass heuristic.
pub const COMPASS_INFORMATIVE_RATIO: f32 = 0.30;

pub fn compass_heuristic_is_informative<T: ToF32Fast>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    anisotropy: Anisotropy,
) -> bool {
    let (sx, sy, sz) = shape.coords(source);
    let (tx, ty, tz) = shape.coords(target);

    let dx = (sx as i64 - tx as i64).unsigned_abs();
    let dy = (sy as i64 - ty as i64).unsigned_abs();
    let dz = (sz as i64 - tz as i64).unsigned_abs();
    let cheb = dx.max(dy).max(dz);
    if cheb == 0 {
        // The caller normally handles source == target. Return early here as well
        // to avoid dividing by zero.
        return true;
    }

    // Median field value along the straight source->target segment.
    let mut samples: Vec<f32> = Vec::with_capacity(cheb as usize + 1);
    let (fsx, fsy, fsz) = (sx as f64, sy as f64, sz as f64);
    let (seg_x, seg_y, seg_z) = (
        tx as f64 - sx as f64,
        ty as f64 - sy as f64,
        tz as f64 - sz as f64,
    );
    for k in 0..=cheb {
        let t = k as f64 / cheb as f64;
        let px = (fsx + seg_x * t).round() as u64;
        let py = (fsy + seg_y * t).round() as u64;
        let pz = (fsz + seg_z * t).round() as u64;
        let idx = shape.linear(px, py, pz) as usize;
        samples.push(field[idx].to_f32_fast());
    }
    samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let line_cost = samples[samples.len() / 2];

    let h = euclidean_heuristic(sx, sy, sz, tx, ty, tz, anisotropy);
    h >= COMPASS_INFORMATIVE_RATIO * line_cost * cheb as f32
}

/// Slice-based fast path for unidirectional Dijkstra.
pub fn dijkstra_unidirectional_slice<T>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>>
where
    T: ToF32Fast,
{
    let total = shape.total();

    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_unidirectional_slice: slice length {} != shape.total() {}",
            field.len(),
            total
        )));
    }
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if target >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: total,
        });
    }
    if source == target {
        return Ok(vec![source]);
    }

    let mut distances = vec![f32::INFINITY; total as usize];
    let mut parents = vec![0u64; total as usize];
    distances[source as usize] = 0.0;

    let mut queue = BinaryHeapQueue::<f32, u64>::new();
    queue.push(0.0, source);

    let sx_i = shape.sx as i64;
    let sxy_i = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx_i, sxy_i);
    let masks = neighborhood_masks();
    let neighbor_count = connectivity.count();

    let sx_u = shape.sx;
    let sy_u = shape.sy;
    let sz_u = shape.sz;

    while let Some((dist, loc)) = queue.pop() {
        if dist > distances[loc as usize] {
            continue;
        }
        if loc == target {
            return Ok(reconstruct_path(&parents, source, target));
        }

        let (lx, ly, lz) = shape.coords(loc);
        let current_dist = distances[loc as usize];

        for i in 0..neighbor_count {
            let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];

            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0
                || nx >= sx_u as i64
                || ny < 0
                || ny >= sy_u as i64
                || nz < 0
                || nz >= sz_u as i64
            {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;

            if let Some(ref g) = graph {
                if !g.allows(loc, masks[i]) {
                    continue;
                }
            }

            let neighbor_cost_f32 = field[neighbor as usize].to_f32_fast();
            let new_dist = current_dist + neighbor_cost_f32;

            if new_dist < distances[neighbor as usize] {
                distances[neighbor as usize] = new_dist;
                parents[neighbor as usize] = loc + 1;
                queue.push(new_dist, neighbor);
            }
        }
    }

    Err(Dijkstra3dError::Unreachable)
}

/// Reconstruct the path from `source` to `target` using a `u32` parent array.
fn reconstruct_path_u32(parents: &[u32], source: u64, target: u64) -> Vec<u64> {
    let mut path = vec![target];
    let mut current = target;
    while current != source {
        let parent = parents[current as usize];
        if parent == 0 {
            break;
        }
        current = (parent - 1) as u64;
        path.push(current);
    }
    path.reverse();
    path
}

/// Minimal integer priority-queue abstraction shared by the integer fast path.
pub(crate) trait IntQueue {
    fn push_i(&mut self, priority: u64, payload: u32);

    fn pop_i(&mut self) -> Option<(u64, u32)>;

    fn peek_key_i(&mut self) -> Option<u64>;
}

impl IntQueue for BucketQueue {
    #[inline]
    fn push_i(&mut self, priority: u64, payload: u32) {
        self.push(priority, payload);
    }
    #[inline]
    fn pop_i(&mut self) -> Option<(u64, u32)> {
        self.pop()
    }
    #[inline]
    fn peek_key_i(&mut self) -> Option<u64> {
        self.peek_key()
    }
}

impl IntQueue for BinaryHeapQueue<u64, u32> {
    #[inline]
    fn push_i(&mut self, priority: u64, payload: u32) {
        self.push(priority, payload);
    }
    #[inline]
    fn pop_i(&mut self) -> Option<(u64, u32)> {
        self.pop()
    }
    #[inline]
    fn peek_key_i(&mut self) -> Option<u64> {
        <Self as PriorityQueue<u64, u32>>::peek(self).map(|(p, _)| p)
    }
}

/// Distance-accumulator width for the integer search. Narrower widths touch fewer
/// bytes per voxel in the `distances` array, the dominant allocation for large
/// volumes.
pub(crate) trait Dist: Copy + Ord {
    const MAX: Self;
    const ZERO: Self;

    fn add_cost(self, w: u64) -> Self;

    fn to_priority(self) -> u64;
}
impl Dist for u16 {
    const MAX: Self = u16::MAX;
    const ZERO: Self = 0;
    #[inline]
    fn add_cost(self, w: u64) -> Self {
        self + w as u16
    }
    #[inline]
    fn to_priority(self) -> u64 {
        self as u64
    }
}
impl Dist for u32 {
    const MAX: Self = u32::MAX;
    const ZERO: Self = 0;
    #[inline]
    fn add_cost(self, w: u64) -> Self {
        self + w as u32
    }
    #[inline]
    fn to_priority(self) -> u64 {
        self as u64
    }
}
impl Dist for u64 {
    const MAX: Self = u64::MAX;
    const ZERO: Self = 0;
    #[inline]
    fn add_cost(self, w: u64) -> Self {
        self + w
    }
    #[inline]
    fn to_priority(self) -> u64 {
        self
    }
}

/// Which [`Dist`] width the integer search should monomorphize on.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum DistWidth {
    U16,
    U32,
    U64,
}

/// Priority queue forced by the external ablation harness.
///
/// This diagnostic type is not part of the stable API.
#[doc(hidden)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum AblationQueue {
    Dial,

    BinaryHeap,
}

/// Distance accumulator forced by the external ablation harness.
#[doc(hidden)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum AblationDistanceWidth {
    U16,

    U32,

    U64,
}

/// Pick the narrowest [`Dist`] width that can represent every finite distance.
#[inline]
pub(crate) fn select_dist_width(dist_bound: u64) -> DistWidth {
    if dist_bound <= u16::MAX as u64 {
        DistWidth::U16
    } else if dist_bound <= u32::MAX as u64 {
        DistWidth::U32
    } else {
        DistWidth::U64
    }
}

/// Validate the conservative integer-distance bound used to select accumulator
/// widths. `u64::MAX` is reserved as the unreached sentinel.
pub(crate) fn checked_int_distance_bound(shape: VolumeShape, max_weight: u64) -> Result<u64> {
    let max_steps = shape
        .sx
        .checked_add(shape.sy)
        .and_then(|sum| sum.checked_add(shape.sz))
        .and_then(|sum| sum.checked_add(1))
        .ok_or_else(|| {
            Dijkstra3dError::InvalidInput(format!(
                "volume dimensions ({}, {}, {}) overflow integer distance bounds",
                shape.sx, shape.sy, shape.sz
            ))
        })?;
    let bound = max_steps.checked_mul(max_weight).ok_or_else(|| {
        Dijkstra3dError::InvalidInput(format!(
            "integer costs with maximum weight {max_weight} are too large for shape ({}, {}, {})",
            shape.sx, shape.sy, shape.sz
        ))
    })?;
    if bound == u64::MAX {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "integer costs with maximum weight {max_weight} collide with the u64::MAX distance sentinel"
        )));
    }
    Ok(bound)
}

/// Integer slice fast-path for unidirectional Dijkstra.
pub fn dijkstra_unidirectional_slice_int<T: ToU64Fast>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>> {
    let total = shape.total();

    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_unidirectional_slice_int: slice length {} != shape.total() {}",
            field.len(),
            total
        )));
    }
    if total > u32::MAX as u64 {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_unidirectional_slice_int: volume {total} exceeds u32::MAX voxels; \
             use the u64 fast path"
        )));
    }
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if target >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: total,
        });
    }
    if source == target {
        return Ok(vec![source]);
    }

    // Pre-scan for the maximum edge weight (field is non-empty: total >= 1).
    let max_weight = field.iter().map(|&v| v.to_u64_fast()).max().unwrap_or(0);

    let dist_bound = checked_int_distance_bound(shape, max_weight)?;
    let width = select_dist_width(dist_bound);

    let use_bucket = max_weight < 65_536;

    match (use_bucket, width) {
        (true, DistWidth::U16) => slice_int_search::<_, _, u16>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (true, DistWidth::U32) => slice_int_search::<_, _, u32>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (true, DistWidth::U64) => slice_int_search::<_, _, u64>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (false, DistWidth::U16) => slice_int_search::<_, _, u16>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BinaryHeapQueue::<u64, u32>::new(),
        ),
        (false, DistWidth::U32) => slice_int_search::<_, _, u32>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BinaryHeapQueue::<u64, u32>::new(),
        ),
        (false, DistWidth::U64) => slice_int_search::<_, _, u64>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BinaryHeapQueue::<u64, u32>::new(),
        ),
    }
}

/// Run an integer shortest-path query with a forced queue and distance width.
///
/// This is a diagnostic entry point for controlled ablations.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn dijkstra_unidirectional_slice_int_ablation<T: ToU64Fast>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    queue: AblationQueue,
    width: AblationDistanceWidth,
) -> Result<Vec<u64>> {
    let total = shape.total();
    if field.len() as u64 != total || total > u32::MAX as u64 {
        return Err(Dijkstra3dError::InvalidInput(
            "integer ablation field/shape is invalid".into(),
        ));
    }
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if target >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: total,
        });
    }
    if source == target {
        return Ok(vec![source]);
    }

    let max_weight = field
        .iter()
        .map(|&value| value.to_u64_fast())
        .max()
        .unwrap_or(0);
    let dist_bound = checked_int_distance_bound(shape, max_weight)?;
    if queue == AblationQueue::Dial && max_weight >= 65_536 {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "Dial ablation requires max_weight < 65536; got {max_weight}"
        )));
    }
    let width_limit = match width {
        AblationDistanceWidth::U16 => u16::MAX as u64,
        AblationDistanceWidth::U32 => u32::MAX as u64,
        AblationDistanceWidth::U64 => u64::MAX,
    };
    if dist_bound > width_limit {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "forced {width:?} distance cannot represent bound {dist_bound}"
        )));
    }

    macro_rules! run {
        ($dist:ty, $queue:expr) => {
            slice_int_search::<_, _, $dist>(
                field,
                shape,
                source,
                target,
                connectivity,
                graph,
                $queue,
            )
        };
    }

    match (queue, width) {
        (AblationQueue::Dial, AblationDistanceWidth::U16) => {
            run!(u16, BucketQueue::with_capacity(max_weight as u32))
        }
        (AblationQueue::Dial, AblationDistanceWidth::U32) => {
            run!(u32, BucketQueue::with_capacity(max_weight as u32))
        }
        (AblationQueue::Dial, AblationDistanceWidth::U64) => {
            run!(u64, BucketQueue::with_capacity(max_weight as u32))
        }
        (AblationQueue::BinaryHeap, AblationDistanceWidth::U16) => {
            run!(u16, BinaryHeapQueue::<u64, u32>::new())
        }
        (AblationQueue::BinaryHeap, AblationDistanceWidth::U32) => {
            run!(u32, BinaryHeapQueue::<u64, u32>::new())
        }
        (AblationQueue::BinaryHeap, AblationDistanceWidth::U64) => {
            run!(u64, BinaryHeapQueue::<u64, u32>::new())
        }
    }
}

fn slice_int_search<T: ToU64Fast, Q: IntQueue, D: Dist>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    mut queue: Q,
) -> Result<Vec<u64>> {
    let total = shape.total() as usize;

    let mut distances = vec![D::MAX; total];
    let mut parents = vec![0u32; total];
    distances[source as usize] = D::ZERO;
    queue.push_i(0, source as u32);

    let sx_i = shape.sx as i64;
    let sxy_i = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx_i, sxy_i);
    let masks = neighborhood_masks();
    let neighbor_count = connectivity.count();

    let sx_u = shape.sx as i64;
    let sy_u = shape.sy as i64;
    let sz_u = shape.sz as i64;

    while let Some((dist, loc)) = queue.pop_i() {
        let loc_us = loc as usize;
        // Lazy deletion.
        if dist > distances[loc_us].to_priority() {
            continue;
        }
        // Early termination.
        if loc as u64 == target {
            return Ok(reconstruct_path_u32(&parents, source, target));
        }

        let (lx, ly, lz) = shape.coords(loc as u64);
        let current_dist = distances[loc_us];

        for i in 0..neighbor_count {
            let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];

            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0 || nx >= sx_u || ny < 0 || ny >= sy_u || nz < 0 || nz >= sz_u {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;

            if let Some(ref g) = graph {
                if !g.allows(loc as u64, masks[i]) {
                    continue;
                }
            }

            let neighbor_cost = field[neighbor as usize].to_u64_fast();
            let new_dist = current_dist.add_cost(neighbor_cost);

            if new_dist < distances[neighbor as usize] {
                distances[neighbor as usize] = new_dist;
                parents[neighbor as usize] = loc + 1; // +1 sentinel encoding
                queue.push_i(new_dist.to_priority(), neighbor as u32);
            }
        }
    }

    Err(Dijkstra3dError::Unreachable)
}

/// Slice-based fast path for bidirectional Dijkstra.
pub fn dijkstra_bidirectional_slice<T: ToF32Fast>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>> {
    let total = shape.total();
    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_bidirectional_slice: slice length {} != shape.total() {}",
            field.len(),
            total
        )));
    }
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if target >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: total,
        });
    }
    if source == target {
        return Ok(vec![source]);
    }

    let field_tgt_f32 = field[target as usize].to_f32_fast();

    let mut dist_fwd = vec![f32::INFINITY; total as usize];
    let mut parents_fwd = vec![0u64; total as usize];
    dist_fwd[source as usize] = 0.0;
    let mut queue_fwd = BinaryHeapQueue::<f32, u64>::new();
    queue_fwd.push(0.0, source);

    let mut dist_bwd = vec![f32::INFINITY; total as usize];
    let mut parents_bwd = vec![0u64; total as usize];
    dist_bwd[target as usize] = 0.0;
    let mut queue_bwd = BinaryHeapQueue::<f32, u64>::new();
    queue_bwd.push(0.0, target);

    let mut best_cost = f32::INFINITY;
    let mut final_loc: Option<u64> = None;

    let sx = shape.sx as i64;
    let sxy = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx, sxy);
    let masks = neighborhood_masks();
    let neighbor_count = connectivity.count();
    let sx_u = shape.sx;
    let sy_u = shape.sy;
    let sz_u = shape.sz;

    // Optimal bidirectional termination uses the minimum-key frontier sum.
    let mut forward = false;
    loop {
        // Frontier minimum keys (peek, does not consume).
        let kf = match queue_fwd.peek() {
            Some((k, _)) => k,
            None => break,
        };
        let kb = match queue_bwd.peek() {
            Some((k, _)) => k,
            None => break,
        };
        if kf + kb >= best_cost {
            break;
        }

        forward = !forward;
        let (dist, loc) = if forward {
            queue_fwd.pop().unwrap()
        } else {
            queue_bwd.pop().unwrap()
        };
        let loc_us = loc as usize;

        // Lazy deletion: skip stale queue entries on the active side.
        if forward {
            if dist > dist_fwd[loc_us] {
                continue;
            }
        } else if dist > dist_bwd[loc_us] {
            continue;
        }

        // Meeting check at settle: opposite side already reached loc.
        if forward {
            if dist_bwd[loc_us].is_finite() {
                let cost = dist_fwd[loc_us] + dist_bwd[loc_us] + field_tgt_f32
                    - field[loc_us].to_f32_fast();
                if cost < best_cost {
                    best_cost = cost;
                    final_loc = Some(loc);
                }
            }
        } else if dist_fwd[loc_us].is_finite() {
            let cost =
                dist_fwd[loc_us] + dist_bwd[loc_us] + field_tgt_f32 - field[loc_us].to_f32_fast();
            if cost < best_cost {
                best_cost = cost;
                final_loc = Some(loc);
            }
        }

        let (lx, ly, lz) = shape.coords(loc);
        for i in 0..neighbor_count {
            let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];
            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0
                || nx >= sx_u as i64
                || ny < 0
                || ny >= sy_u as i64
                || nz < 0
                || nz >= sz_u as i64
            {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;

            if let Some(ref g) = graph {
                if !g.allows(loc, masks[i]) {
                    continue;
                }
            }

            let neighbor_cost_f32 = field[neighbor as usize].to_f32_fast();

            if forward {
                let new_dist = dist_fwd[loc_us] + neighbor_cost_f32;
                if new_dist < dist_fwd[neighbor as usize] {
                    dist_fwd[neighbor as usize] = new_dist;
                    parents_fwd[neighbor as usize] = loc + 1;
                    queue_fwd.push(new_dist, neighbor);
                    // Meeting via this relaxed edge.
                    if dist_bwd[neighbor as usize].is_finite() {
                        let cost = new_dist + dist_bwd[neighbor as usize] + field_tgt_f32
                            - neighbor_cost_f32;
                        if cost < best_cost {
                            best_cost = cost;
                            final_loc = Some(neighbor);
                        }
                    }
                }
            } else {
                let new_dist = dist_bwd[loc_us] + neighbor_cost_f32;
                if new_dist < dist_bwd[neighbor as usize] {
                    dist_bwd[neighbor as usize] = new_dist;
                    parents_bwd[neighbor as usize] = loc + 1;
                    queue_bwd.push(new_dist, neighbor);
                    if dist_fwd[neighbor as usize].is_finite() {
                        let cost = dist_fwd[neighbor as usize] + new_dist + field_tgt_f32
                            - neighbor_cost_f32;
                        if cost < best_cost {
                            best_cost = cost;
                            final_loc = Some(neighbor);
                        }
                    }
                }
            }
        }
    }

    if let Some(meet) = final_loc {
        let fwd = reconstruct_path(&parents_fwd, source, meet);
        let bwd = reconstruct_path(&parents_bwd, target, meet);
        let mut path = fwd;
        path.extend(bwd.iter().rev().skip(1).copied());
        Ok(path)
    } else {
        Err(Dijkstra3dError::Unreachable)
    }
}

/// Integer slice fast-path for bidirectional Dijkstra.
pub fn dijkstra_bidirectional_slice_int<T: ToU64Fast>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>> {
    let total = shape.total();

    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_bidirectional_slice_int: slice length {} != shape.total() {}",
            field.len(),
            total
        )));
    }
    if total > u32::MAX as u64 {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_bidirectional_slice_int: volume {total} exceeds u32::MAX voxels; \
             use the u64/f32 path"
        )));
    }
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if target >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: total,
        });
    }
    if source == target {
        return Ok(vec![source]);
    }

    // Same width/queue selection logic as the unidirectional dispatcher.
    let max_weight = field.iter().map(|&v| v.to_u64_fast()).max().unwrap_or(0);
    let dist_bound = checked_int_distance_bound(shape, max_weight)?;
    let use_u32 = dist_bound <= u32::MAX as u64;
    let use_bucket = max_weight < 65_536;

    match (use_bucket, use_u32) {
        (true, true) => bidir_int_search::<_, _, u32>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BucketQueue::with_capacity(max_weight as u32),
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (true, false) => bidir_int_search::<_, _, u64>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BucketQueue::with_capacity(max_weight as u32),
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (false, true) => bidir_int_search::<_, _, u32>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BinaryHeapQueue::<u64, u32>::new(),
            BinaryHeapQueue::<u64, u32>::new(),
        ),
        (false, false) => bidir_int_search::<_, _, u64>(
            field,
            shape,
            source,
            target,
            connectivity,
            graph,
            BinaryHeapQueue::<u64, u32>::new(),
            BinaryHeapQueue::<u64, u32>::new(),
        ),
    }
}

/// Shared integer bidirectional search, monomorphized over the queue type `Q`
/// and the distance-accumulator width `D`.
#[allow(clippy::too_many_arguments)]
fn bidir_int_search<T: ToU64Fast, Q: IntQueue, D: Dist>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    mut queue_fwd: Q,
    mut queue_bwd: Q,
) -> Result<Vec<u64>> {
    let total = shape.total() as usize;
    let field_tgt = field[target as usize].to_u64_fast();

    let mut dist_fwd = vec![D::MAX; total];
    let mut parents_fwd = vec![0u32; total];
    dist_fwd[source as usize] = D::ZERO;
    queue_fwd.push_i(0, source as u32);

    let mut dist_bwd = vec![D::MAX; total];
    let mut parents_bwd = vec![0u32; total];
    dist_bwd[target as usize] = D::ZERO;
    queue_bwd.push_i(0, target as u32);

    // Best corrected meeting cost (mu) and its meeting voxel.
    let mut best_cost: u64 = u64::MAX;
    let mut final_loc: Option<u32> = None;

    let sx_i = shape.sx as i64;
    let sxy_i = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx_i, sxy_i);
    let masks = neighborhood_masks();
    let neighbor_count = connectivity.count();
    let sx_u = shape.sx as i64;
    let sy_u = shape.sy as i64;
    let sz_u = shape.sz as i64;

    loop {
        // Exact frontier minima (peek, not last-popped) — the tight stop bound.
        // If either side is exhausted, no further meeting can improve `mu`.
        let kf = match queue_fwd.peek_key_i() {
            Some(k) => k,
            None => break,
        };
        let kb = match queue_bwd.peek_key_i() {
            Some(k) => k,
            None => break,
        };
        // Optimal frontier-sum stop.
        if kf.saturating_add(kb) >= best_cost {
            break;
        }

        // Balance: expand whichever frontier minimum is currently smaller.
        let forward = kf <= kb;
        let (dist, loc) = if forward {
            queue_fwd.pop_i().unwrap()
        } else {
            queue_bwd.pop_i().unwrap()
        };
        let loc_us = loc as usize;

        // Lazy deletion.
        if forward {
            if dist > dist_fwd[loc_us].to_priority() {
                continue;
            }
        } else if dist > dist_bwd[loc_us].to_priority() {
            continue;
        }

        // Meeting check at settle: opposite side already reached loc.
        let opp_reached = if forward {
            dist_bwd[loc_us] != D::MAX
        } else {
            dist_fwd[loc_us] != D::MAX
        };
        if opp_reached {
            let field_loc = field[loc_us].to_u64_fast();
            // s = dist_fwd + dist_bwd + field_tgt >= field_loc always
            // (the side that stepped into loc includes field_loc in its arrival).
            let s = dist_fwd[loc_us]
                .to_priority()
                .saturating_add(dist_bwd[loc_us].to_priority())
                .saturating_add(field_tgt);
            let cost = s - field_loc;
            if cost < best_cost {
                best_cost = cost;
                final_loc = Some(loc);
            }
        }

        let (lx, ly, lz) = shape.coords(loc as u64);
        for i in 0..neighbor_count {
            let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];
            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0 || nx >= sx_u || ny < 0 || ny >= sy_u || nz < 0 || nz >= sz_u {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;
            let neighbor_us = neighbor as usize;

            if let Some(ref g) = graph {
                if !g.allows(loc as u64, masks[i]) {
                    continue;
                }
            }

            let neighbor_cost = field[neighbor_us].to_u64_fast();

            if forward {
                let new_dist = dist_fwd[loc_us].add_cost(neighbor_cost);
                if new_dist < dist_fwd[neighbor_us] {
                    dist_fwd[neighbor_us] = new_dist;
                    parents_fwd[neighbor_us] = loc + 1;
                    queue_fwd.push_i(new_dist.to_priority(), neighbor as u32);
                    // Meeting via this relaxed edge.
                    if dist_bwd[neighbor_us] != D::MAX {
                        let s = new_dist
                            .to_priority()
                            .saturating_add(dist_bwd[neighbor_us].to_priority())
                            .saturating_add(field_tgt);
                        let cost = s - neighbor_cost;
                        if cost < best_cost {
                            best_cost = cost;
                            final_loc = Some(neighbor as u32);
                        }
                    }
                }
            } else {
                let new_dist = dist_bwd[loc_us].add_cost(neighbor_cost);
                if new_dist < dist_bwd[neighbor_us] {
                    dist_bwd[neighbor_us] = new_dist;
                    parents_bwd[neighbor_us] = loc + 1;
                    queue_bwd.push_i(new_dist.to_priority(), neighbor as u32);
                    if dist_fwd[neighbor_us] != D::MAX {
                        let s = dist_fwd[neighbor_us]
                            .to_priority()
                            .saturating_add(new_dist.to_priority())
                            .saturating_add(field_tgt);
                        let cost = s - neighbor_cost;
                        if cost < best_cost {
                            best_cost = cost;
                            final_loc = Some(neighbor as u32);
                        }
                    }
                }
            }
        }
    }

    if let Some(meet) = final_loc {
        let meet = meet as u64;
        let fwd = reconstruct_path_u32(&parents_fwd, source, meet);
        let bwd = reconstruct_path_u32(&parents_bwd, target, meet);
        let mut path = fwd;
        path.extend(bwd.iter().rev().skip(1).copied());
        Ok(path)
    } else {
        Err(Dijkstra3dError::Unreachable)
    }
}

/// Slice-based fast path for compass (A*) Dijkstra.
pub fn dijkstra_compass_slice<T: ToF32Fast>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    anisotropy: Anisotropy,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u64>> {
    let total = shape.total();
    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_compass_slice: slice length {} != shape.total() {}",
            field.len(),
            total
        )));
    }
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if target >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: total,
        });
    }
    if source == target {
        return Ok(vec![source]);
    }

    let mut distances = vec![f32::INFINITY; total as usize];
    let mut parents = vec![0u64; total as usize];
    distances[source as usize] = 0.0;

    let mut queue = BinaryHeapQueue::<f32, u64>::new();

    let (tx, ty, tz) = shape.coords(target);
    let (sx_coord, sy_coord, sz_coord) = shape.coords(source);
    let h_source = euclidean_heuristic(sx_coord, sy_coord, sz_coord, tx, ty, tz, anisotropy);
    queue.push(h_source, source);

    let sx = shape.sx as i64;
    let sxy = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx, sxy);
    let masks = neighborhood_masks();
    let neighbor_count = connectivity.count();
    let sx_u = shape.sx;
    let sy_u = shape.sy;
    let sz_u = shape.sz;

    while let Some((_, loc)) = queue.pop() {
        let current_g = distances[loc as usize];

        if loc == target {
            return Ok(reconstruct_path(&parents, source, target));
        }

        let (lx, ly, lz) = shape.coords(loc);

        for i in 0..neighbor_count {
            let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];
            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0
                || nx >= sx_u as i64
                || ny < 0
                || ny >= sy_u as i64
                || nz < 0
                || nz >= sz_u as i64
            {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;

            if let Some(ref g) = graph {
                if !g.allows(loc, masks[i]) {
                    continue;
                }
            }

            let neighbor_cost_f32 = field[neighbor as usize].to_f32_fast();
            let new_g = current_g + neighbor_cost_f32;

            if new_g < distances[neighbor as usize] {
                distances[neighbor as usize] = new_g;
                parents[neighbor as usize] = loc + 1;

                // (nx, ny, nz) are the neighbor's coordinates already — reuse them
                // instead of recomputing shape.coords(neighbor).
                let h =
                    euclidean_heuristic(nx as u64, ny as u64, nz as u64, tx, ty, tz, anisotropy);
                let f = new_g + h;

                queue.push(f, neighbor);
            }
        }
    }

    Err(Dijkstra3dError::Unreachable)
}

// Batch shortest paths over independent query pairs.

struct BatchScratchInt<D: Dist> {
    distances: Vec<D>,
    parents: Vec<u32>,
}

impl<D: Dist> BatchScratchInt<D> {
    fn new(total: usize) -> Self {
        Self {
            distances: vec![D::MAX; total],
            parents: vec![0u32; total],
        }
    }

    #[inline]
    fn reset(&mut self) {
        self.distances.iter_mut().for_each(|d| *d = D::MAX);
        self.parents.iter_mut().for_each(|p| *p = 0);
    }
}

/// One integer batch search reusing pre-allocated `scratch` and a fresh `queue`.
fn slice_int_search_reuse<T: ToU64Fast, Q: IntQueue, D: Dist>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    scratch: &mut BatchScratchInt<D>,
    mut queue: Q,
) -> Result<Vec<u64>> {
    let out = {
        let distances = &mut scratch.distances;
        let parents = &mut scratch.parents;

        distances[source as usize] = D::ZERO;
        queue.push_i(0, source as u32);

        let sx_i = shape.sx as i64;
        let sxy_i = (shape.sx * shape.sy) as i64;
        let offsets = neighborhood_offsets(sx_i, sxy_i);
        let neighbor_count = connectivity.count();

        let sx_u = shape.sx as i64;
        let sy_u = shape.sy as i64;
        let sz_u = shape.sz as i64;

        let mut result: Result<Vec<u64>> = Err(Dijkstra3dError::Unreachable);
        while let Some((dist, loc)) = queue.pop_i() {
            let loc_us = loc as usize;
            // Lazy deletion.
            if dist > distances[loc_us].to_priority() {
                continue;
            }
            // Early termination.
            if loc as u64 == target {
                result = Ok(reconstruct_path_u32(parents, source, target));
                break;
            }

            let (lx, ly, lz) = shape.coords(loc as u64);
            let current_dist = distances[loc_us];

            for i in 0..neighbor_count {
                let (dx, dy, dz) = crate::neighborhood::DIRECTIONS_26[i];

                let nx = lx as i64 + dx as i64;
                let ny = ly as i64 + dy as i64;
                let nz = lz as i64 + dz as i64;
                if nx < 0 || nx >= sx_u || ny < 0 || ny >= sy_u || nz < 0 || nz >= sz_u {
                    continue;
                }

                let neighbor = (loc as i64 + offsets[i]) as u64;
                let neighbor_us = neighbor as usize;

                let neighbor_cost = field[neighbor_us].to_u64_fast();
                let new_dist = current_dist.add_cost(neighbor_cost);

                if new_dist < distances[neighbor_us] {
                    distances[neighbor_us] = new_dist;
                    parents[neighbor_us] = loc + 1; // +1 sentinel encoding
                    queue.push_i(new_dist.to_priority(), neighbor as u32);
                }
            }
        }
        result
    };

    // Restore the clean state for the next pair this worker handles.
    scratch.reset();
    out
}

/// Batch shortest paths on an unsigned-integer cost field: rayon over pairs.
pub fn dijkstra_batch_slice_int<T: ToU64Fast + Sync>(
    field: &[T],
    shape: VolumeShape,
    pairs: &[(u64, u64)],
    connectivity: Connectivity,
    threads: Option<usize>,
) -> Vec<Result<Vec<u64>>> {
    let total = shape.total();

    // Global (field-level) validation: replicate one error per pair so the
    // return shape stays uniform (element i <-> pairs[i]).
    let global_err = if field.len() as u64 != total {
        Some(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_batch_slice_int: slice length {} != shape.total() {}",
            field.len(),
            total
        )))
    } else if total > u32::MAX as u64 {
        Some(Dijkstra3dError::InvalidInput(format!(
            "dijkstra_batch_slice_int: volume {total} exceeds u32::MAX voxels; \
             use the u64/f32 path"
        )))
    } else {
        None
    };
    if let Some(err) = global_err {
        return pairs.iter().map(|_| Err(err.clone())).collect();
    }

    // Field-global decisions hoisted out of the per-pair loop: max edge weight,
    // distance width, and queue kind are identical for every pair on this field
    // (see `dijkstra_unidirectional_slice_int` for the derivation).
    let max_weight = field.iter().map(|&v| v.to_u64_fast()).max().unwrap_or(0);
    let dist_bound = match checked_int_distance_bound(shape, max_weight) {
        Ok(bound) => bound,
        Err(error) => return pairs.iter().map(|_| Err(error.clone())).collect(),
    };
    let use_u32 = dist_bound <= u32::MAX as u64;
    let use_bucket = max_weight < 65_536;

    // Fan out on the pool `threads` selects (global by default; opt-in
    // P-core-pinned for `Some(n>0)`). The per-pair engine and output are
    // pool-independent.
    run_batch_on_pool(threads, || match (use_bucket, use_u32) {
        (true, true) => batch_int_run::<T, u32, _, _>(field, shape, pairs, connectivity, || {
            BucketQueue::with_capacity(max_weight as u32)
        }),
        (true, false) => batch_int_run::<T, u64, _, _>(field, shape, pairs, connectivity, || {
            BucketQueue::with_capacity(max_weight as u32)
        }),
        (false, true) => batch_int_run::<T, u32, _, _>(field, shape, pairs, connectivity, || {
            BinaryHeapQueue::<u64, u32>::new()
        }),
        (false, false) => batch_int_run::<T, u64, _, _>(field, shape, pairs, connectivity, || {
            BinaryHeapQueue::<u64, u32>::new()
        }),
    })
}

/// Monomorphised batch runner over distance width `D` and queue type `Q`.
fn batch_int_run<T, D, Q, Mk>(
    field: &[T],
    shape: VolumeShape,
    pairs: &[(u64, u64)],
    connectivity: Connectivity,
    make_queue: Mk,
) -> Vec<Result<Vec<u64>>>
where
    T: ToU64Fast + Sync,
    D: Dist,
    Q: IntQueue,
    Mk: Fn() -> Q + Sync + Send,
{
    let total = shape.total();
    pairs
        .par_iter()
        .map_init(
            || BatchScratchInt::<D>::new(total as usize),
            |scratch, &(source, target)| {
                if source >= total {
                    return Err(Dijkstra3dError::OutOfBounds {
                        idx: source,
                        volume_size: total,
                    });
                }
                if target >= total {
                    return Err(Dijkstra3dError::OutOfBounds {
                        idx: target,
                        volume_size: total,
                    });
                }
                if source == target {
                    return Ok(vec![source]);
                }
                slice_int_search_reuse::<T, Q, D>(
                    field,
                    shape,
                    source,
                    target,
                    connectivity,
                    scratch,
                    make_queue(),
                )
            },
        )
        .collect()
}

/// Batch shortest paths on a signed/float cost field: rayon over pairs.
pub fn dijkstra_batch_slice<T: ToF32Fast + Sync>(
    field: &[T],
    shape: VolumeShape,
    pairs: &[(u64, u64)],
    connectivity: Connectivity,
    threads: Option<usize>,
) -> Vec<Result<Vec<u64>>> {
    run_batch_on_pool(threads, || {
        pairs
            .par_iter()
            .map(|&(source, target)| {
                dijkstra_unidirectional_slice(field, shape, source, target, connectivity, None)
            })
            .collect()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::voxel::{ArrayView3Source, VolumeShape};
    use ndarray::Array3;

    fn ones_field(n: usize) -> Array3<u32> {
        Array3::from_elem((n, n, n), 1u32)
    }

    fn run_ones(n: usize, conn: Connectivity) -> Vec<u64> {
        let arr = ones_field(n);
        let src = ArrayView3Source::new(arr.view());
        let shape = VolumeShape::new(n as u64, n as u64, n as u64);
        let s = shape.linear(0, 0, 0);
        let t = shape.linear((n - 1) as u64, (n - 1) as u64, (n - 1) as u64);
        let cfg = DijkstraConfig {
            connectivity: conn,
            anisotropy: Anisotropy::default(),
            mode: Mode::Unidirectional,
        };
        dijkstra(&src, s, t, cfg, None).unwrap()
    }

    /// On a 3x3x3 ones field, end-to-end with uniform unit edges:
    ///   6-conn  -> 6 face moves  (path length 7)
    ///   18-conn -> 3 edge moves  (path length 4)   — same as Euclidean: ties broken by step count
    ///   26-conn -> 2 corner moves (path length 3)
    #[test]
    fn ones_3x3x3_path_length_by_connectivity() {
        assert_eq!(run_ones(3, Connectivity::Six).len(), 7);
        assert_eq!(run_ones(3, Connectivity::Eighteen).len(), 4);
        assert_eq!(run_ones(3, Connectivity::TwentySix).len(), 3);
    }

    #[test]
    fn source_equals_target_returns_singleton() {
        let arr = ones_field(5);
        let src = ArrayView3Source::new(arr.view());
        let shape = VolumeShape::new(5, 5, 5);
        let s = shape.linear(2, 2, 2);
        let path = dijkstra(&src, s, s, DijkstraConfig::default(), None).unwrap();
        assert_eq!(path, vec![s]);
    }

    /// Cost of a path = sum of `field[v]` over every stepped-into voxel
    /// (i.e. all path nodes except the source), matching the edge-cost model.
    fn path_cost_u64<T: ToU64Fast>(field: &[T], path: &[u64]) -> u64 {
        path.iter()
            .skip(1)
            .map(|&v| field[v as usize].to_u64_fast())
            .sum()
    }

    fn path_cost_f32<T: ToF32Fast>(field: &[T], path: &[u64]) -> f64 {
        path.iter()
            .skip(1)
            .map(|&v| field[v as usize].to_f32_fast() as f64)
            .sum()
    }

    #[test]
    fn int_slice_matches_float_slice_cost() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let n = 20usize;
        let n_u = n as u64;
        let shape = VolumeShape::new(n_u, n_u, n_u);
        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(n_u - 1, n_u - 1, n_u - 1);
        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];

        // Exercise u8, u16, u32 dtypes with several seeds each.
        macro_rules! check_dtype {
            ($t:ty, $lo:expr, $hi:expr, $seed_base:expr) => {{
                for seed in 0..4u64 {
                    let mut rng = StdRng::seed_from_u64($seed_base + seed);
                    let field: Vec<$t> = (0..shape.total())
                        .map(|_| rng.random_range($lo..=$hi) as $t)
                        .collect();
                    for &conn in &conns {
                        let float_path =
                            dijkstra_unidirectional_slice(&field, shape, src, tgt, conn, None)
                                .unwrap();
                        let int_path =
                            dijkstra_unidirectional_slice_int(&field, shape, src, tgt, conn, None)
                                .unwrap();

                        // Endpoints must match.
                        assert_eq!(int_path.first(), Some(&src));
                        assert_eq!(int_path.last(), Some(&tgt));

                        // Cost must match exactly; ties may pick different paths.
                        let c_int = path_cost_u64(&field, &int_path);
                        let c_float_i = path_cost_u64(&field, &float_path);
                        assert_eq!(
                            c_int,
                            c_float_i,
                            "cost mismatch dtype={} seed={} conn={:?}: int={} float={}",
                            stringify!($t),
                            seed,
                            conn,
                            c_int,
                            c_float_i
                        );
                        // Confirm that the f32-summed cost agrees as well.
                        let c_float_f = path_cost_f32(&field, &float_path);
                        assert!((c_float_f - c_int as f64).abs() < 1.0);
                    }
                }
            }};
        }

        check_dtype!(u8, 1u32, 255u32, 100);
        check_dtype!(u16, 1u32, 60_000u32, 200);
        check_dtype!(u32, 1u32, 1_000_000u32, 300);
    }

    #[test]
    fn int_slice_ones_path_length_by_connectivity() {
        // Mirror the trait-based ones test: on a 3^3 ones field the shortest
        // path length depends only on connectivity.
        let n = 3u64;
        let shape = VolumeShape::new(n, n, n);
        let field = vec![1u32; shape.total() as usize];
        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(2, 2, 2);
        assert_eq!(
            dijkstra_unidirectional_slice_int(&field, shape, src, tgt, Connectivity::Six, None)
                .unwrap()
                .len(),
            7
        );
        assert_eq!(
            dijkstra_unidirectional_slice_int(
                &field,
                shape,
                src,
                tgt,
                Connectivity::Eighteen,
                None
            )
            .unwrap()
            .len(),
            4
        );
        assert_eq!(
            dijkstra_unidirectional_slice_int(
                &field,
                shape,
                src,
                tgt,
                Connectivity::TwentySix,
                None
            )
            .unwrap()
            .len(),
            3
        );
    }

    #[test]
    fn int_slice_heap_fallback_large_range() {
        // max_weight forces the binary-heap branch (range > 65_536).
        let n = 8u64;
        let shape = VolumeShape::new(n, n, n);
        let mut field = vec![1u32; shape.total() as usize];
        // A single huge value keeps the fast path correct while > 65_536.
        field[10] = 1_000_000;
        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(7, 7, 7);
        let int_path = dijkstra_unidirectional_slice_int(
            &field,
            shape,
            src,
            tgt,
            Connectivity::TwentySix,
            None,
        )
        .unwrap();
        let float_path =
            dijkstra_unidirectional_slice(&field, shape, src, tgt, Connectivity::TwentySix, None)
                .unwrap();
        assert_eq!(
            path_cost_u64(&field, &int_path),
            path_cost_u64(&field, &float_path)
        );
    }

    #[test]
    fn int_slice_rejects_unrepresentable_distance_bound() {
        let shape = VolumeShape::new(2, 2, 2);
        let field = vec![u64::MAX; shape.total() as usize];

        let error = dijkstra_unidirectional_slice_int(
            &field,
            shape,
            0,
            shape.total() - 1,
            Connectivity::TwentySix,
            None,
        )
        .unwrap_err();

        assert!(matches!(error, Dijkstra3dError::InvalidInput(_)));
    }

    #[test]
    fn int_slice_source_equals_target() {
        let shape = VolumeShape::new(4, 4, 4);
        let field = vec![3u32; shape.total() as usize];
        let s = shape.linear(1, 1, 1);
        let path = dijkstra_unidirectional_slice_int(&field, shape, s, s, Connectivity::Six, None)
            .unwrap();
        assert_eq!(path, vec![s]);
    }

    #[test]
    fn int_engine_distance_width_branches_exact_cost() {
        let n = 8u64;
        let shape = VolumeShape::new(n, n, n);
        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(n - 1, n - 1, n - 1);
        let steps = n - 1;

        // Case A
        let wa: u64 = 1_000_000_000;
        let fa = vec![wa; (n * n * n) as usize];
        let pa =
            dijkstra_unidirectional_slice_int(&fa, shape, src, tgt, Connectivity::TwentySix, None)
                .unwrap();
        assert_eq!(path_cost_u64(&fa, &pa), steps * wa);

        // Case B
        let wb: u32 = 150_000_000;
        let fb = vec![wb; (n * n * n) as usize];
        let pb =
            dijkstra_unidirectional_slice_int(&fb, shape, src, tgt, Connectivity::TwentySix, None)
                .unwrap();
        assert_eq!(path_cost_u64(&fb, &pb), steps * wb as u64);
    }

    #[test]
    fn dist_width_selector_boundaries() {
        // Narrowest width whose sentinel stays above every finite distance.
        assert_eq!(select_dist_width(0), DistWidth::U16);
        assert_eq!(select_dist_width(u16::MAX as u64), DistWidth::U16);
        assert_eq!(select_dist_width(u16::MAX as u64 + 1), DistWidth::U32);
        assert_eq!(select_dist_width(u32::MAX as u64), DistWidth::U32);
        assert_eq!(select_dist_width(u32::MAX as u64 + 1), DistWidth::U64);
        assert_eq!(select_dist_width(u64::MAX), DistWidth::U64);
    }

    #[test]
    fn dist_width_u16_matches_u32_and_u64_paths() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let n = 16u64;
        let shape = VolumeShape::new(n, n, n);
        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(n - 1, n - 1, n - 1);
        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];

        for seed in 0..24u64 {
            let mut rng = StdRng::seed_from_u64(0xD157_0000 + seed);
            // Small weights keep dist_bound = (3n+1)*max_w = 49*8 = 392 <= u16::MAX.
            let field: Vec<u32> = (0..shape.total())
                .map(|_| rng.random_range(1..=8u32))
                .collect();

            let max_w = field.iter().copied().max().unwrap() as u64;
            let dist_bound = (shape.sx + shape.sy + shape.sz + 1) * max_w;
            assert_eq!(
                select_dist_width(dist_bound),
                DistWidth::U16,
                "seed {seed}: small-weight field should route to u16"
            );
            let cap = max_w as u32;

            for &conn in &conns {
                let p16 = slice_int_search::<_, _, u16>(
                    &field,
                    shape,
                    src,
                    tgt,
                    conn,
                    None,
                    BucketQueue::with_capacity(cap),
                )
                .unwrap();
                let p32 = slice_int_search::<_, _, u32>(
                    &field,
                    shape,
                    src,
                    tgt,
                    conn,
                    None,
                    BucketQueue::with_capacity(cap),
                )
                .unwrap();
                let p64 = slice_int_search::<_, _, u64>(
                    &field,
                    shape,
                    src,
                    tgt,
                    conn,
                    None,
                    BucketQueue::with_capacity(cap),
                )
                .unwrap();
                assert_eq!(p16, p32, "u16 vs u32 differ seed={seed} conn={conn:?}");
                assert_eq!(p16, p64, "u16 vs u64 differ seed={seed} conn={conn:?}");

                // The public dispatcher selects u16 for this field.
                let pub_path =
                    dijkstra_unidirectional_slice_int(&field, shape, src, tgt, conn, None).unwrap();
                assert_eq!(
                    pub_path, p16,
                    "public path != forced-u16 seed={seed} conn={conn:?}"
                );
            }
        }
    }

    #[test]
    fn ablation_queue_width_factorial_preserves_path_cost() {
        let shape = VolumeShape::new(12, 11, 10);
        let field: Vec<u16> = (0..shape.total())
            .map(|index| 1 + ((index * 17 + 3) % 8) as u16)
            .collect();
        let source = shape.linear(0, 0, 0);
        let target = shape.linear(11, 10, 9);
        let reference = dijkstra_unidirectional_slice_int(
            &field,
            shape,
            source,
            target,
            Connectivity::Six,
            None,
        )
        .unwrap();
        let reference_cost = path_cost_u64(&field, &reference);

        for queue in [AblationQueue::Dial, AblationQueue::BinaryHeap] {
            for width in [
                AblationDistanceWidth::U16,
                AblationDistanceWidth::U32,
                AblationDistanceWidth::U64,
            ] {
                let path = dijkstra_unidirectional_slice_int_ablation(
                    &field,
                    shape,
                    source,
                    target,
                    Connectivity::Six,
                    None,
                    queue,
                    width,
                )
                .unwrap();
                assert_eq!(path_cost_u64(&field, &path), reference_cost);
            }
        }
    }

    #[test]
    fn ablation_rejects_unsafe_forced_distance_width() {
        let shape = VolumeShape::new(64, 64, 64);
        let field = vec![1_000u16; shape.total() as usize];
        let error = dijkstra_unidirectional_slice_int_ablation(
            &field,
            shape,
            0,
            shape.total() - 1,
            Connectivity::Six,
            None,
            AblationQueue::Dial,
            AblationDistanceWidth::U16,
        )
        .unwrap_err();
        assert!(matches!(error, Dijkstra3dError::InvalidInput(_)));
    }

    #[test]
    fn int_engine_u16_width_exact_cost() {
        let n = 32u64;
        let shape = VolumeShape::new(n, n, n);
        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(n - 1, n - 1, n - 1);
        let w: u32 = 20;
        // dist_bound = (3n+1)*W = 97*20 = 1940 <= u16::MAX -> u16 bucket branch.
        let dist_bound = (shape.sx + shape.sy + shape.sz + 1) * w as u64;
        assert_eq!(select_dist_width(dist_bound), DistWidth::U16);
        let field = vec![w; (n * n * n) as usize];
        let p = dijkstra_unidirectional_slice_int(
            &field,
            shape,
            src,
            tgt,
            Connectivity::TwentySix,
            None,
        )
        .unwrap();
        assert_eq!(path_cost_u64(&field, &p), (n - 1) * w as u64);
    }

    /// Verify consecutive path voxels are adjacent under `conn` and distinct.
    fn assert_contiguous(shape: VolumeShape, path: &[u64], conn: Connectivity) {
        for w in path.windows(2) {
            let (ax, ay, az) = shape.coords(w[0]);
            let (bx, by, bz) = shape.coords(w[1]);
            let dx = (ax as i64 - bx as i64).abs();
            let dy = (ay as i64 - by as i64).abs();
            let dz = (az as i64 - bz as i64).abs();
            assert!(
                dx <= 1 && dy <= 1 && dz <= 1,
                "non-adjacent step {:?}->{:?}",
                w[0],
                w[1]
            );
            let l1 = dx + dy + dz;
            assert!(l1 >= 1, "duplicate consecutive voxel {}", w[0]);
            let ok = match conn {
                Connectivity::Six => l1 == 1,
                Connectivity::Eighteen => l1 <= 2,
                Connectivity::TwentySix => true,
            };
            assert!(ok, "step violates connectivity {:?}: l1={}", conn, l1);
        }
    }

    #[test]
    fn bidirectional_int_is_optimal_2000() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];
        let mut trials = 0usize;
        let mut rng = StdRng::seed_from_u64(0xB1D14EC7);

        // 3 dtypes-ish (u8 two ranges + u16) x many seeds. Loop until >= 2100.
        for iter in 0..3000u64 {
            // Random dims 2..=16.
            let a = rng.random_range(2u64..=16);
            let b = rng.random_range(2u64..=16);
            let c = rng.random_range(2u64..=16);
            let shape = VolumeShape::new(a, b, c);
            let total = shape.total();
            let src = rng.random_range(0..total);
            let mut tgt = rng.random_range(0..total);
            while tgt == src {
                tgt = rng.random_range(0..total);
            }
            let conn = conns[(iter % 3) as usize];

            // Alternate dtypes: u8 small, u8 full, u16.
            macro_rules! run {
                ($t:ty, $hi:expr) => {{
                    let field: Vec<$t> = (0..total)
                        .map(|_| rng.random_range(1..=$hi) as $t)
                        .collect();
                    let bi = dijkstra_bidirectional_slice_int(&field, shape, src, tgt, conn, None)
                        .unwrap();
                    let uni =
                        dijkstra_unidirectional_slice_int(&field, shape, src, tgt, conn, None)
                            .unwrap();
                    // The floating-point path must satisfy the same optimum.
                    let bif =
                        dijkstra_bidirectional_slice(&field, shape, src, tgt, conn, None).unwrap();

                    assert_eq!(bi.first(), Some(&src), "bad src endpoint");
                    assert_eq!(bi.last(), Some(&tgt), "bad tgt endpoint");
                    assert_contiguous(shape, &bi, conn);

                    let c_bi = path_cost_u64(&field, &bi);
                    let c_uni = path_cost_u64(&field, &uni);
                    let c_bif = path_cost_u64(&field, &bif);
                    assert_eq!(
                        c_bi, c_uni,
                        "SUBOPTIMAL int bidir: dims=({},{},{}) src={} tgt={} conn={:?} \
                         bidir={} optimum={}",
                        a, b, c, src, tgt, conn, c_bi, c_uni
                    );
                    assert_eq!(
                        c_bif, c_uni,
                        "SUBOPTIMAL f32 bidir: dims=({},{},{}) src={} tgt={} conn={:?} \
                         bidir={} optimum={}",
                        a, b, c, src, tgt, conn, c_bif, c_uni
                    );
                    trials += 1;
                }};
            }

            match iter % 3 {
                0 => run!(u8, 8u32),
                1 => run!(u8, 255u32),
                _ => run!(u16, 1000u32),
            }
        }

        assert!(trials >= 2000, "only ran {} trials", trials);
    }

    #[test]
    fn bidirectional_matches_unidirectional_on_tied_field() {
        let shape = VolumeShape::new(3, 3, 3);
        let field: Vec<u8> = vec![
            1, 3, 1, 4, 3, 4, 3, 2, 4, 1, 3, 1, 2, 3, 2, 3, 3, 2, 1, 4, 4, 3, 4, 1, 3, 3, 3,
        ];
        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(2, 2, 2);
        let conn = Connectivity::TwentySix;
        let bi = dijkstra_bidirectional_slice_int(&field, shape, src, tgt, conn, None).unwrap();
        let bif = dijkstra_bidirectional_slice(&field, shape, src, tgt, conn, None).unwrap();
        let uni = dijkstra_unidirectional_slice_int(&field, shape, src, tgt, conn, None).unwrap();
        assert_eq!(path_cost_u64(&field, &bi), 6);
        assert_eq!(path_cost_u64(&field, &bif), 6);
        assert_eq!(path_cost_u64(&field, &uni), 6);
    }

    #[test]
    fn bidirectional_int_rejects_unrepresentable_distance_bound() {
        let shape = VolumeShape::new(2, 2, 2);
        let field = vec![u64::MAX; shape.total() as usize];

        let error = dijkstra_bidirectional_slice_int(
            &field,
            shape,
            0,
            shape.total() - 1,
            Connectivity::Six,
            None,
        )
        .unwrap_err();

        assert!(matches!(error, Dijkstra3dError::InvalidInput(_)));
    }

    use proptest::prelude::*;
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(400))]
        #[test]
        fn prop_int_engine_cost_matches_float(
            a in 2u64..=5, b in 2u64..=5, c in 2u64..=5,
            weights in prop::collection::vec(1u16..=2000, 125),
            conn_idx in 0usize..3,
        ) {
            let total = (a * b * c) as usize;
            let field: Vec<u16> = weights[..total].to_vec();
            let shape = VolumeShape::new(a, b, c);
            let src = shape.linear(0, 0, 0);
            let tgt = shape.linear(a - 1, b - 1, c - 1);
            let conn = [
                Connectivity::Six,
                Connectivity::Eighteen,
                Connectivity::TwentySix,
            ][conn_idx];
            let ip =
                dijkstra_unidirectional_slice_int(&field, shape, src, tgt, conn, None).unwrap();
            let fp =
                dijkstra_unidirectional_slice(&field, shape, src, tgt, conn, None).unwrap();
            prop_assert_eq!(path_cost_u64(&field, &ip), path_cost_u64(&field, &fp));
        }
    }

    #[test]
    fn batch_int_matches_single_call_paths() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let n = 24usize;
        let n_u = n as u64;
        let shape = VolumeShape::new(n_u, n_u, n_u);
        let total = shape.total();
        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];

        macro_rules! check_dtype {
            ($t:ty, $hi:expr, $seed:expr) => {{
                let mut rng = StdRng::seed_from_u64($seed);
                let field: Vec<$t> =
                    (0..total).map(|_| rng.random_range(1..=$hi) as $t).collect();
                // 40 pairs incl. an unreachable-free field, plus a src==tgt and
                // an out-of-bounds pair to exercise the per-pair error paths.
                let mut pairs: Vec<(u64, u64)> = (0..40)
                    .map(|_| {
                        let s = rng.random_range(0..total);
                        let t = rng.random_range(0..total);
                        (s, t)
                    })
                    .collect();
                pairs.push((7, 7)); // src == tgt
                pairs.push((total, 0)); // out of bounds source

                for &conn in &conns {
                    let batch = dijkstra_batch_slice_int(&field, shape, &pairs, conn, None);
                    assert_eq!(batch.len(), pairs.len());
                    for (i, &(s, t)) in pairs.iter().enumerate() {
                        let single =
                            dijkstra_unidirectional_slice_int(&field, shape, s, t, conn, None);
                        match (&batch[i], &single) {
                            (Ok(bp), Ok(sp)) => assert_eq!(
                                bp, sp,
                                "path mismatch dtype={} conn={:?} pair=({},{})",
                                stringify!($t), conn, s, t
                            ),
                            (Err(be), Err(se)) => assert_eq!(be, se),
                            _ => panic!(
                                "ok/err mismatch dtype={} conn={:?} pair=({},{}): batch={:?} single={:?}",
                                stringify!($t), conn, s, t, batch[i], single
                            ),
                        }
                    }
                }
            }};
        }

        check_dtype!(u8, 8u32, 1); // small range -> bucket, u32 dist
        check_dtype!(u8, 255u32, 2);
        check_dtype!(u16, 60_000u32, 3); // bucket boundary, u32 dist
        check_dtype!(u32, 1_000_000u32, 4); // heap fallback
    }

    /// The float batch must reproduce the single-call `f32` slice path per pair.
    #[test]
    fn batch_float_matches_single_call_paths() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let n = 16usize;
        let n_u = n as u64;
        let shape = VolumeShape::new(n_u, n_u, n_u);
        let total = shape.total();
        let mut rng = StdRng::seed_from_u64(0xF10A7);
        let field: Vec<f32> = (0..total)
            .map(|_| rng.random_range(1.0f32..=100.0f32))
            .collect();
        let pairs: Vec<(u64, u64)> = (0..24)
            .map(|_| (rng.random_range(0..total), rng.random_range(0..total)))
            .collect();

        for &conn in &[Connectivity::Six, Connectivity::TwentySix] {
            let batch = dijkstra_batch_slice(&field, shape, &pairs, conn, None);
            for (i, &(s, t)) in pairs.iter().enumerate() {
                let single = dijkstra_unidirectional_slice(&field, shape, s, t, conn, None);
                match (&batch[i], &single) {
                    (Ok(bp), Ok(sp)) => assert_eq!(bp, sp),
                    (Err(_), Err(_)) => {}
                    _ => panic!("ok/err mismatch pair=({},{})", s, t),
                }
            }
        }
    }

    /// A globally-invalid field (length mismatch) yields one error per pair,
    /// keeping the returned Vec aligned 1:1 with the input pairs.
    #[test]
    fn batch_int_global_error_is_per_pair() {
        let shape = VolumeShape::new(4, 4, 4);
        let field = vec![1u32; 10]; // wrong length (!= 64)
        let pairs = vec![(0u64, 5u64), (1, 2), (3, 4)];
        let out = dijkstra_batch_slice_int(&field, shape, &pairs, Connectivity::TwentySix, Some(0));
        assert_eq!(out.len(), pairs.len());
        for r in &out {
            assert!(matches!(r, Err(Dijkstra3dError::InvalidInput(_))));
        }
    }

    #[test]
    fn batch_int_distance_bound_error_is_per_pair() {
        let shape = VolumeShape::new(2, 2, 2);
        let field = vec![u64::MAX; shape.total() as usize];
        let pairs = [(0, shape.total() - 1), (1, 2)];

        let output = dijkstra_batch_slice_int(&field, shape, &pairs, Connectivity::Six, None);

        assert_eq!(output.len(), pairs.len());
        assert!(output
            .iter()
            .all(|result| matches!(result, Err(Dijkstra3dError::InvalidInput(_)))));
    }

    /// Mixed reachable / degenerate pairs in one batch: each pair is independent,
    /// element i <-> pairs[i], and a src==tgt pair returns the singleton without
    /// disturbing its neighbours.
    #[test]
    fn batch_int_mixed_pairs_independent() {
        let shape = VolumeShape::new(5, 5, 5);
        let field = vec![2u32; shape.total() as usize];
        let s = shape.linear(0, 0, 0);
        let t = shape.linear(4, 4, 4);
        let pairs = vec![(s, t), (s, s), (t, s)];
        let out = dijkstra_batch_slice_int(&field, shape, &pairs, Connectivity::TwentySix, None);
        assert_eq!(out.len(), 3);
        assert_eq!(out[0].as_ref().unwrap().first(), Some(&s));
        assert_eq!(out[0].as_ref().unwrap().last(), Some(&t));
        assert_eq!(out[1].as_ref().unwrap(), &vec![s]); // src == tgt
        assert_eq!(out[2].as_ref().unwrap().first(), Some(&t));
        assert_eq!(out[2].as_ref().unwrap().last(), Some(&s));
    }

    // -----------------------------------------------------------------------
    // Compass heuristic-informativeness gate (compass-heuristic-quality-dispatch)
    // -----------------------------------------------------------------------

    #[test]
    fn compass_gate_classifies_workloads() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let n = 48u64;
        let shape = VolumeShape::new(n, n, n);
        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(n - 1, n - 1, n - 1);
        let aniso = Anisotropy::default();
        let total = shape.total() as usize;
        let mut rng = StdRng::seed_from_u64(0xC0FFEE);

        // random_uniform [1,255]: heuristic negligible relative to mean cost;
        // use unidirectional search.
        let f_uniform: Vec<u8> = (0..total)
            .map(|_| rng.random_range(1..=255u32) as u8)
            .collect();
        assert!(
            !compass_heuristic_is_informative(&f_uniform, shape, src, tgt, aniso),
            "random_uniform should route to unidirectional"
        );

        // smallweight [1,8]: a low-cost near-straight path keeps Compass enabled.
        let f_small: Vec<u8> = (0..total)
            .map(|_| rng.random_range(1..=8u32) as u8)
            .collect();
        assert!(
            compass_heuristic_is_informative(&f_small, shape, src, tgt, aniso),
            "smallweight should keep compass"
        );

        // bimodal
        let mut f_bimodal: Vec<u32> = (0..total).map(|_| rng.random_range(1..=8u32)).collect();
        for v in f_bimodal.iter_mut() {
            if rng.random::<f32>() < 0.02 {
                *v = 200_000;
            }
        }
        assert!(
            compass_heuristic_is_informative(&f_bimodal, shape, src, tgt, aniso),
            "bimodal should keep compass despite a high mean"
        );

        // maze
        let mut f_maze: Vec<u8> = vec![255u8; total];
        for y in (0..n).step_by(2) {
            for z in 0..n {
                for x in 0..n {
                    f_maze[shape.linear(x, y, z) as usize] = 1;
                }
            }
        }
        // Global median is 1 (half the voxels are corridor); the straight
        // diagonal still crosses walls, so the gate must say "uninformative".
        assert!(
            !compass_heuristic_is_informative(&f_maze, shape, src, tgt, aniso),
            "maze should route to unidirectional (walls block the straight line)"
        );

        // plateau (uniform 7)
        let f_plateau: Vec<u32> = vec![7u32; total];
        assert!(
            !compass_heuristic_is_informative(&f_plateau, shape, src, tgt, aniso),
            "plateau should route to unidirectional"
        );
    }

    /// A degenerate source==target query never divides by zero (returns true)
    #[test]
    fn compass_gate_source_equals_target_is_safe() {
        let shape = VolumeShape::new(4, 4, 4);
        let field = vec![3u8; shape.total() as usize];
        let s = shape.linear(1, 1, 1);
        assert!(compass_heuristic_is_informative(
            &field,
            shape,
            s,
            s,
            Anisotropy::default()
        ));
    }

    #[test]
    fn batch_int_output_pool_independent() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let shape = VolumeShape::new(20, 18, 16);
        let total = shape.total();
        let mut rng = StdRng::seed_from_u64(0xBA7C_4001);
        let field: Vec<u16> = (0..total).map(|_| rng.random_range(1..=200u16)).collect();
        let pairs: Vec<(u64, u64)> = (0..40)
            .map(|_| (rng.random_range(0..total), rng.random_range(0..total)))
            .collect();

        let conn = Connectivity::TwentySix;
        let auto = dijkstra_batch_slice_int(&field, shape, &pairs, conn, None);
        let global = dijkstra_batch_slice_int(&field, shape, &pairs, conn, Some(0));
        let pinned = dijkstra_batch_slice_int(&field, shape, &pairs, conn, Some(2));
        assert_eq!(auto, global, "auto vs global pool output differs");
        assert_eq!(auto, pinned, "auto vs pinned pool output differs");
    }
}