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
use anyhow::{Context, bail};
use bstr::ByteSlice;
use iterator::{ClusterOrRecords, find_clusters};
use itertools::Itertools;
use lib_tsalign::a_star_aligner::{
    alignment_geometry::{AlignmentCoordinates, AlignmentRange},
    alignment_result::alignment::Alignment,
    template_switch_distance::AlignmentType,
};
use rust_htslib::bam;
use std::{borrow::Cow, ops::Range, path::PathBuf, sync::Arc};
use tokio::{
    fs::File,
    io::{AsyncWriteExt, BufWriter},
    pin,
    sync::mpsc,
};
use tokio_stream::StreamExt;
use tracing::{error, instrument, trace, warn, warn_span};

use crate::{
    common::{
        ImmutableSequence, SequencePair,
        aligner::{AlignmentOrchestrator, AlignmentQuery, InProgress, cli::CliAlignmentArgs},
        alignment::{ForwardAlignment, query_offset_at},
        contig::ContigName,
        coords::{GenomePosition, GenomeRegion},
        csv::CSVAuxData,
        list_of_regions::Targets,
        reference::{ReferenceQueryResult, ReferenceReader},
    },
    counter,
    vcf::pipeline::{
        clusterizer::{
            local_phasing::BamPhaseResolverError,
            phasing::{FlankAllele, SplitIntoHaplotypesError},
        },
        reader::VCFReaderWithSampleIndex,
        record::InputRecord,
    },
};

use super::Message;

pub mod cluster;
mod iterator;
pub mod local_phasing;
pub mod phasing;

pub struct Clusterizer {
    input: VCFReaderWithSampleIndex,
    targets: Option<Targets>,
    reference: ReferenceReader,
    output: mpsc::Sender<Message>,
    settings: ClusterizerSettings,
    /// Optional indexed BAM for local read-based phasing of `UnphasedHet` records.
    pub bam: Option<bam::IndexedReader>,
    pub phasing: local_phasing::PhasingSettings,
}

#[derive(clap::Args, Debug, Default)]
pub struct ClusterizerSettings {
    /// Select how clusters are pre-selected. Currently, the default option is the only sensible one, and the other one is for debug purposes.
    #[command(flatten)]
    pub cluster_strategy: cluster::ClusteringSettings,

    #[command(flatten)]
    pub aligner: CliAlignmentArgs,

    /// Write a TSV report of clusters that could not be resolved into haplotypes.
    ///
    /// One line per unresolvable cluster, with three tab-separated columns:
    ///
    /// 1. the cluster region as `contig:start-end` (1-based, inclusive)
    ///
    /// 2. the phasing status of the cluster: `trivial` (no phasing needed),
    ///    `no reads` (no `--phasing-bam` given), `error(...)` (phasing failed,
    ///    the parenthesised text names the cause), or `phased[D,D,...]` with one
    ///    decision per record that phasing attempted — `OK_DIRECT`, `OK_FLIP`,
    ///    `NO_EVIDENCE`, `MIN_READS` or `MIN_CONFIDENCE`
    ///
    /// 3. why the cluster is unresolvable: `MoreThanOneUnphasedHet`,
    ///    `MissingAllele`, `MixedPloidy` or `HomAcrossPhaseSets`
    ///
    /// The records of these clusters are still passed through to the output VCF unchanged.
    #[arg(
        long = "output-unresolvable",
        value_name = "FILE",
        help_heading = "Output"
    )]
    pub unresolvable_out: Option<PathBuf>,
}

impl Clusterizer {
    pub(super) const fn new(
        input: VCFReaderWithSampleIndex,
        reference: ReferenceReader,
        targets: Option<Targets>,
        output: mpsc::Sender<Message>,
        settings: ClusterizerSettings,
        bam: Option<bam::IndexedReader>,
        phasing: local_phasing::PhasingSettings,
    ) -> Self {
        Self {
            input,
            targets,
            reference,
            output,
            settings,
            bam,
            phasing,
        }
    }

    pub async fn run(self) -> anyhow::Result<()> {
        let Self {
            input,
            targets,
            reference,
            output,
            settings,
            mut bam,
            phasing: phasing_settings,
        } = self;

        let aligner = AlignmentOrchestrator::try_from(&settings.aligner)
            .map_err(|e| anyhow::anyhow!("Cannot initialize aligners: {e}"))?;

        let aligner_padding = settings.aligner.padding;
        let aligner_range_extension = settings.aligner.range_extension;
        let strategy = settings.cluster_strategy;

        let sample_name = input
            .header()
            .id_to_sample(u32::try_from(input.sample_ix)?.into())
            .to_str_lossy()
            .to_string();
        let clusters = find_clusters(strategy.clone(), aligner_padding, input, targets);
        let ctx = AlignmentContext {
            strategy: &strategy,
            reference: &reference,
            aligner: &aligner,
            padding: aligner_padding,
            range_extension: aligner_range_extension,
            sample_name: &sample_name,
        };

        pin!(clusters);
        let mut cluster_id = 0usize;
        let mut proximity_cluster_id = 0usize;

        let mut unresolvable_out = if let Some(p) = settings.unresolvable_out {
            Some(BufWriter::new(File::create(p).await?))
        } else {
            None
        };

        while let Some(e) = clusters.next().await {
            match e {
                ClusterOrRecords::Cluster { records, flanks } => {
                    proximity_cluster_id += 1;
                    counter!("clusters").inc(1);
                    let proximity_id_str = proximity_cluster_id.to_string();

                    // Local phasing replaces entries with re-genotyped copies, so `records` keeps
                    // the input as read.
                    let mut classified = records.clone();

                    // `phasing_ran` records whether local phasing actually ran to completion on
                    // this cluster, so the resolution outcome below can be attributed to it.
                    let (phasing_status, phasing_ran) = run_local_phasing(
                        &mut classified,
                        &flanks,
                        &reference,
                        bam.as_mut(),
                        &phasing_settings,
                    )
                    .await;

                    let sub_clusters =
                        match phasing::split_into_haplotype_clusters(&classified, &strategy) {
                            Ok(sc) => sc,
                            Err(e) => {
                                report_unresolvable(
                                    &e,
                                    &records,
                                    &phasing_status,
                                    phasing_ran,
                                    unresolvable_out.as_mut(),
                                )
                                .await?;
                                output
                                    .send(Message::passthrough(records))
                                    .await
                                    .context("the channel closed unexpectedly")?;
                                continue;
                            }
                        };

                    counter!("clusters.resolved").inc(1);
                    if phasing_ran {
                        counter!("clusters.resolved.after_phasing").inc(1);
                    }

                    dispatch_sub_clusters(
                        &ctx,
                        sub_clusters,
                        &classified,
                        &flanks,
                        &proximity_id_str,
                        &mut cluster_id,
                        &output,
                    )
                    .await?;
                }
                ClusterOrRecords::Records(records) => {
                    output
                        .send(Message::passthrough(records))
                        .await
                        .context("Channel closed !?")?;
                }
                // VCF pipeline does not use the in-memory cache (no enable_cache() call),
                // so SequenceDone is a no-op here.
                ClusterOrRecords::SequenceDone => {} // continue
            }
        }
        if let Some(o) = &mut unresolvable_out {
            o.flush().await?;
        }
        Ok(())
    }
}

/// Align each haplotype sub-cluster of one proximity cluster and forward it to the writer.
/// `cluster_id` is the running sub-cluster counter, advanced once per sub-cluster.
async fn dispatch_sub_clusters(
    ctx: &AlignmentContext<'_>,
    sub_clusters: Vec<phasing::HaplotypeSubCluster>,
    cluster: &[Arc<InputRecord>],
    flanks: &[Arc<InputRecord>],
    cluster_grp: &str,
    cluster_id: &mut usize,
    output: &mpsc::Sender<Message>,
) -> anyhow::Result<()> {
    let input_phasesets = phasing::input_phasesets(cluster);
    for mut sub in sub_clusters {
        *cluster_id += 1;
        sub.records.sort_by_key(|(r, _)| r.pos());
        let recs: Vec<(InputRecord, u32)> = sub
            .records
            .iter()
            .map(|(r, a)| ((**r).clone(), *a))
            .collect();
        let sub_phasing = phasing::OutputPhasing::from_subcluster(sub.haplo, sub.phaseset);
        // The cluster's records outside this sub-cluster are its flanks too: those on its
        // haplotype were split off or dropped as lone records, but still are on the alt.
        let mut records: Vec<_> = cluster
            .iter()
            .filter(|r| !sub.records.iter().any(|(s, _)| Arc::ptr_eq(s, r)))
            .chain(flanks)
            .cloned()
            .collect();
        records.sort_by_key(|r| r.pos());
        let sub_flanks = SubClusterFlanks {
            records: &records,
            haplo: sub.haplo,
            phaseset: sub.phaseset.filter(|ps| input_phasesets.contains(ps)),
        };
        // A sub-cluster that is no cluster on its own is written as is, without realigning it.
        let pending = if ctx
            .strategy
            .is_cluster(&sub.records, |r| &*r.0, |r| Some(r.1))
        {
            start_alignment(
                ctx,
                &recs,
                &sub_flanks,
                &cluster_id.to_string(),
                cluster_grp,
                sub_phasing,
            )
            .await
        } else {
            counter!("clusters.sub_clusters.not_realigned").inc(1);
            None
        };
        output
            .send(Message::cluster(pending, recs, sub_phasing))
            .await?;
    }
    Ok(())
}

/// The flanks of one sub-cluster, and what decides which of their alleles it carries.
struct SubClusterFlanks<'a> {
    /// Position-sorted. Their effective genotype counts, so local phasing carries over.
    records: &'a [Arc<InputRecord>],
    haplo: phasing::Haplotype,
    /// The sub-cluster's phase set, if it comes from the input (see
    /// [`phasing::input_phasesets`]).
    phaseset: Option<i32>,
}

/// The loop-invariant inputs needed to start the alignment of one sub-cluster.
struct AlignmentContext<'a> {
    strategy: &'a cluster::ClusteringSettings,
    reference: &'a ReferenceReader,
    aligner: &'a AlignmentOrchestrator,
    padding: usize,
    range_extension: usize,
    sample_name: &'a str,
}

/// Try to resolve the phasing of `classified` from read evidence.
///
/// Returns the phasing status as reported by `--output-unresolvable`, and whether phasing
/// actually ran to completion (so the resolution outcome can be attributed to it).
async fn run_local_phasing(
    classified: &mut [Arc<InputRecord>],
    flanks: &[Arc<InputRecord>],
    reference: &ReferenceReader,
    bam: Option<&mut bam::IndexedReader>,
    settings: &local_phasing::PhasingSettings,
) -> (Cow<'static, str>, bool) {
    if phasing::is_trivially_resolvable(classified) {
        counter!("clusters.phasing.not_needed").inc(1);
        return ("trivial".into(), false);
    }
    let Some(bam_reader) = bam else {
        counter!("clusters.phasing.skipped.no_reads").inc(1);
        return ("no reads".into(), false);
    };
    let Ok(cluster_region) = extract_region(classified.iter().map(Arc::as_ref)) else {
        counter!("clusters.phasing.failed.no_region").inc(1);
        return ("error(region resolution)".into(), false);
    };
    // Local phasing walks reads through a graph over the reference, so it needs context around
    // the cluster.
    let Some((ref_seq, ref_start)) = fetch_phasing_reference(reference, &cluster_region).await
    else {
        counter!("clusters.phasing.failed.no_reference").inc(1);
        return ("error(no reference)".into(), false);
    };

    match tokio::task::block_in_place(|| {
        local_phasing::resolve_phasing(
            classified,
            flanks,
            &cluster_region,
            bam_reader,
            settings,
            local_phasing::RefSlice::new(&ref_seq, ref_start),
        )
    }) {
        Err(BamPhaseResolverError::MultiplePhaseSets(_)) => {
            counter!("clusters.phasing.failed.multiple_phasesets").inc(1);
            ("error(multiple phasesets)".into(), false)
        }
        Err(BamPhaseResolverError::BamReadError(_)) => {
            counter!("clusters.phasing.failed.bam_error").inc(1);
            ("error(bam error)".into(), false)
        }
        Err(BamPhaseResolverError::Other(_)) => {
            counter!("clusters.phasing.failed.other").inc(1);
            ("error(other)".into(), false)
        }
        Ok(decisions) => {
            counter!("clusters.phasing.completed").inc(1);
            let results = decisions
                .into_iter()
                .map(|d| match d {
                    local_phasing::Decision::Resolved(local_phasing::Orientation::Direct) => {
                        "OK_DIRECT"
                    }
                    local_phasing::Decision::Resolved(local_phasing::Orientation::Flipped) => {
                        "OK_FLIP"
                    }
                    local_phasing::Decision::NoEvidence => "NO_EVIDENCE",
                    local_phasing::Decision::InsufficientReads => "MIN_READS",
                    local_phasing::Decision::LowConfidence => "MIN_CONFIDENCE",
                })
                .join(",");
            (format!("phased[{results}]").into(), true)
        }
    }
}

/// Count a cluster that could not be split into haplotypes, and report it to the
/// `--output-unresolvable` file if one is configured.
async fn report_unresolvable(
    error: &SplitIntoHaplotypesError,
    records: &[Arc<InputRecord>],
    phasing_status: &str,
    phasing_ran: bool,
    unresolvable_out: Option<&mut BufWriter<File>>,
) -> anyhow::Result<()> {
    match error {
        SplitIntoHaplotypesError::MoreThanOneUnphasedHet => {
            counter!("clusters.unresolvable.multiple_unphased_het").inc(1);
        }
        SplitIntoHaplotypesError::MissingAllele => {
            counter!("clusters.unresolvable.missing_allele").inc(1);
        }
        SplitIntoHaplotypesError::MixedPloidy => {
            counter!("clusters.unresolvable.mixed_ploidy").inc(1);
        }
        SplitIntoHaplotypesError::HomAcrossPhaseSets => {
            counter!("clusters.unresolvable.hom_across_phasesets").inc(1);
        }
        SplitIntoHaplotypesError::Other(_) => {
            counter!("clusters.unresolvable.other").inc(1);
        }
    }
    if phasing_ran {
        counter!("clusters.unresolvable.after_phasing").inc(1);
    }
    if let Some(file) = unresolvable_out {
        file.write_all(
            format!(
                "{}\t{}\t{:?}\n",
                extract_region(records.iter().map(Arc::as_ref))?,
                phasing_status,
                error
            )
            .as_bytes(),
        )
        .await?;
    }
    Ok(())
}

/// Prepare one sub-cluster and hand it to the aligner.
///
/// `None` on any preparation / alignment-start failure: the sub-cluster still carries its records
/// and phasing, so the writer reconstructs per-haplotype biallelic records instead of dropping
/// the variants.
async fn start_alignment(
    ctx: &AlignmentContext<'_>,
    recs: &[(InputRecord, u32)],
    flanks: &SubClusterFlanks<'_>,
    cluster_id: &str,
    cluster_grp: &str,
    phasing: phasing::OutputPhasing,
) -> Option<Box<(InProgress, CSVAuxData)>> {
    let prepared = match prepare_cluster(
        ctx.reference,
        recs,
        flanks,
        ctx.padding,
        ctx.range_extension,
    )
    .await
    {
        Ok(Some(prepared)) => prepared,
        Ok(None) => return None,
        Err((reg, err)) => {
            let _s = reg.map(|r| warn_span!("Failed to prepare", pos = %r).entered());
            counter!("alignments.skipped.overlapping_mutations").inc(1);
            warn!("{err}");
            return None;
        }
    };

    let pending = match ctx.aligner.get_or_compute_alignment(
        ctx.reference.get_name(),
        &prepared.reference_region.clone(),
        prepared.region.clone(),
        // the record extent, which unlike `region` includes the anchor base of a leading insertion
        &prepared.vcf_region,
        None,
        prepared.query.clone(),
    ) {
        Ok(pending) => pending,
        Err(e) => {
            error!("Could not get or start the computation of an alignment: {e}");
            return None;
        }
    };

    let AlignmentQuery { sequences, ranges } = prepared.query;

    Some(Box::new((
        pending,
        CSVAuxData {
            cluster_id: cluster_id.to_string(),
            cluster_grp: cluster_grp.to_string(),
            sequences,
            ranges,
            ref_context_region: prepared.reference_region.clone(),
            // VCF alt sequence is synthetic (reference + applied mutations), so there is no
            // distinct alt context window — the region is intentionally the same.
            alt_context_region: prepared.reference_region,
            region: prepared.region,
            vcf_record_region: Some(prepared.vcf_region.to_string()),
            sample_name: Some(ctx.sample_name.to_string()),
            read_id: None,
            forward_alignment: ForwardAlignment(prepared.fw_alignment),
            cost: ctx.aligner.costs.clone(),
            reference_name: ctx.reference.get_name().to_string(),
            output_phasing: Some(phasing),
            unknown_flanks: prepared.unknown_flanks,
        },
    )))
}

#[derive(Clone, Debug)]
struct PreparedCluster {
    query: AlignmentQuery,
    reference_region: GenomeRegion,
    /// The region the cluster's mutations actually edit: the window that is aligned, and the
    /// record's identity. See [`extract_edited_region`].
    region: GenomeRegion,
    /// The POS-based extent of the source records, i.e. `region` plus the anchor bases VCF puts
    /// in front of indels. A label for looking the records up again, nothing else depends on it.
    vcf_region: GenomeRegion,
    fw_alignment: Alignment<AlignmentType>,
    /// The query spans of the flanks whose allele on this haplotype is unknown, left as
    /// reference. An empty span marks a point.
    unknown_flanks: Vec<Range<usize>>,
}

async fn prepare_cluster(
    reference: &ReferenceReader,
    cluster: &[(InputRecord, u32)],
    flanks: &SubClusterFlanks<'_>,
    padding: usize,
    range_extension: usize,
) -> Result<Option<PreparedCluster>, (Option<GenomeRegion>, anyhow::Error)> {
    let vcf_region = extract_region(cluster.iter().map(|(r, _)| r)).map_err(|e| (None, e))?;
    let region = extract_edited_region(cluster).map_err(|e| (Some(vcf_region.clone()), e))?;
    let Some(ReferenceQueryResult {
        region: actual_region,
        sequence: reference_sequence,
        range_in_sequence,
    }) = reference
        .get_seq(region.clone(), padding, padding)
        .await
        .map_err(|e| (Some(vcf_region.clone()), e))?
    else {
        return Ok(None);
    };

    let _span = warn_span!("prepare_cluster", pos = %region, vcf = %vcf_region).entered();

    // `range_in_sequence` is where the cluster sits in the padded sequence, so the paddings that
    // were actually available (both are clamped at the contig boundaries) follow from it.
    let actual_padding_left = range_in_sequence.start;
    let actual_padding_right = reference_sequence.len() - range_in_sequence.end;
    let range_offset = actual_padding_left.saturating_sub(range_extension);
    let range_limit = (reference_sequence.len() - actual_padding_right + range_extension)
        .min(reference_sequence.len());

    let window_start = actual_region.start().position_0();
    let window = window_start..window_start + reference_sequence.len();
    let built = build_alt(
        &reference_sequence,
        cluster,
        flanks,
        window.clone(),
        window_start + range_offset..window_start + range_limit,
    )
    .map_err(|e| (Some(vcf_region.clone()), e))?;
    let (query_sequence, fw_alignment) = built.alt;

    // Applied flanks shift the query against the reference, so the query side of the range
    // follows from the forward alignment. An insertion at either edge of the range is inside it.
    let query_at = |offset, after_insertions| {
        query_offset_at(&fw_alignment, offset, after_insertions)
            .map_err(|e| (Some(vcf_region.clone()), e))
    };
    let ranges = AlignmentRange::new_offset_limit(
        AlignmentCoordinates::new(range_offset, query_at(range_offset, false)?),
        AlignmentCoordinates::new(range_limit, query_at(range_limit, true)?),
    );
    let unknown_flanks = built
        .unknown
        .iter()
        .map(|span| {
            let start = span.start.clamp(window.start, window.end) - window.start;
            let end = span.end.clamp(window.start, window.end) - window.start;
            Ok(query_at(start, false)?..query_at(end, true)?)
        })
        .collect::<Result<_, _>>()?;

    Ok(Some(PreparedCluster {
        query: AlignmentQuery {
            sequences: SequencePair {
                reference: reference_sequence,
                query: query_sequence,
            },
            ranges,
        },
        reference_region: actual_region,
        region,
        vcf_region,
        fw_alignment,
        unknown_flanks,
    }))
}

/// Reference context fetched on each side of a cluster for local phasing.
///
/// It has to cover how far the variant graph's window reaches past the cluster region, which a
/// compile-time assert in `local_phasing::variant_graph` checks. Falling short is not dangerous:
/// `VariantGraph::build` then returns `None`, the cluster is unsupported and its records get no
/// evidence.
const PHASING_REF_PADDING: usize = 256;

/// The reference window local phasing needs around `cluster_region`, with the 0-based position
/// of its first base.
///
/// `None` when the reference cannot serve the query — an unknown contig, or a soft-masked
/// stretch inside the cluster. Phasing is then skipped for this cluster rather than run against
/// allele sequences that could not be built.
async fn fetch_phasing_reference(
    reference: &ReferenceReader,
    cluster_region: &GenomeRegion,
) -> Option<(ImmutableSequence, i64)> {
    let window = reference
        .get_seq(
            cluster_region.clone(),
            PHASING_REF_PADDING,
            PHASING_REF_PADDING,
        )
        .await
        .inspect_err(|e| warn!("local_phasing: reference query failed: {e}"))
        .ok()??;
    let start = i64::try_from(window.region.start().position_0()).ok()?;
    Some((window.sequence, start))
}

fn extract_region<'a>(
    cluster: impl IntoIterator<Item = &'a InputRecord>,
) -> anyhow::Result<GenomeRegion> {
    let (start, end, contig) = {
        let (mut start, mut end, mut contig) = (i64::MAX, 0, None);
        for r in cluster {
            start = start.min(r.pos());
            end = end.max(r.end());
            if contig.is_none()
                && let Some(present) = r.rid()
            {
                let name = r.header().rid2name(present)?;
                contig = Some(ContigName::new(name));
            }
        }
        (
            usize::try_from(start)?,
            usize::try_from(end)?,
            contig.context("No rid present in records??")?,
        )
    };
    let query_region = GenomeRegion::new_bounded(GenomePosition::new_0(contig, start), end - start);
    Ok(query_region)
}

/// The region a cluster's mutations actually edit, as opposed to the raw VCF extent that
/// [`extract_region`] reports.
///
/// VCF anchors an indel one base left of the edit, so a cluster starting with one covers a
/// reference base it does not touch. The `reads` subcommand derives its cluster regions from the
/// CIGAR, where an insertion sits after the preceding match and covers no reference base at all —
/// the same event therefore came out one base wider in `vcf` than in `reads`. Shifting each record
/// past its shared allele prefix removes the anchor and makes the two agree; a cluster of nothing
/// but an insertion becomes a zero-width region at the point it is inserted into.
///
/// The end needs no such correction: dropping the prefix shortens a record's reference allele by
/// exactly as much as it moves its start right, so `end()` already points past the last edited
/// base.
fn extract_edited_region(cluster: &[(InputRecord, u32)]) -> anyhow::Result<GenomeRegion> {
    let raw = extract_region(cluster.iter().map(|(r, _)| r))?;
    let mut start = usize::MAX;
    for (record, allele) in cluster {
        start = start.min(usize::try_from(record.pos())? + cluster::edit_offset(record, *allele));
    }
    let end = raw.end_excl().context("cluster region is unbounded?")?;
    GenomeRegion::from_incl_excl(
        GenomePosition::new_0(raw.contig().clone(), start),
        Some(end),
    )
}

/// Validate and anchor-trim the alleles of one record, returning the position and alleles to
/// splice into the alt sequence. `None` = the record contributes nothing (already logged).
fn normalise_alleles<'a>(
    mut pos: usize,
    mut ref_allele: &'a [u8],
    mut alt_allele: &'a [u8],
) -> Option<(usize, &'a [u8], &'a [u8])> {
    if alt_allele == b"*" {
        // The allele is missing because an upstream deletion spans this position. The
        // sequence change is fully described by that deletion record, so this one must
        // contribute nothing -- and in particular must not advance `last_end`, nor trip
        // the overlap check of the caller, which it does by construction.
        trace!("Skipping record at {pos}: allele is deleted by an upstream deletion");
        return None;
    }

    if let Some(allele) = [ref_allele, alt_allele].into_iter().find(|a| !is_dna(a)) {
        // Symbolic alleles (`<DEL>`, `<NON_REF>`, ...), breakends and missing alleles
        // carry no literal sequence, so splicing them in would corrupt the alt sequence.
        warn!(
            "Skipping record at {pos}: allele `{}` is not a DNA sequence",
            String::from_utf8_lossy(allele)
        );
        return None;
    }

    // Strip the bases both alleles share at the front: they are not edited, they only shift the
    // record to the right. For a plain VCF indel (`A -> AC`, `AC -> A`) that is the single anchor
    // base, but a repeat-expansion record (`(CAG)x84 -> (CAG)x100`) shares far more, and the
    // shared part must be removed here as well: [`cluster::edit_offset`] removes all of it when it
    // places the cluster, and the two must agree or the mutation lands outside the aligned window.
    let shared_prefix = ref_allele
        .iter()
        .zip(alt_allele)
        .take_while(|(r, a)| r.eq_ignore_ascii_case(a))
        .count();
    ref_allele = ref_allele.get(shared_prefix..).unwrap_or_default();
    alt_allele = alt_allele.get(shared_prefix..).unwrap_or_default();
    pos += shared_prefix;

    if ref_allele.is_empty() && alt_allele.is_empty() {
        warn!("Empty record; Skipping.");
        return None;
    }

    Some((pos, ref_allele, alt_allele))
}

/// Whether `allele` is a literal DNA sequence, unlike symbolic alleles, breakends or `*`.
pub(super) fn is_dna(allele: &[u8]) -> bool {
    allele
        .iter()
        .all(|b| matches!(b.to_ascii_uppercase(), b'A' | b'C' | b'G' | b'T' | b'N'))
}

/// Append the alignment of one anchor-trimmed mutation to `cigar`.
fn push_mutation_cigar(
    cigar: &mut Alignment<AlignmentType>,
    ref_allele: &[u8],
    alt_allele: &[u8],
) -> anyhow::Result<()> {
    match (ref_allele.len(), alt_allele.len()) {
        (0, 0) => {
            bail!("Empty record; should have been caught earlier!");
        }
        // TODO all of the following cases can actually be seen as only the n,m case but for clarity we leave these here.
        (1, 1) => {
            // SNV
            cigar.push(AlignmentType::PrimarySubstitution);
        }
        (0, m) => {
            // insertion
            cigar.push_n(m, AlignmentType::PrimaryInsertion);
        }
        (n, 0) => {
            // deletion
            cigar.push_n(n, AlignmentType::PrimaryDeletion);
        }
        (n, m) => {
            // TODO perhaps run some simple local aligner here? For now, we're gonna put match/mismatch and ins/del
            let match_len = n.min(m);
            for (r, a) in ref_allele.iter().zip(alt_allele.iter()).take(match_len) {
                if r.eq_ignore_ascii_case(a) {
                    cigar.push(AlignmentType::PrimaryMatch);
                } else {
                    cigar.push(AlignmentType::PrimarySubstitution);
                }
            }

            let extra = n.max(m) - match_len;
            if n > m {
                cigar.push_n(extra, AlignmentType::PrimaryDeletion);
            } else {
                cigar.push_n(extra, AlignmentType::PrimaryInsertion);
            }
        }
    }
    Ok(())
}

/// One record's change to the alt sequence: the anchor-trimmed reference allele at
/// `[pos, end)` is replaced by `alt`.
#[derive(Debug, Clone, Copy)]
struct Edit<'a> {
    pos: usize,
    end: usize,
    ref_allele: &'a [u8],
    alt: &'a [u8],
}

/// The edit of allele `allele_idx` of a cluster record. `None` = the record contributes nothing
/// (already logged).
fn cluster_edit(record: &InputRecord, allele_idx: u32) -> anyhow::Result<Option<Edit<'_>>> {
    let pos = usize::try_from(record.pos())?;
    let end = usize::try_from(record.end())?;
    let alleles = record.alleles();
    let Some((ref_allele, alt_alleles)) = alleles.split_first() else {
        warn!("Record at {pos} has no alt allele");
        return Ok(None);
    };
    if allele_idx == 0 {
        warn!(
            "Record at {pos} has invalid allele index {allele_idx} (only {} alleles); skipping",
            alleles.len()
        );
        return Ok(None);
    }
    let alt_allele = alt_alleles
        .get(allele_idx as usize - 1)
        .context("alt allele not found")?;
    Ok(
        normalise_alleles(pos, ref_allele, alt_allele).map(|(pos, ref_allele, alt)| Edit {
            pos,
            end,
            ref_allele,
            alt,
        }),
    )
}

/// The alt sequence of one sub-cluster with its forward alignment, and the reference spans of
/// the flanks whose allele on this haplotype is unknown.
struct BuiltAlt {
    alt: (ImmutableSequence, Alignment<AlignmentType>),
    unknown: Vec<Range<usize>>,
}

/// Build the alt sequence of a sub-cluster over the reference `window`: its own records, plus
/// every flank whose allele on its haplotype is certain. A flank never fails the sub-cluster:
/// one that cannot be applied counts as unknown. `range` is the alignment range; flanks inside
/// or touching it are never applied.
fn build_alt(
    reference: &[u8],
    cluster: &[(InputRecord, u32)],
    flanks: &SubClusterFlanks<'_>,
    window: Range<usize>,
    range: Range<usize>,
) -> anyhow::Result<BuiltAlt> {
    let mut edits = Vec::with_capacity(cluster.len());
    for (record, allele) in cluster {
        edits.extend(cluster_edit(record, *allele)?);
    }

    let mut unknown = Vec::new();
    let mut flank_edits: Vec<Edit<'_>> = Vec::new();
    for flank in flanks.records {
        let (Ok(pos), Ok(end)) = (usize::try_from(flank.pos()), usize::try_from(flank.end()))
        else {
            continue;
        };
        if end <= window.start || pos >= window.end {
            continue; // not near this sub-cluster
        }
        let allele = match phasing::flank_allele(flank.gt(), flanks.haplo, flanks.phaseset) {
            FlankAllele::Ref => {
                counter!("flanks.ref").inc(1);
                continue;
            }
            FlankAllele::Unknown => {
                counter!("flanks.unknown.phase").inc(1);
                unknown.push(pos..end);
                continue;
            }
            FlankAllele::Apply(allele) => allele,
        };
        let mut give_up = |reason| {
            trace!("Flank at {pos} is left as reference: {reason}");
            unknown.push(pos..end);
        };
        if pos < window.start || end > window.end {
            counter!("flanks.unknown.window_edge").inc(1);
            give_up("it reaches beyond the context window");
            continue;
        }
        if end >= range.start && pos <= range.end {
            counter!("flanks.unknown.in_range").inc(1);
            give_up("it reaches the alignment range");
            continue;
        }
        let alleles = flank.alleles();
        let (Some(&ref_allele), Some(&alt)) = (alleles.first(), alleles.get(allele as usize))
        else {
            counter!("flanks.unknown.symbolic").inc(1);
            give_up("the allele is missing");
            continue;
        };
        if alt == b"*" {
            // The upstream deletion that spans it is a record of its own.
            counter!("flanks.ref").inc(1);
            continue;
        }
        if !is_dna(ref_allele) || !is_dna(alt) {
            counter!("flanks.unknown.symbolic").inc(1);
            give_up("the allele is not a DNA sequence");
            continue;
        }
        let Some((pos, ref_allele, alt)) = normalise_alleles(pos, ref_allele, alt) else {
            continue;
        };
        if flank_edits.last().is_some_and(|last| pos < last.end) {
            counter!("flanks.unknown.overlap").inc(1);
            give_up("it overlaps a flank applied before");
            continue;
        }
        counter!("flanks.applied").inc(1);
        flank_edits.push(Edit {
            pos,
            end,
            ref_allele,
            alt,
        });
    }

    edits.extend(flank_edits);
    edits.sort_by_key(|e| (e.pos, e.end));
    Ok(BuiltAlt {
        alt: apply_mutations(reference, window.start, &edits)?,
        unknown,
    })
}

/// Build the alt sequence: `reference` (starting at genome position `reference_start`) with the
/// position-sorted `edits` applied.
#[instrument(name = "build_query_sequence", skip_all)]
fn apply_mutations(
    reference: &[u8],
    reference_start: usize,
    edits: &[Edit<'_>],
) -> anyhow::Result<(ImmutableSequence, Alignment<AlignmentType>)> {
    let mut alt_sequence = Vec::new();
    let mut cigar = Alignment::new();
    let mut last_end = reference_start;
    let reference_end = reference_start + reference.len();

    let pos2off = |pos: usize| pos - reference_start;

    for &Edit {
        pos,
        end,
        ref_allele,
        alt: alt_allele,
    } in edits
    {
        if pos < last_end {
            bail!(
                "Overlapping mutation: last mutation ended at {last_end}, \
                 but this one starts at {pos}"
            );
        }

        if end > reference_end {
            warn!(
                "Skipping out-of-bounds mutation at {pos}: \
                 record end {end} exceeds reference end {reference_end}"
            );
            continue;
        }

        if pos > end {
            warn!("Skip negative-sized mutation: the position is {pos} but the end is {end}",);
            continue;
        }

        if pos - last_end > 0 {
            alt_sequence.extend_from_slice(
                reference
                    .get(pos2off(last_end)..pos2off(pos))
                    .context("invalid reference offsets")?,
            );
            cigar.push_n(pos - last_end, AlignmentType::PrimaryMatch);
        }

        // The reference is uppercased on read, so alleles are normalised to match.
        alt_sequence.extend(alt_allele.iter().map(u8::to_ascii_uppercase));

        push_mutation_cigar(&mut cigar, ref_allele, alt_allele)?;

        last_end = end;
    }

    alt_sequence.extend_from_slice(
        reference
            .get(pos2off(last_end)..)
            .context("invalid ref offsets")?,
    );
    cigar.push_n(
        reference.len() - pos2off(last_end),
        AlignmentType::PrimaryMatch,
    );

    Ok((alt_sequence.into(), cigar))
}

#[cfg(test)]
mod tests {
    use rust_htslib::bcf::{self, Header, Writer, record::GenotypeAllele};

    use bstr::ByteSlice as _;
    use rust_htslib::faidx;
    use std::path::Path;

    use std::sync::Arc;

    use super::{
        SubClusterFlanks, extract_edited_region, extract_region, normalise_alleles, prepare_cluster,
    };
    use crate::{
        common::reference::{CliReferenceArg, ReferenceReader},
        vcf::pipeline::{
            clusterizer::{cluster::edit_offset, phasing::Haplotype},
            record::InputRecord,
        },
    };

    fn make_writer() -> Writer {
        let mut header = Header::new();
        header.push_record(b"##contig=<ID=chr1,length=100000000>");
        header.push_record(b"##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
        header.push_record(b"##FORMAT=<ID=PS,Number=1,Type=Integer,Description=\"Phase set\">");
        header.push_sample(b"S1");
        Writer::from_path("/dev/null", &header, true, bcf::Format::Vcf).unwrap()
    }

    /// A record at the 0-based `pos` with genotype `gt` and, if given, phase set `ps`.
    fn make_record_gt(
        writer: &Writer,
        pos: i64,
        alleles: &[&[u8]],
        gt: [GenotypeAllele; 2],
        ps: Option<i32>,
    ) -> Arc<InputRecord> {
        let mut rec = writer.empty_record();
        let rid = rec.header().name2rid(b"chr1").unwrap();
        rec.set_rid(Some(rid));
        rec.set_pos(pos);
        rec.set_alleles(alleles).unwrap();
        rec.push_genotypes(&gt).unwrap();
        if let Some(ps) = ps {
            rec.push_format_integer(b"PS", &[ps]).unwrap();
        }
        Arc::new(InputRecord::new(rec, 0))
    }

    const HOM_ALT: [GenotypeAllele; 2] = [GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
    const UNPHASED_HET: [GenotypeAllele; 2] =
        [GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)];

    const fn no_flanks() -> SubClusterFlanks<'static> {
        SubClusterFlanks {
            records: &[],
            haplo: Haplotype::H0,
            phaseset: None,
        }
    }

    /// A minimal heterozygous record at the 0-based `pos` with the given alleles.
    fn make_record(writer: &Writer, pos: i64, alleles: &[&[u8]]) -> InputRecord {
        let mut rec = writer.empty_record();
        let rid = rec.header().name2rid(b"chr1").unwrap();
        rec.set_rid(Some(rid));
        rec.set_pos(pos);
        rec.set_alleles(alleles).unwrap();
        rec.push_genotypes(&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)])
            .unwrap();
        InputRecord::new(rec, 0)
    }

    /// The reported bug from <https://version.helsinki.fi/kraujasp/twitcher/-/work_items/80>
    /// An insertion followed by an SNV. The insertion's anchor base is not
    /// edited, so the region must start at the same location as the SNV
    #[test]
    fn leading_insertion_does_not_widen_the_edited_region() {
        let w = make_writer();
        let cluster = [
            (make_record(&w, 1_070_825, &[b"C", b"CGG"]), 1),
            (make_record(&w, 1_070_826, &[b"C", b"G"]), 1),
        ];

        let raw = extract_region(cluster.iter().map(|(r, _)| r)).unwrap();
        assert_eq!(raw.to_string(), "chr1:1070826-1070827");

        let edited = extract_edited_region(&cluster).unwrap();
        assert_eq!(edited.start().position_0(), 1_070_826);
        assert_eq!(edited.len(), Some(1));
        assert_eq!(edited.to_string(), "chr1:1070827-1070827");
    }

    /// A leading deletion carries the same anchor base, and must be corrected the same way.
    #[test]
    fn leading_deletion_does_not_widen_the_edited_region() {
        let w = make_writer();
        let cluster = [
            (make_record(&w, 100, &[b"AT", b"A"]), 1),
            (make_record(&w, 105, &[b"C", b"G"]), 1),
        ];

        // The deleted base is at 101, so that is where the `reads` subcommand puts its `D(1)`.
        let edited = extract_edited_region(&cluster).unwrap();
        assert_eq!(edited.start().position_0(), 101);
        assert_eq!(edited.end_excl().unwrap().position_0(), 106);
    }

    /// A cluster of nothing but an insertion covers no reference base at all, exactly as the
    /// CIGAR-derived cluster of an `I` operation does.
    #[test]
    fn lone_insertion_becomes_a_zero_width_region() {
        let w = make_writer();
        let cluster = [(make_record(&w, 100, &[b"A", b"ATTT"]), 1)];

        let edited = extract_edited_region(&cluster).unwrap();
        assert_eq!(edited.start().position_0(), 101);
        assert_eq!(edited.len(), Some(0));
    }

    /// Without an anchor base to strip there is nothing to correct: substitutions keep the raw
    /// VCF extent.
    #[test]
    fn substitutions_keep_the_raw_extent() {
        let w = make_writer();
        let cluster = [
            (make_record(&w, 100, &[b"A", b"T"]), 1),
            (make_record(&w, 104, &[b"GT", b"CA"]), 1),
        ];

        let raw = extract_region(cluster.iter().map(|(r, _)| r)).unwrap();
        assert_eq!(extract_edited_region(&cluster).unwrap(), raw);
    }

    /// The correction uses the allele the cluster was built with, not the first alt.
    #[test]
    fn edited_region_follows_the_selected_allele() {
        let w = make_writer();
        let insertion = [(make_record(&w, 100, &[b"C", b"CGG", b"G"]), 1)];
        let substitution = [(make_record(&w, 100, &[b"C", b"CGG", b"G"]), 2)];

        assert_eq!(
            extract_edited_region(&insertion)
                .unwrap()
                .start()
                .position_0(),
            101
        );
        assert_eq!(
            extract_edited_region(&substitution)
                .unwrap()
                .start()
                .position_0(),
            100
        );
    }

    /// A record whose edit starts after a later record's does not drag the region's start right.
    #[test]
    fn the_edited_start_is_the_minimum_over_all_records() {
        let w = make_writer();
        let cluster = [
            (make_record(&w, 100, &[b"ATTTT", b"A"]), 1),
            (make_record(&w, 102, &[b"T", b"G"]), 1),
        ];

        let edited = extract_edited_region(&cluster).unwrap();
        assert_eq!(edited.start().position_0(), 101);
        assert_eq!(edited.end_excl().unwrap().position_0(), 105);
    }

    /// The position [`normalise_alleles`] splices at must be the one
    /// [`super::cluster::edit_offset`] reports, or the mutation lands outside the window that
    /// [`prepare_cluster`] builds around the edited region.
    #[test]
    fn normalise_alleles_agrees_with_edit_offset() {
        let w = make_writer();
        for alleles in [
            [b"A".as_slice(), b"AT".as_slice()],
            [b"AT", b"A"],
            [b"A", b"T"],
            [b"AT", b"GC"],
            [b"AT", b"AGC"],
            [b"CAGCAGCAG", b"CAGCAGCAGCAG"],
            [b"AAT", b"AAG"],
            // A soft-masked reference yields lowercase alleles; both sides must strip the
            // shared prefix the same way regardless of case.
            [b"a", b"aT"],
            [b"aCg", b"AcgT"],
            [b"at", b"A"],
        ] {
            let record = make_record(&w, 100, &alleles);
            let (pos, ..) = normalise_alleles(100, alleles[0], alleles[1]).unwrap();
            assert_eq!(
                pos - 100,
                edit_offset(&record, 1),
                "alleles {}/{}",
                alleles[0].as_bstr(),
                alleles[1].as_bstr()
            );
        }
    }

    /// A repeat expansion shares far more than the single anchor base.
    #[test]
    fn normalise_alleles_strips_the_entire_shared_prefix() {
        let (pos, reference, alt) = normalise_alleles(100, b"CAGCAGCAG", b"CAGCAGCAGCAG").unwrap();
        assert_eq!(pos, 109);
        assert!(reference.is_empty());
        assert_eq!(alt, b"CAG");
    }

    /// Identical alleles edit nothing and must not be spliced.
    #[test]
    fn normalise_alleles_rejects_an_unedited_record() {
        assert!(normalise_alleles(100, b"ACGT", b"ACGT").is_none());
    }

    /// A 400 base `ACGT` repeat, plus its index, opened as a reference.
    fn acgt_reference(dir: &Path) -> ReferenceReader {
        let path = dir.join("ref.fa");
        let sequence: Vec<u8> = b"ACGT".repeat(100);
        let mut fasta = b">chr1\n".to_vec();
        for line in sequence.chunks(80) {
            fasta.extend_from_slice(line);
            fasta.push(b'\n');
        }
        std::fs::write(&path, fasta).unwrap();
        faidx::build(&path).unwrap();
        ReferenceReader::try_from(&CliReferenceArg::from(path.to_str().unwrap())).unwrap()
    }

    /// The aligned window covers the edited region, not the POS-based extent of the records.
    ///
    /// The deletion below removes the `C` at 101, which is exactly the base the `reads`
    /// subcommand's `1D` covers, so both subcommands align the same window.
    #[tokio::test(flavor = "multi_thread")]
    async fn the_aligned_window_starts_at_the_edited_region() {
        let dir = tempfile::tempdir().unwrap();
        let reference = acgt_reference(dir.path());
        let w = make_writer();
        let cluster = [
            (make_record(&w, 100, &[b"AC", b"A"]), 1),
            (make_record(&w, 105, &[b"C", b"G"]), 1),
        ];

        let prepared = prepare_cluster(&reference, &cluster, &no_flanks(), 10, 0)
            .await
            .unwrap()
            .unwrap();

        assert_eq!(prepared.region.to_string(), "chr1:102-106");
        assert_eq!(prepared.vcf_region.to_string(), "chr1:101-106");
        // The window is the edited region plus ten bases on either side.
        assert_eq!(prepared.reference_region.to_string(), "chr1:92-116");
        assert_eq!(prepared.query.sequences.reference.len(), 25);
        // One base is deleted, so the alt sequence is one shorter.
        assert_eq!(prepared.query.sequences.query.len(), 24);

        let ranges = &prepared.query.ranges;
        assert_eq!(ranges.reference_offset(), 10);
        assert_eq!(ranges.reference_limit(), 15);
        assert_eq!(ranges.query_offset(), 10);
        assert_eq!(ranges.query_limit(), 14);
    }

    /// A lone insertion edits no reference base at all. The `reads` subcommand builds the same
    /// zero-width region from an `I` operation, so the window must be zero-width here too.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_lone_insertion_yields_a_zero_width_window() {
        let dir = tempfile::tempdir().unwrap();
        let reference = acgt_reference(dir.path());
        let w = make_writer();
        let cluster = [(make_record(&w, 100, &[b"A", b"ATTT"]), 1)];

        let prepared = prepare_cluster(&reference, &cluster, &no_flanks(), 10, 0)
            .await
            .unwrap()
            .unwrap();

        assert_eq!(prepared.region.len(), Some(0));
        // A zero-length interval, and the only region string samtools cannot be handed back.
        assert_eq!(prepared.region.to_string(), "chr1:102-101");
        assert_eq!(prepared.reference_region.to_string(), "chr1:92-111");
        assert_eq!(prepared.query.sequences.reference.len(), 20);
        assert_eq!(prepared.query.sequences.query.len(), 23);

        let ranges = &prepared.query.ranges;
        assert_eq!(ranges.reference_offset(), 10);
        assert_eq!(ranges.reference_limit(), 10);
        assert_eq!(ranges.query_offset(), 10);
        assert_eq!(ranges.query_limit(), 13);
    }

    /// A zero-width window with no padding has no sequence to align. That must fail this one
    /// cluster with an error, not abort the process inside htslib.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_zero_width_window_without_padding_fails_the_cluster() {
        let dir = tempfile::tempdir().unwrap();
        let reference = acgt_reference(dir.path());
        let w = make_writer();
        let cluster = [(make_record(&w, 100, &[b"A", b"ATTT"]), 1)];

        assert!(
            prepare_cluster(&reference, &cluster, &no_flanks(), 0, 0)
                .await
                .is_err()
        );
    }

    /// An SNV cluster at 105 with 20 bases of context and no range extension, next to `flanks`.
    /// The reference is `ACGT` repeated, so the window `[85, 126)` starts with `C`.
    async fn prepare_with_flanks(
        flanks: &[Arc<InputRecord>],
        haplo: Haplotype,
        phaseset: Option<i32>,
    ) -> super::PreparedCluster {
        let dir = tempfile::tempdir().unwrap();
        let reference = acgt_reference(dir.path());
        let w = make_writer();
        let cluster = [(make_record(&w, 105, &[b"C", b"G"]), 1)];
        let flanks = SubClusterFlanks {
            records: flanks,
            haplo,
            phaseset,
        };
        prepare_cluster(&reference, &cluster, &flanks, 20, 0)
            .await
            .unwrap()
            .unwrap()
    }

    /// A hom insertion on the left is applied and shifts the query side of the range.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_applied_left_insertion_shifts_the_query_range() {
        let w = make_writer();
        let flank = make_record_gt(&w, 90, &[b"G", b"GTT"], HOM_ALT, None);
        let prepared = prepare_with_flanks(&[flank], Haplotype::H0, None).await;

        let seqs = &prepared.query.sequences;
        assert_eq!(seqs.reference.len(), 41);
        assert_eq!(seqs.query.len(), 43);
        assert_eq!(&seqs.query[5..8], b"GTT");
        let ranges = &prepared.query.ranges;
        assert_eq!(
            (ranges.reference_offset(), ranges.reference_limit()),
            (20, 21)
        );
        assert_eq!((ranges.query_offset(), ranges.query_limit()), (22, 23));
        assert!(prepared.unknown_flanks.is_empty());
    }

    /// A hom deletion on the right is applied and does not move the range.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_applied_right_deletion_shortens_the_alt_after_the_range() {
        let w = make_writer();
        let flank = make_record_gt(&w, 115, &[b"TACG", b"T"], HOM_ALT, None);
        let prepared = prepare_with_flanks(&[flank], Haplotype::H0, None).await;

        assert_eq!(prepared.query.sequences.query.len(), 38);
        let ranges = &prepared.query.ranges;
        assert_eq!((ranges.query_offset(), ranges.query_limit()), (20, 21));
    }

    /// An unphased het flank is left as reference, and its span is reported in query coordinates.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_unphased_het_flank_is_left_as_reference() {
        let w = make_writer();
        let flanks = [
            make_record_gt(&w, 90, &[b"G", b"GTT"], HOM_ALT, None),
            make_record_gt(&w, 115, &[b"T", b"A"], UNPHASED_HET, None),
        ];
        let prepared = prepare_with_flanks(&flanks, Haplotype::H0, None).await;

        assert_eq!(prepared.query.sequences.query[32], b'T');
        assert_eq!(prepared.unknown_flanks.len(), 1);
        assert_eq!(prepared.unknown_flanks[0], 32..33);
    }

    /// Only a flank in the sub-cluster's own input phase set is applied, by haplotype slot.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_phased_flank_is_applied_on_its_haplotype_only() {
        use GenotypeAllele::Phased;
        let w = make_writer();
        let flanks = [
            make_record_gt(&w, 95, &[b"T", b"A"], [Phased(1), Phased(0)], Some(7)),
            make_record_gt(&w, 115, &[b"T", b"A"], [Phased(0), Phased(1)], Some(7)),
        ];

        let h0 = prepare_with_flanks(&flanks, Haplotype::H0, Some(7)).await;
        assert_eq!(
            (h0.query.sequences.query[10], h0.query.sequences.query[30]),
            (b'A', b'T')
        );
        assert!(h0.unknown_flanks.is_empty());

        let h1 = prepare_with_flanks(&flanks, Haplotype::H1, Some(7)).await;
        assert_eq!(
            (h1.query.sequences.query[10], h1.query.sequences.query[30]),
            (b'T', b'A')
        );

        // A phase set that did not come from the input never matches.
        let synthetic = prepare_with_flanks(&flanks, Haplotype::H0, None).await;
        assert_eq!(synthetic.unknown_flanks, [10..11, 30..31]);
    }

    /// Flanks that cannot be applied are left as reference instead of failing the cluster.
    #[tokio::test(flavor = "multi_thread")]
    async fn flanks_that_cannot_be_applied_never_fail_the_cluster() {
        let w = make_writer();
        let flanks = [
            // Starts before the window [85, 126).
            make_record_gt(&w, 80, &[b"ACGTACGT", b"A"], HOM_ALT, None),
            // Overlaps the flank before it.
            make_record_gt(&w, 95, &[b"TACG", b"T"], HOM_ALT, None),
            make_record_gt(&w, 96, &[b"A", b"C"], HOM_ALT, None),
            // Touches the alignment range [105, 106).
            make_record_gt(&w, 104, &[b"A", b"G"], HOM_ALT, None),
            // Symbolic.
            make_record_gt(&w, 110, &[b"G", b"<DEL>"], HOM_ALT, None),
        ];
        let prepared = prepare_with_flanks(&flanks, Haplotype::H0, None).await;

        // Only the deletion at 95 is applied: three bases shorter.
        assert_eq!(prepared.query.sequences.query.len(), 38);
        assert_eq!(prepared.unknown_flanks, [0..3, 11..11, 16..17, 22..23]);
    }
}