twitcher 0.9.1

Find template switch mutations in genomic data
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
use std::{
    ops::{ControlFlow, Range},
    sync::Arc,
};

use rust_htslib::bam;

use super::{MAX_INDEL_SLIDE, RefSlice, comparison_span, trim_alleles};
use crate::{
    common::coords::{GenomePosition, GenomeRegion},
    vcf::pipeline::record::InputRecord,
};

/// Reference bases added on each side of the union of the records' comparison spans. They are
/// compared too, which confirms where a read is anchored.
const ANCHOR_FLANK: i64 = 5;

// The window reaches past the cluster region by a comparison span's reach (`MAX_INDEL_SLIDE +
// 1`), the repeat extension (`MAX_INDEL_SLIDE`), one base and `ANCHOR_FLANK`; the reference
// fetched for phasing has to cover that.
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
const _: () =
    assert!((2 * MAX_INDEL_SLIDE + 2 + ANCHOR_FLANK) as usize <= super::super::PHASING_REF_PADDING);

/// One slot's allele on a [`VariantGraph`] site.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Choice {
    Ref,
    /// Replace `at..end` by `Strand::alts[alt]`.
    Edit {
        at: i64,
        end: i64,
        alt: Range<usize>,
        deletion: bool,
    },
    /// `*`: valid only under a deletion covering this position.
    Star(i64),
}

impl Choice {
    fn pos(&self) -> Option<i64> {
        match self {
            Choice::Ref => None,
            Choice::Edit { at, .. } => Some(*at),
            Choice::Star(p) => Some(*p),
        }
    }
}

#[derive(Debug)]
struct Site {
    /// Index into `nodes`; `None` for a hom record or a flank, which no read labels.
    node: Option<usize>,
    /// Min over the choices of `Edit::at` / `Star` position.
    pos: i64,
    /// `[slot 0, slot 1]`; a hom site holds the same choice twice.
    choices: [Choice; 2],
    /// Index in forward site order, shared by both strands: insertions at one position are
    /// spelled by ascending rank forward and descending rank backward.
    rank: usize,
}

#[derive(Debug)]
struct Strand {
    /// Upper-case reference over `window`, indexed by `pos - window.start`.
    reference: Vec<u8>,
    /// Upper-case alt bytes of every edit, concatenated; `Choice::Edit::alt` indexes into it.
    alts: Vec<u8>,
    /// Sorted by `(pos, has a Star choice)`, so a deletion is decided before a star at the same pos.
    sites: Vec<Site>,
}

impl Strand {
    fn sort_sites(&mut self) {
        self.sites.sort_by_key(|s| {
            (
                s.pos,
                s.choices.iter().any(|c| matches!(c, Choice::Star(_))),
            )
        });
    }

    /// The same strand seen from the other end: `p -> k - 1 - p`, `[a, b) -> [k - b, k - a)`.
    fn mirror(&self, k: i64) -> Option<Strand> {
        let mut alts = Vec::with_capacity(self.alts.len());
        let mut mirror_choice = |c: &Choice| -> Option<Choice> {
            Some(match c {
                Choice::Ref => Choice::Ref,
                Choice::Star(p) => Choice::Star(k - 1 - p),
                Choice::Edit {
                    at,
                    end,
                    alt,
                    deletion,
                } => {
                    let start = alts.len();
                    alts.extend(self.alts.get(alt.clone())?.iter().rev());
                    Choice::Edit {
                        at: k - end,
                        end: k - at,
                        alt: start..alts.len(),
                        deletion: *deletion,
                    }
                }
            })
        };
        let sites = self
            .sites
            .iter()
            .map(|s| {
                let [c0, c1] = &s.choices;
                let choices = [mirror_choice(c0)?, mirror_choice(c1)?];
                let pos = choices.iter().filter_map(Choice::pos).min()?;
                Some(Site { pos, choices, ..*s })
            })
            .collect::<Option<_>>()?;
        let mut rev = Strand {
            reference: self.reference.iter().rev().copied().collect(),
            alts,
            sites,
        };
        rev.sort_sites();
        Some(rev)
    }
}

/// The cluster as a graph of VCF sites over one window, in both directions, for walking a read
/// through it.
#[derive(Debug)]
pub(super) struct VariantGraph {
    window: Range<i64>,
    /// Spans of the records and included flanks, sorted by start and merged. An anchor never
    /// lies inside one.
    spans: Vec<Range<i64>>,
    fwd: Strand,
    /// `fwd.mirror(K)`, K = window.start + window.end, so the mirrored window is `window` again.
    rev: Strand,
}

/// Start of the repeat-free stretch beyond `span` on the right: the largest over `d` in
/// `1..=dmax` of the first `p >= span.end` with `ref[p] != ref[p - d]`.
fn right_edge(reference: RefSlice<'_>, span: &Range<i64>, dmax: i64) -> i64 {
    (1..=dmax)
        .map(|d| {
            (0..MAX_INDEL_SLIDE)
                .map(|k| span.end + k)
                .find(|&p| !reference.same_base(p, p - d))
                .unwrap_or(span.end + MAX_INDEL_SLIDE)
        })
        .max()
        .unwrap_or(span.end - 1)
}

/// Mirror of [`right_edge`]: the smallest over `d` of the last `p < span.start` with
/// `ref[p] != ref[p + d]`.
fn left_edge(reference: RefSlice<'_>, span: &Range<i64>, dmax: i64) -> i64 {
    (1..=dmax)
        .map(|d| {
            (1..=MAX_INDEL_SLIDE)
                .map(|k| span.start - k)
                .find(|&p| !reference.same_base(p, p + d))
                .unwrap_or(span.start - MAX_INDEL_SLIDE)
        })
        .min()
        .unwrap_or(span.start)
}

/// The choice allele `idx` of a record at `pos` stands for, and its signed length change.
/// Edit alt bytes are appended to `alts`.
fn make_choice(idx: u32, all: &[&[u8]], pos: i64, alts: &mut Vec<u8>) -> Option<(Choice, i64)> {
    if idx == 0 {
        return Some((Choice::Ref, 0));
    }
    let alt = *all.get(usize::try_from(idx).ok()?)?;
    if alt == b"*" {
        return Some((Choice::Star(pos), 0));
    }
    let (at, r, a) = trim_alleles(pos, all.first()?, alt);
    let (rl, al) = (i64::try_from(r.len()).ok()?, i64::try_from(a.len()).ok()?);
    let start = alts.len();
    alts.extend(a.iter().map(u8::to_ascii_uppercase));
    let choice = Choice::Edit {
        at,
        end: at + rl,
        alt: start..alts.len(),
        deletion: a.is_empty() && !r.is_empty(),
    };
    Some((choice, al - rl))
}

/// The site of `rec` on GT allele indices `used`, its comparison span, and by how much the
/// lengths of its two choices differ. Edit alt bytes are appended to `alts`.
fn make_site(
    rec: &InputRecord,
    used: [u32; 2],
    node: Option<usize>,
    reference: RefSlice<'_>,
    alts: &mut Vec<u8>,
) -> Option<(Site, Range<i64>, i64)> {
    let all = rec.alleles();
    let pos = rec.pos();
    let ref_allele = *all.first()?;
    let mut allele_list: Vec<&[u8]> = vec![ref_allele];
    for &u in &used {
        let a = *all.get(usize::try_from(u).ok()?)?;
        if u > 0 && a != b"*" {
            allele_list.push(a);
        }
    }
    let span = if allele_list.len() > 1 {
        comparison_span(pos, &allele_list, reference)?
    } else {
        pos..pos + i64::try_from(ref_allele.len()).ok()?
    };

    let [u0, u1] = used;
    let (c0, d0) = make_choice(u0, &all, pos, alts)?;
    let (c1, d1) = if u1 == u0 {
        (c0.clone(), d0)
    } else {
        make_choice(u1, &all, pos, alts)?
    };
    let choices = [c0, c1];
    let site = Site {
        node,
        pos: choices.iter().filter_map(Choice::pos).min().unwrap_or(pos),
        choices,
        rank: 0, // set once sorted
    };
    Some((site, span, (d0 - d1).abs()))
}

/// Choice expansions one read may cost, both strands together. Past it the read abstains.
const MAX_WALK_STEPS: usize = 4096;

/// Sites one path may decide, which bounds the walk's recursion: it runs on a tokio worker with
/// a 2 MiB stack. A level costs at most 0.5 KiB optimised and 2 KiB at opt-level 0 (measured),
/// so the deepest walk takes at most 1 MiB; `test_walk_depth_fits_worker_stack` checks it. Past
/// it the read abstains.
const MAX_WALK_DEPTH: usize = 512;

/// What [`VariantGraph::label`] made of one read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ReadOutcome {
    /// Both strands kept a path; the labels are set.
    Labelled,
    /// No base is aligned to the window outside every span.
    NoAnchor,
    /// Every path of a strand mismatched the read.
    NoPath,
    /// More than [`MAX_WALK_STEPS`] choice expansions, or a path deeper than
    /// [`MAX_WALK_DEPTH`] sites.
    Capped,
}

/// Buffers reused across reads.
#[derive(Default)]
pub(super) struct WalkScratch {
    /// Slot chosen at each site decided on the current path, in site order from the walk's
    /// first site.
    chosen: Vec<u8>,
    /// Per node: `1 << slot` set when a leaf decided it so, [`UNDECIDED`] when a leaf left it
    /// undecided.
    flags: Vec<u8>,
}

const UNDECIDED: u8 = 4;

/// (reference position, query index) of the first base aligned (M/=/X) to a position in
/// `window` outside every span. Decodes `read.raw_cigar()`, so it does not allocate.
fn anchor(read: &bam::Record, window: &Range<i64>, spans: &[Range<i64>]) -> Option<(i64, usize)> {
    let mut rpos = read.pos();
    let mut qpos: usize = 0;
    for &raw in read.raw_cigar() {
        let n = raw >> 4;
        match raw & 0xf {
            // M, =, X
            0 | 7 | 8 => {
                let end = rpos + i64::from(n);
                let mut p = rpos.max(window.start);
                // `spans` are sorted and merged, so one pass skips every span covering `p`.
                for s in spans {
                    if s.contains(&p) {
                        p = s.end;
                    }
                }
                if p < end.min(window.end) {
                    return Some((p, qpos.checked_add(usize::try_from(p - rpos).ok()?)?));
                }
                rpos = end;
                qpos = qpos.checked_add(n as usize)?;
            }
            // I, S
            1 | 4 => qpos = qpos.checked_add(n as usize)?,
            // D, N
            2 | 3 => rpos += i64::from(n),
            5 | 6 => {} // H, P
            _ => return None,
        }
    }
    None
}

/// One read walking one strand of a [`VariantGraph`].
struct Walk<'a> {
    strand: &'a Strand,
    window: &'a Range<i64>,
    seq: bam::record::Seq<'a>,
    qual: &'a [u8],
    min_base_qual: u8,
    /// Query index the walk starts from: read step `k` is base `q0 + k` forward, `q0 - 1 - k`
    /// backward.
    q0: usize,
    forward: bool,
    /// Read bases available in the walk direction.
    avail: usize,
    /// First site on the walked side of the anchor; `chosen[j]` is the slot of site `s0 + j`.
    s0: usize,
    /// Choice expansions so far, both strands.
    steps: usize,
    /// Some path of this strand reached its end.
    any_leaf: bool,
    chosen: &'a mut Vec<u8>,
    flags: &'a mut [u8],
}

impl<'a> Walk<'a> {
    /// Read step `k` equals `expected`, or is below `min_base_qual`.
    fn base_matches(&self, k: usize, expected: u8) -> bool {
        let i = if self.forward {
            self.q0.checked_add(k)
        } else {
            self.q0.checked_sub(k + 1)
        };
        // `Seq` indexing panics out of range.
        i.filter(|&i| i < self.seq.len()).is_some_and(|i| {
            self.seq[i] == expected || self.qual.get(i).is_some_and(|&q| q < self.min_base_qual)
        })
    }

    /// The sites decided on the current path with their chosen choices, in site order.
    fn chosen_sites(&self) -> impl Iterator<Item = (&'a Site, &'a Choice)> {
        let sites = self.strand.sites.get(self.s0..).unwrap_or_default();
        sites
            .iter()
            .zip(self.chosen.iter())
            .filter_map(|(site, &slot)| Some((site, site.choices.get(usize::from(slot))?)))
    }

    fn chosen_choices(&self) -> impl Iterator<Item = &'a Choice> {
        self.chosen_sites().map(|(_, choice)| choice)
    }

    fn chosen_edits(&self) -> impl Iterator<Item = (i64, i64, bool)> {
        self.chosen_choices().filter_map(|c| match *c {
            Choice::Edit {
                at, end, deletion, ..
            } => Some((at, end, deletion)),
            _ => None,
        })
    }

    fn valid(&self, choice: &Choice, c: i64) -> bool {
        match *choice {
            Choice::Ref => true,
            Choice::Edit { at, end, .. } => {
                at >= c && !self.chosen_edits().any(|(a, e, _)| at < e && a < end)
            }
            // A star still ahead is checked as the walk passes it ([`Self::star_in`]), so the
            // covering deletion may be decided later; one already passed needs that deletion.
            Choice::Star(p) => {
                p >= c
                    || self
                        .chosen_edits()
                        .any(|(a, e, deletion)| deletion && (a..e).contains(&p))
            }
        }
    }

    /// A chosen `*` lies in `range`, which the walk is about to spell as non-deleted bases.
    fn star_in(&self, range: Range<i64>) -> bool {
        self.chosen_choices()
            .any(|ch| matches!(*ch, Choice::Star(p) if range.contains(&p)))
    }

    /// The chosen edit to spell at `c` with its insertion key: the insertion with the smallest
    /// key above `after` (the last one spelled at `c`), else the edit replacing reference bases
    /// from `c`. The key is the forward rank, reversed backward, so both strands spell
    /// insertions at one position in the same order.
    fn next_edit(&self, c: i64, after: Option<usize>) -> Option<(usize, &'a Choice)> {
        let mut insertion: Option<(usize, &'a Choice)> = None;
        let mut replacing = None;
        for (site, choice) in self.chosen_sites() {
            let Choice::Edit { at, end, .. } = *choice else {
                continue;
            };
            if at != c {
                continue;
            }
            if end > at {
                replacing = Some((0, choice));
                continue;
            }
            let key = if self.forward {
                site.rank
            } else {
                usize::MAX - site.rank
            };
            if after.is_none_or(|a| key > a) && insertion.is_none_or(|(k, _)| key < k) {
                insertion = Some((key, choice));
            }
        }
        insertion.or(replacing)
    }

    /// A path ended: flag the slot of every site it decided, the rest as undecided.
    fn leaf(&mut self) {
        self.any_leaf = true;
        let sites = self.strand.sites.get(self.s0..).unwrap_or_default();
        for (j, site) in sites.iter().enumerate() {
            if let Some(flag) = site.node.and_then(|n| self.flags.get_mut(n)) {
                *flag |= self.chosen.get(j).map_or(UNDECIDED, |&slot| 1 << slot);
            }
        }
    }

    /// Walk on from strand position `c` and read step `k`; `last_ins` is the key of the last
    /// insertion spelled at `c`. The next site to decide is `s0 + chosen.len()`. `Break` once
    /// the step budget or the depth cap is exceeded.
    fn walk(&mut self, mut c: i64, mut k: usize, mut last_ins: Option<usize>) -> ControlFlow<()> {
        let strand = self.strand;
        loop {
            if k >= self.avail || c >= self.window.end {
                self.leaf();
                return ControlFlow::Continue(());
            }
            if let Some(site) = strand.sites.get(self.s0 + self.chosen.len())
                && site.pos <= c
            {
                if self.chosen.len() >= MAX_WALK_DEPTH {
                    return ControlFlow::Break(());
                }
                let [c0, c1] = &site.choices;
                let slots = if c0 == c1 { 1 } else { 2 }; // hom: one choice
                for (slot, choice) in (0u8..).zip(&site.choices).take(slots) {
                    self.steps += 1;
                    if self.steps > MAX_WALK_STEPS {
                        return ControlFlow::Break(());
                    }
                    if self.valid(choice, c) {
                        self.chosen.push(slot);
                        let flow = self.walk(c, k, last_ins);
                        self.chosen.pop();
                        flow?;
                    }
                }
                return ControlFlow::Continue(());
            }
            if let Some((
                key,
                Choice::Edit {
                    end, alt, deletion, ..
                },
            )) = self.next_edit(c, last_ins)
            {
                let Some(alt) = strand.alts.get(alt.clone()) else {
                    return ControlFlow::Continue(());
                };
                if !*deletion && self.star_in(c..*end) {
                    return ControlFlow::Continue(());
                }
                for (j, &b) in alt.iter().enumerate() {
                    if k + j >= self.avail {
                        self.leaf();
                        return ControlFlow::Continue(());
                    }
                    if !self.base_matches(k + j, b) {
                        return ControlFlow::Continue(());
                    }
                }
                k += alt.len();
                if *end == c {
                    last_ins = Some(key);
                } else {
                    c = *end;
                    last_ins = None;
                }
                continue;
            }
            let base = usize::try_from(c - self.window.start)
                .ok()
                .and_then(|i| strand.reference.get(i));
            if self.star_in(c..c + 1) || !base.is_some_and(|&b| self.base_matches(k, b)) {
                return ControlFlow::Continue(());
            }
            c += 1;
            k += 1;
            last_ins = None;
        }
    }
}

impl VariantGraph {
    /// `nodes[i] = (index into records, GT allele indices of slot 0 and 1)`. `None` when the
    /// cluster cannot be expressed: a record with a missing allele or one that is neither a node
    /// nor hom, a symbolic allele, an unbounded repeat, or an uncovered reference.
    ///
    /// `flanks` are records near the cluster. Each one whose comparison span lies inside the
    /// window is an unlabelled site: hom fixed, otherwise both GT slots allowed (a missing slot
    /// is REF). The others are skipped; a flank never makes `build` fail.
    pub(super) fn build(
        records: &[Arc<InputRecord>],
        flanks: &[Arc<InputRecord>],
        nodes: &[(usize, [u32; 2])],
        reference: RefSlice<'_>,
    ) -> Option<Self> {
        let mut alts = Vec::new();
        let mut sites = Vec::new();
        let mut spans = Vec::new();
        let mut dmax = 0i64;
        for (ri, rec) in records.iter().enumerate() {
            let gt = rec.gt();
            if !gt.has_alt() {
                continue;
            }
            let node = nodes.iter().position(|&(i, _)| i == ri);
            let used: [u32; 2] = match node {
                Some(n) => nodes.get(n)?.1,
                None if gt.is_hom() => {
                    let a = gt.slots().first()?.0?;
                    [a, a]
                }
                None => return None, // 1/., haploid, or a het that is not a node
            };
            let (site, span, delta) = make_site(rec, used, node, reference, &mut alts)?;
            dmax += delta;
            sites.push(site);
            spans.push(span);
        }

        // Flanks count towards the edge extension but never widen the window's base union, so
        // the window does not depend on which of them end up inside it.
        let mut flank_sites = Vec::new();
        for rec in flanks {
            let gt = rec.gt();
            if !gt.has_alt() {
                continue;
            }
            let slots = gt.slots();
            // a haploid record is read as hom
            let slot = |i| {
                slots
                    .get(i)
                    .or(slots.first())
                    .and_then(|a| a.0)
                    .unwrap_or(0)
            };
            if let Some((site, span, delta)) =
                make_site(rec, [slot(0), slot(1)], None, reference, &mut alts)
            {
                dmax += delta;
                flank_sites.push((site, span));
            }
        }

        let union = spans.iter().map(|s| s.start).min()?..spans.iter().map(|s| s.end).max()?;
        let dmax = dmax.min(MAX_INDEL_SLIDE);
        let window = if dmax > 0 {
            left_edge(reference, &union, dmax) - ANCHOR_FLANK
                ..right_edge(reference, &union, dmax) + 1 + ANCHOR_FLANK
        } else {
            union.start - ANCHOR_FLANK..union.end + ANCHOR_FLANK
        };
        let window_ref = reference.get(window.clone())?.to_ascii_uppercase();

        for (site, span) in flank_sites {
            if window.start <= span.start && span.end <= window.end {
                sites.push(site);
                spans.push(span);
            }
        }
        spans.sort_by_key(|s: &Range<i64>| (s.start, s.end));
        let mut merged: Vec<Range<i64>> = Vec::with_capacity(spans.len());
        for s in spans {
            match merged.last_mut() {
                Some(last) if s.start <= last.end => last.end = last.end.max(s.end),
                _ => merged.push(s),
            }
        }
        let spans = merged;

        let mut fwd = Strand {
            reference: window_ref,
            alts,
            sites,
        };
        fwd.sort_sites();
        for (rank, site) in fwd.sites.iter_mut().enumerate() {
            site.rank = rank;
        }
        let rev = fwd.mirror(window.start + window.end)?;
        Some(Self {
            window,
            spans,
            fwd,
            rev,
        })
    }

    /// Walk `read` from its [`anchor`] forward on `fwd` and backward on `rev`, and label each
    /// node `Some(slot1)` when every surviving path of its strand decided it with that slot.
    /// Bases below `min_base_qual` match anything. `labels.len()` = node count. Every label is
    /// `None` unless `Labelled` is returned.
    pub(super) fn label(
        &self,
        read: &bam::Record,
        min_base_qual: u8,
        scratch: &mut WalkScratch,
        labels: &mut [Option<bool>],
    ) -> ReadOutcome {
        labels.fill(None);
        let Some((a, qa)) = anchor(read, &self.window, &self.spans) else {
            return ReadOutcome::NoAnchor;
        };
        let WalkScratch { chosen, flags } = scratch;
        chosen.clear();
        flags.clear();
        flags.resize(labels.len(), 0);
        let (seq, qual) = (read.seq(), read.qual());
        let k = self.window.start + self.window.end;
        let mut steps = 0;
        for (strand, forward, c, avail) in [
            (&self.fwd, true, a, seq.len().saturating_sub(qa)),
            (&self.rev, false, k - a, qa),
        ] {
            let mut walk = Walk {
                strand,
                window: &self.window,
                seq,
                qual,
                min_base_qual,
                q0: qa,
                forward,
                avail,
                s0: strand.sites.partition_point(|s| s.pos < c),
                steps,
                any_leaf: false,
                chosen: &mut *chosen,
                flags: flags.as_mut_slice(),
            };
            if walk.walk(c, 0, None).is_break() {
                return ReadOutcome::Capped;
            }
            if !walk.any_leaf {
                return ReadOutcome::NoPath;
            }
            steps = walk.steps;
        }
        for (label, &flag) in labels.iter_mut().zip(flags.iter()) {
            // Exactly one slot's bit: every leaf decided the node, all the same way.
            *label = match flag {
                0b01 => Some(false),
                0b10 => Some(true),
                _ => None,
            };
        }
        ReadOutcome::Labelled
    }

    /// The BAM fetch region: `window` on the cluster's contig.
    pub(super) fn fetch_region(&self, cluster_region: &GenomeRegion) -> Option<GenomeRegion> {
        let start = usize::try_from(self.window.start).ok()?;
        let len = usize::try_from(self.window.end - self.window.start).ok()?;
        Some(GenomeRegion::new_bounded(
            GenomePosition::new_0(cluster_region.contig().clone(), start),
            len,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::super::tests::{
        make_unphased_het, make_unphased_het_multi, make_vcf_header, reference_for, reference_with,
    };
    use super::*;
    use rust_htslib::bcf::{Format, Writer};

    fn writer() -> Writer {
        Writer::from_path("/dev/null", &make_vcf_header(), true, Format::Vcf).unwrap()
    }

    fn two_snvs(w: &Writer) -> Vec<Arc<InputRecord>> {
        vec![
            Arc::new(make_unphased_het(w, 100, b"A", b"T")),
            Arc::new(make_unphased_het(w, 110, b"G", b"C")),
        ]
    }

    fn graph(
        records: &[Arc<InputRecord>],
        nodes: &[(usize, [u32; 2])],
        reference: &[u8],
    ) -> Option<VariantGraph> {
        flank_graph(records, &[], nodes, reference)
    }

    fn flank_graph(
        records: &[Arc<InputRecord>],
        flanks: &[Arc<InputRecord>],
        nodes: &[(usize, [u32; 2])],
        reference: &[u8],
    ) -> Option<VariantGraph> {
        VariantGraph::build(records, flanks, nodes, RefSlice::new(reference, 0))
    }

    fn site_keys(s: &Strand) -> Vec<(i64, Option<usize>)> {
        s.sites.iter().map(|s| (s.pos, s.node)).collect()
    }

    #[test]
    fn test_graph_two_snvs() {
        let w = writer();
        let records = two_snvs(&w);
        let reference = reference_for(&records);
        let g = graph(&records, &[(0, [0, 1]), (1, [0, 1])], &reference).unwrap();
        assert_eq!(g.window, 95..116);
        assert_eq!(g.spans, vec![100..101, 110..111]);
        assert_eq!(site_keys(&g.fwd), vec![(100, Some(0)), (110, Some(1))]);
        assert_eq!(site_keys(&g.rev), vec![(100, Some(1)), (110, Some(0))]); // K = 211
        let mut r = g.fwd.reference.clone();
        r.reverse();
        assert_eq!(g.rev.reference, r);
    }

    #[test]
    fn test_graph_hom_site_has_no_node() {
        let w = writer();
        let records = vec![
            Arc::new(make_unphased_het(&w, 100, b"A", b"T")),
            Arc::new(make_unphased_het_multi(&w, 110, &[b"G", b"C"], (1, 1))),
        ];
        let reference = reference_for(&records);
        let g = graph(&records, &[(0, [0, 1])], &reference).unwrap();
        assert_eq!(site_keys(&g.fwd), vec![(100, Some(0)), (110, None)]);
        let hom = &g.fwd.sites[1];
        assert_eq!(hom.choices[0], hom.choices[1]);
        assert_ne!(hom.choices[0], Choice::Ref);
    }

    #[test]
    fn test_graph_deletion_mirrors() {
        let w = writer();
        let reference = reference_with(&[(90, b"ACGTCAGTCACGATCAGTCAGT")]);
        let records = vec![Arc::new(make_unphased_het(&w, 100, b"CG", b"C"))];
        let g = graph(&records, &[(0, [0, 1])], &reference).unwrap();
        let k = g.window.start + g.window.end;
        let edit = |s: &Strand| match &s.sites[0].choices[1] {
            Choice::Edit {
                at, end, deletion, ..
            } => (*at, *end, *deletion),
            c => panic!("{c:?}"),
        };
        assert_eq!(edit(&g.fwd), (101, 102, true));
        assert_eq!(edit(&g.rev), (k - 102, k - 101, true));
    }

    #[test]
    fn test_graph_insertion_alt_reversed() {
        let w = writer();
        let reference = reference_with(&[(90, b"ACGTCAGTCACGATCAGTCAGT")]);
        let records = vec![Arc::new(make_unphased_het(&w, 100, b"C", b"CGT"))];
        let g = graph(&records, &[(0, [0, 1])], &reference).unwrap();
        assert_eq!(g.fwd.alts, b"GT");
        assert_eq!(g.rev.alts, b"TG");
    }

    #[test]
    fn test_graph_symbolic_allele_is_none() {
        let w = writer();
        let records = vec![
            Arc::new(make_unphased_het(&w, 100, b"A", b"T")),
            Arc::new(make_unphased_het(&w, 110, b"G", b"<DEL>")),
        ];
        let reference = reference_for(&records);
        assert!(graph(&records, &[(0, [0, 1]), (1, [0, 1])], &reference).is_none());
    }

    #[test]
    fn test_graph_missing_allele_record_is_none() {
        let w = writer();
        let mut records = two_snvs(&w);
        records.push(Arc::new(make_unphased_het_multi(
            &w,
            120,
            &[b"A", b"T"],
            (1, u32::MAX),
        )));
        let reference = reference_for(&records);
        assert!(graph(&records, &[(0, [0, 1]), (1, [0, 1])], &reference).is_none());
    }

    #[test]
    fn test_graph_reference_too_short_is_none() {
        let w = writer();
        let records = two_snvs(&w);
        let reference = reference_for(&records);
        assert!(graph(&records, &[(0, [0, 1]), (1, [0, 1])], &reference[..103]).is_none());
    }

    use super::super::tests::{make_bam_record, make_bam_record_q};
    use rust_htslib::bam::record::{Cigar, CigarString};

    /// `reference[pos..pos+len]` with `(offset, base)` changes.
    fn read_seq(reference: &[u8], pos: usize, len: usize, changes: &[(usize, u8)]) -> Vec<u8> {
        let mut s = reference[pos..pos + len].to_vec();
        for &(i, b) in changes {
            s[i] = b;
        }
        s
    }

    // ── walking reads through the graph ───────────────────────────────────────

    use ReadOutcome::{Capped, Labelled, NoAnchor, NoPath};

    fn run_walk(
        g: &VariantGraph,
        read: &bam::Record,
        n: usize,
    ) -> (ReadOutcome, Vec<Option<bool>>) {
        let mut labels = vec![Some(true); n]; // stale values `label` must clear
        let outcome = g.label(read, 20, &mut WalkScratch::default(), &mut labels);
        (outcome, labels)
    }

    fn two_snv_graph() -> (VariantGraph, Vec<u8>) {
        let w = writer();
        let records = two_snvs(&w);
        let reference = reference_for(&records);
        let g = graph(&records, &[(0, [0, 1]), (1, [0, 1])], &reference).unwrap();
        (g, reference)
    }

    /// `n` A>T SNVs at 100, 102, ...
    fn snv_ladder(n: usize) -> (VariantGraph, Vec<u8>) {
        let w = writer();
        let records: Vec<_> = (0..n)
            .map(|i| Arc::new(make_unphased_het(&w, 100 + 2 * i as i64, b"A", b"T")))
            .collect();
        let reference = reference_for(&records);
        let nodes: Vec<_> = (0..n).map(|i| (i, [0, 1])).collect();
        (graph(&records, &nodes, &reference).unwrap(), reference)
    }

    #[test]
    fn test_walk_full_cover() {
        let (g, reference) = two_snv_graph();
        let seq = read_seq(&reference, 90, 40, &[(10, b'T')]);
        let r = make_bam_record(90, &seq, &CigarString(vec![Cigar::Match(40)]));
        assert_eq!(
            run_walk(&g, &r, 2),
            (Labelled, vec![Some(true), Some(false)])
        );
    }

    #[test]
    fn test_walk_soft_clip_extends() {
        let (g, reference) = two_snv_graph();
        let seq = read_seq(&reference, 90, 40, &[(10, b'T'), (20, b'C')]);
        let r = make_bam_record(
            90,
            &seq,
            &CigarString(vec![Cigar::Match(12), Cigar::SoftClip(28)]),
        );
        assert_eq!(
            run_walk(&g, &r, 2),
            (Labelled, vec![Some(true), Some(true)])
        );
    }

    #[test]
    fn test_walk_left_clip_walks_backward() {
        let (g, reference) = two_snv_graph();
        // read base i sits at reference 90 + i; the anchor is 105, so node 0 is reached backwards
        let seq = read_seq(&reference, 90, 40, &[(10, b'T'), (20, b'C')]);
        let r = make_bam_record(
            105,
            &seq,
            &CigarString(vec![Cigar::SoftClip(15), Cigar::Match(25)]),
        );
        assert_eq!(
            run_walk(&g, &r, 2),
            (Labelled, vec![Some(true), Some(true)])
        );
    }

    #[test]
    fn test_walk_read_ends_before_second() {
        let (g, reference) = two_snv_graph();
        let seq = read_seq(&reference, 90, 13, &[(10, b'T')]);
        let r = make_bam_record(90, &seq, &CigarString(vec![Cigar::Match(13)]));
        assert_eq!(run_walk(&g, &r, 2), (Labelled, vec![Some(true), None]));
    }

    #[test]
    fn test_walk_low_qual_is_wildcard() {
        let (g, reference) = two_snv_graph();
        let seq = read_seq(&reference, 90, 40, &[(10, b'T'), (20, b'C')]);
        let mut quals = vec![60u8; 40];
        quals[20] = 5;
        let r = make_bam_record_q(90, &seq, &CigarString(vec![Cigar::Match(40)]), &quals);
        assert_eq!(run_walk(&g, &r, 2), (Labelled, vec![Some(true), None]));
    }

    #[test]
    fn test_walk_high_qual_flank_mismatch() {
        let (g, reference) = two_snv_graph();
        let seq = read_seq(&reference, 90, 40, &[(10, b'T'), (7, b'C')]);
        let r = make_bam_record(90, &seq, &CigarString(vec![Cigar::Match(40)]));
        assert_eq!(run_walk(&g, &r, 2), (NoPath, vec![None, None]));
    }

    #[test]
    fn test_walk_no_aligned_base_in_window() {
        let (g, reference) = two_snv_graph();
        let seq = read_seq(&reference, 90, 15, &[]);
        let r = make_bam_record(
            90,
            &seq,
            &CigarString(vec![Cigar::Match(5), Cigar::Del(25), Cigar::Match(10)]),
        );
        assert_eq!(run_walk(&g, &r, 2), (NoAnchor, vec![None, None]));
    }

    fn homopolymer_graph() -> (VariantGraph, Vec<u8>) {
        let w = writer();
        let records = vec![Arc::new(make_unphased_het(&w, 99, b"CA", b"C"))];
        let reference = reference_with(&[(90, b"CGTCGTCGTCAAAAAGTCGTCGTCG")]);
        let g = graph(&records, &[(0, [0, 1])], &reference).unwrap();
        (g, reference)
    }

    #[test]
    fn test_walk_shifted_homopolymer_deletion() {
        let (g, reference) = homopolymer_graph();
        let mut seq = reference[90..104].to_vec();
        seq.extend_from_slice(&reference[105..125]);
        let r = make_bam_record(
            90,
            &seq,
            &CigarString(vec![Cigar::Match(14), Cigar::Del(1), Cigar::Match(20)]),
        );
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_read_ending_inside_repeat_is_undecided() {
        let (g, reference) = homopolymer_graph();
        let r = make_bam_record(
            90,
            &reference[90..102],
            &CigarString(vec![Cigar::Match(12)]),
        );
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![None]));
    }

    /// `T>TC` + `T>C` at the start of a T run (104..=114, G at 115); the window reaches past the
    /// run to 98..121.
    const T_RUN: &[u8] = b"CGTCGTCGTCCTCCTTTTTTTTTTTGAAAGTCGTCG";

    /// The T-run cluster, with a flank A>G at 117 of GT `flank_gt` if given: inside the window,
    /// outside every span.
    fn t_run_graph(w: &Writer, flank_gt: Option<(u32, u32)>) -> VariantGraph {
        let reference = reference_with(&[(90, T_RUN)]);
        let records = vec![
            Arc::new(make_unphased_het(w, 104, b"T", b"TC")),
            Arc::new(make_unphased_het(w, 105, b"T", b"C")),
        ];
        let flanks: Vec<_> = flank_gt
            .map(|gt| Arc::new(make_unphased_het_multi(w, 117, &[b"A", b"G"], gt)))
            .into_iter()
            .collect();
        flank_graph(&records, &flanks, &[(0, [0, 1]), (1, [0, 1])], &reference).unwrap()
    }

    /// The ins-only haplotype of [`t_run_graph`], with `flank` at 117.
    fn t_run_ins_read(flank: u8) -> bam::Record {
        let reference = reference_with(&[(90, T_RUN)]);
        let mut seq = reference[85..105].to_vec();
        seq.push(b'C');
        seq.extend_from_slice(&reference[105..144]);
        seq[117 - 85 + 1] = flank;
        let ops = vec![Cigar::Match(20), Cigar::Ins(1), Cigar::Match(39)];
        make_bam_record(85, &seq, &CigarString(ops))
    }

    /// The window reaches the G after the T run, where the SNV-only haplotype runs out of step
    /// with the read: only the ins-only path survives. A hom flank inside the window keeps reads
    /// carrying it.
    #[test]
    fn test_walk_flank_hom_inside_window_keeps_reads() {
        let w = writer();
        let ins_labels = (Labelled, vec![Some(true), Some(false)]);
        let without = t_run_graph(&w, None);
        assert_eq!(without.window, 98..121);
        assert_eq!(run_walk(&without, &t_run_ins_read(b'A'), 2), ins_labels);

        let r = t_run_ins_read(b'G');
        let with = t_run_graph(&w, Some((1, 1)));
        assert_eq!(with.window, 98..121, "the flank must not move the window");
        assert_eq!(run_walk(&with, &r, 2), ins_labels);
        assert_eq!(run_walk(&without, &r, 2), (NoPath, vec![None, None]));
    }

    /// 0/1 and 1/. (the missing slot is REF) flanks allow both alleles and get no label.
    #[test]
    fn test_walk_flank_het_is_free() {
        let w = writer();
        for gt in [(0, 1), (1, u32::MAX)] {
            let g = t_run_graph(&w, Some(gt));
            let flank = g.fwd.sites.iter().find(|s| s.pos == 117).unwrap();
            assert_eq!(flank.node, None);
            assert!(flank.choices.contains(&Choice::Ref));
            assert_ne!(flank.choices[0], flank.choices[1]);
            assert!(g.spans.contains(&(117..118)));
            for base in *b"AG" {
                assert_eq!(
                    run_walk(&g, &t_run_ins_read(base), 2),
                    (Labelled, vec![Some(true), Some(false)])
                );
            }
        }
    }

    #[test]
    fn test_graph_flank_outside_window_is_skipped() {
        let w = writer();
        let records = two_snvs(&w);
        let flanks = vec![
            // MNV 114..118 straddles the window end at 116
            Arc::new(make_unphased_het(&w, 114, b"AAAA", b"CGCG")),
            Arc::new(make_unphased_het_multi(&w, 130, &[b"A", b"G"], (1, 1))),
            // inside the window, but symbolic
            Arc::new(make_unphased_het(&w, 97, b"A", b"<DEL>")),
        ];
        let reference = reference_for(&records);
        let g = flank_graph(&records, &flanks, &[(0, [0, 1]), (1, [0, 1])], &reference).unwrap();
        assert_eq!(g.window, 95..116);
        assert_eq!(g.spans, vec![100..101, 110..111]);
        assert_eq!(site_keys(&g.fwd), vec![(100, Some(0)), (110, Some(1))]);
    }

    #[test]
    fn test_anchor_skips_spans() {
        let (window, spans) = (95..116, [100..101, 110..111]);
        let at = |pos, len, ops| {
            anchor(
                &make_bam_record(pos, &vec![b'A'; len], &CigarString(ops)),
                &window,
                &spans,
            )
        };
        assert_eq!(at(90, 40, vec![Cigar::Match(40)]), Some((95, 5)));
        assert_eq!(at(100, 30, vec![Cigar::Match(30)]), Some((101, 1)));
        let deleted = vec![Cigar::Match(5), Cigar::Del(25), Cigar::Match(10)];
        assert_eq!(at(90, 15, deleted), None);
    }

    #[test]
    fn test_walk_more_than_eight_nodes() {
        let (g, reference) = snv_ladder(12);
        let changes: Vec<_> = (0..12).step_by(2).map(|i| (5 + 2 * i, b'T')).collect();
        let seq = read_seq(&reference, 95, 40, &changes);
        let r = make_bam_record(95, &seq, &CigarString(vec![Cigar::Match(40)]));
        let expect: Vec<_> = (0..12).map(|i| Some(i % 2 == 0)).collect();
        assert_eq!(run_walk(&g, &r, 12), (Labelled, expect));
    }

    #[test]
    fn test_walk_read_inside_long_cluster() {
        let w = writer();
        let records: Vec<_> = (0..6)
            .map(|i| Arc::new(make_unphased_het(&w, 100 + 20 * i, b"A", b"T")))
            .collect();
        let reference = reference_for(&records);
        let nodes: Vec<_> = (0..6).map(|i| (i, [0, 1])).collect();
        let g = graph(&records, &nodes, &reference).unwrap();
        let seq = read_seq(&reference, 125, 40, &[(15, b'T')]);
        let r = make_bam_record(125, &seq, &CigarString(vec![Cigar::Match(40)]));
        assert_eq!(
            run_walk(&g, &r, 6),
            (
                Labelled,
                vec![None, None, Some(true), Some(false), None, None]
            )
        );
    }

    #[test]
    fn test_walk_middle_anchor_walks_both_ways() {
        let w = writer();
        let records = vec![
            Arc::new(make_unphased_het(&w, 100, b"A", b"T")),
            Arc::new(make_unphased_het(&w, 130, b"G", b"C")),
            Arc::new(make_unphased_het(&w, 160, b"T", b"G")),
        ];
        let reference = reference_for(&records);
        let nodes = [(0, [0, 1]), (1, [0, 1]), (2, [0, 1])];
        let g = graph(&records, &nodes, &reference).unwrap();
        // read base i sits at reference 95 + i; anchored at 110
        let seq = read_seq(&reference, 95, 45, &[(5, b'T'), (35, b'C')]);
        let r = make_bam_record(
            110,
            &seq,
            &CigarString(vec![Cigar::SoftClip(15), Cigar::Match(30)]),
        );
        assert_eq!(
            run_walk(&g, &r, 3),
            (Labelled, vec![Some(true), Some(true), None])
        );
    }

    #[test]
    fn test_walk_overlapping_alts() {
        let w = writer();
        let reference = reference_with(&[(90, b"ACGTCAGTCACGATCAGTCAGT")]);
        let records = vec![
            Arc::new(make_unphased_het(&w, 100, b"CG", b"C")),
            Arc::new(make_unphased_het(&w, 101, b"G", b"T")),
        ];
        let g = graph(&records, &[(0, [0, 1]), (1, [0, 1])], &reference).unwrap();
        let mut a = reference[85..101].to_vec();
        a.extend_from_slice(&reference[102..140]);
        let a = make_bam_record(
            85,
            &a,
            &CigarString(vec![Cigar::Match(16), Cigar::Del(1), Cigar::Match(38)]),
        );
        let b = read_seq(&reference, 85, 55, &[(16, b'T')]);
        let b = make_bam_record(85, &b, &CigarString(vec![Cigar::Match(55)]));
        assert_eq!(
            run_walk(&g, &a, 2),
            (Labelled, vec![Some(true), Some(false)])
        );
        assert_eq!(
            run_walk(&g, &b, 2),
            (Labelled, vec![Some(false), Some(true)])
        );
        // one scratch reused across reads gives the same answers
        let (mut scratch, mut labels) = (WalkScratch::default(), vec![None; 2]);
        for (read, expect) in [
            (&a, [Some(true), Some(false)]),
            (&b, [Some(false), Some(true)]),
        ] {
            assert_eq!(g.label(read, 20, &mut scratch, &mut labels), Labelled);
            assert_eq!(labels, expect);
        }
    }

    #[test]
    fn test_walk_star_needs_covering_deletion() {
        let w = writer();
        let reference = reference_with(&[(90, b"ACGTCAGTCATGATCAGTCAGT")]);
        let records = vec![
            Arc::new(make_unphased_het(&w, 100, b"TG", b"T")),
            Arc::new(make_unphased_het_multi(
                &w,
                101,
                &[b"G", b"T", b"*"],
                (1, 2),
            )),
        ];
        let g = graph(&records, &[(0, [0, 1]), (1, [1, 2])], &reference).unwrap();
        let mut del = reference[85..101].to_vec();
        del.extend_from_slice(&reference[102..140]);
        let del = make_bam_record(
            85,
            &del,
            &CigarString(vec![Cigar::Match(16), Cigar::Del(1), Cigar::Match(38)]),
        );
        let m55 = CigarString(vec![Cigar::Match(55)]);
        let snv = make_bam_record(85, &read_seq(&reference, 85, 55, &[(16, b'T')]), &m55);
        let refr = make_bam_record(85, &reference[85..140], &m55);
        assert_eq!(
            run_walk(&g, &del, 2),
            (Labelled, vec![Some(true), Some(true)])
        );
        assert_eq!(
            run_walk(&g, &snv, 2),
            (Labelled, vec![Some(false), Some(false)])
        );
        assert_eq!(run_walk(&g, &refr, 2), (NoPath, vec![None, None]));
    }

    #[test]
    fn test_walk_cap_abstains() {
        let (g, reference) = snv_ladder(13);
        let r = make_bam_record_q(
            95,
            &reference[95..135],
            &CigarString(vec![Cigar::Match(40)]),
            &[5; 40],
        );
        assert_eq!(run_walk(&g, &r, 13), (Capped, vec![None; 13]));
    }

    // ── single records ────────────────────────────────────────────────────────

    /// Pasted where an indel would otherwise sit in the poly-A background, whose edge
    /// extension runs off the 300 bp test reference.
    const FLANK: &[u8] = b"CGTCAGTCAG";

    /// One-record graph; node 0 on GT slots `slots`.
    fn record_graph(rec: InputRecord, slots: [u32; 2], reference: &[u8]) -> Option<VariantGraph> {
        graph(&[Arc::new(rec)], &[(0, slots)], reference)
    }

    /// `REF>ALT` at `pos`, 0/1.
    fn biallelic(pos: i64, ref_a: &[u8], alt_a: &[u8], reference: &[u8]) -> Option<VariantGraph> {
        record_graph(
            make_unphased_het(&writer(), pos, ref_a, alt_a),
            [0, 1],
            reference,
        )
    }

    /// `alleles` at `pos`, 1/2.
    fn one_two(pos: i64, alleles: &[&[u8]], reference: &[u8]) -> Option<VariantGraph> {
        let rec = make_unphased_het_multi(&writer(), pos, alleles, (1, 2));
        record_graph(rec, [1, 2], reference)
    }

    /// The single node's label; also `None` when there is no graph.
    fn node_label(g: Option<&VariantGraph>, read: &bam::Record) -> Option<bool> {
        g.and_then(|g| run_walk(g, read, 1).1[0])
    }

    fn m(n: u32) -> CigarString {
        CigarString(vec![Cigar::Match(n)])
    }

    /// The read `seq` aligned at 100 with `ops`, padded with ten reference bases on each side so
    /// it has an anchor outside the record's span.
    fn padded(reference: &[u8], seq: &[u8], mut ops: Vec<Cigar>) -> bam::Record {
        let end = usize::try_from(CigarString(ops.clone()).into_view(100).end_pos()).unwrap();
        let mut s = reference[90..100].to_vec();
        s.extend_from_slice(seq);
        s.extend_from_slice(&reference[end..end + 10]);
        ops.insert(0, Cigar::Match(10));
        ops.push(Cigar::Match(10));
        make_bam_record(90, &s, &CigarString(ops))
    }

    #[test]
    fn test_walk_snv_alt() {
        let reference = reference_with(&[(102, b"A")]);
        let g = biallelic(102, b"A", b"T", &reference).unwrap();
        // flank bases are compared too, so only the variant base may differ
        let r = make_bam_record(100, b"AATAA", &m(5));
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_snv_ref() {
        let reference = reference_with(&[(102, b"A")]);
        let g = biallelic(102, b"A", b"T", &reference).unwrap();
        let r = make_bam_record(100, b"AAAAA", &m(5));
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_snv_no_cover() {
        let reference = reference_with(&[(200, b"A")]);
        let g = biallelic(200, b"A", b"T", &reference);
        let r = make_bam_record(100, b"AAAAA", &m(5));
        assert_eq!(node_label(g.as_ref(), &r), None);
    }

    #[test]
    fn test_walk_mnv_alt() {
        let reference = reference_with(&[(102, b"AT")]);
        let g = biallelic(102, b"AT", b"GC", &reference).unwrap();
        let r = make_bam_record(100, b"AAGCAA", &m(6));
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_mnv_ref() {
        let reference = reference_with(&[(102, b"AT")]);
        let g = biallelic(102, b"AT", b"GC", &reference).unwrap();
        let r = make_bam_record(100, b"AAATAA", &m(6));
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_mnv_read_starts_inside_ref_span() {
        let reference = reference_with(&[(100, b"AT")]);
        let g = biallelic(100, b"AT", b"AC", &reference).unwrap();
        let alt = make_bam_record(101, b"CA", &m(2));
        assert_eq!(run_walk(&g, &alt, 1), (Labelled, vec![Some(true)]));
        let refr = make_bam_record(101, b"TA", &m(2));
        assert_eq!(run_walk(&g, &refr, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_symbolic_allele_is_uninformative() {
        let reference = reference_with(&[(102, b"A")]);
        let g = biallelic(102, b"A", b"<DEL>", &reference);
        let r = make_bam_record(100, b"AAAAA", &m(5));
        assert_eq!(node_label(g.as_ref(), &r), None);
    }

    #[test]
    fn test_walk_deletion_alt() {
        let reference = reference_with(&[(90, FLANK), (100, b"AT")]);
        let g = biallelic(100, b"AT", b"A", &reference).unwrap();
        let ops = vec![Cigar::Match(1), Cigar::Del(1), Cigar::Match(1)];
        let r = padded(&reference, b"AA", ops);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_deletion_ref() {
        let reference = reference_with(&[(90, FLANK), (100, b"AT")]);
        let g = biallelic(100, b"AT", b"A", &reference).unwrap();
        let r = padded(&reference, b"ATA", vec![Cigar::Match(3)]);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_insertion_alt() {
        let reference = reference_with(&[(90, FLANK), (100, b"AC")]);
        let g = biallelic(100, b"A", b"AT", &reference).unwrap();
        let ops = vec![Cigar::Match(1), Cigar::Ins(1), Cigar::Match(1)];
        let r = padded(&reference, b"ATC", ops);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_insertion_ref() {
        let reference = reference_with(&[(90, FLANK), (100, b"AC")]);
        let g = biallelic(100, b"A", b"AT", &reference).unwrap();
        let r = padded(&reference, b"AC", vec![Cigar::Match(2)]);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_insertion_foreign_is_uninformative() {
        let reference = reference_with(&[(90, FLANK), (100, b"AC")]);
        let g = biallelic(100, b"A", b"AT", &reference).unwrap();
        let ops = vec![Cigar::Match(1), Cigar::Ins(1), Cigar::Match(1)];
        let r = padded(&reference, b"AGC", ops);
        assert_eq!(run_walk(&g, &r, 1), (NoPath, vec![None]));
    }

    #[test]
    fn test_walk_deletion_third_allele_is_uninformative() {
        let reference = reference_with(&[(90, FLANK), (100, b"ATTTC")]);
        let g = biallelic(100, b"ATTT", b"A", &reference).unwrap();
        let ops = vec![Cigar::Match(1), Cigar::Del(1), Cigar::Match(3)];
        let r = padded(&reference, b"AGGC", ops);
        assert_eq!(run_walk(&g, &r, 1), (NoPath, vec![None]));
    }

    #[test]
    fn test_walk_deletion_exact_is_alt() {
        let reference = reference_with(&[(90, FLANK), (100, b"ATTTC")]);
        let g = biallelic(100, b"ATTT", b"A", &reference).unwrap();
        let ops = vec![Cigar::Match(1), Cigar::Del(3), Cigar::Match(1)];
        let r = padded(&reference, b"AC", ops);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_deletion_no_indel_is_ref() {
        let reference = reference_with(&[(90, FLANK), (100, b"ATTTC")]);
        let g = biallelic(100, b"ATTT", b"A", &reference).unwrap();
        let r = padded(&reference, b"ATTTC", vec![Cigar::Match(5)]);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_deletion_partial_coverage_is_uninformative() {
        let reference = reference_with(&[(90, FLANK), (100, b"ATTTTTTTTTC")]);
        let g = biallelic(100, b"ATTTTTTTTT", b"A", &reference).unwrap();
        // both reads lie wholly inside the span 100..111
        let short = make_bam_record(100, b"ATTTT", &m(5));
        assert_eq!(run_walk(&g, &short, 1), (NoAnchor, vec![None]));
        let late = make_bam_record(101, b"TTTTTTTTTC", &m(10));
        assert_eq!(run_walk(&g, &late, 1), (NoAnchor, vec![None]));
    }

    #[test]
    fn test_walk_insertion_shifted_in_homopolymer_is_alt() {
        let reference = reference_with(&[(90, FLANK), (100, b"ATTTTC")]);
        let g = biallelic(100, b"A", b"AT", &reference).unwrap();
        let ops = vec![Cigar::Match(3), Cigar::Ins(1), Cigar::Match(3)];
        let r = padded(&reference, b"ATTTTTC", ops);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
        let refr = padded(&reference, b"ATTTTC", vec![Cigar::Match(6)]);
        assert_eq!(run_walk(&g, &refr, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_deletion_shifted_in_homopolymer_is_alt() {
        let reference = reference_with(&[(90, FLANK), (100, b"ATTTTC")]);
        let g = biallelic(100, b"AT", b"A", &reference).unwrap();
        let ops = vec![Cigar::Match(3), Cigar::Del(1), Cigar::Match(2)];
        let r = padded(&reference, b"ATTTC", ops);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_insertion_shifted_in_dinucleotide_repeat() {
        let reference = reference_with(&[(100, b"CATATATG")]);
        let g = biallelic(100, b"C", b"CAT", &reference).unwrap();
        let ops = vec![Cigar::Match(5), Cigar::Ins(2), Cigar::Match(3)];
        let r = padded(&reference, b"CATATATATG", ops);
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_insertion_foreign_unit_in_repeat_is_uninformative() {
        let reference = reference_with(&[(90, FLANK), (100, b"ATTTTC")]);
        let g = biallelic(100, b"A", b"AT", &reference).unwrap();
        let ops = vec![Cigar::Match(3), Cigar::Ins(1), Cigar::Match(3)];
        let r = padded(&reference, b"ATTGTTC", ops);
        assert_eq!(run_walk(&g, &r, 1), (NoPath, vec![None]));
    }

    #[test]
    fn test_walk_deletion_in_overlong_repeat_is_uninformative() {
        let reference = reference_with(&[]);
        let g = biallelic(150, b"AA", b"A", &reference);
        let r = make_bam_record(
            0,
            &[b'A'; 299],
            &CigarString(vec![Cigar::Match(20), Cigar::Del(1), Cigar::Match(279)]),
        );
        assert_eq!(node_label(g.as_ref(), &r), None);
        let plain = make_bam_record(0, &[b'A'; 300], &m(300));
        assert_eq!(node_label(g.as_ref(), &plain), None);
    }

    #[test]
    fn test_walk_insertion_in_overlong_repeat_is_uninformative() {
        let reference = reference_with(&[]);
        let g = biallelic(150, b"A", b"AA", &reference);
        let r = make_bam_record(
            0,
            &[b'A'; 301],
            &CigarString(vec![Cigar::Match(20), Cigar::Ins(1), Cigar::Match(280)]),
        );
        assert_eq!(node_label(g.as_ref(), &r), None);
    }

    #[test]
    fn test_walk_complex_edge_insertions_are_alt() {
        // flank ends before the read starts at 98
        let reference = reference_with(&[(88, FLANK), (100, b"AC")]);
        let g = biallelic(100, b"AC", b"GACG", &reference).unwrap();
        let r = make_bam_record(
            98,
            b"AAGACGAA",
            &CigarString(vec![
                Cigar::Match(2),
                Cigar::Ins(1),
                Cigar::Match(2),
                Cigar::Ins(1),
                Cigar::Match(2),
            ]),
        );
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    /// Complex fixtures: flank ends before the reads start at 99.
    fn complex_graph() -> VariantGraph {
        let reference = reference_with(&[(89, FLANK), (100, b"ACCCGGCTAAT")]);
        biallelic(100, b"ACCCGGCTAAT", b"GCCCGGCTAA", &reference).unwrap()
    }

    #[test]
    fn test_walk_complex_alt() {
        let g = complex_graph();
        let r = make_bam_record(
            99,
            b"AGCCCGGCTAAAAAAA",
            &CigarString(vec![Cigar::Match(11), Cigar::Del(1), Cigar::Match(5)]),
        );
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_complex_ref() {
        let g = complex_graph();
        let r = make_bam_record(99, b"AACCCGGCTAATAAAAA", &m(17));
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_complex_alt_alternative_cigar() {
        let g = complex_graph();
        let r = make_bam_record(
            99,
            b"AGCCCGGCTAAAAAAA",
            &CigarString(vec![
                Cigar::Equal(1),
                Cigar::Diff(1),
                Cigar::Equal(9),
                Cigar::Del(1),
                Cigar::Equal(5),
            ]),
        );
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    /// A read wholly inside the span 99..112 has no anchor. One starting inside it and running
    /// past it is anchored at 112; walking back, its T at 110 rules out the ALT haplotype, which
    /// spells `GCTAAA` there, so it is REF although it never reaches the start of the record.
    #[test]
    fn test_walk_complex_reads_starting_inside_span() {
        let g = complex_graph();
        let r = make_bam_record(100, b"ACCCG", &m(5));
        assert_eq!(run_walk(&g, &r, 1), (NoAnchor, vec![None]));
        let late = make_bam_record(105, b"GCTAATAAAA", &m(10));
        assert_eq!(run_walk(&g, &late, 1), (Labelled, vec![Some(false)]));
    }

    const MULTI: [&[u8]; 3] = [b"CTTT", b"C", b"CTTTT"];

    /// `CTTT>C,CTTTT` 1/2 changes the length by -3 and +1, so its two haplotypes differ by 4.
    #[test]
    fn test_graph_opposite_indels_shift_by_difference() {
        // span 100..105; TTTG repeats to 116, so only d = 4 runs on to the C at 117
        let reference = reference_with(&[(100, b"CTTTGTTTGTTTGTTTGC")]);
        let g = one_two(100, &MULTI, &reference).unwrap();
        // right_edge = 117 (d = 4); end = 117 + 1 + ANCHOR_FLANK. d <= 3 stops by 107
        assert_eq!(g.window.end, 123);
    }

    #[test]
    fn test_walk_multiallelic_insertion_alt_not_called_ref() {
        let reference = reference_with(&[(100, b"CTTTA")]);
        let g = one_two(100, &MULTI, &reference).unwrap();
        let r = make_bam_record(
            100,
            b"CTTTTAAAAA",
            &CigarString(vec![Cigar::Match(4), Cigar::Ins(1), Cigar::Match(5)]),
        );
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_multiallelic_foreign_insertion_is_uninformative() {
        let reference = reference_with(&[(100, b"CTTTA")]);
        let g = one_two(100, &MULTI, &reference);
        let r = make_bam_record(
            100,
            b"CTTTGGAAAAA",
            &CigarString(vec![Cigar::Match(4), Cigar::Ins(2), Cigar::Match(5)]),
        );
        assert_eq!(node_label(g.as_ref(), &r), None);
    }

    #[test]
    fn test_walk_multiallelic_deletion_alt() {
        let reference = reference_with(&[(100, b"CTTTA")]);
        let g = one_two(100, &MULTI, &reference).unwrap();
        let r = make_bam_record(
            100,
            b"CAAAAA",
            &CigarString(vec![Cigar::Match(1), Cigar::Del(3), Cigar::Match(5)]),
        );
        assert_eq!(run_walk(&g, &r, 1), (Labelled, vec![Some(false)]));
    }

    #[test]
    fn test_walk_snv_picks_each_allele() {
        let reference = reference_with(&[(102, b"A")]);
        let g = one_two(102, &[b"A", b"T", b"C"], &reference).unwrap();
        let alt1 = make_bam_record(100, b"AATAA", &m(5));
        let alt2 = make_bam_record(100, b"AACAA", &m(5));
        let refr = make_bam_record(100, b"AAAAA", &m(5));
        let other = make_bam_record(100, b"AAGAA", &m(5));
        assert_eq!(run_walk(&g, &alt1, 1), (Labelled, vec![Some(false)]));
        assert_eq!(run_walk(&g, &alt2, 1), (Labelled, vec![Some(true)]));
        // REF is neither slot of a 1/2 node
        assert_eq!(run_walk(&g, &refr, 1), (NoPath, vec![None]));
        assert_eq!(node_label(Some(&g), &other), None);
    }

    #[test]
    fn test_walk_insertion_discrimination() {
        let reference = reference_with(&[(90, FLANK), (100, b"AC")]);
        let g = one_two(100, &[b"A", b"AT", b"AG"], &reference).unwrap();
        let ins = vec![Cigar::Match(1), Cigar::Ins(1), Cigar::Match(1)];
        let ins_t = padded(&reference, b"ATC", ins.clone());
        let ins_g = padded(&reference, b"AGC", ins);
        assert_eq!(run_walk(&g, &ins_t, 1), (Labelled, vec![Some(false)]));
        assert_eq!(run_walk(&g, &ins_g, 1), (Labelled, vec![Some(true)]));
    }

    #[test]
    fn test_walk_deletion_length_discrimination() {
        let reference = reference_with(&[(90, FLANK), (100, b"ATGC")]);
        let g = biallelic(100, b"ATG", b"A", &reference).unwrap();
        let del2 = padded(
            &reference,
            b"AC",
            vec![Cigar::Match(1), Cigar::Del(2), Cigar::Match(1)],
        );
        let del1 = padded(
            &reference,
            b"AGC",
            vec![Cigar::Match(1), Cigar::Del(1), Cigar::Match(2)],
        );
        assert_eq!(run_walk(&g, &del2, 1), (Labelled, vec![Some(true)]));
        assert_eq!(node_label(Some(&g), &del1), None);
    }

    /// `CCGG` inserted before 103: anchored left of the insertions (forward walk) and, through
    /// a soft clip, at 104 right of them (reverse walk).
    fn ccgg_reads(reference: &[u8]) -> [bam::Record; 2] {
        let mut seq = reference[85..103].to_vec();
        seq.extend_from_slice(b"CCGG");
        seq.extend_from_slice(&reference[103..140]);
        let left = CigarString(vec![Cigar::Match(18), Cigar::Ins(4), Cigar::Match(37)]);
        let right = CigarString(vec![Cigar::SoftClip(22), Cigar::Match(37)]);
        [
            make_bam_record(85, &seq, &left),
            make_bam_record(103, &seq, &right),
        ]
    }

    /// Two insertions at one position: backward they are spelled in reverse site order.
    #[test]
    fn test_walk_same_pos_insertions_backward() {
        let w = writer();
        let reference = reference_with(&[(90, b"ACGTCAGTCACGATCAGTCAGT")]);
        // both insert before 103: CC then GG
        let records = vec![
            Arc::new(make_unphased_het(&w, 102, b"A", b"ACC")),
            Arc::new(make_unphased_het(&w, 102, b"A", b"AGG")),
        ];
        let g = graph(&records, &[(0, [0, 1]), (1, [0, 1])], &reference).unwrap();
        for r in &ccgg_reads(&reference) {
            assert_eq!(run_walk(&g, r, 2), (Labelled, vec![Some(true), Some(true)]));
        }
    }

    /// The insertion order is the forward rank on both strands, even where `rev` sorts the two
    /// sites the other way round: record 1's SNV choice mirrors to before record 0's insertion.
    #[test]
    fn test_walk_same_pos_insertions_swapped_on_rev() {
        let w = writer();
        let reference = reference_with(&[(90, b"ACGTCAGTCACGATCAGTCAGT")]);
        // CC before 103 (0/1); GG before 103 or T>C at 103 (1/2)
        let records = vec![
            Arc::new(make_unphased_het(&w, 102, b"A", b"ACC")),
            Arc::new(make_unphased_het_multi(
                &w,
                102,
                &[b"AT", b"AGGT", b"AC"],
                (1, 2),
            )),
        ];
        let g = graph(&records, &[(0, [0, 1]), (1, [1, 2])], &reference).unwrap();
        let rev_pos = |n| g.rev.sites.iter().position(|s| s.node == Some(n));
        assert!(rev_pos(1) < rev_pos(0), "rev must sort record 1 first");
        for r in &ccgg_reads(&reference) {
            assert_eq!(
                run_walk(&g, r, 2),
                (Labelled, vec![Some(true), Some(false)])
            );
        }
    }

    /// A star site decided only after an edit moved the walk past the star: accepted behind a
    /// deletion, rejected behind a substitution, which spelled the starred base.
    #[test]
    fn test_walk_star_decided_after_cursor_passed() {
        let w = writer();
        // C G A T at 100..104
        let reference = reference_with(&[(90, b"ACGTCAGTCACGATCAGTCAGT")]);
        let star = || {
            Arc::new(make_unphased_het_multi(
                &w,
                102,
                &[b"A", b"T", b"*"],
                (1, 2),
            ))
        };
        let nodes = [(0, [0, 1]), (1, [1, 2])];

        // CGA>C deletes 101..103, so the star site (pos 102) is decided at 103
        let records = vec![Arc::new(make_unphased_het(&w, 100, b"CGA", b"C")), star()];
        let g = graph(&records, &nodes, &reference).unwrap();
        let mut seq = reference[85..101].to_vec();
        seq.extend_from_slice(&reference[103..140]);
        let ops = vec![Cigar::Match(16), Cigar::Del(2), Cigar::Match(37)];
        let r = make_bam_record(85, &seq, &CigarString(ops));
        assert_eq!(
            run_walk(&g, &r, 2),
            (Labelled, vec![Some(true), Some(true)])
        );

        // CGA>TTT spells 102, so a `*` there cannot hold
        let records = vec![Arc::new(make_unphased_het(&w, 100, b"CGA", b"TTT")), star()];
        let g = graph(&records, &nodes, &reference).unwrap();
        let seq = read_seq(&reference, 85, 55, &[(15, b'T'), (16, b'T'), (17, b'T')]);
        let r = make_bam_record(85, &seq, &m(55));
        assert_eq!(run_walk(&g, &r, 2), (NoPath, vec![None, None]));
    }

    /// The deepest walk allowed fits a tokio worker's 2 MiB stack: a read over
    /// `MAX_WALK_DEPTH` het sites is labelled, one site more caps it at that depth.
    #[test]
    fn test_walk_depth_fits_worker_stack() {
        let run = |n: usize| {
            std::thread::Builder::new()
                .stack_size(2 * 1024 * 1024)
                .spawn(move || {
                    let w = writer();
                    let records: Vec<_> = (0..n)
                        .map(|i| Arc::new(make_unphased_het(&w, 100 + 2 * i as i64, b"A", b"T")))
                        .collect();
                    let nodes: Vec<_> = (0..n).map(|i| (i, [0, 1])).collect();
                    let reference = vec![b'A'; 2 * n + 200];
                    let g = graph(&records, &nodes, &reference).unwrap();
                    let len = 2 * n + 15; // past the window end at 2n + 104
                    let r = make_bam_record(95, &reference[95..95 + len], &m(len as u32));
                    run_walk(&g, &r, n).0
                })
                .unwrap()
                .join()
                .unwrap()
        };
        assert_eq!(run(MAX_WALK_DEPTH), Labelled);
        assert_eq!(run(MAX_WALK_DEPTH + 1), Capped);
    }

    /// On the reverse strand the star site sorts before its covering deletion, because its
    /// other choice deletes further right (forward) than that deletion.
    #[test]
    fn test_walk_star_before_its_deletion_backward() {
        let w = writer();
        // T G C A at 100..104, then T G
        let reference = reference_with(&[(90, b"ACGTCAGTCATGCATGATCAGTCAGT")]);
        let records = vec![
            Arc::new(make_unphased_het(&w, 100, b"TG", b"T")),
            Arc::new(make_unphased_het_multi(
                &w,
                101,
                &[b"GCA", b"G", b"*"],
                (1, 2),
            )),
        ];
        let g = graph(&records, &[(0, [0, 1]), (1, [1, 2])], &reference).unwrap();
        let rev_pos = |n| g.rev.sites.iter().position(|s| s.node == Some(n));
        assert!(
            rev_pos(1) < rev_pos(0),
            "star site must come first backwards"
        );
        // deletion of G at 101 with `*` at the second record
        let mut seq = reference[85..101].to_vec();
        seq.extend_from_slice(&reference[102..140]);
        let left = make_bam_record(
            85,
            &seq,
            &CigarString(vec![Cigar::Match(16), Cigar::Del(1), Cigar::Match(38)]),
        );
        // anchored at 105, right of the span 100..105
        let right = make_bam_record(
            105,
            &seq,
            &CigarString(vec![Cigar::SoftClip(19), Cigar::Match(35)]),
        );
        for r in [&left, &right] {
            assert_eq!(run_walk(&g, r, 2), (Labelled, vec![Some(true), Some(true)]));
        }
    }
}