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
//! Cumulative edge-weight distance field.
//!
//! Upstream reference: `dijkstra3d.hpp::distance_field3d`.

use crate::atomic_dist::{atomic_dist_vec, AtomicDist};
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::*;

/// Distance field result with optional max-distance location.
#[derive(Debug, Clone)]
pub struct DistanceFieldOutput {
    pub distances: Vec<f32>,

    pub max_location: Option<u64>,
}

/// Compute distance field from one or more sources.
pub fn distance_field<V>(
    field: &V,
    sources: &[u64],
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    return_max_location: bool,
) -> Result<DistanceFieldOutput>
where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    if sources.is_empty() {
        return Err(Dijkstra3dError::InvalidInput(
            "sources cannot be empty".into(),
        ));
    }

    // Validate all sources
    for &src in sources {
        if src >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: src,
                volume_size: total,
            });
        }
    }

    // Initialize distances to infinity
    let mut distances = vec![f32::INFINITY; total as usize];

    // Initialize queue with all sources at distance 0
    let mut queue = BinaryHeapQueue::new();
    for &src in sources {
        distances[src as usize] = 0.0;
        queue.push(0.0, src);
    }

    // Precompute neighbor offsets and masks
    let offsets = neighborhood_offsets(shape.sx as i64, shape.stride_z() as i64);
    let neighbor_count = connectivity.count();

    // Dijkstra expansion
    while let Some((_dist, loc)) = queue.pop() {
        let current_dist = distances[loc as usize];

        // Lazy deletion: skip stale entries
        if _dist > current_dist {
            continue;
        }

        // Compute current coordinates for bounds checking
        let (x, y, z) = shape.coords(loc);

        // Expand to neighbors
        for i in 0..neighbor_count {
            // Per-axis bounds check using DIRECTIONS_26
            let dir = crate::neighborhood::DIRECTIONS_26[i];
            let nx = x as i64 + dir.0 as i64;
            let ny = y as i64 + dir.1 as i64;
            let nz = z as i64 + dir.2 as i64;

            if nx < 0
                || nx >= shape.sx as i64
                || ny < 0
                || ny >= shape.sy as i64
                || nz < 0
                || nz >= shape.sz as i64
            {
                continue;
            }

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

            let masks = neighborhood_masks();
            // Optional connectivity graph filtering
            if let Some(g) = &graph {
                if !g.allows(loc, masks[i]) {
                    continue;
                }
            }

            // Get neighbor cost
            let neighbor_val = field.get(neighbor)?;
            let neighbor_cost_f32 = neighbor_val.to_f32().ok_or_else(|| {
                Dijkstra3dError::InvalidInput("field value not convertible to f32".into())
            })?;

            // Edge cost: field[neighbor] (uniform edges, no geometric weight)
            let new_dist = current_dist + neighbor_cost_f32;

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

    // Find max location if requested
    let max_location = if return_max_location {
        let mut max_idx = None;
        let mut max_dist = f32::NEG_INFINITY;

        for (idx, &dist) in distances.iter().enumerate() {
            if dist.is_finite() && dist > max_dist {
                max_dist = dist;
                max_idx = Some(idx as u64);
            }
        }

        max_idx
    } else {
        None
    };

    Ok(DistanceFieldOutput {
        distances,
        max_location,
    })
}

/// Compute distance field from one or more sources using parallel
/// **delta-stepping** relaxation.
///
/// Functionally equivalent to [`distance_field`] but uses rayon to expand
/// multiple voxels concurrently. Same input contract; same output.
///
/// # Why delta-stepping (and not plain BSP)
pub fn distance_field_parallel<V>(
    field: &V,
    sources: &[u64],
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    return_max_location: bool,
) -> Result<DistanceFieldOutput>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    if sources.is_empty() {
        return Err(Dijkstra3dError::InvalidInput(
            "sources cannot be empty".into(),
        ));
    }
    for &src in sources {
        if src >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: src,
                volume_size: total,
            });
        }
    }

    let delta = choose_delta(field, total);
    let (dist, _stats) = delta_step_distance(field, sources, connectivity, graph, delta, false);

    // Materialize output: read every atomic into a plain Vec<f32>.
    let distances: Vec<f32> = dist.iter().map(|d| d.load()).collect();

    let max_location = if return_max_location {
        find_max_finite(&distances)
    } else {
        None
    };

    Ok(DistanceFieldOutput {
        distances,
        max_location,
    })
}

/// Pick a delta-stepping bucket width from the field's edge-weight scale.
fn choose_delta<V>(field: &V, total: u64) -> f32
where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    if total == 0 {
        return 1.0;
    }
    // Sample up to 4096 evenly-spaced voxels.
    let sample_n = total.min(4096);
    let stride = (total / sample_n).max(1);
    let mut sum = 0.0f64;
    let mut count = 0u64;
    let mut idx = 0u64;
    while idx < total && count < sample_n {
        if let Ok(v) = field.get(idx) {
            if let Some(f) = v.to_f32() {
                if f.is_finite() && f > 0.0 {
                    sum += f as f64;
                    count += 1;
                }
            }
        }
        idx += stride;
    }
    if count == 0 {
        return 1.0;
    }
    ((sum / count as f64) as f32).max(1.0)
}

/// Diagnostic stats for the delta-stepping parallel distance field.
#[doc(hidden)]
pub struct BspStats {
    /// Voxels expanded per parallel round (length == number of rounds; a
    /// bucket processed to fixpoint spans multiple rounds).
    pub round_frontier_sizes: Vec<usize>,
    /// Total voxels pushed across all rounds (work amplification vs volume).
    pub total_pushed: u64,
    /// Delta bucket width used.
    pub delta: f32,
    /// Number of distinct buckets touched.
    pub buckets: usize,
}

/// Instrumented variant of [`distance_field_parallel`] used only by the
/// `bsp_round_count_distance` example. Not part of the stable API.
#[doc(hidden)]
pub fn distance_field_parallel_instrumented<V>(
    field: &V,
    sources: &[u64],
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    delta: Option<f32>,
) -> Result<BspStats>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
{
    let total = field.shape().total();
    let delta = delta.unwrap_or_else(|| choose_delta(field, total));
    let (_dist, stats) = delta_step_distance(field, sources, connectivity, graph, delta, true);
    Ok(stats)
}

const DISTANCE_FUSION_THRESHOLD: usize = 2048;

/// Delta-stepping core shared by the public and instrumented entry points.
fn delta_step_distance<V>(
    field: &V,
    sources: &[u64],
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    delta: f32,
    collect_stats: bool,
) -> (Vec<AtomicDist>, BspStats)
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive,
{
    let shape = field.shape();
    let total = shape.total();

    // Atomic distances per voxel, all initialized to +INFINITY.
    let dist = atomic_dist_vec(total as usize);
    for &src in sources {
        dist[src as usize].store_zero();
    }

    let offsets = neighborhood_offsets(shape.sx as i64, shape.stride_z() as i64);
    let masks = neighborhood_masks();
    let neighbor_count = connectivity.count();
    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 inv_delta = 1.0f32 / delta;

    let nthreads = rayon::current_num_threads().max(1);
    let fusion_threshold = DISTANCE_FUSION_THRESHOLD.max(nthreads * 256);

    // Buckets grown on demand. Sources all sit in bucket 0 (distance 0).
    let mut buckets: Vec<Vec<u64>> = vec![sources.to_vec()];

    let mut round_frontier_sizes: Vec<usize> = Vec::new();
    let mut total_pushed = 0u64;
    let mut buckets_touched = 0usize;

    // Reused scatter helper: push a relaxed (idx, band) into its target bucket,
    // growing the ring on demand.
    let mut b = 0usize;
    while b < buckets.len() {
        if buckets[b].is_empty() {
            b += 1;
            continue;
        }
        buckets_touched += 1;

        // Process bucket b to a fixpoint. A relaxation can land a neighbor
        // back in bucket b (edge cost < Δ) — that neighbor is reprocessed on
        // the next iteration of this loop. It can never land in a bucket < b.
        loop {
            let work = std::mem::take(&mut buckets[b]);
            if work.is_empty() {
                break;
            }
            if collect_stats {
                round_frontier_sizes.push(work.len());
            }

            if work.len() < fusion_threshold {
                // barrier-free sequential expansion
                let mut acc: Vec<(u64, u32)> = Vec::with_capacity(work.len() * neighbor_count);
                for &loc in &work {
                    expand_voxel_distance_into(
                        field,
                        loc,
                        &dist,
                        &offsets,
                        &masks,
                        neighbor_count,
                        graph_ref,
                        &shape,
                        sx,
                        sy,
                        sz,
                        b,
                        inv_delta,
                        &mut acc,
                    );
                }
                total_pushed += acc.len() as u64;
                for &(idx, band) in &acc {
                    let band = band as usize;
                    if band >= buckets.len() {
                        buckets.resize_with(band + 1, Vec::new);
                    }
                    buckets[band].push(idx);
                }
            } else {
                let min_len = (work.len() / (nthreads * 4)).max(1);
                let mut worker_bufs: Vec<Vec<(u64, u32)>> = work
                    .par_iter()
                    .with_min_len(min_len)
                    .fold(
                        || Vec::with_capacity(64),
                        |mut acc, &loc| {
                            expand_voxel_distance_into(
                                field,
                                loc,
                                &dist,
                                &offsets,
                                &masks,
                                neighbor_count,
                                graph_ref,
                                &shape,
                                sx,
                                sy,
                                sz,
                                b,
                                inv_delta,
                                &mut acc,
                            );
                            acc
                        },
                    )
                    .collect();

                // Scatter the relaxed neighbors into their target buckets.
                for buf in &mut worker_bufs {
                    total_pushed += buf.len() as u64;
                    for &(idx, band) in buf.iter() {
                        let band = band as usize;
                        if band >= buckets.len() {
                            buckets.resize_with(band + 1, Vec::new);
                        }
                        buckets[band].push(idx);
                    }
                }
            }
        }

        b += 1;
    }

    let stats = BspStats {
        round_frontier_sizes,
        total_pushed,
        delta,
        buckets: buckets_touched,
    };
    (dist, stats)
}

/// Core relaxation kernel for delta-stepping
#[inline]
#[allow(clippy::too_many_arguments)]
fn expand_voxel_distance_into<V>(
    field: &V,
    loc: u64,
    dist: &[AtomicDist],
    offsets: &[i64; 26],
    masks: &[u32; 26],
    neighbor_count: usize,
    graph: Option<&ConnectivityGraph<'_>>,
    shape: &crate::voxel::VolumeShape,
    sx: i64,
    sy: i64,
    sz: i64,
    current_bucket: usize,
    inv_delta: f32,
    out: &mut Vec<(u64, u32)>,
) where
    V: VoxelSource,
    V::Item: ToPrimitive,
{
    let current_dist = dist[loc as usize].load();
    if !current_dist.is_finite() {
        return;
    }
    // Stale-skip, this voxel has since been relaxed into an earlier bucket
    if (current_dist * inv_delta) as usize != current_bucket {
        return;
    }

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

    for i in 0..neighbor_count {
        let dir = DIRECTIONS_26[i];
        let nx = x as i64 + dir.0 as i64;
        let ny = y as i64 + dir.1 as i64;
        let nz = z as i64 + dir.2 as i64;

        if nx < 0 || nx >= sx || ny < 0 || ny >= sy || nz < 0 || nz >= sz {
            continue;
        }

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

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

        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;
        if dist[neighbor as usize].relax(new_dist) {
            let band = (new_dist * inv_delta) as u32;
            out.push((neighbor, band));
        }
    }
}

/// Linear scan for the max-finite-distance voxel index.
#[inline]
fn find_max_finite(distances: &[f32]) -> Option<u64> {
    let mut max_idx = None;
    let mut max_dist = f32::NEG_INFINITY;
    for (idx, &d) in distances.iter().enumerate() {
        if d.is_finite() && d > max_dist {
            max_dist = d;
            max_idx = Some(idx as u64);
        }
    }
    max_idx
}

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

    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "distance_field_slice_int: slice length {} != shape.total() {}",
            field.len(),
            total
        )));
    }
    if total > u32::MAX as u64 {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "distance_field_slice_int: volume {total} exceeds u32::MAX voxels; \
             use the u64 trait path"
        )));
    }
    if sources.is_empty() {
        return Err(Dijkstra3dError::InvalidInput(
            "sources cannot be empty".into(),
        ));
    }
    for &src in sources {
        if src >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: src,
                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);

    // Any finite distance is bounded by (steps to reach the voxel) * max_weight,
    // and any voxel is reachable in <= sx+sy+sz axis steps.
    let dist_bound = checked_int_distance_bound(shape, max_weight)?;
    let width = select_dist_width(dist_bound);

    // Bucket queue is only worthwhile (and memory-bounded) for a small range.
    // `ring_len = max_weight + 1`; cap the ring at 65_536 buckets.
    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 {
        let distances = match (use_bucket, width) {
            (true, DistWidth::U16) => distance_field_slice_int_search_padded::<_, _, u16>(
                field,
                shape,
                padded,
                sources,
                connectivity,
                BucketQueue::with_capacity(max_weight as u32),
            ),
            (true, DistWidth::U32) => distance_field_slice_int_search_padded::<_, _, u32>(
                field,
                shape,
                padded,
                sources,
                connectivity,
                BucketQueue::with_capacity(max_weight as u32),
            ),
            (true, DistWidth::U64) => distance_field_slice_int_search_padded::<_, _, u64>(
                field,
                shape,
                padded,
                sources,
                connectivity,
                BucketQueue::with_capacity(max_weight as u32),
            ),
            (false, DistWidth::U16) => distance_field_slice_int_search_padded::<_, _, u16>(
                field,
                shape,
                padded,
                sources,
                connectivity,
                BinaryHeapQueue::<u64, u32>::new(),
            ),
            (false, DistWidth::U32) => distance_field_slice_int_search_padded::<_, _, u32>(
                field,
                shape,
                padded,
                sources,
                connectivity,
                BinaryHeapQueue::<u64, u32>::new(),
            ),
            (false, DistWidth::U64) => distance_field_slice_int_search_padded::<_, _, u64>(
                field,
                shape,
                padded,
                sources,
                connectivity,
                BinaryHeapQueue::<u64, u32>::new(),
            ),
        };
        return Ok(DistanceFieldOutput {
            distances,
            max_location: None,
        });
    }

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

    Ok(DistanceFieldOutput {
        distances,
        max_location: None,
    })
}

/// Shared integer distance-field search, monomorphized over the queue
/// implementation and the distance-accumulator width `D` (`u32` or `u64`).
fn distance_field_slice_int_search<T: ToU64Fast, Q: IntQueue, D: Dist>(
    field: &[T],
    shape: VolumeShape,
    sources: &[u64],
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    mut queue: Q,
) -> Vec<f32> {
    let total = shape.total() as usize;

    let mut distances = vec![D::MAX; total];
    for &src in sources {
        distances[src as usize] = D::ZERO;
        queue.push_i(0, src 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: skip stale entries.
        if dist > distances[loc_us].to_priority() {
            continue;
        }

        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) = 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;
                queue.push_i(new_dist.to_priority(), neighbor as u32);
            }
        }
    }

    // Convert integer distances to f32, mapping the MAX sentinel to +INFINITY.
    distances
        .iter()
        .map(|&d| {
            if d == D::MAX {
                f32::INFINITY
            } else {
                d.to_priority() as f32
            }
        })
        .collect()
}

/// Diagnostic/bench-only entry point that forces the unpadded integer distance
/// search (no halo), with no connectivity graph.
#[doc(hidden)]
pub fn distance_field_slice_int_unpadded<T: ToU64Fast>(
    field: &[T],
    shape: VolumeShape,
    sources: &[u64],
    connectivity: Connectivity,
) -> Result<DistanceFieldOutput> {
    let total = shape.total();
    if field.len() as u64 != total || total > u32::MAX as u64 || sources.is_empty() {
        return Err(Dijkstra3dError::InvalidInput(
            "distance_field_slice_int_unpadded: invalid input".into(),
        ));
    }
    for &src in sources {
        if src >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: src,
                volume_size: total,
            });
        }
    }
    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;
    let distances = match (use_bucket, use_u32) {
        (true, true) => distance_field_slice_int_search::<_, _, u32>(
            field,
            shape,
            sources,
            connectivity,
            None,
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (true, false) => distance_field_slice_int_search::<_, _, u64>(
            field,
            shape,
            sources,
            connectivity,
            None,
            BucketQueue::with_capacity(max_weight as u32),
        ),
        (false, true) => distance_field_slice_int_search::<_, _, u32>(
            field,
            shape,
            sources,
            connectivity,
            None,
            BinaryHeapQueue::<u64, u32>::new(),
        ),
        (false, false) => distance_field_slice_int_search::<_, _, u64>(
            field,
            shape,
            sources,
            connectivity,
            None,
            BinaryHeapQueue::<u64, u32>::new(),
        ),
    };
    Ok(DistanceFieldOutput {
        distances,
        max_location: None,
    })
}

/// Halo-padded full-volume distance search.
#[allow(clippy::too_many_arguments)]
fn distance_field_slice_int_search_padded<T: ToU64Fast, Q: IntQueue, D: Dist>(
    field: &[T],
    shape: VolumeShape,
    padded: PaddedShape,
    sources: &[u64],
    connectivity: Connectivity,
    mut queue: Q,
) -> Vec<f32> {
    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 distances 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];
    crate::halo::set_halo_zero::<D>(&mut distances, psx as usize, psy as usize, psz as usize);

    for &src in sources {
        let (sxc, syc, szc) = shape.coords(src);
        let sp = crate::halo::to_padded_index(sxc, syc, szc, padded) as u32;
        distances[sp as usize] = D::ZERO;
        queue.push_i(0, sp);
    }

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

    // No `coords()` and 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;
                queue.push_i(new_dist.to_priority(), neighbor as u32);
            }
        }
    }

    // Extract interior distances in original order; map the sentinel to +INFINITY.
    // Exact for finite distances < 2^24 (see `distance_field_slice_int_search`).
    let sx = shape.sx;
    let sy = shape.sy;
    let sz = shape.sz;
    let sxy = sx * sy;
    let mut out = vec![0f32; (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 d = distances[(pad_base + x) as usize];
                out[(orig_base + x) as usize] = if d == D::MAX {
                    f32::INFINITY
                } else {
                    d.to_priority() as f32
                };
            }
        }
    }
    out
}

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

    #[test]
    fn distance_parallel_matches_sequential_uniform() {
        let arr = Array3::<u32>::from_elem((8, 8, 8), 1);
        let source = ArrayView3Source::new(arr.view());
        let sources = vec![0u64];

        let seq = distance_field(&source, &sources, Connectivity::TwentySix, None, false).unwrap();
        let par = distance_field_parallel(&source, &sources, Connectivity::TwentySix, None, false)
            .unwrap();

        assert_eq!(seq.distances.len(), par.distances.len());
        for i in 0..seq.distances.len() {
            assert!(
                (seq.distances[i] - par.distances[i]).abs() < 1e-5,
                "voxel {}: seq {} != par {}",
                i,
                seq.distances[i],
                par.distances[i]
            );
        }
    }

    #[test]
    fn distance_parallel_multi_source_collision() {
        let arr = Array3::<u32>::from_elem((6, 6, 6), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let s0 = shape.linear(0, 0, 0);
        let s1 = shape.linear(5, 5, 5);

        let seq = distance_field(&source, &[s0, s1], Connectivity::TwentySix, None, false).unwrap();
        let par = distance_field_parallel(&source, &[s0, s1], Connectivity::TwentySix, None, false)
            .unwrap();

        for i in 0..seq.distances.len() {
            assert!((seq.distances[i] - par.distances[i]).abs() < 1e-5);
        }
    }

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

        for &n in &[9usize, 16, 23] {
            let mut rng = StdRng::seed_from_u64(0xD3175A + n as u64);
            let arr =
                Array3::<u32>::from_shape_simple_fn((n, n, n), || rng.random_range(1..=255u32));
            let source = ArrayView3Source::new(arr.view());
            let shape = source.shape();

            // A few source configurations, including multi-source collisions.
            let s0 = shape.linear(0, 0, 0);
            let sc = shape.linear((n / 2) as u64, (n / 2) as u64, (n / 2) as u64);
            let s_end = shape.linear((n - 1) as u64, (n - 1) as u64, (n - 1) as u64);
            let configs: [Vec<u64>; 3] = [vec![s0], vec![s0, s_end], vec![sc]];

            for srcs in &configs {
                let seq =
                    distance_field(&source, srcs, Connectivity::TwentySix, None, false).unwrap();
                let par =
                    distance_field_parallel(&source, srcs, Connectivity::TwentySix, None, false)
                        .unwrap();
                assert_eq!(seq.distances.len(), par.distances.len());
                for i in 0..seq.distances.len() {
                    assert!(
                        (seq.distances[i] - par.distances[i]).abs() < 1e-3,
                        "n={n} srcs={srcs:?} voxel {i}: seq {} != par {}",
                        seq.distances[i],
                        par.distances[i]
                    );
                }
            }
        }
    }

    /// Delta-stepping must be correct for any Δ, including degenerate extremes
    /// (Δ=∞ collapses to Bellman-Ford; tiny Δ approaches serial Dijkstra).
    #[test]
    fn distance_parallel_correct_across_delta_extremes() {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let n = 14usize;
        let mut rng = StdRng::seed_from_u64(7);
        let arr = Array3::<u32>::from_shape_simple_fn((n, n, n), || rng.random_range(1..=255u32));
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let srcs = vec![shape.linear(0, 0, 0)];

        let seq = distance_field(&source, &srcs, Connectivity::TwentySix, None, false).unwrap();

        for &delta in &[1.0f32, 7.0, 100.0, 1.0e9] {
            let (dist, _stats) = super::delta_step_distance(
                &source,
                &srcs,
                Connectivity::TwentySix,
                None,
                delta,
                false,
            );
            for i in 0..seq.distances.len() {
                let par = dist[i].load();
                assert!(
                    (seq.distances[i] - par).abs() < 1e-3,
                    "Δ={delta} voxel {i}: seq {} != par {}",
                    seq.distances[i],
                    par
                );
            }
        }
    }

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

        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];

        // (sx, sy, sz) volumes, deliberately non-cubic to exercise strides.
        let shapes = [(8u64, 8, 8), (6, 7, 5), (10, 4, 9)];

        // Weight ranges chosen so worst-case path cost (<= (sx+sy+sz)*max_w)
        // stays far below 2^24: e.g. (10+9+... )*4000 << 16.7M.
        macro_rules! check_dtype {
            ($t:ty, $lo:expr, $hi:expr, $seed_base:expr) => {{
                for &(sx, sy, sz) in &shapes {
                    let shape = VolumeShape::new(sx, sy, sz);
                    let total = shape.total();
                    for seed in 0..3u64 {
                        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();

                        // Trait source built in Fortran (x-fastest) order so that
                        // ArrayView3Source::get(idx) == slice[idx].
                        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());

                        // Several source configurations, incl. multi-source.
                        let s0 = shape.linear(0, 0, 0);
                        let s_end = shape.linear(sx - 1, sy - 1, sz - 1);
                        let s_mid = shape.linear(sx / 2, sy / 2, sz / 2);
                        let source_sets: [Vec<u64>; 4] = [
                            vec![s0],
                            vec![s0, s_end],
                            vec![s_mid],
                            vec![s0, s_mid, s_end],
                        ];

                        for sources in &source_sets {
                            for &conn in &conns {
                                let a =
                                    distance_field(&trait_src, sources, conn, None, false).unwrap();
                                let b =
                                    distance_field_slice_int(&slice, shape, sources, conn, None)
                                        .unwrap();

                                assert_eq!(
                                    a.distances,
                                    b.distances,
                                    "dtype={} shape={:?} seed={} sources={:?} conn={:?}",
                                    stringify!($t),
                                    (sx, sy, sz),
                                    seed,
                                    sources,
                                    conn
                                );
                            }
                        }
                    }
                }
            }};
        }

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

    /// Unreachable voxels (a barrier the connectivity graph forbids crossing)
    /// must stay at `f32::INFINITY` in both paths.
    #[test]
    fn distance_int_slice_matches_trait_unreachable() {
        let shape = VolumeShape::new(4, 4, 4);
        let total = shape.total();
        let slice = vec![1u32; total as usize];
        let arr = ndarray::Array3::from_elem((4usize, 4, 4), 1u32);
        let trait_src = ArrayView3Source::new(arr.view());
        let sources = vec![shape.linear(0, 0, 0)];

        let a = distance_field(&trait_src, &sources, Connectivity::Six, None, false).unwrap();
        let b = distance_field_slice_int(&slice, shape, &sources, Connectivity::Six, None).unwrap();
        assert_eq!(a.distances, b.distances);
    }

    /// halo-padded full-volume distance search.
    #[test]
    fn distance_slice_int_padded_matches_unpadded() {
        use crate::connectivity_graph::ConnectivityGraph;
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];
        let shapes = [(8u64, 8, 8), (6, 7, 5), (10, 4, 9)];

        macro_rules! check_dtype {
            ($t:ty, $lo:expr, $hi:expr, $seed_base:expr) => {{
                for &(sx, sy, sz) in &shapes {
                    let shape = VolumeShape::new(sx, sy, sz);
                    let total = shape.total();
                    let allow_all = vec![u32::MAX; total as usize];
                    for seed in 0..3u64 {
                        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 s0 = shape.linear(0, 0, 0);
                        let s_end = shape.linear(sx - 1, sy - 1, sz - 1);
                        let s_mid = shape.linear(sx / 2, sy / 2, sz / 2);
                        let source_sets: [Vec<u64>; 4] = [
                            vec![s0],
                            vec![s0, s_end],
                            vec![s_mid],
                            vec![s0, s_mid, s_end],
                        ];

                        for sources in &source_sets {
                            for &conn in &conns {
                                let padded = distance_field_slice_int(
                                    &slice, shape, sources, conn, None,
                                )
                                .unwrap();
                                let g = ConnectivityGraph::new(&allow_all, shape).unwrap();
                                let unpadded = distance_field_slice_int(
                                    &slice, shape, sources, conn, Some(g),
                                )
                                .unwrap();
                                assert_eq!(
                                    padded.distances, unpadded.distances,
                                    "padded != unpadded dtype={} shape={:?} seed={} sources={:?} conn={:?}",
                                    stringify!($t), (sx, sy, sz), seed, sources, conn
                                );
                            }
                        }
                    }
                }
            }};
        }

        check_dtype!(u8, 1u32, 255u32, 400); // bucket + u32
        check_dtype!(u16, 1u32, 4_000u32, 500); // bucket + u32
        check_dtype!(u32, 1u32, 5_000u32, 600); // bucket + u32
        check_dtype!(u32, 70_000u32, 100_000u32, 700); // heap + u32
    }

    #[test]
    fn distance_int_slice_rejects_empty_sources() {
        let shape = VolumeShape::new(4, 4, 4);
        let slice = vec![1u32; shape.total() as usize];
        let result = distance_field_slice_int(&slice, shape, &[], Connectivity::Six, None);
        assert!(matches!(result, Err(Dijkstra3dError::InvalidInput(_))));
    }

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

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

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

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

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

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

        for seed in 0..16u64 {
            let mut rng = StdRng::seed_from_u64(0xD15C_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 d16 = distance_field_slice_int_search::<_, _, u16>(
                    &field,
                    shape,
                    &sources,
                    conn,
                    None,
                    BucketQueue::with_capacity(cap),
                );
                let d32 = distance_field_slice_int_search::<_, _, u32>(
                    &field,
                    shape,
                    &sources,
                    conn,
                    None,
                    BucketQueue::with_capacity(cap),
                );
                let d64 = distance_field_slice_int_search::<_, _, u64>(
                    &field,
                    shape,
                    &sources,
                    conn,
                    None,
                    BucketQueue::with_capacity(cap),
                );
                assert_eq!(
                    d16, d32,
                    "u16 vs u32 field differ seed={seed} conn={conn:?}"
                );
                assert_eq!(
                    d16, d64,
                    "u16 vs u64 field differ seed={seed} conn={conn:?}"
                );

                // Public dispatcher picks u16 and must match.
                let pub_field = distance_field_slice_int(&field, shape, &sources, conn, None)
                    .unwrap()
                    .distances;
                assert_eq!(
                    pub_field, d16,
                    "public field != u16 seed={seed} conn={conn:?}"
                );
            }
        }
    }

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

        let mut rng = StdRng::seed_from_u64(9001);
        // 2x2x256: high diameter, frontier width <= 4.
        let arr = Array3::<u32>::from_shape_simple_fn((2, 2, 256), || rng.random_range(1..=200u32));
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let srcs = vec![shape.linear(0, 0, 0)];

        let seq = distance_field(&source, &srcs, Connectivity::TwentySix, None, false).unwrap();
        let par =
            distance_field_parallel(&source, &srcs, Connectivity::TwentySix, None, false).unwrap();
        assert_eq!(seq.distances.len(), par.distances.len());
        for i in 0..seq.distances.len() {
            assert!(
                (seq.distances[i] - par.distances[i]).abs() < 1e-3,
                "narrow-frontier voxel {i}: seq {} != par {}",
                seq.distances[i],
                par.distances[i]
            );
        }
    }

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

        let n = 34usize;
        let mut rng = StdRng::seed_from_u64(0x0DD1);
        let arr = Array3::<u32>::from_shape_simple_fn((n, n, n), || rng.random_range(1..=64u32));
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let srcs = vec![
            shape.linear(0, 0, 0),
            shape.linear((n - 1) as u64, (n - 1) as u64, (n - 1) as u64),
        ];

        let seq = distance_field(&source, &srcs, Connectivity::TwentySix, None, false).unwrap();

        let mut reference: Option<Vec<f32>> = None;
        for &threads in &[1usize, 2, 4, 8, 12] {
            let pool = ThreadPoolBuilder::new()
                .num_threads(threads)
                .build()
                .unwrap();
            let par = pool.install(|| {
                distance_field_parallel(&source, &srcs, Connectivity::TwentySix, None, false)
                    .unwrap()
            });
            // Exactly equal to sequential (integer distances < 2^24 → f32-exact).
            assert_eq!(
                par.distances, seq.distances,
                "threads={threads}: distances differ from sequential"
            );
            match &reference {
                None => reference = Some(par.distances),
                Some(r) => assert_eq!(
                    r, &par.distances,
                    "threads={threads}: distances differ across thread counts (race)"
                ),
            }
        }
    }
}