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
//! Parental field and path reconstruction.
//!
//! Upstream reference: `dijkstra3d.hpp::parental_field3d` and the path-trace logic.

use crate::atomic_dist::{atomic_dist_parent_vec, atomic_dist_parent_vec_int, AtomicDistParent};
use crate::connectivity_graph::ConnectivityGraph;
use crate::dijkstra::{checked_int_distance_bound, select_dist_width, Dist, DistWidth, IntQueue};
use crate::halo::PaddedShape;
use crate::neighborhood::{neighborhood_masks, neighborhood_offsets, DIRECTIONS_26};
use crate::queue::binary_heap::BinaryHeapQueue;
use crate::queue::bucket::BucketQueue;
use crate::queue::PriorityQueue;
use crate::voxel::{ToU64Fast, VolumeShape, VoxelSource};
use crate::{Connectivity, Dijkstra3dError, Result};
use num_traits::ToPrimitive;
use rayon::prelude::*;
use std::collections::VecDeque;

/// Precomputed neighborhood metadata for efficient neighbor iteration.
pub struct NeighborhoodContext {
    pub offsets: [i64; 26],

    pub masks: [u32; 26],

    pub neighbor_count: usize,
}

impl NeighborhoodContext {
    /// Build the neighbor offsets/masks/count for `shape` and `connectivity`.
    pub fn new(shape: &VolumeShape, connectivity: Connectivity) -> Self {
        let sx = shape.sx as i64;
        let sxy = (shape.sx * shape.sy) as i64;
        Self {
            offsets: neighborhood_offsets(sx, sxy),
            masks: neighborhood_masks(),
            neighbor_count: connectivity.count(),
        }
    }
}

/// Check if neighbor is within bounds (per-axis check prevents wraparound).
#[inline]
pub(crate) fn is_neighbor_in_bounds(
    x: u64,
    y: u64,
    z: u64,
    dx: i32,
    dy: i32,
    dz: i32,
    sx: i64,
    sy: i64,
    sz: i64,
) -> bool {
    let nx = x as i64 + dx as i64;
    let ny = y as i64 + dy as i64;
    let nz = z as i64 + dz as i64;

    nx >= 0 && nx < sx && ny >= 0 && ny < sy && nz >= 0 && nz < sz
}

/// Heap entry for [`LibstdcxxCompatHeap`].
#[derive(Clone, Copy, Debug)]
pub(crate) struct UpstreamCompatEntry<T> {
    pub(crate) priority: f32,
    pub(crate) payload: T,
}

/// Minimal emulation of the libstdc++ heap used by upstream dijkstra3d 1.15.2.
///
/// Upstream's comparator uses `left.key >= right.key`, which violates the
/// strict-weak-order requirement. Equal-key behavior therefore depends on the
/// library's exact push/pop heap operations and cannot be represented by a
/// stable global secondary key in Rust's [`std::collections::BinaryHeap`].
#[derive(Debug)]
pub(crate) struct LibstdcxxCompatHeap<T> {
    entries: Vec<UpstreamCompatEntry<T>>,
}

impl<T> Default for LibstdcxxCompatHeap<T> {
    fn default() -> Self {
        Self {
            entries: Vec::new(),
        }
    }
}

impl<T: Copy> LibstdcxxCompatHeap<T> {
    pub(crate) fn push(&mut self, entry: UpstreamCompatEntry<T>) {
        self.entries.push(entry);
        let mut hole = self.entries.len() - 1;
        while hole > 0 {
            let parent = (hole - 1) / 2;
            if self.entries[parent].priority < entry.priority {
                break;
            }
            self.entries[hole] = self.entries[parent];
            hole = parent;
        }
        self.entries[hole] = entry;
    }

    pub(crate) fn pop(&mut self) -> Option<UpstreamCompatEntry<T>> {
        let result = self.entries.first().copied()?;
        let replacement = self.entries.pop()?;
        let len = self.entries.len();
        if len == 0 {
            return Some(result);
        }

        let top = 0usize;
        let mut hole = top;
        let mut second_child = hole;
        while second_child < (len - 1) / 2 {
            second_child = 2 * (second_child + 1);
            if self.entries[second_child].priority >= self.entries[second_child - 1].priority {
                second_child -= 1;
            }
            self.entries[hole] = self.entries[second_child];
            hole = second_child;
        }
        if len % 2 == 0 && second_child == (len - 2) / 2 {
            second_child = 2 * (second_child + 1);
            self.entries[hole] = self.entries[second_child - 1];
            hole = second_child - 1;
        }

        while hole > top {
            let parent = (hole - 1) / 2;
            if self.entries[parent].priority < replacement.priority {
                break;
            }
            self.entries[hole] = self.entries[parent];
            hole = parent;
        }
        self.entries[hole] = replacement;
        Some(result)
    }
}

/// Upstream dijkstra3d 1.15.2 neighborhood iteration order.
///
/// This table is deliberately separate from [`DIRECTIONS_26`]. The ordinary
/// Rust path keeps its existing ordering and optimized dispatch, while the
/// opt-in compatibility path mirrors upstream's `(x, y, z)`/Fortran boundary.
pub(crate) const UPSTREAM_DIRECTIONS_26: [(i32, i32, i32); 26] = [
    (-1, 0, 0),
    (1, 0, 0),
    (0, -1, 0),
    (0, 1, 0),
    (0, 0, -1),
    (0, 0, 1),
    (-1, -1, 0),
    (-1, 1, 0),
    (1, -1, 0),
    (1, 1, 0),
    (0, -1, -1),
    (0, -1, 1),
    (0, 1, -1),
    (0, 1, 1),
    (-1, 0, -1),
    (-1, 0, 1),
    (1, 0, -1),
    (1, 0, 1),
    (-1, -1, -1),
    (1, -1, -1),
    (-1, 1, -1),
    (-1, -1, 1),
    (1, 1, -1),
    (1, -1, 1),
    (-1, 1, 1),
    (1, 1, 1),
];

/// Try to relax a neighbor in the sequential (non-parallel) case.
///
/// Returns `Some(new_dist)` if the relaxation succeeded, `None` otherwise.
#[inline]
fn try_relax_neighbor<V>(
    field: &V,
    _loc: u64,
    neighbor: u64,
    current_dist: f32,
    distances: &[f32],
    total: u64,
) -> Result<Option<f32>>
where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    // Edge cost: field[neighbor] (uniform edges, no geometric weight)
    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 = current_dist + neighbor_cost_f32;

    // Check if this is an improvement
    if new_dist < distances[neighbor as usize] {
        Ok(Some(new_dist))
    } else {
        Ok(None)
    }
}

/// Compute the parental field rooted at `source`.
pub fn parental_field<V>(
    field: &V,
    source: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u32>>
where
    V: VoxelSource,
    V::Item: num_traits::ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    // Validate source
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }

    // Initialize distances and parents
    let mut distances = vec![f32::INFINITY; total as usize];
    let mut parents = vec![0u32; total as usize];

    distances[source as usize] = 0.0;

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

    // Precompute neighborhood metadata
    let ctx = NeighborhoodContext::new(&shape, connectivity);
    let sx = shape.sx as i64;
    let sy = shape.sy as i64;
    let sz = shape.sz as i64;

    // Dijkstra to completion (no early stop)
    while let Some((dist, loc)) = queue.pop() {
        // Lazy deletion
        if dist > distances[loc as usize] {
            continue;
        }

        // Convert to coordinates for per-axis bounds checking
        let (x, y, z) = shape.coords(loc);
        let current_dist = distances[loc as usize];

        // Explore neighbors
        for i in 0..ctx.neighbor_count {
            // Get direction from canonical table
            let (dx, dy, dz) = DIRECTIONS_26[i];

            // Per-axis bounds check (prevents wraparound)
            if !is_neighbor_in_bounds(x, y, z, dx, dy, dz, sx, sy, sz) {
                continue;
            }

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

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

            // Try to relax this neighbor
            if let Some(new_dist) =
                try_relax_neighbor(field, loc, neighbor, current_dist, &distances, total)?
            {
                // Relaxation succeeded - update distance and parent
                distances[neighbor as usize] = new_dist;
                parents[neighbor as usize] = (loc + 1) as u32; // +1 sentinel encoding
                queue.push(new_dist, neighbor);
            }
        }
    }

    Ok(parents)
}

/// Compute an upstream-compatible parental field using deterministic tie rules.
///
/// This path mirrors upstream's logical `(x, y, z)` axes, neighborhood order,
/// `f32` accumulation, strict-relaxation rule, and the exact libstdc++ heap
/// operations observed in the pinned Linux upstream wheels. It intentionally
/// bypasses the integer, bucket, halo, and parallel engines. Callers must opt
/// in explicitly; [`parental_field`] remains the default fast implementation.
///
/// Exact compatibility is scoped to the pinned upstream build behavior because
/// upstream's non-strict C++ comparator does not define a portable tie order.
pub fn parental_field_upstream_compat<V>(
    field: &V,
    source: u64,
    connectivity: Connectivity,
) -> Result<Vec<u32>>
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,
        });
    }

    let mut distances = vec![f32::INFINITY; total as usize];
    let mut parents = vec![0u32; total as usize];
    let mut queue = LibstdcxxCompatHeap::<u64>::default();

    distances[source as usize] = 0.0;
    queue.push(UpstreamCompatEntry {
        priority: 0.0,
        payload: source,
    });

    while let Some(entry) = queue.pop() {
        let loc = entry.payload;
        if entry.priority > distances[loc as usize] {
            continue;
        }

        let (x, y, z) = shape.coords(loc);
        let current_dist = distances[loc as usize];
        for &(dx, dy, dz) in &UPSTREAM_DIRECTIONS_26[..connectivity.count()] {
            if !is_neighbor_in_bounds(
                x,
                y,
                z,
                dx,
                dy,
                dz,
                shape.sx as i64,
                shape.sy as i64,
                shape.sz as i64,
            ) {
                continue;
            }

            let neighbor = shape.linear(
                (x as i64 + dx as i64) as u64,
                (y as i64 + dy as i64) as u64,
                (z as i64 + dz as i64) as u64,
            );
            let neighbor_cost =
                field
                    .get(neighbor)?
                    .to_f32()
                    .ok_or(Dijkstra3dError::OutOfBounds {
                        idx: neighbor,
                        volume_size: total,
                    })?;
            let new_dist = current_dist + neighbor_cost;
            if new_dist < distances[neighbor as usize] {
                distances[neighbor as usize] = new_dist;
                parents[neighbor as usize] = (loc + 1) as u32;
                queue.push(UpstreamCompatEntry {
                    priority: new_dist,
                    payload: neighbor,
                });
            }
        }
    }

    Ok(parents)
}

/// Contiguous x-fastest specialization of [`parental_field_upstream_compat`].
///
/// The caller must supply `field` in the linear order described by `shape`.
/// This keeps the pinned upstream heap and neighbor ordering unchanged while
/// avoiding a fallible ndarray lookup and coordinate-to-linear conversion for
/// every relaxation. Non-contiguous Python inputs continue through the generic
/// compatibility implementation.
pub fn parental_field_upstream_compat_slice<T>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    connectivity: Connectivity,
) -> Result<Vec<u32>>
where
    T: ToPrimitive,
{
    let total = shape.total();
    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "parental_field_upstream_compat_slice: slice length {} != shape.total() {total}",
            field.len()
        )));
    }
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if total > u32::MAX as u64 {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "parental_field_upstream_compat_slice: volume {total} exceeds u32::MAX voxels"
        )));
    }

    let mut distances = vec![f32::INFINITY; total as usize];
    let mut parents = vec![0u32; total as usize];
    let mut queue = LibstdcxxCompatHeap::<u32>::default();
    let stride_y = shape.sx as i64;
    let stride_z = (shape.sx * shape.sy) as i64;
    let offsets = UPSTREAM_DIRECTIONS_26
        .map(|(dx, dy, dz)| dx as i64 + dy as i64 * stride_y + dz as i64 * stride_z);
    let neighbor_count = connectivity.count();

    distances[source as usize] = 0.0;
    queue.push(UpstreamCompatEntry {
        priority: 0.0,
        payload: source as u32,
    });

    while let Some(entry) = queue.pop() {
        let loc = entry.payload as usize;
        if entry.priority > distances[loc] {
            continue;
        }

        let (x, y, z) = shape.coords(loc as u64);
        let interior =
            x > 0 && x + 1 < shape.sx && y > 0 && y + 1 < shape.sy && z > 0 && z + 1 < shape.sz;
        let current_dist = distances[loc];
        for (direction, &offset) in UPSTREAM_DIRECTIONS_26[..neighbor_count]
            .iter()
            .zip(&offsets[..neighbor_count])
        {
            let (dx, dy, dz) = *direction;
            if !interior
                && !is_neighbor_in_bounds(
                    x,
                    y,
                    z,
                    dx,
                    dy,
                    dz,
                    shape.sx as i64,
                    shape.sy as i64,
                    shape.sz as i64,
                )
            {
                continue;
            }

            let neighbor = (loc as i64 + offset) as usize;
            let neighbor_cost = field[neighbor]
                .to_f32()
                .ok_or(Dijkstra3dError::OutOfBounds {
                    idx: neighbor as u64,
                    volume_size: total,
                })?;
            let new_dist = current_dist + neighbor_cost;
            if new_dist < distances[neighbor] {
                distances[neighbor] = new_dist;
                parents[neighbor] = (loc + 1) as u32;
                queue.push(UpstreamCompatEntry {
                    priority: new_dist,
                    payload: neighbor as u32,
                });
            }
        }
    }

    Ok(parents)
}

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

    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "parental_field_slice_int: slice length {} != shape.total() {}",
            field.len(),
            total
        )));
    }
    if total > u32::MAX as u64 {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "parental_field_slice_int: volume {total} exceeds u32::MAX voxels; \
             parent indices must fit in u32 — use the trait/f32 path"
        )));
    }
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }

    // 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;

    // Halo-padded full-volume fast path.
    let padded = PaddedShape::new(shape.sx, shape.sy, shape.sz);
    if graph.is_none() && padded.ptotal() <= u32::MAX as u64 {
        return match (use_bucket, width) {
            (true, DistWidth::U16) => parental_slice_int_search_padded::<_, u16>(
                field,
                shape,
                padded,
                source,
                connectivity,
                BucketQueue::with_capacity(max_weight as u32),
            ),
            (true, DistWidth::U32) => parental_slice_int_search_padded::<_, u32>(
                field,
                shape,
                padded,
                source,
                connectivity,
                BucketQueue::with_capacity(max_weight as u32),
            ),
            (true, DistWidth::U64) => parental_slice_int_search_padded::<_, u64>(
                field,
                shape,
                padded,
                source,
                connectivity,
                BucketQueue::with_capacity(max_weight as u32),
            ),
            (false, DistWidth::U16) => parental_slice_int_search_padded::<_, u16>(
                field,
                shape,
                padded,
                source,
                connectivity,
                BinaryHeapQueue::<u64, u32>::new(),
            ),
            (false, DistWidth::U32) => parental_slice_int_search_padded::<_, u32>(
                field,
                shape,
                padded,
                source,
                connectivity,
                BinaryHeapQueue::<u64, u32>::new(),
            ),
            (false, DistWidth::U64) => parental_slice_int_search_padded::<_, u64>(
                field,
                shape,
                padded,
                source,
                connectivity,
                BinaryHeapQueue::<u64, u32>::new(),
            ),
        };
    }

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

fn parental_slice_int_search<T: ToU64Fast, D: Dist>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    mut queue: impl IntQueue,
) -> Result<Vec<u32>> {
    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 ctx = NeighborhoodContext::new(&shape, connectivity);
    let sx = shape.sx as i64;
    let sy = shape.sy as i64;
    let sz = shape.sz as i64;

    // Dijkstra to completion (no early stop), mirroring `parental_field`.
    while let Some((dist, loc)) = queue.pop_i() {
        let loc_us = loc as usize;
        // Lazy deletion.
        if dist > distances[loc_us].to_priority() {
            continue;
        }

        let (x, y, z) = shape.coords(loc as u64);
        let current_dist = distances[loc_us];

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

            if !is_neighbor_in_bounds(x, y, z, dx, dy, dz, sx, sy, sz) {
                continue;
            }

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

            if let Some(ref g) = graph {
                if !g.allows(loc as u64, ctx.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);
            }
        }
    }

    Ok(parents)
}

/// Diagnostic/bench-only entry point that forces the unpadded integer parental
/// search (no halo), with no connectivity graph.
#[doc(hidden)]
pub fn parental_field_slice_int_unpadded<T: ToU64Fast>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    connectivity: Connectivity,
) -> Result<Vec<u32>> {
    let total = shape.total();
    if field.len() as u64 != total || total > u32::MAX as u64 || source >= total {
        return Err(Dijkstra3dError::InvalidInput(
            "parental_field_slice_int_unpadded: invalid input".into(),
        ));
    }
    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) => parental_slice_int_search::<_, u32>(
            field,
            shape,
            source,
            connectivity,
            None,
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (true, false) => parental_slice_int_search::<_, u64>(
            field,
            shape,
            source,
            connectivity,
            None,
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (false, true) => parental_slice_int_search::<_, u32>(
            field,
            shape,
            source,
            connectivity,
            None,
            BinaryHeapQueue::<u64, u32>::new(),
        ),
        (false, false) => parental_slice_int_search::<_, u64>(
            field,
            shape,
            source,
            connectivity,
            None,
            BinaryHeapQueue::<u64, u32>::new(),
        ),
    }
}

/// Halo-padded full-volume parental search.
#[allow(clippy::too_many_arguments)]
fn parental_slice_int_search_padded<T: ToU64Fast, D: Dist>(
    field: &[T],
    shape: VolumeShape,
    padded: PaddedShape,
    source: u64,
    connectivity: Connectivity,
    mut queue: impl IntQueue,
) -> Result<Vec<u32>> {
    let psx = padded.psx;
    let psy = padded.psy;
    let psz = padded.psz;
    let psxy = padded.psxy();
    let ptotal = padded.ptotal() as usize;

    // Padded field copy + padded state, with an impassable halo.
    let field_pad = crate::halo::pad_field(field, shape.sx, shape.sy, shape.sz, padded);
    let mut distances = vec![D::MAX; ptotal];
    let mut parents = vec![0u32; ptotal];
    crate::halo::set_halo_zero::<D>(&mut distances, psx as usize, psy as usize, psz as usize);

    let (sxc, syc, szc) = shape.coords(source);
    let source_pad = crate::halo::to_padded_index(sxc, syc, szc, padded) as u32;
    distances[source_pad as usize] = D::ZERO;
    queue.push_i(0, source_pad);

    let offsets = neighborhood_offsets(psx as i64, psxy as i64);
    let neighbor_count = connectivity.count();

    // Dijkstra to completion (no early stop). No `coords()`, no per-axis bounds
    // check: the halo guarantees every `loc + off` is a valid padded index.
    while let Some((dist, loc)) = queue.pop_i() {
        let loc_us = loc as usize;
        // SAFETY: `loc` is a valid interior padded index (function invariants).
        let current_dist = unsafe { *distances.get_unchecked(loc_us) };
        if dist > current_dist.to_priority() {
            continue;
        }

        for &off in &offsets[..neighbor_count] {
            // SAFETY: `loc` is interior, so `loc + off` is in `0..ptotal`.
            let neighbor = (loc as i64 + off) as usize;
            let neighbor_cost = unsafe { field_pad.get_unchecked(neighbor).to_u64_fast() };
            let new_dist = current_dist.add_cost(neighbor_cost);

            // SAFETY: `neighbor < ptotal` as above.
            let dn = unsafe { distances.get_unchecked_mut(neighbor) };
            if new_dist < *dn {
                *dn = new_dist;
                // SAFETY: same in-range `neighbor`.
                unsafe {
                    *parents.get_unchecked_mut(neighbor) = loc + 1; // +1 sentinel
                }
                queue.push_i(new_dist.to_priority(), neighbor as u32);
            }
        }
    }

    let sx = shape.sx;
    let sy = shape.sy;
    let sz = shape.sz;
    let sxy = sx * sy;
    let mut out = vec![0u32; (sx * sy * sz) as usize];
    for z in 0..sz {
        for y in 0..sy {
            let pad_base = (z + 1) * psxy + (y + 1) * psx + 1;
            let orig_base = z * sxy + y * sx;
            for x in 0..sx {
                let par_pad = parents[(pad_base + x) as usize];
                if par_pad != 0 {
                    let orig_par =
                        crate::halo::from_padded_index((par_pad - 1) as u64, sx, sxy, psx, psxy);
                    out[(orig_base + x) as usize] = (orig_par + 1) as u32;
                }
            }
        }
    }
    Ok(out)
}

/// Trace a path from `target` back to the source using a precomputed parental field.
pub fn path_from_parents(parents: &[u32], target: u64) -> Result<Vec<u64>> {
    if target >= parents.len() as u64 {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: target,
            volume_size: parents.len() as u64,
        });
    }

    let mut path = vec![target];
    let mut current = target;

    // Walk backwards following parents
    for _ in 0..parents.len() {
        let parent = parents[current as usize];
        if parent == 0 {
            path.reverse();
            return Ok(path);
        }
        current = (parent - 1) as u64; // Decode from +1 encoding
        if current >= parents.len() as u64 {
            return Err(Dijkstra3dError::InvalidInput(format!(
                "parental field references voxel {current} outside volume of size {}",
                parents.len()
            )));
        }
        path.push(current);
    }

    Err(Dijkstra3dError::InvalidInput(
        "parental field contains a cycle".into(),
    ))
}

// Parallel bucket-fusion kernel.
const PARENTAL_FUSION_THRESHOLD: usize = 2048;

trait ParAcc: Copy + Send + Sync {
    fn init_vec(n: usize) -> Vec<AtomicDistParent>;

    fn read_cost<V: VoxelSource>(field: &V, idx: u64) -> Option<Self>
    where
        V::Item: ToPrimitive;

    fn add(self, cost: Self) -> Self;

    fn load_dist(dp: &AtomicDistParent) -> Self;

    fn is_reached(self) -> bool;

    fn relax(dp: &AtomicDistParent, new: Self, parent: u32) -> bool;
}

impl ParAcc for f32 {
    #[inline]
    fn init_vec(n: usize) -> Vec<AtomicDistParent> {
        atomic_dist_parent_vec(n)
    }
    #[inline]
    fn read_cost<V: VoxelSource>(field: &V, idx: u64) -> Option<Self>
    where
        V::Item: ToPrimitive,
    {
        field.get(idx).ok().and_then(|v| v.to_f32())
    }
    #[inline]
    fn add(self, cost: Self) -> Self {
        self + cost
    }
    #[inline]
    fn load_dist(dp: &AtomicDistParent) -> Self {
        dp.load_dist()
    }
    #[inline]
    fn is_reached(self) -> bool {
        self.is_finite()
    }
    #[inline]
    fn relax(dp: &AtomicDistParent, new: Self, parent: u32) -> bool {
        dp.relax_with_parent(new, parent)
    }
}

impl ParAcc for u32 {
    #[inline]
    fn init_vec(n: usize) -> Vec<AtomicDistParent> {
        atomic_dist_parent_vec_int(n)
    }
    #[inline]
    fn read_cost<V: VoxelSource>(field: &V, idx: u64) -> Option<Self>
    where
        V::Item: ToPrimitive,
    {
        field
            .get(idx)
            .ok()
            .and_then(|v| v.to_u64())
            .map(|w| w as u32)
    }
    #[inline]
    fn add(self, cost: Self) -> Self {
        self.saturating_add(cost)
    }
    #[inline]
    fn load_dist(dp: &AtomicDistParent) -> Self {
        dp.load_dist_int()
    }
    #[inline]
    fn is_reached(self) -> bool {
        self != u32::MAX
    }
    #[inline]
    fn relax(dp: &AtomicDistParent, new: Self, parent: u32) -> bool {
        dp.relax_with_parent_int(new, parent)
    }
}

/// One O(V) pass to decide whether the integer engine is applicable.
fn scan_field_integer<V>(field: &V, total: u64) -> (u64, bool)
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
{
    (0..total)
        .into_par_iter()
        .fold(
            || (0u64, true),
            |(mx, ok), i| match field.get(i) {
                Ok(v) => match v.to_f64() {
                    Some(f)
                        if f.is_finite()
                            && f >= 0.0
                            && f.fract() == 0.0
                            && f <= u32::MAX as f64 =>
                    {
                        let w = v.to_u64().unwrap_or(u64::MAX);
                        (mx.max(w), ok)
                    }
                    _ => (mx, false),
                },
                Err(_) => (mx, false),
            },
        )
        .reduce(|| (0u64, true), |a, b| (a.0.max(b.0), a.1 && b.1))
}

/// Diagnostic counts for the bucket-fusion driver (barriers vs fused phases).
#[derive(Default, Debug, Clone, Copy)]
#[doc(hidden)]
pub struct FusionRunStats {
    pub parallel_rounds: usize,

    pub fused_phases: usize,

    pub fused_pops: u64,
}

/// Bucket-fusion parallel parental driver, generic over the distance
/// accumulator `D` (integer `u32` or fallback `f32`).
fn parental_parallel_run<V, D>(
    field: &V,
    source: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    shape: VolumeShape,
    fusion_enabled: bool,
    stats: Option<&mut FusionRunStats>,
) -> Vec<u32>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
    D: ParAcc,
{
    let total = shape.total() as usize;
    let dist_parent = D::init_vec(total);
    dist_parent[source as usize].store_source();

    let ctx = NeighborhoodContext::new(&shape, connectivity);
    let sx = shape.sx as i64;
    let sy = shape.sy as i64;
    let sz = shape.sz as i64;
    let graph_ref = graph.as_ref();

    let nthreads = rayon::current_num_threads().max(1);
    // Scale the fusion cutoff with the pool: a bigger pool needs a wider frontier
    // before a barrier-synchronized round out-earns a barrier-free sweep.
    let threshold = PARENTAL_FUSION_THRESHOLD.max(nthreads * 256);

    let mut frontier: Vec<u64> = vec![source];
    let mut fused: VecDeque<u64> = VecDeque::new();
    let mut buf: Vec<u64> = Vec::with_capacity(64);
    let mut s = FusionRunStats::default();

    while !frontier.is_empty() {
        if fusion_enabled && frontier.len() < threshold {
            // --- Bucket fusion: barrier-free sequential worklist ---
            s.fused_phases += 1;
            fused.clear();
            fused.extend(frontier.drain(..));
            loop {
                // Pending set outgrew the threshold — worth a parallel round now.
                if fused.len() >= threshold {
                    break;
                }
                let loc = match fused.pop_front() {
                    Some(l) => l,
                    None => break,
                };
                s.fused_pops += 1;
                buf.clear();
                expand_voxel_parental_generic::<V, D>(
                    field,
                    loc,
                    &dist_parent,
                    &ctx,
                    graph_ref,
                    &shape,
                    sx,
                    sy,
                    sz,
                    &mut buf,
                );
                for &nb in &buf {
                    fused.push_back(nb);
                }
            }
            frontier.clear();
            frontier.extend(fused.drain(..));
        } else {
            // --- Over-decomposed parallel round (one global barrier) ---
            s.parallel_rounds += 1;
            let min_len = (frontier.len() / (nthreads * 4)).max(1);
            let mut next_buffers: Vec<Vec<u64>> = frontier
                .par_iter()
                .with_min_len(min_len)
                .fold(
                    || Vec::with_capacity(64),
                    |mut acc, &loc| {
                        expand_voxel_parental_generic::<V, D>(
                            field,
                            loc,
                            &dist_parent,
                            &ctx,
                            graph_ref,
                            &shape,
                            sx,
                            sy,
                            sz,
                            &mut acc,
                        );
                        acc
                    },
                )
                .collect();

            let total_next: usize = next_buffers.iter().map(Vec::len).sum();
            let mut next_frontier: Vec<u64> = Vec::with_capacity(total_next);
            for b in &mut next_buffers {
                next_frontier.append(b);
            }
            frontier = next_frontier;
        }
    }

    if let Some(out) = stats {
        *out = s;
    }

    dist_parent.iter().map(|dp| dp.load().0).collect()
}

/// Generic relaxation kernel for [`parental_parallel_run`]: push every neighbor
/// that strictly improves into `out`. Monomorphized over the accumulator `D`.
#[inline]
#[allow(clippy::too_many_arguments)]
fn expand_voxel_parental_generic<V, D>(
    field: &V,
    loc: u64,
    dist_parent: &[AtomicDistParent],
    ctx: &NeighborhoodContext,
    graph: Option<&ConnectivityGraph<'_>>,
    shape: &VolumeShape,
    sx: i64,
    sy: i64,
    sz: i64,
    out: &mut Vec<u64>,
) where
    V: VoxelSource,
    V::Item: ToPrimitive,
    D: ParAcc,
{
    let current_dist = D::load_dist(&dist_parent[loc as usize]);
    if !current_dist.is_reached() {
        return;
    }

    let (x, y, z) = shape.coords(loc);

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

        if !is_neighbor_in_bounds(x, y, z, dx, dy, dz, sx, sy, sz) {
            continue;
        }

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

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

        let cost = match D::read_cost(field, neighbor) {
            Some(c) => c,
            None => continue,
        };

        let new_dist = current_dist.add(cost);

        if D::relax(&dist_parent[neighbor as usize], new_dist, loc as u32) {
            out.push(neighbor);
        }
    }
}

/// Compute the parental field rooted at `source` using parallel relaxation.
pub fn parental_field_parallel<V>(
    field: &V,
    source: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<Vec<u32>>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }

    if total > (u32::MAX as u64 - 1) {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "parental_field_parallel: volume too large ({} voxels); \
             parent indices must fit in u32 (max {})",
            total,
            u32::MAX - 1
        )));
    }

    let (max_weight, all_integer) = scan_field_integer(field, total);
    let use_int = if all_integer {
        checked_int_distance_bound(shape, max_weight)? < u32::MAX as u64
    } else {
        false
    };

    let parents = if use_int {
        parental_parallel_run::<V, u32>(field, source, connectivity, graph, shape, true, None)
    } else {
        parental_parallel_run::<V, f32>(field, source, connectivity, graph, shape, true, None)
    };

    Ok(parents)
}

/// Force the parental parallel driver with or without bucket fusion.
#[doc(hidden)]
pub fn parental_field_parallel_ablation<V>(
    field: &V,
    source: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    fusion_enabled: bool,
) -> Result<Vec<u32>>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    if total > (u32::MAX as u64 - 1) {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "parental ablation volume has {total} voxels; maximum is {}",
            u32::MAX - 1
        )));
    }

    let (max_weight, all_integer) = scan_field_integer(field, total);
    let use_int = if all_integer {
        checked_int_distance_bound(shape, max_weight)? < u32::MAX as u64
    } else {
        false
    };
    let parents = if use_int {
        parental_parallel_run::<V, u32>(
            field,
            source,
            connectivity,
            graph,
            shape,
            fusion_enabled,
            None,
        )
    } else {
        parental_parallel_run::<V, f32>(
            field,
            source,
            connectivity,
            graph,
            shape,
            fusion_enabled,
            None,
        )
    };
    Ok(parents)
}

/// Diagnostic stats for the BSP parallel parental field.
#[doc(hidden)]
pub struct BspStats {
    pub round_frontier_sizes: Vec<usize>,

    pub total_pushed: u64,
}

/// Instrumented variant of [`parental_field_parallel`] used only by the
/// `bsp_round_count_parental` example to observe round counts / frontier
/// sizes. Not part of the stable API.
#[doc(hidden)]
pub fn parental_field_parallel_instrumented<V>(
    field: &V,
    source: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<BspStats>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();
    let dist_parent = atomic_dist_parent_vec(total as usize);
    dist_parent[source as usize].store_source();
    let mut frontier: Vec<u64> = vec![source];
    let ctx = NeighborhoodContext::new(&shape, connectivity);
    let sx = shape.sx as i64;
    let sy = shape.sy as i64;
    let sz = shape.sz as i64;
    let graph_ref = graph.as_ref();

    let mut round_frontier_sizes = Vec::new();
    let mut total_pushed = 0u64;
    while !frontier.is_empty() {
        round_frontier_sizes.push(frontier.len());
        let next_frontier: Vec<u64> = frontier
            .par_iter()
            .fold(Vec::new, |mut acc, &loc| {
                expand_voxel_into(
                    field,
                    loc,
                    &dist_parent,
                    &ctx,
                    graph_ref,
                    &shape,
                    sx,
                    sy,
                    sz,
                    &mut acc,
                );
                acc
            })
            .reduce(Vec::new, |mut a, mut b| {
                a.append(&mut b);
                a
            });
        total_pushed += next_frontier.len() as u64;
        frontier = next_frontier;
    }
    Ok(BspStats {
        round_frontier_sizes,
        total_pushed,
    })
}

/// Instrumented run of the bucket-fusion driver. Not part of the stable API.
#[doc(hidden)]
pub fn parental_field_parallel_fused_stats<V>(
    field: &V,
    source: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
) -> Result<FusionRunStats>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();
    if source >= total {
        return Err(Dijkstra3dError::OutOfBounds {
            idx: source,
            volume_size: total,
        });
    }
    let (max_weight, all_integer) = scan_field_integer(field, total);
    let use_int = if all_integer {
        checked_int_distance_bound(shape, max_weight)? < u32::MAX as u64
    } else {
        false
    };
    let mut stats = FusionRunStats::default();
    if use_int {
        let _ = parental_parallel_run::<V, u32>(
            field,
            source,
            connectivity,
            graph,
            shape,
            true,
            Some(&mut stats),
        );
    } else {
        let _ = parental_parallel_run::<V, f32>(
            field,
            source,
            connectivity,
            graph,
            shape,
            true,
            Some(&mut stats),
        );
    }
    Ok(stats)
}

/// Core relaxation kernel: push every neighbor that successfully relaxes into
/// `out`.
#[inline]
#[allow(clippy::too_many_arguments)]
fn expand_voxel_into<V>(
    field: &V,
    loc: u64,
    dist_parent: &[AtomicDistParent],
    ctx: &NeighborhoodContext,
    graph: Option<&ConnectivityGraph<'_>>,
    shape: &VolumeShape,
    sx: i64,
    sy: i64,
    sz: i64,
    out: &mut Vec<u64>,
) where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    let current_dist = dist_parent[loc as usize].load_dist();

    if !current_dist.is_finite() {
        return;
    }

    let (x, y, z) = shape.coords(loc);

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

        if !is_neighbor_in_bounds(x, y, z, dx, dy, dz, sx, sy, sz) {
            continue;
        }

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

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

        // Edge cost: field[neighbor]. Errors → skip neighbor.
        let neighbor_cost_f32 = match field.get(neighbor) {
            Ok(v) => match v.to_f32() {
                Some(f) => f,
                None => continue,
            },
            Err(_) => continue,
        };

        let new_dist = current_dist + neighbor_cost_f32;

        // Attempt atomic relax. `loc as u32` is safe because the caller
        // checked `total <= u32::MAX - 1` before calling.
        let did_relax = dist_parent[neighbor as usize].relax_with_parent(new_dist, loc as u32);

        if did_relax {
            out.push(neighbor);
        }
    }
}

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

    #[test]
    fn path_from_parents_returns_out_of_bounds_for_invalid_target() {
        let err = path_from_parents(&[0; 8], 8).unwrap_err();

        assert_eq!(
            err,
            Dijkstra3dError::OutOfBounds {
                idx: 8,
                volume_size: 8,
            }
        );
    }

    #[test]
    fn path_from_parents_rejects_parent_outside_field() {
        let err = path_from_parents(&[0, 9], 1).unwrap_err();

        assert_eq!(
            err,
            Dijkstra3dError::InvalidInput(
                "parental field references voxel 8 outside volume of size 2".into()
            )
        );
    }

    #[test]
    fn path_from_parents_rejects_parent_cycle() {
        let err = path_from_parents(&[2, 1], 0).unwrap_err();

        assert_eq!(
            err,
            Dijkstra3dError::InvalidInput("parental field contains a cycle".into())
        );
    }

    #[test]
    fn upstream_compat_selects_pinned_upstream_parent_when_f32_costs_tie() {
        let field = Array3::<f32>::from_elem((1, 2, 3), 1.0);
        let source = ArrayView3Source::new(field.view());
        let shape = source.shape();
        let parents =
            parental_field_upstream_compat(&source, shape.linear(0, 0, 0), Connectivity::TwentySix)
                .unwrap();

        let path = path_from_parents(&parents, shape.linear(0, 0, 2)).unwrap();

        assert_eq!(
            path,
            [
                shape.linear(0, 0, 0),
                shape.linear(0, 1, 1),
                shape.linear(0, 0, 2),
            ]
        );
    }

    #[test]
    fn upstream_compat_slice_matches_generic_for_all_connectivities() {
        let shape = VolumeShape::new(4, 3, 5);
        let field = (0..shape.total())
            .map(|index| (index % 7 + 1) as f32)
            .collect::<Vec<_>>();
        let array = Array3::from_shape_vec(
            (shape.sx as usize, shape.sy as usize, shape.sz as usize).f(),
            field.clone(),
        )
        .unwrap();
        let source = ArrayView3Source::new(array.view());

        for connectivity in [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ] {
            let generic = parental_field_upstream_compat(&source, 0, connectivity).unwrap();
            let contiguous =
                parental_field_upstream_compat_slice(&field, shape, 0, connectivity).unwrap();

            assert_eq!(contiguous, generic, "connectivity={connectivity:?}");
        }
    }

    #[test]
    fn upstream_compat_slice_rejects_length_mismatch() {
        let shape = VolumeShape::new(2, 2, 2);

        let error =
            parental_field_upstream_compat_slice(&[1.0f32; 7], shape, 0, Connectivity::TwentySix)
                .unwrap_err();

        assert_eq!(
            error,
            Dijkstra3dError::InvalidInput(
                "parental_field_upstream_compat_slice: slice length 7 != shape.total() 8".into()
            )
        );
    }

    /// Sequential and parallel must produce equal-cost paths to every
    /// reachable target.
    #[test]
    fn parental_parallel_matches_sequential_uniform() {
        let arr = Array3::<u32>::from_elem((8, 8, 8), 1);
        let source = ArrayView3Source::new(arr.view());
        let src = source.shape().linear(0, 0, 0);

        let seq = parental_field(&source, src, Connectivity::TwentySix, None).unwrap();
        let par = parental_field_parallel(&source, src, Connectivity::TwentySix, None).unwrap();

        let cost_via = |parents: &[u32], tgt: u64| -> f32 {
            let path = path_from_parents(parents, tgt).unwrap();
            // Sum field values along the path excluding the source; this matches
            // the cost convention of parental_field's internal Dijkstra.
            path.iter()
                .skip(1)
                .map(|&v| arr.as_slice_memory_order().unwrap()[v as usize] as f32)
                .sum()
        };

        for tgt in 0..source.shape().total() {
            if tgt == src {
                continue;
            }
            // Both must agree on reachability.
            let seq_reachable = seq[tgt as usize] != 0;
            let par_reachable = par[tgt as usize] != 0;
            assert_eq!(
                seq_reachable, par_reachable,
                "voxel {} reachability mismatch",
                tgt
            );
            if !seq_reachable {
                continue;
            }

            let cost_seq = cost_via(&seq, tgt);
            let cost_par = cost_via(&par, tgt);
            assert!(
                (cost_seq - cost_par).abs() < 1e-5,
                "voxel {}: seq cost {} != par cost {}",
                tgt,
                cost_seq,
                cost_par
            );
        }
    }

    /// The integer slice fast-path must produce a parent array that is
    /// byte-for-byte identical to the trait-based `parental_field` on the same
    /// core-layout data, across dtypes / connectivities / seeds. Any difference
    /// (including tie-break-only differences) fails.
    #[test]
    fn parental_slice_int_matches_trait_cost() {
        use ndarray::ShapeBuilder; // for `.f()`
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        // Non-cubic shape to exercise offset/bounds logic on all axes.
        let (sx, sy, sz) = (6u64, 5u64, 4u64);
        let shape = VolumeShape::new(sx, sy, sz);
        let total = shape.total();
        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];

        macro_rules! check_dtype {
            ($t:ty, $lo:expr, $hi:expr, $seed_base:expr) => {{
                for seed in 0..6u64 {
                    let mut rng = StdRng::seed_from_u64($seed_base + seed);
                    // Keep accumulated distances within f32's exact-integer range
                    // (< 2^24) so the trait path's f32 heap compares identically
                    // to the integer heap — a precondition for byte identity.
                    let slice: Vec<$t> = (0..total)
                        .map(|_| rng.random_range($lo..=$hi) as $t)
                        .collect();

                    // Fortran-order ndarray so ArrayView3Source reads the same
                    // core linear layout as the raw slice.
                    let arr = ndarray::Array3::from_shape_vec(
                        (sx as usize, sy as usize, sz as usize).f(),
                        slice.clone(),
                    )
                    .unwrap();
                    let trait_src = ArrayView3Source::new(arr.view());

                    // A few source positions including corner, center, and edges.
                    let sources = [
                        shape.linear(0, 0, 0),
                        shape.linear(sx - 1, sy - 1, sz - 1),
                        shape.linear(sx / 2, sy / 2, sz / 2),
                        shape.linear(sx - 1, 0, sz / 2),
                    ];
                    for &source in &sources {
                        for &conn in &conns {
                            let a = parental_field(&trait_src, source, conn, None).unwrap();
                            let b = parental_field_slice_int(&slice, shape, source, conn, None)
                                .unwrap();
                            // Bucket-queue tie-breaking may pick a different but
                            // equally-optimal parent, so parents need not be
                            // byte-identical. Both are shortest-path trees from
                            // `source`: the reconstructed path cost to every
                            // reachable voxel must match exactly.
                            let cost = |p: &[u64]| -> u64 {
                                p.iter().skip(1).map(|&v| slice[v as usize] as u64).sum()
                            };
                            for target in 0..total {
                                let pa = path_from_parents(&a, target).unwrap();
                                let pb = path_from_parents(&b, target).unwrap();
                                assert_eq!(
                                    cost(&pa),
                                    cost(&pb),
                                    "cost mismatch dtype={} seed={} source={} conn={:?} target={}",
                                    stringify!($t),
                                    seed,
                                    source,
                                    conn,
                                    target
                                );
                            }
                        }
                    }
                }
            }};
        }

        // u32 kept small so distances stay < 2^24 (exact in f32).
        check_dtype!(u8, 1u32, 255u32, 1000);
        check_dtype!(u16, 1u32, 4000u32, 2000);
        check_dtype!(u32, 1u32, 5000u32, 3000);
    }

    /// The halo-padded full-volume search must be byte-for-byte identical to the
    /// unpadded integer search across dtypes / distance widths / queue kinds /
    /// connectivities / sources.
    #[test]
    fn parental_slice_int_padded_matches_unpadded() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let (sx, sy, sz) = (6u64, 5u64, 4u64);
        let shape = VolumeShape::new(sx, sy, sz);
        let total = shape.total();
        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];
        // Permissive graph: every voxel permits all 26 directions (0xFFFFFFFF).
        let allow_all = vec![u32::MAX; total as usize];

        macro_rules! check_dtype {
            ($t:ty, $lo:expr, $hi:expr, $seed_base:expr) => {{
                for seed in 0..6u64 {
                    let mut rng = StdRng::seed_from_u64($seed_base + seed);
                    let slice: Vec<$t> = (0..total)
                        .map(|_| rng.random_range($lo..=$hi) as $t)
                        .collect();

                    let sources = [
                        shape.linear(0, 0, 0),
                        shape.linear(sx - 1, sy - 1, sz - 1),
                        shape.linear(sx / 2, sy / 2, sz / 2),
                        shape.linear(sx - 1, 0, sz / 2),
                    ];
                    for &source in &sources {
                        for &conn in &conns {
                            let padded =
                                parental_field_slice_int(&slice, shape, source, conn, None)
                                    .unwrap();
                            let g = ConnectivityGraph::new(&allow_all, shape).unwrap();
                            let unpadded =
                                parental_field_slice_int(&slice, shape, source, conn, Some(g))
                                    .unwrap();
                            assert_eq!(
                                padded,
                                unpadded,
                                "padded != unpadded dtype={} seed={} source={} conn={:?}",
                                stringify!($t),
                                seed,
                                source,
                                conn
                            );
                        }
                    }
                }
            }};
        }

        check_dtype!(u8, 1u32, 255u32, 4000); // bucket + u32
        check_dtype!(u16, 1u32, 4_000u32, 5000); // bucket + u32
        check_dtype!(u32, 1u32, 5_000u32, 6000); // bucket + u32
        check_dtype!(u32, 70_000u32, 100_000u32, 7000); // heap + u32
    }

    #[test]
    fn parental_slice_int_rejects_oob_source() {
        let shape = VolumeShape::new(4, 4, 4);
        let field = vec![1u32; shape.total() as usize];
        let result = parental_field_slice_int(&field, shape, 1000, Connectivity::TwentySix, None);
        assert!(matches!(result, Err(Dijkstra3dError::OutOfBounds { .. })));
    }

    #[test]
    fn parental_slice_int_rejects_len_mismatch() {
        let shape = VolumeShape::new(4, 4, 4);
        let field = vec![1u32; 10];
        let result = parental_field_slice_int(&field, shape, 0, Connectivity::Six, None);
        assert!(matches!(result, Err(Dijkstra3dError::InvalidInput(_))));
    }

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

        let error =
            parental_field_slice_int(&field, shape, 0, Connectivity::Six, None).unwrap_err();

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

    #[test]
    fn parental_parallel_rejects_oob_source() {
        let arr = Array3::<u32>::from_elem((4, 4, 4), 1);
        let source = ArrayView3Source::new(arr.view());
        let result = parental_field_parallel(&source, 1000, Connectivity::TwentySix, None);
        assert!(matches!(result, Err(Dijkstra3dError::OutOfBounds { .. })));
    }

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

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

        for seed in 0..16u64 {
            let mut rng = StdRng::seed_from_u64(0x9A5E_0000 + seed);
            let field: Vec<u32> = (0..shape.total())
                .map(|_| rng.random_range(1..=6u32))
                .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);
            let cap = max_w as u32;

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

                // Public dispatcher picks u16 and must match. Bucket queue gives
                // the same tie-break as the forced-u16 search above.
                let pub_parents = parental_field_slice_int(&field, shape, src, conn, None).unwrap();
                assert_eq!(
                    pub_parents, p16,
                    "public parents != u16 seed={seed} conn={conn:?}"
                );
            }
        }
    }

    /// Path-cost helper for the trait-backed field.
    fn parental_path_cost<T>(source: &ArrayView3Source<'_, T>, parents: &[u32], tgt: u64) -> u64
    where
        T: Copy + ToPrimitive,
    {
        path_from_parents(parents, tgt)
            .unwrap()
            .iter()
            .skip(1)
            .map(|&v| source.get(v).unwrap().to_u64().unwrap())
            .sum()
    }

    /// Integer parallel path (non-uniform weights) must be cost-equivalent to the
    /// sequential trait Dijkstra across connectivities.
    #[test]
    fn parental_parallel_int_matches_sequential_random_weights() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let (sx, sy, sz) = (10usize, 9, 8);
        for seed in 0..4u64 {
            let mut rng = StdRng::seed_from_u64(1000 + seed);
            let arr =
                Array3::<u32>::from_shape_simple_fn((sx, sy, sz), || rng.random_range(1..=50u32));
            let source = ArrayView3Source::new(arr.view());
            let shape = source.shape();
            let src = shape.linear(sx as u64 / 2, sy as u64 / 2, sz as u64 / 2);

            for &conn in &[
                Connectivity::Six,
                Connectivity::Eighteen,
                Connectivity::TwentySix,
            ] {
                let seq = parental_field(&source, src, conn, None).unwrap();
                let par = parental_field_parallel(&source, src, conn, None).unwrap();
                for tgt in 0..shape.total() {
                    if tgt == src {
                        continue;
                    }
                    let sr = seq[tgt as usize] != 0;
                    let pr = par[tgt as usize] != 0;
                    assert_eq!(sr, pr, "reachability seed={seed} conn={conn:?} tgt={tgt}");
                    if !sr {
                        continue;
                    }
                    assert_eq!(
                        parental_path_cost(&source, &seq, tgt),
                        parental_path_cost(&source, &par, tgt),
                        "cost seed={seed} conn={conn:?} tgt={tgt}"
                    );
                }
            }
        }
    }

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

        let mut rng = StdRng::seed_from_u64(4242);
        // 2x2x200: diameter ~200, frontier width <= 4.
        let arr = Array3::<u32>::from_shape_simple_fn((2, 2, 200), || rng.random_range(1..=9u32));
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let src = shape.linear(0, 0, 0);
        let conn = Connectivity::TwentySix;

        let seq = parental_field(&source, src, conn, None).unwrap();
        let par = parental_field_parallel(&source, src, conn, None).unwrap();
        for tgt in 0..shape.total() {
            if tgt == src {
                continue;
            }
            assert_eq!(
                parental_path_cost(&source, &seq, tgt),
                parental_path_cost(&source, &par, tgt),
                "narrow-frontier cost mismatch tgt={tgt}"
            );
        }
    }

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

        let n = 32usize;
        let mut rng = StdRng::seed_from_u64(77);
        let arr = Array3::<u32>::from_shape_simple_fn((n, n, n), || rng.random_range(1..=17u32));
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let total = shape.total();
        let src = shape.linear(n as u64 / 2, n as u64 / 2, n as u64 / 2);
        let conn = Connectivity::TwentySix;

        let seq = parental_field(&source, src, conn, None).unwrap();
        let cost_vec = |parents: &[u32]| -> Vec<u64> {
            (0..total)
                .map(|t| {
                    if t == src || parents[t as usize] == 0 {
                        0
                    } else {
                        parental_path_cost(&source, parents, t)
                    }
                })
                .collect()
        };
        let seq_costs = cost_vec(&seq);

        let mut reference: Option<Vec<u64>> = None;
        for &threads in &[1usize, 2, 4, 8, 12] {
            let pool = ThreadPoolBuilder::new()
                .num_threads(threads)
                .build()
                .unwrap();
            let par = pool.install(|| parental_field_parallel(&source, src, conn, None).unwrap());
            // Reachability + cost vs sequential.
            for t in 0..total {
                if t == src {
                    continue;
                }
                assert_eq!(
                    seq[t as usize] != 0,
                    par[t as usize] != 0,
                    "threads={threads} tgt={t} reachability"
                );
            }
            let costs = cost_vec(&par);
            assert_eq!(costs, seq_costs, "threads={threads}: cost vs sequential");
            match &reference {
                None => reference = Some(costs),
                Some(r) => assert_eq!(
                    r, &costs,
                    "threads={threads}: parallel cost differs across thread counts (race)"
                ),
            }
        }
    }

    #[test]
    fn parental_parallel_f32_fallback_matches_sequential() {
        let arr = Array3::<f32>::from_shape_fn((6, 5, 4), |(x, y, z)| {
            1.0 + 0.5 * (((x + y + z) % 3) as f32)
        });
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let src = shape.linear(0, 0, 0);
        let conn = Connectivity::TwentySix;

        let seq = parental_field(&source, src, conn, None).unwrap();
        let par = parental_field_parallel(&source, src, conn, None).unwrap();

        let cost = |parents: &[u32], tgt: u64| -> f32 {
            path_from_parents(parents, tgt)
                .unwrap()
                .iter()
                .skip(1)
                .map(|&v| source.get(v).unwrap())
                .sum()
        };
        for tgt in 0..shape.total() {
            if tgt == src {
                continue;
            }
            assert!(
                (cost(&seq, tgt) - cost(&par, tgt)).abs() < 1e-4,
                "f32 fallback cost mismatch tgt={tgt}: {} vs {}",
                cost(&seq, tgt),
                cost(&par, tgt)
            );
        }
    }

    #[test]
    fn parental_fusion_cuts_barriers_on_narrow_frontier() {
        let arr = Array3::<u32>::from_elem((4, 4, 500), 1u32);
        let source = ArrayView3Source::new(arr.view());
        let src = source.shape().linear(0, 0, 0);
        let conn = Connectivity::TwentySix;

        let pure_bsp = parental_field_parallel_instrumented(&source, src, conn, None).unwrap();
        let fused = parental_field_parallel_fused_stats(&source, src, conn, None).unwrap();

        let pure_bsp_barriers = pure_bsp.round_frontier_sizes.len();
        assert!(
            fused.parallel_rounds * 10 < pure_bsp_barriers,
            "fusion should cut global barriers >10x: pure-BSP={pure_bsp_barriers} fused={}",
            fused.parallel_rounds
        );
    }

    #[test]
    fn parental_fusion_ablation_preserves_target_costs() {
        let shape = VolumeShape::new(12, 11, 10);
        let values: Vec<u16> = (0..shape.total())
            .map(|index| 1 + ((index * 13 + 5) % 8) as u16)
            .collect();
        let array = Array3::from_shape_fn((12, 11, 10), |(x, y, z)| {
            values[shape.linear(x as u64, y as u64, z as u64) as usize]
        });
        let field = ArrayView3Source::new(array.view());
        let source = shape.linear(0, 0, 0);
        let fused = parental_field_parallel_ablation(&field, source, Connectivity::Six, None, true)
            .unwrap();
        let pure = parental_field_parallel_ablation(&field, source, Connectivity::Six, None, false)
            .unwrap();

        for target in [
            shape.linear(11, 10, 9),
            shape.linear(7, 4, 8),
            shape.linear(3, 9, 2),
        ] {
            let fused_path = path_from_parents(&fused, target).unwrap();
            let pure_path = path_from_parents(&pure, target).unwrap();
            let fused_cost: u64 = fused_path
                .iter()
                .skip(1)
                .map(|&index| values[index as usize] as u64)
                .sum();
            let pure_cost: u64 = pure_path
                .iter()
                .skip(1)
                .map(|&index| values[index as usize] as u64)
                .sum();
            assert_eq!(fused_cost, pure_cost);
        }
    }
}