gen-models 0.2.2

Models for the gen sequence graph and version control system.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
use std::path::{Path, PathBuf};

use gen_core::{
    DoltHashId, HashId, NodeIntervalBlock, Sha256Hash, calculate_hash,
    config::Workspace,
    region::{Region, RegionResolutionError, RegionResolver},
    traits::Capnp,
};
use intervaltree::IntervalTree;
use rusqlite::{Result as SqlResult, Row, params, types::Type};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
    Direction, ModelSelect, ModelSelectError,
    accession::{Accession, AccessionError, AccessionSelect, AccessionSpan, NewAccession},
    assets::{AssetRef, AssetRole, OperationKind},
    db::{DbContext, GraphConnection, max_rows_per_batch},
    errors::{FileAdditionError, OperationError},
    file_types::FileTypes,
    gen_models_capnp::{annotation, annotation_group, annotation_group_sample},
    history::{HistoryStore, dolt::DoltHistoryStore},
    operations::{FileAddition, OperationFile, OperationInfo, OperationSummary, track_asset_refs},
    region::GenRegionError,
    select::query_models,
};
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
#[model_select(table = "annotation_groups")]
pub struct AnnotationGroup {
    #[model_select(primary_key)]
    pub name: String,
}

impl AnnotationGroup {
    pub fn create(conn: &GraphConnection, name: &str) -> rusqlite::Result<AnnotationGroup> {
        let mut stmt = conn
            .prepare("INSERT INTO annotation_groups (name) VALUES (?1) returning (name);")
            .unwrap();
        stmt.query_row((name,), |row| Ok(AnnotationGroup { name: row.get(0)? }))
    }

    pub fn get_or_create(
        conn: &GraphConnection,
        name: &str,
    ) -> Result<AnnotationGroup, AnnotationGroupError> {
        let mut statement = conn.prepare(
            "INSERT INTO annotation_groups (name) VALUES (?1) ON CONFLICT(name) DO NOTHING;",
        )?;
        statement.execute(params![name])?;
        Ok(AnnotationGroup {
            name: name.to_string(),
        })
    }

    pub fn query_by_sample(
        conn: &GraphConnection,
        sample_name: &str,
        history_ref: Option<&str>,
    ) -> Vec<AnnotationGroup> {
        let samples = AnnotationGroupSample::select(conn)
            .sample_name(sample_name)
            .with_ref(history_ref);
        AnnotationGroup::select(conn)
            .join_filtered_on(
                AnnotationGroupSelect::Name,
                AnnotationGroupSampleSelect::AnnotationGroup,
                samples,
            )
            .order_by(AnnotationGroupSelect::Name, Direction::Asc)
            .load()
            .expect("should load annotation groups for sample")
    }
}

impl<'a> Capnp<'a> for AnnotationGroup {
    type Builder = annotation_group::Builder<'a>;
    type Reader = annotation_group::Reader<'a>;

    fn write_capnp(&self, builder: &mut Self::Builder) {
        builder.set_name(&self.name);
    }

    fn read_capnp(reader: Self::Reader) -> Self {
        AnnotationGroup {
            name: reader.get_name().unwrap().to_string().unwrap(),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
#[model_select(table = "annotations", from_row = annotation_from_row)]
pub struct Annotation {
    pub id: HashId,
    pub name: String,
    #[model_select(column = "annotation_group")]
    pub group: String,
    pub accession_id: HashId,
    #[model_select(skip)]
    pub extra: Option<AnnotationExtra>,
}

fn annotation_from_row(row: &Row) -> SqlResult<Annotation> {
    Ok(Annotation {
        id: row.get(0)?,
        name: row.get(1)?,
        group: row.get(2)?,
        accession_id: row.get(3)?,
        extra: deserialize_annotation_extra(row.get(4)?).map_err(|error| {
            rusqlite::Error::FromSqlConversionFailure(4, Type::Text, Box::new(error))
        })?,
    })
}

/// For use with create/bulk_create methods.
#[derive(Clone, Debug)]
pub struct NewAnnotation<'a> {
    /// User-facing annotation name.
    pub name: &'a str,
    /// Accession covered by this annotation.
    pub accession_id: HashId,
    /// Format-specific annotation metadata.
    pub extra: Option<&'a AnnotationExtra>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct AnnotationExtra {
    pub genbank: Option<GenBankExtra>,
    pub gff: Option<GffExtra>,
    pub bed: Option<BedExtra>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct GenBankExtra {
    pub kind: String,
    pub qualifiers: Vec<GenBankQualifier>,
    pub location_operator: Option<GenBankLocationOperator>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct GenBankQualifier {
    pub key: String,
    pub value: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum GenBankLocationOperator {
    Join,
    Order,
    Bond,
    OneOf,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct GffExtra {
    pub source: Option<String>,
    pub ty: String,
    pub score: Option<String>,
    pub phase: Option<String>,
    pub attributes: Vec<GffAttribute>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct GffAttribute {
    pub key: String,
    pub values: Vec<String>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct BedExtra {
    pub score: Option<String>,
    pub thick_start: Option<i64>,
    pub thick_end: Option<i64>,
    pub item_rgb: Option<String>,
    pub block_count: Option<u64>,
    pub block_sizes: Option<Vec<i64>>,
    pub block_starts: Option<Vec<i64>>,
    pub other_fields: Vec<String>,
}

fn serialize_annotation_extra(extra: Option<&AnnotationExtra>) -> Result<String, AnnotationError> {
    serde_json::to_string(extra.unwrap_or(&AnnotationExtra::default()))
        .map_err(|err| AnnotationError::SerializationError(err.to_string()))
}

fn deserialize_annotation_extra(
    value: Option<String>,
) -> Result<Option<AnnotationExtra>, AnnotationError> {
    value
        .map(|value| serde_json::from_str(&value))
        .transpose()
        .map(|value| value.filter(|extra| extra != &AnnotationExtra::default()))
        .map_err(|err| AnnotationError::SerializationError(err.to_string()))
}

impl<'a> Capnp<'a> for Annotation {
    type Builder = annotation::Builder<'a>;
    type Reader = annotation::Reader<'a>;

    fn write_capnp(&self, builder: &mut Self::Builder) {
        builder.set_id(&self.id.0).unwrap();
        builder.set_name(&self.name);
        builder.set_annotation_group(&self.group);
        builder.set_accession_id(&self.accession_id.0).unwrap();
        builder.set_extra(
            serialize_annotation_extra(self.extra.as_ref())
                .unwrap_or_default()
                .as_str(),
        );
    }

    fn read_capnp(reader: Self::Reader) -> Self {
        let id = reader
            .get_id()
            .unwrap()
            .as_slice()
            .unwrap()
            .try_into()
            .unwrap();
        let name = reader.get_name().unwrap().to_string().unwrap();
        let group = reader.get_annotation_group().unwrap().to_string().unwrap();
        let accession_id = reader
            .get_accession_id()
            .unwrap()
            .as_slice()
            .unwrap()
            .try_into()
            .unwrap();
        let extra = deserialize_annotation_extra(
            reader
                .get_extra()
                .ok()
                .map(|value| value.to_string().unwrap())
                .filter(|value| !value.is_empty()),
        )
        .unwrap_or(None);

        Annotation {
            id,
            name,
            group,
            accession_id,
            extra,
        }
    }
}

#[derive(Debug, Error, PartialEq)]
pub enum AnnotationError {
    #[error("Database error: {0}")]
    DatabaseError(#[from] rusqlite::Error),
    #[error("Selector error: {0}")]
    ModelSelect(#[from] ModelSelectError),
    #[error("Annotation group error: {0}")]
    AnnotationGroupError(#[from] AnnotationGroupError),
    #[error("Accession error: {0}")]
    AccessionError(#[from] AccessionError),
    #[error("Annotation extra serialization error: {0}")]
    SerializationError(String),
}

#[derive(Debug, Error)]
pub enum AddAnnotationError {
    #[error("Region parse error: {0}")]
    RegionParse(#[from] gen_core::region::RegionParseError),
    #[error("Region resolution error: {0}")]
    RegionResolution(#[from] GenRegionError),
    #[error("Accession error: {0}")]
    Accession(#[from] AccessionError),
    #[error("Annotation error: {0}")]
    Annotation(#[from] AnnotationError),
}

impl Annotation {
    pub fn generate_id(name: &str, group: &str, accession_id: &HashId) -> HashId {
        HashId(calculate_hash(&format!("{name}:{group}:{accession_id}",)))
    }

    pub fn create(
        conn: &GraphConnection,
        group: &str,
        annotation: &NewAnnotation<'_>,
    ) -> Result<Annotation, AnnotationError> {
        let id = Annotation::generate_id(annotation.name, group, &annotation.accession_id);
        let query = "INSERT INTO annotations (id, name, annotation_group, accession_id, extra) VALUES (?1, ?2, ?3, ?4, ?5);";
        let mut stmt = conn.prepare(query)?;
        let extra_json = serialize_annotation_extra(annotation.extra)?;
        stmt.execute(params![
            id,
            annotation.name,
            group,
            annotation.accession_id,
            extra_json
        ])?;
        Ok(Annotation {
            id,
            name: annotation.name.to_string(),
            group: group.to_string(),
            accession_id: annotation.accession_id,
            extra: annotation.extra.cloned(),
        })
    }

    pub fn get_or_create(
        conn: &GraphConnection,
        name: &str,
        group: &str,
        accession_id: &HashId,
        extra: Option<&AnnotationExtra>,
    ) -> Result<Annotation, AnnotationError> {
        AnnotationGroup::get_or_create(conn, group)?;
        let id = Annotation::generate_id(name, group, accession_id);
        let mut statement = conn.prepare(
            "INSERT INTO annotations (id, name, annotation_group, accession_id, extra) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(accession_id, annotation_group, name) DO NOTHING;",
        )?;
        let extra_json = serialize_annotation_extra(extra)?;
        statement.execute(params![id, name, group, accession_id, extra_json])?;
        Ok(Annotation {
            id,
            name: name.to_string(),
            group: group.to_string(),
            accession_id: *accession_id,
            extra: extra.cloned(),
        })
    }

    /// Creates annotations for one group, preserving existing rows with matching identities.
    pub fn bulk_create(
        conn: &GraphConnection,
        group: &str,
        annotations: &[NewAnnotation<'_>],
    ) -> Result<(), AnnotationError> {
        if annotations.is_empty() {
            return Ok(());
        }

        AnnotationGroup::get_or_create(conn, group)?;
        let batch_size = max_rows_per_batch(conn, 5);
        for annotation_batch in annotations.chunks(batch_size) {
            let mut rows = Vec::with_capacity(annotation_batch.len());
            let mut parameters: Vec<Box<dyn rusqlite::ToSql>> =
                Vec::with_capacity(annotation_batch.len() * 5);
            for annotation in annotation_batch {
                parameters.push(Box::new(Annotation::generate_id(
                    annotation.name,
                    group,
                    &annotation.accession_id,
                )));
                parameters.push(Box::new(annotation.name.to_string()));
                parameters.push(Box::new(group.to_string()));
                parameters.push(Box::new(annotation.accession_id));
                parameters.push(Box::new(serialize_annotation_extra(annotation.extra)?));
                rows.push("(?, ?, ?, ?, ?)");
            }
            let query = format!(
                "INSERT INTO annotations (id, name, annotation_group, accession_id, extra) VALUES {} ON CONFLICT(accession_id, annotation_group, name) DO NOTHING;",
                rows.join(",")
            );
            conn.execute(&query, rusqlite::params_from_iter(parameters))?;
        }
        Ok(())
    }

    pub fn create_with_samples(
        conn: &GraphConnection,
        name: &str,
        group: &str,
        accession_id: &HashId,
        extra: Option<&AnnotationExtra>,
        sample_names: &[&str],
    ) -> Result<Annotation, AnnotationError> {
        let annotation = Annotation::get_or_create(conn, name, group, accession_id, extra)?;
        annotation.add_samples(conn, sample_names)?;
        Ok(annotation)
    }

    pub fn add_samples(
        &self,
        conn: &GraphConnection,
        sample_names: &[&str],
    ) -> Result<(), AnnotationError> {
        if sample_names.is_empty() {
            return Ok(());
        }
        AnnotationGroup::get_or_create(conn, &self.group)?;
        let query = "INSERT INTO annotation_group_samples (annotation_group, sample_name) VALUES (?1, ?2) ON CONFLICT(annotation_group, sample_name) DO NOTHING;";
        let mut stmt = conn.prepare(query)?;
        for sample_name in sample_names {
            stmt.execute(params![self.group, sample_name])?;
        }
        Ok(())
    }

    pub fn get_samples(
        conn: &GraphConnection,
        annotation_group: &str,
    ) -> Result<Vec<String>, AnnotationError> {
        Ok(AnnotationGroupSample::select(conn)
            .annotation_group(annotation_group)
            .only(AnnotationGroupSampleSelect::SampleName)
            .load()?)
    }

    pub fn query_by_sample(
        conn: &GraphConnection,
        sample_name: &str,
        history_ref: Option<&str>,
    ) -> Result<Vec<Annotation>, AnnotationError> {
        let samples = AnnotationGroupSample::select(conn)
            .sample_name(sample_name)
            .with_ref(history_ref);
        Ok(Annotation::select(conn)
            .join_filtered_on(
                AnnotationSelect::Group,
                AnnotationGroupSampleSelect::AnnotationGroup,
                samples,
            )
            .load()?)
    }

    pub fn query_by_group(
        conn: &GraphConnection,
        group: &str,
        history_ref: Option<&str>,
    ) -> Result<Vec<Annotation>, AnnotationError> {
        let select = Annotation::select(conn).group(group).with_ref(history_ref);
        Ok(select.load()?)
    }

    pub fn query_by_group_and_block_group(
        conn: &GraphConnection,
        group: &str,
        block_group_id: &HashId,
        history_ref: Option<&str>,
    ) -> Result<Vec<Annotation>, AnnotationError> {
        let accessions = Accession::select(conn)
            .block_group_id(*block_group_id)
            .with_ref(history_ref);
        Ok(Annotation::select(conn)
            .group(group)
            .join_filtered_on(
                AnnotationSelect::AccessionId,
                AccessionSelect::Id,
                accessions,
            )
            .load()?)
    }

    /// List every annotation on a block group, following the sample lineage.
    ///
    /// Collects annotations attached to the block group named `block_group_name`
    /// in `collection_name`, considering `sample_name` together with all of its
    /// ancestor samples. This mirrors how a block group inherits its parents'
    /// annotations. Results are de-duplicated by annotation id and ordered from
    /// the closest sample in the lineage outward. Two annotations that share a
    /// name but come from different samples (e.g. a parent and child both
    /// annotating "mreB") are both included, since each is a distinct
    /// annotation record; unlike [`RegionResolver::resolve`], this is a listing
    /// operation and does not need to disambiguate by name.
    ///
    /// # Arguments
    ///
    /// * `collection_name` - Collection the block group belongs to.
    /// * `sample_name` - Sample whose lineage is walked, including the sample
    ///   itself.
    /// * `block_group_name` - Name shared by the block group across the lineage.
    ///
    /// # Errors
    ///
    /// Returns [`AnnotationError::DatabaseError`] if the query fails.
    pub fn query_with_lineage(
        conn: &GraphConnection,
        collection_name: &str,
        sample_name: &str,
        block_group_name: &str,
    ) -> Result<Vec<Annotation>, AnnotationError> {
        let query = "WITH RECURSIVE visible_samples(name, depth, path) AS (
                 SELECT ?2, 0, ',' || ?2 || ','
                 UNION ALL
                 SELECT sl.parent_sample_name,
                        visible.depth + 1,
                        visible.path || sl.parent_sample_name || ','
                 FROM sample_lineage sl
                 JOIN visible_samples visible ON sl.child_sample_name = visible.name
                 WHERE instr(visible.path, ',' || sl.parent_sample_name || ',') = 0
             )
             SELECT a.id,
                    a.name,
                    a.annotation_group,
                    a.accession_id,
                    a.extra \
             FROM annotations a \
             JOIN accessions acc ON a.accession_id = acc.id \
             JOIN block_groups bg ON acc.block_group_id = bg.id \
             JOIN visible_samples visible ON bg.sample_name = visible.name \
             WHERE bg.collection_name = ?1 \
               AND bg.name = ?3
             GROUP BY a.id, a.name, a.annotation_group, a.accession_id, a.extra
             ORDER BY min(visible.depth), a.name, a.id";
        Ok(query_models::<Annotation, _>(
            conn,
            query,
            params![collection_name, sample_name, block_group_name],
        )?)
    }

    pub fn intervaltree(
        &self,
        conn: &GraphConnection,
    ) -> Result<IntervalTree<i64, NodeIntervalBlock>, AnnotationError> {
        let accession = Accession::select(conn)
            .id(self.accession_id)
            .load()?
            .into_iter()
            .next()
            .ok_or(rusqlite::Error::QueryReturnedNoRows)?;
        accession.intervaltree(conn).map_err(Into::into)
    }
}

impl RegionResolver for Annotation {
    type Connection = GraphConnection;
    type Error = AnnotationError;

    fn resolve(
        region: &Region,
        conn: &Self::Connection,
        collection_name: &str,
        sample_name: &str,
    ) -> Result<Self, RegionResolutionError<Self::Error>> {
        let matches = query_models::<Annotation, _>(
            conn,
            "WITH RECURSIVE visible_samples(name, depth, path) AS (
                 SELECT ?2, 0, ',' || ?2 || ','
                 UNION ALL
                 SELECT sl.parent_sample_name,
                        visible.depth + 1,
                        visible.path || sl.parent_sample_name || ','
                 FROM sample_lineage sl
                 JOIN visible_samples visible ON sl.child_sample_name = visible.name
                 WHERE instr(visible.path, ',' || sl.parent_sample_name || ',') = 0
             ),
             matching_annotations AS (
                 SELECT a.id,
                        a.name,
                        a.annotation_group,
                        a.accession_id,
                        a.extra,
                        min(visible.depth) AS depth \
                 FROM annotations a \
                 JOIN accessions acc ON a.accession_id = acc.id \
                 JOIN block_groups bg ON acc.block_group_id = bg.id \
                 JOIN visible_samples visible ON bg.sample_name = visible.name \
                 WHERE bg.collection_name = ?1 \
                   AND lower(a.name) = lower(?3)
                 GROUP BY a.id, a.name, a.annotation_group, a.accession_id, a.extra
             )
             SELECT id, name, annotation_group, accession_id, extra \
             FROM matching_annotations \
             WHERE depth = (SELECT min(depth) FROM matching_annotations)",
            params![collection_name, sample_name, region.name],
        )
        .map_err(AnnotationError::from)?;

        match matches.len() {
            0 => Err(RegionResolutionError::NotFound(region.name.clone())),
            1 => Ok(matches.into_iter().next().unwrap()),
            _ => Err(RegionResolutionError::Ambiguous(format!(
                "multiple annotations named {}",
                region.name
            ))),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
#[model_select(
    table = "annotation_group_samples",
    default_sort(annotation_group = "asc", sample_name = "asc")
)]
pub struct AnnotationGroupSample {
    #[model_select(primary_key)]
    pub annotation_group: String,
    #[model_select(primary_key)]
    pub sample_name: String,
}

impl<'a> Capnp<'a> for AnnotationGroupSample {
    type Builder = annotation_group_sample::Builder<'a>;
    type Reader = annotation_group_sample::Reader<'a>;

    fn write_capnp(&self, builder: &mut Self::Builder) {
        builder.set_annotation_group(&self.annotation_group);
        builder.set_sample_name(&self.sample_name);
    }

    fn read_capnp(reader: Self::Reader) -> Self {
        let annotation_group = reader.get_annotation_group().unwrap().to_string().unwrap();
        let sample_name = reader.get_sample_name().unwrap().to_string().unwrap();
        AnnotationGroupSample {
            annotation_group,
            sample_name,
        }
    }
}

impl AnnotationGroupSample {
    pub fn create(
        conn: &GraphConnection,
        annotation_group: &str,
        sample_name: &str,
    ) -> Result<(), AnnotationError> {
        AnnotationGroup::get_or_create(conn, annotation_group)?;
        let query = "INSERT INTO annotation_group_samples (annotation_group, sample_name) VALUES (?1, ?2) ON CONFLICT(annotation_group, sample_name) DO NOTHING;";
        let mut stmt = conn.prepare(query)?;
        stmt.execute(params![annotation_group, sample_name])?;
        Ok(())
    }

    pub fn delete(
        conn: &GraphConnection,
        annotation_group: &str,
        sample_name: &str,
    ) -> Result<(), AnnotationError> {
        let query = "DELETE FROM annotation_group_samples WHERE annotation_group = ?1 AND sample_name = ?2;";
        let mut stmt = conn.prepare(query)?;
        stmt.execute(params![annotation_group, sample_name])?;
        Ok(())
    }
}

#[derive(Debug, Error, PartialEq)]
pub enum AnnotationGroupError {
    #[error("Database error: {0}")]
    DatabaseError(#[from] rusqlite::Error),
}

#[derive(Debug, Error)]
pub enum AnnotationFileError {
    #[error("Database error: {0}")]
    DatabaseError(#[from] rusqlite::Error),
    #[error("File addition error: {0}")]
    FileAdditionError(#[from] FileAdditionError),
    #[error("Operation error: {0}")]
    OperationError(#[from] OperationError),
    #[error(
        "Unable to detect annotation file format from the file extension. Use --format to specify it explicitly."
    )]
    MissingFileExtension,
    #[error("Unsupported annotation file type: {0}")]
    UnsupportedFileType(String),
}

pub fn parse_annotation_file_type(value: &str) -> Result<FileTypes, AnnotationFileError> {
    match value.trim().to_ascii_lowercase().as_str() {
        "gff3" | "gff" => Ok(FileTypes::Gff3),
        "bed" => Ok(FileTypes::Bed),
        "genbank" | "gb" => Ok(FileTypes::GenBank),
        other => Err(AnnotationFileError::UnsupportedFileType(other.to_string())),
    }
}

pub fn annotation_file_extension(path: &str) -> Option<String> {
    let path = Path::new(path);
    let mut ext = path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_ascii_lowercase());
    if matches!(ext.as_deref(), Some("gz") | Some("bgz")) {
        ext = path
            .file_stem()
            .and_then(|stem| stem.to_str())
            .and_then(|stem| Path::new(stem).extension().and_then(|ext| ext.to_str()))
            .map(|ext| ext.to_ascii_lowercase());
    }
    ext
}

pub fn annotation_index_file_path(
    workspace: &Workspace,
    path: &str,
    explicit_index_path: Option<&str>,
) -> Option<String> {
    if let Some(index_path) = explicit_index_path {
        return Some(index_path.to_string());
    }

    let mut candidates = vec![format!("{path}.tbi")];
    let path_buf = PathBuf::from(path);
    if let Some(extension) = path_buf.extension().and_then(|ext| ext.to_str()) {
        let mut extension_candidate = path_buf.clone();
        extension_candidate.set_extension(format!("{extension}.tbi"));
        let extension_candidate = extension_candidate.to_string_lossy().to_string();
        if !candidates
            .iter()
            .any(|candidate| candidate == &extension_candidate)
        {
            candidates.push(extension_candidate);
        }
    }

    for candidate in candidates {
        let exists = if Path::new(&candidate).is_absolute() {
            Path::new(&candidate).exists()
        } else {
            workspace
                .repo_root()
                .ok()
                .is_some_and(|repo_root| repo_root.join(&candidate).exists())
        };
        if exists {
            return Some(candidate);
        }
    }

    None
}

pub fn add_annotation(
    context: &DbContext,
    collection: &str,
    name: &str,
    group: Option<&str>,
    sample: &str,
    region: &str,
) -> Result<OperationSummary, AddAnnotationError> {
    let graph_conn = context.graph().conn();
    let parsed_region = Region::parse(region)?;
    let resolved_region = crate::region::resolve(&parsed_region, graph_conn, collection, sample)?;
    let spans = AccessionSpan::from_resolved_region(
        graph_conn,
        context.workspace(),
        &resolved_region,
        None,
    )?;

    let accession = Accession::get_or_create(
        graph_conn,
        &NewAccession {
            name: name.to_string(),
            block_group_id: resolved_region.block_group.id,
            parent_accession_id: None,
            spans,
        },
    )?;

    let annotation_group = group.unwrap_or("default");
    let annotation =
        Annotation::get_or_create(graph_conn, name, annotation_group, &accession.id, None)?;
    AnnotationGroupSample::create(graph_conn, &annotation.group, sample)?;

    Ok(OperationSummary::new(
        OperationInfo {
            files: vec![],
            description: format!("add annotation {name}"),
        },
        format!("add annotation {name}"),
    ))
}

/// Optional content checksums collected while annotation assets were already being streamed.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct AnnotationFileChecksumOverrides {
    /// Checksum of the annotation file.
    pub annotation: Option<Sha256Hash>,
    /// Checksum of the annotation index.
    pub index: Option<Sha256Hash>,
}

/// Adds an annotation asset and optional index to operation history.
///
/// Callers pass checksums only when the corresponding remote streams were already consumed for
/// annotation work. This keeps operation creation independent of remote credentials while local
/// assets are retained and hashed during preparation.
pub fn add_annotation_file(
    context: &DbContext,
    path: &str,
    format: Option<&str>,
    index: Option<&str>,
    name: Option<&str>,
    message: Option<&str>,
    checksum_overrides: AnnotationFileChecksumOverrides,
) -> Result<DoltHashId, AnnotationFileError> {
    let workspace = context.workspace();
    let graph_conn = context.graph().conn();

    let file_type = match format {
        Some(format) => parse_annotation_file_type(format)?,
        None => {
            let ext =
                annotation_file_extension(path).ok_or(AnnotationFileError::MissingFileExtension)?;
            parse_annotation_file_type(&ext)?
        }
    };
    let file_addition =
        FileAddition::prepare(workspace, path, file_type, checksum_overrides.annotation)?;
    let annotation_logical_path =
        OperationFile::storage_file_path(workspace, path, file_addition.checksum.as_ref())?;
    let prepared_index =
        if let Some(index_path) = annotation_index_file_path(workspace, path, index) {
            let index_file_type = FileTypes::infer_from_path(&index_path);
            let file_addition = FileAddition::prepare(
                workspace,
                &index_path,
                index_file_type,
                checksum_overrides.index,
            )?;
            let logical_path = OperationFile::storage_file_path(
                workspace,
                &index_path,
                file_addition.checksum.as_ref(),
            )?;
            let name = Path::new(&index_path)
                .file_name()
                .and_then(|value| value.to_str())
                .map(str::to_string);
            Some((file_addition, logical_path, name))
        } else {
            None
        };
    let name = name.or_else(|| Path::new(path).file_name().and_then(|value| value.to_str()));
    let name_value = name.unwrap_or_default();
    let annotation_asset_ref_id = AssetRef::id_hash(
        &file_addition.asset_uri,
        file_addition.file_type.as_str(),
        file_addition.checksum.as_ref(),
        &AssetRole::Annotation,
        Some(&annotation_logical_path),
        name,
        None,
    );
    let index_file_addition_id = prepared_index
        .as_ref()
        .map(|(index_file, _, _)| index_file.id.to_string())
        .unwrap_or_default();
    let log_id = HashId(calculate_hash(&format!(
        "{file_addition_id}:{name_value}:{index_file_addition_id}",
        file_addition_id = file_addition.id
    )));
    let summary = message
        .map(str::to_string)
        .unwrap_or_else(|| format!("Add annotation file {path}"));
    let created_on = chrono::Utc::now()
        .timestamp_nanos_opt()
        .expect("should create annotation asset timestamp");
    let mut tracked_assets = vec![AssetRef::from_file_addition(
        &file_addition,
        AssetRole::Annotation,
        Some(&annotation_logical_path),
        name,
        None,
        created_on,
    )];
    if let Some((index_file_addition, index_logical_path, index_name)) = prepared_index.as_ref() {
        tracked_assets.push(AssetRef::from_file_addition(
            index_file_addition,
            AssetRole::AnnotationIndex,
            Some(index_logical_path),
            index_name.as_deref(),
            Some(&annotation_asset_ref_id),
            created_on,
        ));
    }
    track_asset_refs(
        graph_conn,
        Some(&log_id),
        &OperationKind::AnnotationFile,
        &summary,
        &tracked_assets,
    )?;
    let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
    if history_store.status()?.is_empty() {
        return Err(OperationError::NoChanges.into());
    }

    let commit_hash = history_store.commit_all(&summary)?;

    Ok(commit_hash)
}

#[cfg(test)]
mod tests {
    use std::{collections::HashSet, fs};

    use gen_core::{HashId, region::RegionResolutionError};

    use super::*;
    use crate::{
        assets::{AssetRef, AssetRole, OperationAsset, OperationLog},
        block_group::{BlockGroup, PathCache},
        block_group_edge::{BlockGroupEdge, BlockGroupEdgeData},
        errors::OperationError,
        operations::{calculate_reader_checksum, commit_operation_summary},
        path::Path,
        sample::Sample,
        sample_lineage::SampleLineage,
        test_helpers::{create_bg, get_connection, setup_block_group, setup_gen},
    };

    mod region_resolver {
        use super::*;

        #[test]
        fn resolves_annotation_by_name_case_insensitively() {
            let conn = get_connection(None).unwrap();
            let (block_group_id, path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
            let accession =
                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
            let annotation =
                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();

            let region = Region::parse("MREB").unwrap();
            let resolved = Annotation::resolve(&region, &conn, "test", "test").unwrap();
            assert_eq!(resolved.id, annotation.id);
        }

        #[test]
        fn returns_not_found_for_missing_annotation() {
            let conn = get_connection(None).unwrap();
            let (_block_group_id, _path) = setup_block_group(&conn);

            let region = Region::parse("missing").unwrap();
            let err = Annotation::resolve(&region, &conn, "test", "test").unwrap_err();
            assert!(matches!(
                err,
                RegionResolutionError::NotFound(name) if name == "missing"
            ));
        }

        #[test]
        fn returns_ambiguous_for_multiple_matching_annotations() {
            let conn = get_connection(None).unwrap();
            let (block_group_id, path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
            let accession =
                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
            let _ = Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();

            let other_block_group = create_bg(&conn, "test", "test", "other");
            let edge_ids = Path::edges_for_path(&conn, &path.id, None)
                .into_iter()
                .map(|edge| edge.id)
                .collect::<Vec<_>>();
            let block_group_edges = edge_ids
                .iter()
                .map(|edge_id| BlockGroupEdgeData {
                    block_group_id: other_block_group.id,
                    edge_id: *edge_id,
                    chromosome_index: 0,
                    phased: 0,
                })
                .collect::<Vec<_>>();
            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
            let other_path =
                Path::create(&conn, "other-path", &other_block_group.id, &edge_ids).unwrap();
            let other_accession =
                BlockGroup::add_accession(&conn, &other_path, "ann-accession-2", 0, 5, &mut cache)
                    .unwrap();
            let _ = Annotation::get_or_create(&conn, "MREB", "genes", &other_accession.id, None)
                .unwrap();

            let region = Region::parse("mreB").unwrap();
            let err = Annotation::resolve(&region, &conn, "test", "test").unwrap_err();
            assert!(matches!(
                err,
                RegionResolutionError::Ambiguous(name) if name == "multiple annotations named mreB"
            ));
        }

        #[test]
        fn resolves_closest_annotation_in_sample_lineage() {
            let conn = get_connection(None).unwrap();
            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
                .unwrap();
            let parent_accession = BlockGroup::add_accession(
                &conn,
                &parent_path,
                "parent-accession",
                0,
                5,
                &mut cache,
            )
            .unwrap();
            let _parent_annotation =
                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
                    .unwrap();

            let child_block_group = create_bg(&conn, "test", "child", "chr1");
            let edge_ids = Path::edges_for_path(&conn, &parent_path.id, None)
                .into_iter()
                .map(|edge| edge.id)
                .collect::<Vec<_>>();
            let block_group_edges = edge_ids
                .iter()
                .map(|edge_id| BlockGroupEdgeData {
                    block_group_id: child_block_group.id,
                    edge_id: *edge_id,
                    chromosome_index: 0,
                    phased: 0,
                })
                .collect::<Vec<_>>();
            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
            let child_path =
                Path::create(&conn, "child-path", &child_block_group.id, &edge_ids).unwrap();
            let child_accession =
                BlockGroup::add_accession(&conn, &child_path, "child-accession", 0, 5, &mut cache)
                    .unwrap();
            let child_annotation =
                Annotation::get_or_create(&conn, "MREB", "genes", &child_accession.id, None)
                    .unwrap();
            SampleLineage::create(&conn, "test", "child").unwrap();

            let region = Region::parse("mreB").unwrap();
            let resolved = Annotation::resolve(&region, &conn, "test", "child").unwrap();

            assert_eq!(resolved.id, child_annotation.id);
        }

        #[test]
        fn falls_back_to_parent_annotation_when_child_has_none() {
            let conn = get_connection(None).unwrap();
            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
                .unwrap();
            let parent_accession = BlockGroup::add_accession(
                &conn,
                &parent_path,
                "parent-only-accession",
                0,
                5,
                &mut cache,
            )
            .unwrap();
            let parent_annotation =
                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
                    .unwrap();

            let child_block_group = create_bg(&conn, "test", "child", "chr1");
            let edge_ids = Path::edges_for_path(&conn, &parent_path.id, None)
                .into_iter()
                .map(|edge| edge.id)
                .collect::<Vec<_>>();
            let block_group_edges = edge_ids
                .iter()
                .map(|edge_id| BlockGroupEdgeData {
                    block_group_id: child_block_group.id,
                    edge_id: *edge_id,
                    chromosome_index: 0,
                    phased: 0,
                })
                .collect::<Vec<_>>();
            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
            let _child_path =
                Path::create(&conn, "child-path", &child_block_group.id, &edge_ids).unwrap();
            SampleLineage::create(&conn, "test", "child").unwrap();

            let region = Region::parse("mreB").unwrap();
            let resolved = Annotation::resolve(&region, &conn, "test", "child").unwrap();

            assert_eq!(resolved.id, parent_annotation.id);
        }
    }

    mod lineage_listing {
        use super::*;

        /// Attach a block group that shares `parent_path`'s edges, give it its
        /// own path and accession, and annotate it. Returns the annotation.
        #[expect(clippy::too_many_arguments, reason = "test helper wiring")]
        fn annotate_block_group(
            conn: &GraphConnection,
            parent_path: &Path,
            cache: &mut PathCache,
            collection_name: &str,
            sample_name: &str,
            block_group_name: &str,
            accession_name: &str,
            annotation_name: &str,
        ) -> Annotation {
            let block_group = create_bg(conn, collection_name, sample_name, block_group_name);
            let edge_ids = Path::edges_for_path(conn, &parent_path.id, None)
                .into_iter()
                .map(|edge| edge.id)
                .collect::<Vec<_>>();
            let block_group_edges = edge_ids
                .iter()
                .map(|edge_id| BlockGroupEdgeData {
                    block_group_id: block_group.id,
                    edge_id: *edge_id,
                    chromosome_index: 0,
                    phased: 0,
                })
                .collect::<Vec<_>>();
            BlockGroupEdge::bulk_create(conn, &block_group_edges);
            let path = Path::create(conn, accession_name, &block_group.id, &edge_ids).unwrap();
            let accession =
                BlockGroup::add_accession(conn, &path, accession_name, 0, 5, cache).unwrap();
            Annotation::get_or_create(conn, annotation_name, "genes", &accession.id, None).unwrap()
        }

        #[test]
        fn test_lists_annotations_on_block_group() {
            let conn = get_connection(None).unwrap();
            let (block_group_id, path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
            let accession =
                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
            let annotation =
                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();

            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();

            assert_eq!(listed, vec![annotation]);
        }

        #[test]
        fn test_includes_parent_annotations_via_lineage() {
            let conn = get_connection(None).unwrap();
            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
                .unwrap();
            let parent_accession = BlockGroup::add_accession(
                &conn,
                &parent_path,
                "parent-accession",
                0,
                5,
                &mut cache,
            )
            .unwrap();
            let parent_annotation =
                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
                    .unwrap();

            let child_annotation = annotate_block_group(
                &conn,
                &parent_path,
                &mut cache,
                "test",
                "child",
                "chr1",
                "child-accession",
                "ftsZ",
            );
            SampleLineage::create(&conn, "test", "child").unwrap();

            let listed = Annotation::query_with_lineage(&conn, "test", "child", "chr1").unwrap();

            let ids: HashSet<HashId> = listed.iter().map(|a| a.id).collect();
            assert_eq!(
                ids,
                HashSet::from([parent_annotation.id, child_annotation.id])
            );
        }

        #[test]
        fn test_excludes_annotations_on_other_block_group_names() {
            let conn = get_connection(None).unwrap();
            let (block_group_id, path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
            let accession =
                BlockGroup::add_accession(&conn, &path, "chr1-accession", 0, 5, &mut cache)
                    .unwrap();
            let chr1_annotation =
                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();

            let _chr2_annotation = annotate_block_group(
                &conn,
                &path,
                &mut cache,
                "test",
                "test",
                "chr2",
                "chr2-accession",
                "ftsZ",
            );

            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();

            assert_eq!(listed, vec![chr1_annotation]);
        }

        #[test]
        fn test_excludes_annotations_from_samples_outside_the_lineage() {
            let conn = get_connection(None).unwrap();
            let (block_group_id, path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
            let accession =
                BlockGroup::add_accession(&conn, &path, "test-accession", 0, 5, &mut cache)
                    .unwrap();
            let test_annotation =
                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();

            let _unrelated_annotation = annotate_block_group(
                &conn,
                &path,
                &mut cache,
                "test",
                "unrelated",
                "chr1",
                "unrelated-accession",
                "ftsZ",
            );

            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();

            assert_eq!(listed, vec![test_annotation]);
        }

        #[test]
        fn test_keeps_both_when_parent_and_child_share_an_annotation_name() {
            let conn = get_connection(None).unwrap();
            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
            let mut cache = PathCache::new(&conn);
            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
                .unwrap();
            let parent_accession = BlockGroup::add_accession(
                &conn,
                &parent_path,
                "parent-accession",
                0,
                5,
                &mut cache,
            )
            .unwrap();
            let parent_annotation =
                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
                    .unwrap();

            let child_annotation = annotate_block_group(
                &conn,
                &parent_path,
                &mut cache,
                "test",
                "child",
                "chr1",
                "child-accession",
                "mreB",
            );
            SampleLineage::create(&conn, "test", "child").unwrap();

            let listed = Annotation::query_with_lineage(&conn, "test", "child", "chr1").unwrap();

            // Same name, distinct annotation ids: listing keeps both rather than
            // collapsing by name. `resolve` would pick only the child's here
            // since it's the closer match (depth 0 vs. depth 1) and error on tie.
            assert_eq!(listed, vec![child_annotation, parent_annotation]);
        }
    }

    #[test]
    fn annotation_groups_all_lists_groups_in_name_order() {
        let conn = get_connection(None).unwrap();
        AnnotationGroup::create(&conn, "zebra").unwrap();
        AnnotationGroup::create(&conn, "ant").unwrap();

        let groups = AnnotationGroup::all(&conn).expect("should load annotation groups");

        assert_eq!(
            groups,
            vec![
                AnnotationGroup { name: "ant".into() },
                AnnotationGroup {
                    name: "zebra".into()
                }
            ]
        );
    }

    #[test]
    fn create_annotation_with_samples() {
        let conn = get_connection(None).unwrap();
        let (block_group_id, path) = setup_block_group(&conn);

        let _ = Sample::create(
            &conn,
            crate::sample::NewSample {
                name: "sample-1",
                is_reference: false,
            },
        )
        .unwrap();
        let _ = Sample::create(
            &conn,
            crate::sample::NewSample {
                name: "sample-2",
                is_reference: false,
            },
        )
        .unwrap();

        let mut cache = PathCache::new(&conn);
        let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
        let accession =
            BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();

        let annotations = [NewAnnotation {
            name: "gene-a",
            accession_id: accession.id,
            extra: None,
        }];
        Annotation::bulk_create(&conn, "project-tracks", &annotations).unwrap();
        AnnotationGroupSample::create(&conn, "project-tracks", "sample-1").unwrap();
        AnnotationGroupSample::create(&conn, "project-tracks", "sample-2").unwrap();
        let annotation = Annotation::query_by_group(&conn, "project-tracks", None)
            .unwrap()
            .pop()
            .expect("should create annotation");
        Annotation::bulk_create(&conn, "project-tracks", &annotations).unwrap();

        assert_eq!(
            Annotation::query_by_group(&conn, "project-tracks", None).unwrap(),
            vec![annotation.clone()]
        );

        let mut samples = Annotation::get_samples(&conn, &annotation.group).unwrap();
        samples.sort();
        assert_eq!(
            samples,
            vec!["sample-1".to_string(), "sample-2".to_string()]
        );

        let by_sample = Annotation::query_by_sample(&conn, "sample-1", None).unwrap();
        assert_eq!(by_sample.len(), 1);
        assert_eq!(by_sample[0], annotation);

        let by_group = Annotation::query_by_group(&conn, "project-tracks", None).unwrap();
        assert_eq!(by_group, vec![annotation]);
    }

    #[test]
    fn deserialize_annotation_extra_defaults_missing_fields() {
        // Ensure that if we add new fields to the AnnotationExtra struct, like new_annotation_format we still parse old ones
        let extra = deserialize_annotation_extra(Some(r#"{"genbank":{"kind":"CDS"}}"#.to_string()))
            .unwrap()
            .unwrap();

        assert_eq!(
            extra.genbank,
            Some(GenBankExtra {
                kind: "CDS".to_string(),
                ..GenBankExtra::default()
            })
        );
        assert_eq!(extra.gff, None);
        assert_eq!(extra.bed, None);
    }

    #[test]
    fn deserialize_annotation_extra_ignores_unknown_fields() {
        // ensure if we drop a format, removed_top_level key here, we still parse
        let extra = deserialize_annotation_extra(Some(
            r#"{"genbank":{"kind":"CDS","legacy_field":"value"},"removed_top_level":true}"#
                .to_string(),
        ))
        .unwrap()
        .unwrap();

        assert_eq!(
            extra.genbank,
            Some(GenBankExtra {
                kind: "CDS".to_string(),
                ..GenBankExtra::default()
            })
        );
        assert_eq!(extra.gff, None);
        assert_eq!(extra.bed, None);
    }

    #[test]
    fn deserialize_and_reserialize_annotation_extra_keeps_compatible_fields() {
        // Ensure that if we parse an older field, we can still reserialize it with the compatible fields kept.
        let extra = deserialize_annotation_extra(Some(
            r#"{"genbank":{"kind":"CDS","legacy_field":"value"},"removed_top_level":true}"#
                .to_string(),
        ))
        .unwrap()
        .unwrap();

        let reserialized = serialize_annotation_extra(Some(&extra)).unwrap();
        let reparsed: AnnotationExtra = serde_json::from_str(&reserialized).unwrap();

        assert_eq!(
            reparsed.genbank,
            Some(GenBankExtra {
                kind: "CDS".to_string(),
                ..GenBankExtra::default()
            })
        );
        assert_eq!(reparsed.gff, None);
        assert_eq!(reparsed.bed, None);
    }

    #[test]
    fn parse_annotation_file_type_values() {
        assert_eq!(parse_annotation_file_type("gff3").unwrap(), FileTypes::Gff3);
        assert_eq!(parse_annotation_file_type("GFF").unwrap(), FileTypes::Gff3);
        assert_eq!(parse_annotation_file_type("bed").unwrap(), FileTypes::Bed);
        assert_eq!(
            parse_annotation_file_type("GenBank").unwrap(),
            FileTypes::GenBank
        );
        assert_eq!(
            parse_annotation_file_type("gb").unwrap(),
            FileTypes::GenBank
        );
        let err = parse_annotation_file_type("bam").unwrap_err();
        assert!(matches!(err, AnnotationFileError::UnsupportedFileType(_)));
    }

    #[test]
    fn add_annotation_creates_annotation() {
        let context = setup_gen();
        let graph_conn = context.graph().conn();
        let history_store = DoltHistoryStore::new(graph_conn);
        let _ = setup_block_group(graph_conn);

        let operation_summary = add_annotation(
            &context,
            "test",
            "gene-a",
            Some("track-1"),
            "test",
            "chr1:1-5",
        )
        .unwrap();
        let commit_hash = commit_operation_summary(&context, &operation_summary).unwrap();
        assert_eq!(history_store.current_head().unwrap(), Some(commit_hash));
        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
        operation_logs.sort_by_key(|operation_log| std::cmp::Reverse(operation_log.created_on));
        assert_eq!(
            operation_logs[0].operation_kind,
            OperationKind::Other("add annotation gene-a".to_string())
        );

        let annotations = Annotation::query_by_group(graph_conn, "track-1", None).unwrap();
        assert_eq!(annotations.len(), 1);
        assert_eq!(annotations[0].name, "gene-a");
    }

    #[test]
    fn test_add_annotation_detects_no_changes() {
        let context = setup_gen();
        let graph_conn = context.graph().conn();
        let _ = setup_block_group(graph_conn);

        let operation_summary = add_annotation(
            &context,
            "test",
            "gene-a",
            Some("track-1"),
            "test",
            "chr1:1-5",
        )
        .unwrap();
        commit_operation_summary(&context, &operation_summary).unwrap();

        let operation_summary = add_annotation(
            &context,
            "test",
            "gene-a",
            Some("track-1"),
            "test",
            "chr1:1-5",
        )
        .unwrap();
        let err = commit_operation_summary(&context, &operation_summary).unwrap_err();
        assert_eq!(err, OperationError::NoChanges);
    }

    #[test]
    fn add_annotation_file_creates_operation() {
        let context = setup_gen();
        let graph_conn = context.graph().conn();
        let history_store = DoltHistoryStore::new(graph_conn);

        let repo_root = context.workspace().repo_root().unwrap();
        let annotation_path = repo_root.join("fixtures").join("annotation.gff3");
        fs::create_dir_all(annotation_path.parent().unwrap()).unwrap();
        fs::write(&annotation_path, "##gff-version 3\n").unwrap();
        let annotation_path_str = annotation_path.to_string_lossy().to_string();

        let commit_hash = add_annotation_file(
            &context,
            &annotation_path_str,
            None,
            None,
            Some("track-1"),
            None,
            AnnotationFileChecksumOverrides::default(),
        )
        .unwrap();
        assert_eq!(history_store.current_head().unwrap(), Some(commit_hash));

        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
        asset_refs.sort_by(|left, right| left.role.as_str().cmp(right.role.as_str()));
        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
        operation_logs.sort_by_key(|operation_log| operation_log.created_on);
        assert_eq!(asset_refs.len(), 1);
        assert_eq!(asset_refs[0].role, AssetRole::Annotation);
        assert_eq!(asset_refs[0].name.as_deref(), Some("track-1"));
        assert!(
            asset_refs[0]
                .logical_path
                .as_deref()
                .unwrap_or_default()
                .ends_with("fixtures/annotation.gff3")
        );
        assert_eq!(operation_logs.len(), 1);
        assert_eq!(
            operation_logs[0].operation_kind,
            OperationKind::AnnotationFile
        );
        let operation_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
        assert_eq!(operation_assets.len(), 1);
        assert_eq!(operation_assets[0].role, AssetRole::Annotation);
        assert!(
            history_store
                .log(None)
                .unwrap()
                .iter()
                .any(|entry| entry.commit_hash == commit_hash
                    && entry.message.contains("Add annotation file"))
        );
        let err = add_annotation_file(
            &context,
            &annotation_path_str,
            None,
            None,
            Some("track-1"),
            None,
            AnnotationFileChecksumOverrides::default(),
        )
        .unwrap_err();
        assert!(matches!(
            err,
            AnnotationFileError::OperationError(OperationError::NoChanges)
        ));
    }

    #[test]
    fn test_add_annotation_file_tracks_explicit_non_tabix_index() {
        let context = setup_gen();
        let graph_conn = context.graph().conn();

        let repo_root = context
            .workspace()
            .repo_root()
            .expect("should have repo root");
        let annotation_path = repo_root
            .join("fixtures")
            .join("annotation-with-index.gff3");
        let index_path = repo_root.join("fixtures").join("annotation-with-index.csi");
        fs::create_dir_all(
            annotation_path
                .parent()
                .expect("should have annotation parent directory"),
        )
        .expect("should create fixture directory");
        fs::write(&annotation_path, "##gff-version 3\n").expect("should write annotation fixture");
        fs::write(&index_path, "index").expect("should write index fixture");

        add_annotation_file(
            &context,
            annotation_path
                .to_str()
                .expect("should encode annotation path"),
            None,
            Some(index_path.to_str().expect("should encode index path")),
            Some("track-with-index"),
            None,
            AnnotationFileChecksumOverrides::default(),
        )
        .expect("should create annotation file operation");

        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
        asset_refs.sort_by(|left, right| {
            left.role
                .as_str()
                .cmp(right.role.as_str())
                .then_with(|| left.logical_path.cmp(&right.logical_path))
        });
        assert_eq!(asset_refs.len(), 2);
        assert_eq!(asset_refs[0].role, AssetRole::Annotation);
        assert_eq!(asset_refs[1].role, AssetRole::AnnotationIndex);
        assert_eq!(
            asset_refs[1].upstream_asset_ref_id,
            Some(asset_refs[0].id),
            "annotation index should identify its immutable upstream annotation"
        );
        assert_eq!(
            asset_refs[0].checksum,
            Some(calculate_reader_checksum("##gff-version 3\n".as_bytes()).unwrap())
        );
        assert_eq!(
            asset_refs[1].checksum,
            Some(calculate_reader_checksum("index".as_bytes()).unwrap())
        );
        assert_eq!(asset_refs[1].file_type.as_str(), "none");
        assert_eq!(
            asset_refs[1]
                .logical_path
                .as_deref()
                .expect("should store index logical path"),
            "fixtures/annotation-with-index.csi"
        );
    }

    #[test]
    fn test_add_annotation_file_does_not_read_remote_assets() {
        let context = setup_gen();
        let annotation_uri = "http://127.0.0.1:1/annotation.gff3".to_string();
        let index_uri = "http://127.0.0.1:1/annotation.gff3.csi".to_string();

        add_annotation_file(
            &context,
            &annotation_uri,
            None,
            Some(&index_uri),
            Some("remote-annotation"),
            None,
            AnnotationFileChecksumOverrides::default(),
        )
        .expect("should track remote annotation assets");

        let asset_refs =
            AssetRef::all(context.graph().conn()).expect("should load asset references");
        assert_eq!(asset_refs.len(), 2);
        assert!(
            asset_refs
                .iter()
                .all(|asset_ref| asset_ref.checksum.is_none())
        );
        assert!(
            asset_refs
                .iter()
                .any(|asset_ref| asset_ref.uri == annotation_uri)
        );
        assert!(
            asset_refs
                .iter()
                .any(|asset_ref| asset_ref.uri == index_uri)
        );
    }

    #[test]
    fn test_add_annotation_file_passes_remote_checksum_overrides() {
        let context = setup_gen();
        let annotation_uri = "http://127.0.0.1:1/annotation.gff3";
        let index_uri = "http://127.0.0.1:1/annotation.gff3.csi";
        let annotation_checksum = Sha256Hash::convert_str("known annotation contents");
        let index_checksum = Sha256Hash::convert_str("known index contents");

        add_annotation_file(
            &context,
            annotation_uri,
            None,
            Some(index_uri),
            Some("remote-annotation"),
            None,
            AnnotationFileChecksumOverrides {
                annotation: Some(annotation_checksum),
                index: Some(index_checksum),
            },
        )
        .expect("should track checksummed remote assets without reading them");

        let asset_refs =
            AssetRef::all(context.graph().conn()).expect("should load asset references");
        assert_eq!(asset_refs.len(), 2);
        let annotation = asset_refs
            .iter()
            .find(|asset_ref| asset_ref.role == AssetRole::Annotation)
            .expect("should track annotation asset");
        let index = asset_refs
            .iter()
            .find(|asset_ref| asset_ref.role == AssetRole::AnnotationIndex)
            .expect("should track annotation index");
        assert_eq!(annotation.uri, annotation_uri);
        assert_eq!(annotation.checksum, Some(annotation_checksum));
        assert_eq!(index.uri, index_uri);
        assert_eq!(index.checksum, Some(index_checksum));
    }

    #[test]
    fn test_add_annotation_file_does_not_store_absolute_external_index_path() {
        let context = setup_gen();
        let graph_conn = context.graph().conn();
        let repo_root = context
            .workspace()
            .repo_root()
            .expect("should have repo root");
        let annotation_path = repo_root.join("annotation.gff3");
        fs::write(&annotation_path, "##gff-version 3\n").expect("should write annotation fixture");

        let external_dir = tempfile::tempdir().expect("should create external directory");
        let index_path = external_dir.path().join("private-index.csi");
        fs::write(&index_path, "private index contents").expect("should write external index");
        let index_path = index_path
            .to_str()
            .expect("should encode external index path");

        add_annotation_file(
            &context,
            annotation_path
                .to_str()
                .expect("should encode annotation path"),
            None,
            Some(index_path),
            None,
            None,
            AnnotationFileChecksumOverrides::default(),
        )
        .expect("should create annotation file operation");

        let index_asset = AssetRef::all(graph_conn)
            .expect("should load asset references")
            .into_iter()
            .find(|asset| asset.role == AssetRole::AnnotationIndex)
            .expect("should store annotation index asset");
        let checksum = index_asset
            .checksum
            .expect("local index asset should have checksum");
        let expected_logical_path = format!(".gen/assets/{checksum}.csi");
        assert_eq!(
            index_asset.logical_path.as_deref(),
            Some(expected_logical_path.as_str())
        );
        assert_ne!(index_asset.logical_path.as_deref(), Some(index_path));
        assert!(!index_asset.uri.contains(index_path));
    }
}