Skip to main content

gen_models/
annotations.rs

1use std::{
2    fs::{self, File},
3    io::{self, BufReader, Read, Write},
4    path::{Path, PathBuf},
5    sync::Arc,
6};
7
8use flate2::read::MultiGzDecoder;
9use gen_core::{
10    DoltHashId, HashId, NodeIntervalBlock, Sha256Hash, calculate_hash,
11    config::Workspace,
12    region::{Region, RegionResolutionError, RegionResolver},
13    traits::Capnp,
14};
15use intervaltree::IntervalTree;
16use rusqlite::{Result as SqlResult, Row, params, types::Type};
17use serde::{Deserialize, Serialize};
18use tempfile::{Builder as TempFileBuilder, TempDir};
19use thiserror::Error;
20
21use crate::{
22    Direction, ForeignKeyCache, ModelSelect, ModelSelectError,
23    accession::{Accession, AccessionError, AccessionSelect, AccessionSpan, NewAccession},
24    assets::{
25        ANNOTATION_ATTRIBUTE_INDEX_ROLE, AssetRef, AssetRole, AssetUri, ChecksummedWriter,
26        CompressionType, LocalAssetUri, OperationKind,
27    },
28    db::{DbContext, GraphConnection, max_rows_per_batch},
29    errors::{FileAdditionError, OperationError},
30    file_types::FileTypes,
31    gen_models_capnp::{annotation, annotation_group, annotation_group_sample},
32    history::{HistoryStore, dolt::DoltHistoryStore},
33    interval_tree::IntervalTreeSource,
34    operations::{
35        FileAddition, FileSource, OperationFile, OperationInfo, OperationSummary,
36        calculate_reader_checksum, track_asset_refs,
37    },
38    region::GenRegionError,
39    select::query_models,
40};
41
42mod progress;
43pub use progress::{AnnotationFileAddOptions, AnnotationFileProgressStage};
44
45use self::progress::{ReportCompressionOnFirstWrite, report_annotation_file_progress};
46
47#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
48#[model_select(table = "annotation_groups")]
49pub struct AnnotationGroup {
50    #[model_select(primary_key)]
51    pub name: String,
52}
53
54impl AnnotationGroup {
55    pub fn create(conn: &GraphConnection, name: &str) -> rusqlite::Result<AnnotationGroup> {
56        let mut stmt = conn
57            .prepare("INSERT INTO annotation_groups (name) VALUES (?1) returning (name);")
58            .unwrap();
59        stmt.query_row((name,), |row| Ok(AnnotationGroup { name: row.get(0)? }))
60    }
61
62    pub fn get_or_create(
63        conn: &GraphConnection,
64        name: &str,
65    ) -> Result<AnnotationGroup, AnnotationGroupError> {
66        let mut statement = conn.prepare(
67            "INSERT INTO annotation_groups (name) VALUES (?1) ON CONFLICT(name) DO NOTHING;",
68        )?;
69        statement.execute(params![name])?;
70        Ok(AnnotationGroup {
71            name: name.to_string(),
72        })
73    }
74
75    pub fn query_by_sample(
76        conn: &GraphConnection,
77        sample_name: &str,
78        history_ref: Option<&str>,
79    ) -> Vec<AnnotationGroup> {
80        let samples = AnnotationGroupSample::select(conn)
81            .sample_name(sample_name)
82            .with_ref(history_ref);
83        AnnotationGroup::select(conn)
84            .join_filtered_on(
85                AnnotationGroupSelect::Name,
86                AnnotationGroupSampleSelect::AnnotationGroup,
87                samples,
88            )
89            .order_by(AnnotationGroupSelect::Name, Direction::Asc)
90            .load()
91            .expect("should load annotation groups for sample")
92    }
93}
94
95impl<'a> Capnp<'a> for AnnotationGroup {
96    type Builder = annotation_group::Builder<'a>;
97    type Reader = annotation_group::Reader<'a>;
98
99    fn write_capnp(&self, builder: &mut Self::Builder) {
100        builder.set_name(&self.name);
101    }
102
103    fn read_capnp(reader: Self::Reader) -> Self {
104        AnnotationGroup {
105            name: reader.get_name().unwrap().to_string().unwrap(),
106        }
107    }
108}
109
110#[derive(Clone, Debug, Deserialize, Serialize, ModelSelect)]
111#[model_select(table = "annotations", from_row = annotation_from_row)]
112pub struct Annotation {
113    pub id: HashId,
114    pub name: String,
115    #[model_select(column = "annotation_group")]
116    pub group: String,
117    #[model_select(foreign_key(Accession, cache = cached_accession))]
118    pub accession_id: HashId,
119    /// Runtime-only related accession cache used by file translators and database-loaded relations.
120    #[serde(skip)]
121    #[model_select(skip)]
122    pub cached_accession: ForeignKeyCache<Accession>,
123    /// Runtime-only interval tree attached by a file annotation translator.
124    #[serde(skip)]
125    #[model_select(skip)]
126    pub cached_interval_tree: Option<Arc<IntervalTree<i64, NodeIntervalBlock>>>,
127    /// History ref this runtime model was selected from.
128    #[serde(skip)]
129    #[model_select(history_ref)]
130    pub history_ref: Option<String>,
131    #[model_select(skip)]
132    pub extra: Option<AnnotationExtra>,
133}
134
135impl PartialEq for Annotation {
136    fn eq(&self, other: &Self) -> bool {
137        self.id == other.id
138            && self.name == other.name
139            && self.group == other.group
140            && self.accession_id == other.accession_id
141            && self.extra == other.extra
142    }
143}
144
145impl Eq for Annotation {}
146
147fn annotation_from_row(row: &Row) -> SqlResult<Annotation> {
148    Ok(Annotation {
149        id: row.get(0)?,
150        name: row.get(1)?,
151        group: row.get(2)?,
152        accession_id: row.get(3)?,
153        cached_accession: ForeignKeyCache::default(),
154        cached_interval_tree: None,
155        history_ref: None,
156        extra: deserialize_annotation_extra(row.get(4)?).map_err(|error| {
157            rusqlite::Error::FromSqlConversionFailure(4, Type::Text, Box::new(error))
158        })?,
159    })
160}
161
162/// For use with create/bulk_create methods.
163#[derive(Clone, Debug)]
164pub struct NewAnnotation<'a> {
165    /// User-facing annotation name.
166    pub name: &'a str,
167    /// Accession covered by this annotation.
168    pub accession_id: HashId,
169    /// Format-specific annotation metadata.
170    pub extra: Option<&'a AnnotationExtra>,
171}
172
173#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
174#[serde(default)]
175pub struct AnnotationExtra {
176    pub genbank: Option<GenBankExtra>,
177    pub gff: Option<GffExtra>,
178    pub bed: Option<BedExtra>,
179}
180
181#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
182#[serde(default)]
183pub struct GenBankExtra {
184    pub kind: String,
185    pub qualifiers: Vec<GenBankQualifier>,
186    pub location_operator: Option<GenBankLocationOperator>,
187}
188
189#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
190#[serde(default)]
191pub struct GenBankQualifier {
192    pub key: String,
193    pub value: Option<String>,
194}
195
196#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
197pub enum GenBankLocationOperator {
198    Join,
199    Order,
200    Bond,
201    OneOf,
202}
203
204#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
205#[serde(default)]
206pub struct GffExtra {
207    pub source: Option<String>,
208    pub ty: String,
209    pub score: Option<String>,
210    pub phase: Option<String>,
211    pub attributes: Vec<GffAttribute>,
212}
213
214#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
215#[serde(default)]
216pub struct GffAttribute {
217    pub key: String,
218    pub values: Vec<String>,
219}
220
221#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
222#[serde(default)]
223pub struct BedExtra {
224    pub score: Option<String>,
225    pub thick_start: Option<i64>,
226    pub thick_end: Option<i64>,
227    pub item_rgb: Option<String>,
228    pub block_count: Option<u64>,
229    pub block_sizes: Option<Vec<i64>>,
230    pub block_starts: Option<Vec<i64>>,
231    pub other_fields: Vec<String>,
232}
233
234fn serialize_annotation_extra(extra: Option<&AnnotationExtra>) -> Result<String, AnnotationError> {
235    serde_json::to_string(extra.unwrap_or(&AnnotationExtra::default()))
236        .map_err(|err| AnnotationError::SerializationError(err.to_string()))
237}
238
239fn deserialize_annotation_extra(
240    value: Option<String>,
241) -> Result<Option<AnnotationExtra>, AnnotationError> {
242    value
243        .map(|value| serde_json::from_str(&value))
244        .transpose()
245        .map(|value| value.filter(|extra| extra != &AnnotationExtra::default()))
246        .map_err(|err| AnnotationError::SerializationError(err.to_string()))
247}
248
249impl<'a> Capnp<'a> for Annotation {
250    type Builder = annotation::Builder<'a>;
251    type Reader = annotation::Reader<'a>;
252
253    fn write_capnp(&self, builder: &mut Self::Builder) {
254        builder.set_id(&self.id.0).unwrap();
255        builder.set_name(&self.name);
256        builder.set_annotation_group(&self.group);
257        builder.set_accession_id(&self.accession_id.0).unwrap();
258        builder.set_extra(
259            serialize_annotation_extra(self.extra.as_ref())
260                .unwrap_or_default()
261                .as_str(),
262        );
263    }
264
265    fn read_capnp(reader: Self::Reader) -> Self {
266        let id = reader
267            .get_id()
268            .unwrap()
269            .as_slice()
270            .unwrap()
271            .try_into()
272            .unwrap();
273        let name = reader.get_name().unwrap().to_string().unwrap();
274        let group = reader.get_annotation_group().unwrap().to_string().unwrap();
275        let accession_id = reader
276            .get_accession_id()
277            .unwrap()
278            .as_slice()
279            .unwrap()
280            .try_into()
281            .unwrap();
282        let extra = deserialize_annotation_extra(
283            reader
284                .get_extra()
285                .ok()
286                .map(|value| value.to_string().unwrap())
287                .filter(|value| !value.is_empty()),
288        )
289        .unwrap_or(None);
290
291        Annotation {
292            id,
293            name,
294            group,
295            accession_id,
296            cached_accession: ForeignKeyCache::default(),
297            cached_interval_tree: None,
298            history_ref: None,
299            extra,
300        }
301    }
302}
303
304#[derive(Debug, Error, PartialEq)]
305pub enum AnnotationError {
306    #[error("Database error: {0}")]
307    DatabaseError(#[from] rusqlite::Error),
308    #[error("Selector error: {0}")]
309    ModelSelect(#[from] ModelSelectError),
310    #[error("Annotation group error: {0}")]
311    AnnotationGroupError(#[from] AnnotationGroupError),
312    #[error("Accession error: {0}")]
313    AccessionError(#[from] AccessionError),
314    #[error("Annotation extra serialization error: {0}")]
315    SerializationError(String),
316}
317
318#[derive(Debug, Error)]
319pub enum AddAnnotationError {
320    #[error("Region parse error: {0}")]
321    RegionParse(#[from] gen_core::region::RegionParseError),
322    #[error("Region resolution error: {0}")]
323    RegionResolution(#[from] GenRegionError),
324    #[error("Accession error: {0}")]
325    Accession(#[from] AccessionError),
326    #[error("Annotation error: {0}")]
327    Annotation(#[from] AnnotationError),
328}
329
330impl Annotation {
331    pub fn generate_id(name: &str, group: &str, accession_id: &HashId) -> HashId {
332        HashId(calculate_hash(&format!("{name}:{group}:{accession_id}",)))
333    }
334
335    pub fn create(
336        conn: &GraphConnection,
337        group: &str,
338        annotation: &NewAnnotation<'_>,
339    ) -> Result<Annotation, AnnotationError> {
340        let id = Annotation::generate_id(annotation.name, group, &annotation.accession_id);
341        let query = "INSERT INTO annotations (id, name, annotation_group, accession_id, extra) VALUES (?1, ?2, ?3, ?4, ?5);";
342        let mut stmt = conn.prepare(query)?;
343        let extra_json = serialize_annotation_extra(annotation.extra)?;
344        stmt.execute(params![
345            id,
346            annotation.name,
347            group,
348            annotation.accession_id,
349            extra_json
350        ])?;
351        Ok(Annotation {
352            id,
353            name: annotation.name.to_string(),
354            group: group.to_string(),
355            accession_id: annotation.accession_id,
356            cached_accession: ForeignKeyCache::default(),
357            cached_interval_tree: None,
358            history_ref: None,
359            extra: annotation.extra.cloned(),
360        })
361    }
362
363    pub fn get_or_create(
364        conn: &GraphConnection,
365        name: &str,
366        group: &str,
367        accession_id: &HashId,
368        extra: Option<&AnnotationExtra>,
369    ) -> Result<Annotation, AnnotationError> {
370        AnnotationGroup::get_or_create(conn, group)?;
371        let id = Annotation::generate_id(name, group, accession_id);
372        let mut statement = conn.prepare(
373            "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;",
374        )?;
375        let extra_json = serialize_annotation_extra(extra)?;
376        statement.execute(params![id, name, group, accession_id, extra_json])?;
377        Ok(Annotation {
378            id,
379            name: name.to_string(),
380            group: group.to_string(),
381            accession_id: *accession_id,
382            cached_accession: ForeignKeyCache::default(),
383            cached_interval_tree: None,
384            history_ref: None,
385            extra: extra.cloned(),
386        })
387    }
388
389    /// Creates annotations for one group, preserving existing rows with matching identities.
390    pub fn bulk_create(
391        conn: &GraphConnection,
392        group: &str,
393        annotations: &[NewAnnotation<'_>],
394    ) -> Result<(), AnnotationError> {
395        if annotations.is_empty() {
396            return Ok(());
397        }
398
399        AnnotationGroup::get_or_create(conn, group)?;
400        let batch_size = max_rows_per_batch(conn, 5);
401        for annotation_batch in annotations.chunks(batch_size) {
402            let mut rows = Vec::with_capacity(annotation_batch.len());
403            let mut parameters: Vec<Box<dyn rusqlite::ToSql>> =
404                Vec::with_capacity(annotation_batch.len() * 5);
405            for annotation in annotation_batch {
406                parameters.push(Box::new(Annotation::generate_id(
407                    annotation.name,
408                    group,
409                    &annotation.accession_id,
410                )));
411                parameters.push(Box::new(annotation.name.to_string()));
412                parameters.push(Box::new(group.to_string()));
413                parameters.push(Box::new(annotation.accession_id));
414                parameters.push(Box::new(serialize_annotation_extra(annotation.extra)?));
415                rows.push("(?, ?, ?, ?, ?)");
416            }
417            let query = format!(
418                "INSERT INTO annotations (id, name, annotation_group, accession_id, extra) VALUES {} ON CONFLICT(accession_id, annotation_group, name) DO NOTHING;",
419                rows.join(",")
420            );
421            conn.execute(&query, rusqlite::params_from_iter(parameters))?;
422        }
423        Ok(())
424    }
425
426    pub fn create_with_samples(
427        conn: &GraphConnection,
428        name: &str,
429        group: &str,
430        accession_id: &HashId,
431        extra: Option<&AnnotationExtra>,
432        sample_names: &[&str],
433    ) -> Result<Annotation, AnnotationError> {
434        let annotation = Annotation::get_or_create(conn, name, group, accession_id, extra)?;
435        annotation.add_samples(conn, sample_names)?;
436        Ok(annotation)
437    }
438
439    pub fn add_samples(
440        &self,
441        conn: &GraphConnection,
442        sample_names: &[&str],
443    ) -> Result<(), AnnotationError> {
444        if sample_names.is_empty() {
445            return Ok(());
446        }
447        AnnotationGroup::get_or_create(conn, &self.group)?;
448        let query = "INSERT INTO annotation_group_samples (annotation_group, sample_name) VALUES (?1, ?2) ON CONFLICT(annotation_group, sample_name) DO NOTHING;";
449        let mut stmt = conn.prepare(query)?;
450        for sample_name in sample_names {
451            stmt.execute(params![self.group, sample_name])?;
452        }
453        Ok(())
454    }
455
456    pub fn get_samples(
457        conn: &GraphConnection,
458        annotation_group: &str,
459    ) -> Result<Vec<String>, AnnotationError> {
460        Ok(AnnotationGroupSample::select(conn)
461            .annotation_group(annotation_group)
462            .only(AnnotationGroupSampleSelect::SampleName)
463            .load()?)
464    }
465
466    pub fn query_by_sample(
467        conn: &GraphConnection,
468        sample_name: &str,
469        history_ref: Option<&str>,
470    ) -> Result<Vec<Annotation>, AnnotationError> {
471        let samples = AnnotationGroupSample::select(conn)
472            .sample_name(sample_name)
473            .with_ref(history_ref);
474        Ok(Annotation::select(conn)
475            .join_filtered_on(
476                AnnotationSelect::Group,
477                AnnotationGroupSampleSelect::AnnotationGroup,
478                samples,
479            )
480            .load()?)
481    }
482
483    pub fn query_by_group(
484        conn: &GraphConnection,
485        group: &str,
486        history_ref: Option<&str>,
487    ) -> Result<Vec<Annotation>, AnnotationError> {
488        let select = Annotation::select(conn).group(group).with_ref(history_ref);
489        Ok(select.load()?)
490    }
491
492    pub fn query_by_group_and_block_group(
493        conn: &GraphConnection,
494        group: &str,
495        block_group_id: &HashId,
496        history_ref: Option<&str>,
497    ) -> Result<Vec<Annotation>, AnnotationError> {
498        let accessions = Accession::select(conn)
499            .block_group_id(*block_group_id)
500            .with_ref(history_ref);
501        Ok(Annotation::select(conn)
502            .group(group)
503            .join_filtered_on(
504                AnnotationSelect::AccessionId,
505                AccessionSelect::Id,
506                accessions,
507            )
508            .load()?)
509    }
510
511    /// List every annotation on a block group, following the sample lineage.
512    ///
513    /// Collects annotations attached to the block group named `block_group_name`
514    /// in `collection_name`, considering `sample_name` together with all of its
515    /// ancestor samples. This mirrors how a block group inherits its parents'
516    /// annotations. Results are de-duplicated by annotation id and ordered from
517    /// the closest sample in the lineage outward. Two annotations that share a
518    /// name but come from different samples (e.g. a parent and child both
519    /// annotating "mreB") are both included, since each is a distinct
520    /// annotation record; unlike [`RegionResolver::resolve`], this is a listing
521    /// operation and does not need to disambiguate by name.
522    ///
523    /// # Arguments
524    ///
525    /// * `collection_name` - Collection the block group belongs to.
526    /// * `sample_name` - Sample whose lineage is walked, including the sample
527    ///   itself.
528    /// * `block_group_name` - Name shared by the block group across the lineage.
529    ///
530    /// # Errors
531    ///
532    /// Returns [`AnnotationError::DatabaseError`] if the query fails.
533    pub fn query_with_lineage(
534        conn: &GraphConnection,
535        collection_name: &str,
536        sample_name: &str,
537        block_group_name: &str,
538    ) -> Result<Vec<Annotation>, AnnotationError> {
539        let query = "WITH RECURSIVE visible_samples(name, depth, path) AS (
540                 SELECT ?2, 0, ',' || ?2 || ','
541                 UNION ALL
542                 SELECT sl.parent_sample_name,
543                        visible.depth + 1,
544                        visible.path || sl.parent_sample_name || ','
545                 FROM sample_lineage sl
546                 JOIN visible_samples visible ON sl.child_sample_name = visible.name
547                 WHERE instr(visible.path, ',' || sl.parent_sample_name || ',') = 0
548             )
549             SELECT a.id,
550                    a.name,
551                    a.annotation_group,
552                    a.accession_id,
553                    a.extra \
554             FROM annotations a \
555             JOIN accessions acc ON a.accession_id = acc.id \
556             JOIN block_groups bg ON acc.block_group_id = bg.id \
557             JOIN visible_samples visible ON bg.sample_name = visible.name \
558             WHERE bg.collection_name = ?1 \
559               AND bg.name = ?3
560             GROUP BY a.id, a.name, a.annotation_group, a.accession_id, a.extra
561             ORDER BY min(visible.depth), a.name, a.id";
562        Ok(query_models::<Annotation, _>(
563            conn,
564            query,
565            params![collection_name, sample_name, block_group_name],
566        )?)
567    }
568
569    pub(crate) fn resolve_candidates(
570        region: &Region,
571        conn: &GraphConnection,
572        collection_name: &str,
573        sample_name: &str,
574    ) -> Result<Vec<Self>, AnnotationError> {
575        query_models::<Annotation, _>(
576            conn,
577            "WITH RECURSIVE visible_samples(name, depth, path) AS (
578                 SELECT ?2, 0, ',' || ?2 || ','
579                 UNION ALL
580                 SELECT sl.parent_sample_name,
581                        visible.depth + 1,
582                        visible.path || sl.parent_sample_name || ','
583                 FROM sample_lineage sl
584                 JOIN visible_samples visible ON sl.child_sample_name = visible.name
585                 WHERE instr(visible.path, ',' || sl.parent_sample_name || ',') = 0
586             ),
587             matching_annotations AS (
588                 SELECT a.id,
589                        a.name,
590                        a.annotation_group,
591                        a.accession_id,
592                        a.extra,
593                        min(visible.depth) AS depth \
594                 FROM annotations a \
595                 JOIN accessions acc ON a.accession_id = acc.id \
596                 JOIN block_groups bg ON acc.block_group_id = bg.id \
597                 JOIN visible_samples visible ON bg.sample_name = visible.name \
598                 WHERE bg.collection_name = ?1 \
599                   AND lower(a.name) = lower(?3)
600                 GROUP BY a.id, a.name, a.annotation_group, a.accession_id, a.extra
601             )
602             SELECT id, name, annotation_group, accession_id, extra \
603             FROM matching_annotations \
604             WHERE depth = (SELECT min(depth) FROM matching_annotations)",
605            params![collection_name, sample_name, region.name],
606        )
607        .map_err(AnnotationError::from)
608    }
609
610    pub fn intervaltree(
611        &self,
612        conn: &GraphConnection,
613    ) -> Result<Arc<IntervalTree<i64, NodeIntervalBlock>>, AnnotationError> {
614        IntervalTreeSource::intervaltree(self, conn)
615    }
616
617    pub fn length(&self, conn: &GraphConnection) -> Result<i64, AnnotationError> {
618        let interval_tree = self.intervaltree(conn)?;
619        crate::accession::intervaltree_length(&interval_tree).map_err(Into::into)
620    }
621}
622
623impl IntervalTreeSource for Annotation {
624    type Error = AnnotationError;
625
626    fn cached_interval_tree(&self) -> Option<&Arc<IntervalTree<i64, NodeIntervalBlock>>> {
627        self.cached_interval_tree.as_ref()
628    }
629
630    fn set_cached_interval_tree(
631        &mut self,
632        interval_tree: Option<Arc<IntervalTree<i64, NodeIntervalBlock>>>,
633    ) {
634        self.cached_interval_tree = interval_tree;
635    }
636
637    fn load_interval_tree(
638        &self,
639        conn: &GraphConnection,
640    ) -> Result<Arc<IntervalTree<i64, NodeIntervalBlock>>, Self::Error> {
641        let accession = self.get_accession(conn)?;
642        accession.intervaltree(conn).map_err(Into::into)
643    }
644}
645
646impl RegionResolver for Annotation {
647    type Connection = GraphConnection;
648    type Error = AnnotationError;
649
650    fn resolve(
651        region: &Region,
652        conn: &Self::Connection,
653        collection_name: &str,
654        sample_name: &str,
655    ) -> Result<Self, RegionResolutionError<Self::Error>> {
656        let matches = Self::resolve_candidates(region, conn, collection_name, sample_name)?;
657
658        match matches.len() {
659            0 => Err(RegionResolutionError::NotFound(region.name.clone())),
660            1 => Ok(matches.into_iter().next().unwrap()),
661            _ => Err(RegionResolutionError::Ambiguous(format!(
662                "multiple annotations named {}",
663                region.name
664            ))),
665        }
666    }
667}
668
669#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
670#[model_select(
671    table = "annotation_group_samples",
672    default_sort(annotation_group = "asc", sample_name = "asc")
673)]
674pub struct AnnotationGroupSample {
675    #[model_select(primary_key)]
676    pub annotation_group: String,
677    #[model_select(primary_key)]
678    pub sample_name: String,
679}
680
681impl<'a> Capnp<'a> for AnnotationGroupSample {
682    type Builder = annotation_group_sample::Builder<'a>;
683    type Reader = annotation_group_sample::Reader<'a>;
684
685    fn write_capnp(&self, builder: &mut Self::Builder) {
686        builder.set_annotation_group(&self.annotation_group);
687        builder.set_sample_name(&self.sample_name);
688    }
689
690    fn read_capnp(reader: Self::Reader) -> Self {
691        let annotation_group = reader.get_annotation_group().unwrap().to_string().unwrap();
692        let sample_name = reader.get_sample_name().unwrap().to_string().unwrap();
693        AnnotationGroupSample {
694            annotation_group,
695            sample_name,
696        }
697    }
698}
699
700impl AnnotationGroupSample {
701    pub fn create(
702        conn: &GraphConnection,
703        annotation_group: &str,
704        sample_name: &str,
705    ) -> Result<(), AnnotationError> {
706        AnnotationGroup::get_or_create(conn, annotation_group)?;
707        let query = "INSERT INTO annotation_group_samples (annotation_group, sample_name) VALUES (?1, ?2) ON CONFLICT(annotation_group, sample_name) DO NOTHING;";
708        let mut stmt = conn.prepare(query)?;
709        stmt.execute(params![annotation_group, sample_name])?;
710        Ok(())
711    }
712
713    pub fn delete(
714        conn: &GraphConnection,
715        annotation_group: &str,
716        sample_name: &str,
717    ) -> Result<(), AnnotationError> {
718        let query = "DELETE FROM annotation_group_samples WHERE annotation_group = ?1 AND sample_name = ?2;";
719        let mut stmt = conn.prepare(query)?;
720        stmt.execute(params![annotation_group, sample_name])?;
721        Ok(())
722    }
723}
724
725#[derive(Debug, Error, PartialEq)]
726pub enum AnnotationGroupError {
727    #[error("Database error: {0}")]
728    DatabaseError(#[from] rusqlite::Error),
729}
730
731#[derive(Debug, Error)]
732pub enum AnnotationFileError {
733    #[error("Database error: {0}")]
734    DatabaseError(#[from] rusqlite::Error),
735    #[error("File addition error: {0}")]
736    FileAdditionError(#[from] FileAdditionError),
737    #[error("Annotation file I/O error: {0}")]
738    IoError(#[from] io::Error),
739    #[error("Unable to sort or index annotation file: {0}")]
740    GaiError(#[from] gai::Error),
741    #[error("Operation error: {0}")]
742    OperationError(#[from] OperationError),
743    #[error(
744        "Unable to detect annotation file format from the file extension. Use --format to specify it explicitly."
745    )]
746    MissingFileExtension,
747    #[error("Unsupported annotation file type: {0}")]
748    UnsupportedFileType(String),
749}
750
751pub fn parse_annotation_file_type(value: &str) -> Result<FileTypes, AnnotationFileError> {
752    match value.trim().to_ascii_lowercase().as_str() {
753        "gff3" | "gff" => Ok(FileTypes::Gff3),
754        "bed" => Ok(FileTypes::Bed),
755        "genbank" | "gb" => Ok(FileTypes::GenBank),
756        other => Err(AnnotationFileError::UnsupportedFileType(other.to_string())),
757    }
758}
759
760pub fn annotation_file_extension(path: &str) -> Option<String> {
761    let path = Path::new(path);
762    let mut ext = path
763        .extension()
764        .and_then(|ext| ext.to_str())
765        .map(|ext| ext.to_ascii_lowercase());
766    if matches!(ext.as_deref(), Some("gz") | Some("bgz") | Some("bgzf")) {
767        ext = path
768            .file_stem()
769            .and_then(|stem| stem.to_str())
770            .and_then(|stem| Path::new(stem).extension().and_then(|ext| ext.to_str()))
771            .map(|ext| ext.to_ascii_lowercase());
772    }
773    ext
774}
775
776pub fn annotation_index_file_path(
777    workspace: &Workspace,
778    path: &str,
779    explicit_index_path: Option<&str>,
780) -> Option<String> {
781    if let Some(index_path) = explicit_index_path {
782        return Some(index_path.to_string());
783    }
784
785    let mut candidates = vec![format!("{path}.csi"), format!("{path}.tbi")];
786    let path_buf = PathBuf::from(path);
787    if let Some(extension) = path_buf.extension().and_then(|ext| ext.to_str()) {
788        for suffix in ["csi", "tbi"] {
789            let mut extension_candidate = path_buf.clone();
790            extension_candidate.set_extension(format!("{extension}.{suffix}"));
791            let extension_candidate = extension_candidate.to_string_lossy().to_string();
792            if !candidates
793                .iter()
794                .any(|candidate| candidate == &extension_candidate)
795            {
796                candidates.push(extension_candidate);
797            }
798        }
799    }
800
801    for candidate in candidates {
802        let exists = if Path::new(&candidate).is_absolute() {
803            Path::new(&candidate).exists()
804        } else {
805            workspace
806                .repo_root()
807                .ok()
808                .is_some_and(|repo_root| repo_root.join(&candidate).exists())
809        };
810        if exists {
811            return Some(candidate);
812        }
813    }
814
815    None
816}
817
818pub fn add_annotation(
819    context: &DbContext,
820    collection: &str,
821    name: &str,
822    group: Option<&str>,
823    sample: &str,
824    region: &str,
825) -> Result<OperationSummary, AddAnnotationError> {
826    let graph_conn = context.graph().conn();
827    let parsed_region = Region::parse(region)?;
828    let resolved_region = crate::region::resolve(&parsed_region, graph_conn, collection, sample)?;
829    let spans = AccessionSpan::from_resolved_region(
830        graph_conn,
831        context.workspace(),
832        &resolved_region,
833        None,
834    )?;
835
836    let accession = Accession::get_or_create(
837        graph_conn,
838        &NewAccession {
839            name: name.to_string(),
840            block_group_id: resolved_region.block_group.id,
841            parent_accession_id: None,
842            spans,
843        },
844    )?;
845
846    let annotation_group = group.unwrap_or("default");
847    let annotation =
848        Annotation::get_or_create(graph_conn, name, annotation_group, &accession.id, None)?;
849    AnnotationGroupSample::create(graph_conn, &annotation.group, sample)?;
850
851    Ok(OperationSummary::new(
852        OperationInfo {
853            files: vec![],
854            description: format!("add annotation {name}"),
855        },
856        format!("add annotation {name}"),
857    ))
858}
859
860/// Optional content checksums collected while annotation assets were already being streamed.
861#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
862pub struct AnnotationFileChecksumOverrides {
863    /// Checksum of the annotation file.
864    pub annotation: Option<Sha256Hash>,
865    /// Checksum of the annotation index.
866    pub index: Option<Sha256Hash>,
867}
868
869fn prepare_local_sorted_annotation(
870    workspace: &Workspace,
871    path: &str,
872    file_type: FileTypes,
873    checksum_override: Option<Sha256Hash>,
874    progress: &mut Option<&mut dyn FnMut(AnnotationFileProgressStage)>,
875) -> Result<(FileAddition, FileAddition, FileAddition), AnnotationFileError> {
876    let cache_dir = workspace
877        .find_cache_dir()
878        .ok_or_else(|| {
879            io::Error::new(
880                io::ErrorKind::NotFound,
881                "workspace cache directory is unavailable",
882            )
883        })?
884        .join("annotation-indexes");
885    fs::create_dir_all(&cache_dir)?;
886
887    let asset_uri = <dyn AssetUri>::new(workspace, path);
888    if let Some(expected_checksum) = checksum_override {
889        let source_checksum = calculate_reader_checksum(asset_uri.reader(workspace)?)?;
890        if source_checksum != expected_checksum {
891            return Err(FileAdditionError::ChecksumError(
892                "local source checksum does not match the provided checksum".to_string(),
893            )
894            .into());
895        }
896    }
897
898    let source_reader = asset_uri.reader(workspace)?;
899    let (compression_type, replayed_reader) =
900        CompressionType::sniff(source_reader).map_err(FileAdditionError::FileReadError)?;
901    let source_reader: Box<dyn Read> = match compression_type {
902        CompressionType::Plain => Box::new(replayed_reader),
903        CompressionType::Gzip | CompressionType::Bgzf => {
904            Box::new(MultiGzDecoder::new(replayed_reader))
905        }
906    };
907    let asset_dir = workspace
908        .asset_dir()
909        .map_err(FileAdditionError::ConfigError)?;
910    fs::create_dir_all(&asset_dir)?;
911    let mut sorted_source = TempFileBuilder::new()
912        .suffix(&format!(".{}.bgz", FileTypes::suffix(file_type)))
913        .tempfile_in(&asset_dir)?;
914    report_annotation_file_progress(progress, AnnotationFileProgressStage::Sorting);
915    let format = match file_type {
916        FileTypes::Gff3 => gai::SortFormat::Gff,
917        FileTypes::Bed => gai::SortFormat::Bed,
918        other => {
919            return Err(AnnotationFileError::UnsupportedFileType(
920                other.as_str().to_string(),
921            ));
922        }
923    };
924
925    // GAI sorts, writes a .bgz and returns an index all in one pass.
926    let mut checksummed_writer = ChecksummedWriter::new(sorted_source.as_file_mut());
927    let coordinate_index = {
928        let mut compressed_writer =
929            ReportCompressionOnFirstWrite::new(&mut checksummed_writer, || {
930                report_annotation_file_progress(progress, AnnotationFileProgressStage::Compressing)
931            });
932        let mut bgzf_writer = noodles::bgzf::io::Writer::new(&mut compressed_writer);
933        let coordinate_index = match gai::sort_bgzf_with_csi(
934            BufReader::new(source_reader),
935            &mut bgzf_writer,
936            format,
937            true,
938        ) {
939            Ok(coordinate_index) => coordinate_index,
940            Err(error) => {
941                bgzf_writer.into_inner();
942                return Err(error.into());
943            }
944        };
945        bgzf_writer.finish()?.flush()?;
946        coordinate_index
947    };
948    let archive_checksum = checksummed_writer.checksum();
949    let materialized_checksum =
950        calculate_reader_checksum(noodles::bgzf::io::Reader::new(sorted_source.reopen()?))?;
951    let file_addition = FileAddition::prepare_from_source(
952        workspace,
953        path,
954        file_type,
955        FileSource::StagedBgzf {
956            path: sorted_source.path().to_path_buf(),
957            archive_checksum,
958            materialized_checksum,
959        },
960        true,
961    )?;
962
963    let sidecar_temp_dir = TempDir::new_in(&cache_dir)?;
964    let coordinate_index_path = sidecar_temp_dir.path().join("coordinate.csi");
965    let mut coordinate_index_writer =
966        noodles::csi::io::Writer::new(File::create(&coordinate_index_path)?);
967    coordinate_index_writer.write_index(&coordinate_index)?;
968    coordinate_index_writer.into_inner().finish()?.flush()?;
969
970    let source_path = asset_dir.join(
971        file_addition
972            .hashed_filename()
973            .expect("should have a checksum for retained local annotations"),
974    );
975    let index_file_addition = FileAddition::prepare(
976        workspace,
977        &coordinate_index_path.to_string_lossy(),
978        FileTypes::Tabix,
979        None,
980    )?;
981    report_annotation_file_progress(progress, AnnotationFileProgressStage::BuildingIndex);
982    let attribute_index_path = sidecar_temp_dir.path().join("attributes.gai");
983    let name_index_options = match format {
984        gai::SortFormat::Gff => {
985            gai::NameIndexOptions::new(["Name", "name", "gene", "gene_name", "db_xref"], false)?
986        }
987        gai::SortFormat::Bed => gai::NameIndexOptions::bed(false),
988    };
989    gai::build_name_index_with_options(
990        &source_path,
991        &coordinate_index_path,
992        &attribute_index_path,
993        &name_index_options,
994        &gai::BuildOptions::default(),
995    )?;
996    let attribute_index_file_addition = FileAddition::prepare(
997        workspace,
998        &attribute_index_path.to_string_lossy(),
999        FileTypes::None,
1000        None,
1001    )?;
1002
1003    Ok((
1004        file_addition,
1005        index_file_addition,
1006        attribute_index_file_addition,
1007    ))
1008}
1009
1010/// Adds an annotation asset and its available indexes to operation history.
1011///
1012/// Callers pass checksums only when the corresponding remote streams were already consumed for
1013/// annotation work. This keeps operation creation independent of remote credentials while local
1014/// annotation files are sorted, retained, and hashed during preparation.
1015pub fn add_annotation_file(
1016    context: &DbContext,
1017    path: &str,
1018    format: Option<&str>,
1019    index: Option<&str>,
1020    name: Option<&str>,
1021    message: Option<&str>,
1022    checksum_overrides: AnnotationFileChecksumOverrides,
1023) -> Result<DoltHashId, AnnotationFileError> {
1024    add_annotation_file_with_progress(
1025        context,
1026        path,
1027        format,
1028        index,
1029        name,
1030        message,
1031        AnnotationFileAddOptions {
1032            checksum_overrides,
1033            progress: None,
1034        },
1035    )
1036}
1037
1038/// Adds an annotation file and reports local GFF3/BED preparation stages when requested.
1039pub fn add_annotation_file_with_progress(
1040    context: &DbContext,
1041    path: &str,
1042    format: Option<&str>,
1043    index: Option<&str>,
1044    name: Option<&str>,
1045    message: Option<&str>,
1046    options: AnnotationFileAddOptions<'_>,
1047) -> Result<DoltHashId, AnnotationFileError> {
1048    let AnnotationFileAddOptions {
1049        checksum_overrides,
1050        mut progress,
1051    } = options;
1052    let workspace = context.workspace();
1053    let graph_conn = context.graph().conn();
1054
1055    let file_type = match format {
1056        Some(format) => parse_annotation_file_type(format)?,
1057        None => {
1058            let ext =
1059                annotation_file_extension(path).ok_or(AnnotationFileError::MissingFileExtension)?;
1060            parse_annotation_file_type(&ext)?
1061        }
1062    };
1063    let name = name.or_else(|| Path::new(path).file_name().and_then(|value| value.to_str()));
1064    let name_value = name.unwrap_or_default();
1065    let (file_addition, logical_path, sidecars) =
1066        if matches!(file_type, FileTypes::Gff3 | FileTypes::Bed)
1067            && LocalAssetUri::is_local_path_or_file_uri(path)
1068        {
1069            // Sorting changes compressed offsets, so local GFF/BED sidecars are always rebuilt against
1070            // the retained BGZF bytes. A supplied coordinate index describes the original input bytes.
1071            let (file_addition, index_file_addition, attribute_index_file_addition) =
1072                prepare_local_sorted_annotation(
1073                    workspace,
1074                    path,
1075                    file_type,
1076                    checksum_overrides.annotation,
1077                    &mut progress,
1078                )?;
1079            let logical_path =
1080                OperationFile::storage_file_path(workspace, path, file_addition.checksum.as_ref())?;
1081            let filename = Path::new(&logical_path)
1082                .file_name()
1083                .and_then(|value| value.to_str())
1084                .unwrap_or("annotation");
1085            let sidecars = vec![
1086                (
1087                    index_file_addition,
1088                    AssetRole::AnnotationIndex,
1089                    format!("{logical_path}.csi"),
1090                    format!("{filename}.csi"),
1091                ),
1092                (
1093                    attribute_index_file_addition,
1094                    AssetRole::Other(ANNOTATION_ATTRIBUTE_INDEX_ROLE.to_string()),
1095                    format!("{logical_path}.gai"),
1096                    format!("{filename}.gai"),
1097                ),
1098            ];
1099            (file_addition, logical_path, sidecars)
1100        } else {
1101            let file_addition =
1102                FileAddition::prepare(workspace, path, file_type, checksum_overrides.annotation)?;
1103            let logical_path =
1104                OperationFile::storage_file_path(workspace, path, file_addition.checksum.as_ref())?;
1105            let mut sidecars = Vec::new();
1106            if let Some(index_path) = annotation_index_file_path(workspace, path, index) {
1107                let index_file_type = FileTypes::infer_from_path(&index_path);
1108                let index_file_addition = FileAddition::prepare(
1109                    workspace,
1110                    &index_path,
1111                    index_file_type,
1112                    checksum_overrides.index,
1113                )?;
1114                let index_logical_path = OperationFile::storage_file_path(
1115                    workspace,
1116                    &index_path,
1117                    index_file_addition.checksum.as_ref(),
1118                )?;
1119                let index_name = Path::new(&index_path)
1120                    .file_name()
1121                    .and_then(|value| value.to_str())
1122                    .map(str::to_string)
1123                    .unwrap_or_else(|| index_path.clone());
1124                sidecars.push((
1125                    index_file_addition,
1126                    AssetRole::AnnotationIndex,
1127                    index_logical_path,
1128                    index_name,
1129                ));
1130            }
1131            (file_addition, logical_path, sidecars)
1132        };
1133    let created_on = chrono::Utc::now()
1134        .timestamp_nanos_opt()
1135        .expect("should create annotation asset timestamp");
1136    let annotation_asset_ref = AssetRef::from_file_addition(
1137        &file_addition,
1138        AssetRole::Annotation,
1139        Some(&logical_path),
1140        name,
1141        None,
1142        created_on,
1143    );
1144    let annotation_asset_ref_id = annotation_asset_ref.id;
1145    let index_file_addition_ids = sidecars
1146        .iter()
1147        .map(|(file_addition, _, _, _)| file_addition.id.to_string())
1148        .collect::<Vec<_>>()
1149        .join(":");
1150    let log_id = HashId(calculate_hash(&format!(
1151        "{file_addition_id}:{name_value}:{index_file_addition_ids}",
1152        file_addition_id = file_addition.id
1153    )));
1154    let summary = message
1155        .map(str::to_string)
1156        .unwrap_or_else(|| format!("Add annotation file {path}"));
1157    let mut asset_refs = vec![annotation_asset_ref];
1158    for (file_addition, role, logical_path, index_name) in &sidecars {
1159        asset_refs.push(AssetRef::from_file_addition(
1160            file_addition,
1161            role.clone(),
1162            Some(logical_path),
1163            Some(index_name),
1164            Some(&annotation_asset_ref_id),
1165            created_on,
1166        ));
1167    }
1168
1169    track_asset_refs(
1170        graph_conn,
1171        Some(&log_id),
1172        &OperationKind::AnnotationFile,
1173        &summary,
1174        &asset_refs,
1175    )?;
1176    let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
1177    if history_store.status()?.is_empty() {
1178        return Err(OperationError::NoChanges.into());
1179    }
1180
1181    let commit_hash = history_store.commit_all(&summary)?;
1182
1183    Ok(commit_hash)
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188    use std::{
1189        collections::HashSet,
1190        fs::{self, File},
1191        sync::Arc,
1192    };
1193
1194    use gen_core::{HashId, NodeIntervalBlock, Strand, region::RegionResolutionError};
1195    use noodles::bgzf;
1196
1197    use super::*;
1198    use crate::{
1199        assets::{AssetRef, AssetRole, OperationAsset, OperationLog},
1200        block_group::BlockGroup,
1201        block_group_edge::{BlockGroupEdge, BlockGroupEdgeData},
1202        errors::OperationError,
1203        operations::{
1204            calculate_file_checksum, calculate_reader_checksum, commit_operation_summary,
1205        },
1206        path::Path,
1207        sample::Sample,
1208        sample_lineage::SampleLineage,
1209        test_helpers::{create_bg, get_connection, setup_block_group, setup_gen},
1210    };
1211
1212    mod region_resolver {
1213        use super::*;
1214
1215        #[test]
1216        fn resolves_annotation_by_name_case_insensitively() {
1217            let conn = get_connection(None).unwrap();
1218            let (_block_group_id, path) = setup_block_group(&conn);
1219            let accession = BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5).unwrap();
1220            let annotation =
1221                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1222            assert!(annotation.cached_interval_tree().is_none());
1223            assert!(
1224                annotation
1225                    .intervaltree(&conn)
1226                    .expect("should load the persisted annotation tree")
1227                    .query(0..5)
1228                    .next()
1229                    .is_some()
1230            );
1231
1232            let region = Region::parse("MREB").unwrap();
1233            let resolved = Annotation::resolve(&region, &conn, "test", "test").unwrap();
1234            assert_eq!(resolved.id, annotation.id);
1235        }
1236
1237        #[test]
1238        fn returns_not_found_for_missing_annotation() {
1239            let conn = get_connection(None).unwrap();
1240            let (_block_group_id, _path) = setup_block_group(&conn);
1241
1242            let region = Region::parse("missing").unwrap();
1243            let err = Annotation::resolve(&region, &conn, "test", "test").unwrap_err();
1244            assert!(matches!(
1245                err,
1246                RegionResolutionError::NotFound(name) if name == "missing"
1247            ));
1248        }
1249
1250        #[test]
1251        fn returns_ambiguous_for_multiple_matching_annotations() {
1252            let conn = get_connection(None).unwrap();
1253            let (_block_group_id, path) = setup_block_group(&conn);
1254            let accession = BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5).unwrap();
1255            let _ = Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1256
1257            let other_block_group = create_bg(&conn, "test", "test", "other");
1258            let edge_ids = Path::edges_for_path(&conn, &path.id, None)
1259                .into_iter()
1260                .map(|edge| edge.id)
1261                .collect::<Vec<_>>();
1262            let block_group_edges = edge_ids
1263                .iter()
1264                .map(|edge_id| BlockGroupEdgeData {
1265                    block_group_id: other_block_group.id,
1266                    edge_id: *edge_id,
1267                    chromosome_index: 0,
1268                    phased: 0,
1269                })
1270                .collect::<Vec<_>>();
1271            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1272            let other_path =
1273                Path::create(&conn, "other-path", &other_block_group.id, &edge_ids).unwrap();
1274            let other_accession =
1275                BlockGroup::add_accession(&conn, &other_path, "ann-accession-2", 0, 5).unwrap();
1276            let _ = Annotation::get_or_create(&conn, "MREB", "genes", &other_accession.id, None)
1277                .unwrap();
1278
1279            let region = Region::parse("mreB").unwrap();
1280            let err = Annotation::resolve(&region, &conn, "test", "test").unwrap_err();
1281            assert!(matches!(
1282                err,
1283                RegionResolutionError::Ambiguous(name) if name == "multiple annotations named mreB"
1284            ));
1285        }
1286
1287        #[test]
1288        fn resolves_closest_annotation_in_sample_lineage() {
1289            let conn = get_connection(None).unwrap();
1290            let (_parent_block_group_id, parent_path) = setup_block_group(&conn);
1291            let parent_accession =
1292                BlockGroup::add_accession(&conn, &parent_path, "parent-accession", 0, 5).unwrap();
1293            let _parent_annotation =
1294                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1295                    .unwrap();
1296
1297            let child_block_group = create_bg(&conn, "test", "child", "chr1");
1298            let edge_ids = Path::edges_for_path(&conn, &parent_path.id, None)
1299                .into_iter()
1300                .map(|edge| edge.id)
1301                .collect::<Vec<_>>();
1302            let block_group_edges = edge_ids
1303                .iter()
1304                .map(|edge_id| BlockGroupEdgeData {
1305                    block_group_id: child_block_group.id,
1306                    edge_id: *edge_id,
1307                    chromosome_index: 0,
1308                    phased: 0,
1309                })
1310                .collect::<Vec<_>>();
1311            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1312            let child_path =
1313                Path::create(&conn, "child-path", &child_block_group.id, &edge_ids).unwrap();
1314            let child_accession =
1315                BlockGroup::add_accession(&conn, &child_path, "child-accession", 0, 5).unwrap();
1316            let child_annotation =
1317                Annotation::get_or_create(&conn, "MREB", "genes", &child_accession.id, None)
1318                    .unwrap();
1319            SampleLineage::create(&conn, "test", "child").unwrap();
1320
1321            let region = Region::parse("mreB").unwrap();
1322            let resolved = Annotation::resolve(&region, &conn, "test", "child").unwrap();
1323
1324            assert_eq!(resolved.id, child_annotation.id);
1325        }
1326
1327        #[test]
1328        fn falls_back_to_parent_annotation_when_child_has_none() {
1329            let conn = get_connection(None).unwrap();
1330            let (_parent_block_group_id, parent_path) = setup_block_group(&conn);
1331            let parent_accession =
1332                BlockGroup::add_accession(&conn, &parent_path, "parent-only-accession", 0, 5)
1333                    .unwrap();
1334            let parent_annotation =
1335                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1336                    .unwrap();
1337
1338            let child_block_group = create_bg(&conn, "test", "child", "chr1");
1339            let edge_ids = Path::edges_for_path(&conn, &parent_path.id, None)
1340                .into_iter()
1341                .map(|edge| edge.id)
1342                .collect::<Vec<_>>();
1343            let block_group_edges = edge_ids
1344                .iter()
1345                .map(|edge_id| BlockGroupEdgeData {
1346                    block_group_id: child_block_group.id,
1347                    edge_id: *edge_id,
1348                    chromosome_index: 0,
1349                    phased: 0,
1350                })
1351                .collect::<Vec<_>>();
1352            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1353            let _child_path =
1354                Path::create(&conn, "child-path", &child_block_group.id, &edge_ids).unwrap();
1355            SampleLineage::create(&conn, "test", "child").unwrap();
1356
1357            let region = Region::parse("mreB").unwrap();
1358            let resolved = Annotation::resolve(&region, &conn, "test", "child").unwrap();
1359
1360            assert_eq!(resolved.id, parent_annotation.id);
1361        }
1362    }
1363
1364    mod lineage_listing {
1365        use super::*;
1366
1367        /// Attach a block group that shares `parent_path`'s edges, give it its
1368        /// own path and accession, and annotate it. Returns the annotation.
1369        fn annotate_block_group(
1370            conn: &GraphConnection,
1371            parent_path: &Path,
1372            collection_name: &str,
1373            sample_name: &str,
1374            block_group_name: &str,
1375            accession_name: &str,
1376            annotation_name: &str,
1377        ) -> Annotation {
1378            let block_group = create_bg(conn, collection_name, sample_name, block_group_name);
1379            let edge_ids = Path::edges_for_path(conn, &parent_path.id, None)
1380                .into_iter()
1381                .map(|edge| edge.id)
1382                .collect::<Vec<_>>();
1383            let block_group_edges = edge_ids
1384                .iter()
1385                .map(|edge_id| BlockGroupEdgeData {
1386                    block_group_id: block_group.id,
1387                    edge_id: *edge_id,
1388                    chromosome_index: 0,
1389                    phased: 0,
1390                })
1391                .collect::<Vec<_>>();
1392            BlockGroupEdge::bulk_create(conn, &block_group_edges);
1393            let path = Path::create(conn, accession_name, &block_group.id, &edge_ids).unwrap();
1394            let accession = BlockGroup::add_accession(conn, &path, accession_name, 0, 5).unwrap();
1395            Annotation::get_or_create(conn, annotation_name, "genes", &accession.id, None).unwrap()
1396        }
1397
1398        #[test]
1399        fn test_lists_annotations_on_block_group() {
1400            let conn = get_connection(None).unwrap();
1401            let (_block_group_id, path) = setup_block_group(&conn);
1402            let accession = BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5).unwrap();
1403            let annotation =
1404                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1405
1406            let related_accession = annotation
1407                .get_accession(&conn)
1408                .expect("should load persisted annotation accession");
1409            let cached_accession = annotation
1410                .cached_accession
1411                .snapshot()
1412                .expect("should cache persisted annotation accession");
1413            assert!(Arc::ptr_eq(&related_accession, &cached_accession));
1414            assert!(Arc::ptr_eq(
1415                &related_accession,
1416                &annotation
1417                    .get_accession(&conn)
1418                    .expect("should reuse cached annotation accession")
1419            ));
1420
1421            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1422
1423            assert_eq!(listed, vec![annotation]);
1424        }
1425
1426        #[test]
1427        fn test_includes_parent_annotations_via_lineage() {
1428            let conn = get_connection(None).unwrap();
1429            let (_parent_block_group_id, parent_path) = setup_block_group(&conn);
1430            let parent_accession =
1431                BlockGroup::add_accession(&conn, &parent_path, "parent-accession", 0, 5).unwrap();
1432            let parent_annotation =
1433                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1434                    .unwrap();
1435
1436            let child_annotation = annotate_block_group(
1437                &conn,
1438                &parent_path,
1439                "test",
1440                "child",
1441                "chr1",
1442                "child-accession",
1443                "ftsZ",
1444            );
1445            SampleLineage::create(&conn, "test", "child").unwrap();
1446
1447            let listed = Annotation::query_with_lineage(&conn, "test", "child", "chr1").unwrap();
1448
1449            let ids: HashSet<HashId> = listed.iter().map(|a| a.id).collect();
1450            assert_eq!(
1451                ids,
1452                HashSet::from([parent_annotation.id, child_annotation.id])
1453            );
1454        }
1455
1456        #[test]
1457        fn test_excludes_annotations_on_other_block_group_names() {
1458            let conn = get_connection(None).unwrap();
1459            let (_block_group_id, path) = setup_block_group(&conn);
1460            let accession =
1461                BlockGroup::add_accession(&conn, &path, "chr1-accession", 0, 5).unwrap();
1462            let chr1_annotation =
1463                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1464
1465            let _chr2_annotation = annotate_block_group(
1466                &conn,
1467                &path,
1468                "test",
1469                "test",
1470                "chr2",
1471                "chr2-accession",
1472                "ftsZ",
1473            );
1474
1475            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1476
1477            assert_eq!(listed, vec![chr1_annotation]);
1478        }
1479
1480        #[test]
1481        fn test_excludes_annotations_from_samples_outside_the_lineage() {
1482            let conn = get_connection(None).unwrap();
1483            let (_block_group_id, path) = setup_block_group(&conn);
1484            let accession =
1485                BlockGroup::add_accession(&conn, &path, "test-accession", 0, 5).unwrap();
1486            let test_annotation =
1487                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1488
1489            let _unrelated_annotation = annotate_block_group(
1490                &conn,
1491                &path,
1492                "test",
1493                "unrelated",
1494                "chr1",
1495                "unrelated-accession",
1496                "ftsZ",
1497            );
1498
1499            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1500
1501            assert_eq!(listed, vec![test_annotation]);
1502        }
1503
1504        #[test]
1505        fn test_keeps_both_when_parent_and_child_share_an_annotation_name() {
1506            let conn = get_connection(None).unwrap();
1507            let (_parent_block_group_id, parent_path) = setup_block_group(&conn);
1508            let parent_accession =
1509                BlockGroup::add_accession(&conn, &parent_path, "parent-accession", 0, 5).unwrap();
1510            let parent_annotation =
1511                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1512                    .unwrap();
1513
1514            let child_annotation = annotate_block_group(
1515                &conn,
1516                &parent_path,
1517                "test",
1518                "child",
1519                "chr1",
1520                "child-accession",
1521                "mreB",
1522            );
1523            SampleLineage::create(&conn, "test", "child").unwrap();
1524
1525            let listed = Annotation::query_with_lineage(&conn, "test", "child", "chr1").unwrap();
1526
1527            // Same name, distinct annotation ids: listing keeps both rather than
1528            // collapsing by name. `resolve` would pick only the child's here
1529            // since it's the closer match (depth 0 vs. depth 1) and error on tie.
1530            assert_eq!(listed, vec![child_annotation, parent_annotation]);
1531        }
1532    }
1533
1534    #[test]
1535    fn annotation_groups_all_lists_groups_in_name_order() {
1536        let conn = get_connection(None).unwrap();
1537        AnnotationGroup::create(&conn, "zebra").unwrap();
1538        AnnotationGroup::create(&conn, "ant").unwrap();
1539
1540        let groups = AnnotationGroup::all(&conn).expect("should load annotation groups");
1541
1542        assert_eq!(
1543            groups,
1544            vec![
1545                AnnotationGroup { name: "ant".into() },
1546                AnnotationGroup {
1547                    name: "zebra".into()
1548                }
1549            ]
1550        );
1551    }
1552
1553    #[test]
1554    fn create_annotation_with_samples() {
1555        let conn = get_connection(None).unwrap();
1556        let (_block_group_id, path) = setup_block_group(&conn);
1557
1558        let _ = Sample::create(
1559            &conn,
1560            crate::sample::NewSample {
1561                name: "sample-1",
1562                is_reference: false,
1563            },
1564        )
1565        .unwrap();
1566        let _ = Sample::create(
1567            &conn,
1568            crate::sample::NewSample {
1569                name: "sample-2",
1570                is_reference: false,
1571            },
1572        )
1573        .unwrap();
1574        let accession = BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5).unwrap();
1575
1576        let annotations = [NewAnnotation {
1577            name: "gene-a",
1578            accession_id: accession.id,
1579            extra: None,
1580        }];
1581        Annotation::bulk_create(&conn, "project-tracks", &annotations).unwrap();
1582        AnnotationGroupSample::create(&conn, "project-tracks", "sample-1").unwrap();
1583        AnnotationGroupSample::create(&conn, "project-tracks", "sample-2").unwrap();
1584        let annotation = Annotation::query_by_group(&conn, "project-tracks", None)
1585            .unwrap()
1586            .pop()
1587            .expect("should create annotation");
1588        Annotation::bulk_create(&conn, "project-tracks", &annotations).unwrap();
1589
1590        assert_eq!(
1591            Annotation::query_by_group(&conn, "project-tracks", None).unwrap(),
1592            vec![annotation.clone()]
1593        );
1594
1595        let mut samples = Annotation::get_samples(&conn, &annotation.group).unwrap();
1596        samples.sort();
1597        assert_eq!(
1598            samples,
1599            vec!["sample-1".to_string(), "sample-2".to_string()]
1600        );
1601
1602        let by_sample = Annotation::query_by_sample(&conn, "sample-1", None).unwrap();
1603        assert_eq!(by_sample.len(), 1);
1604        assert_eq!(by_sample[0], annotation);
1605
1606        let by_group = Annotation::query_by_group(&conn, "project-tracks", None).unwrap();
1607        assert_eq!(by_group, vec![annotation]);
1608    }
1609
1610    #[test]
1611    fn deserialize_annotation_extra_defaults_missing_fields() {
1612        // Ensure that if we add new fields to the AnnotationExtra struct, like new_annotation_format we still parse old ones
1613        let extra = deserialize_annotation_extra(Some(r#"{"genbank":{"kind":"CDS"}}"#.to_string()))
1614            .unwrap()
1615            .unwrap();
1616
1617        assert_eq!(
1618            extra.genbank,
1619            Some(GenBankExtra {
1620                kind: "CDS".to_string(),
1621                ..GenBankExtra::default()
1622            })
1623        );
1624        assert_eq!(extra.gff, None);
1625        assert_eq!(extra.bed, None);
1626    }
1627
1628    #[test]
1629    fn deserialize_annotation_extra_ignores_unknown_fields() {
1630        // ensure if we drop a format, removed_top_level key here, we still parse
1631        let extra = deserialize_annotation_extra(Some(
1632            r#"{"genbank":{"kind":"CDS","legacy_field":"value"},"removed_top_level":true}"#
1633                .to_string(),
1634        ))
1635        .unwrap()
1636        .unwrap();
1637
1638        assert_eq!(
1639            extra.genbank,
1640            Some(GenBankExtra {
1641                kind: "CDS".to_string(),
1642                ..GenBankExtra::default()
1643            })
1644        );
1645        assert_eq!(extra.gff, None);
1646        assert_eq!(extra.bed, None);
1647    }
1648
1649    #[test]
1650    fn deserialize_and_reserialize_annotation_extra_keeps_compatible_fields() {
1651        // Ensure that if we parse an older field, we can still reserialize it with the compatible fields kept.
1652        let extra = deserialize_annotation_extra(Some(
1653            r#"{"genbank":{"kind":"CDS","legacy_field":"value"},"removed_top_level":true}"#
1654                .to_string(),
1655        ))
1656        .unwrap()
1657        .unwrap();
1658
1659        let reserialized = serialize_annotation_extra(Some(&extra)).unwrap();
1660        let reparsed: AnnotationExtra = serde_json::from_str(&reserialized).unwrap();
1661
1662        assert_eq!(
1663            reparsed.genbank,
1664            Some(GenBankExtra {
1665                kind: "CDS".to_string(),
1666                ..GenBankExtra::default()
1667            })
1668        );
1669        assert_eq!(reparsed.gff, None);
1670        assert_eq!(reparsed.bed, None);
1671    }
1672
1673    #[test]
1674    fn parse_annotation_file_type_values() {
1675        assert_eq!(parse_annotation_file_type("gff3").unwrap(), FileTypes::Gff3);
1676        assert_eq!(parse_annotation_file_type("GFF").unwrap(), FileTypes::Gff3);
1677        assert_eq!(parse_annotation_file_type("bed").unwrap(), FileTypes::Bed);
1678        assert_eq!(
1679            parse_annotation_file_type("GenBank").unwrap(),
1680            FileTypes::GenBank
1681        );
1682        assert_eq!(
1683            parse_annotation_file_type("gb").unwrap(),
1684            FileTypes::GenBank
1685        );
1686        let err = parse_annotation_file_type("bam").unwrap_err();
1687        assert!(matches!(err, AnnotationFileError::UnsupportedFileType(_)));
1688    }
1689
1690    #[test]
1691    fn add_annotation_creates_annotation() {
1692        let context = setup_gen();
1693        let graph_conn = context.graph().conn();
1694        let history_store = DoltHistoryStore::new(graph_conn);
1695        let _ = setup_block_group(graph_conn);
1696
1697        let operation_summary = add_annotation(
1698            &context,
1699            "test",
1700            "gene-a",
1701            Some("track-1"),
1702            "test",
1703            "chr1:1-5",
1704        )
1705        .unwrap();
1706        let commit_hash = commit_operation_summary(&context, &operation_summary).unwrap();
1707        assert_eq!(history_store.current_head().unwrap(), Some(commit_hash));
1708        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
1709        operation_logs.sort_by_key(|operation_log| std::cmp::Reverse(operation_log.created_on));
1710        assert_eq!(
1711            operation_logs[0].operation_kind,
1712            OperationKind::Other("add annotation gene-a".to_string())
1713        );
1714
1715        let annotations = Annotation::query_by_group(graph_conn, "track-1", None).unwrap();
1716        assert_eq!(annotations.len(), 1);
1717        assert_eq!(annotations[0].name, "gene-a");
1718    }
1719
1720    #[test]
1721    fn test_add_annotation_detects_no_changes() {
1722        let context = setup_gen();
1723        let graph_conn = context.graph().conn();
1724        let _ = setup_block_group(graph_conn);
1725
1726        let operation_summary = add_annotation(
1727            &context,
1728            "test",
1729            "gene-a",
1730            Some("track-1"),
1731            "test",
1732            "chr1:1-5",
1733        )
1734        .unwrap();
1735        commit_operation_summary(&context, &operation_summary).unwrap();
1736
1737        let operation_summary = add_annotation(
1738            &context,
1739            "test",
1740            "gene-a",
1741            Some("track-1"),
1742            "test",
1743            "chr1:1-5",
1744        )
1745        .unwrap();
1746        let error = commit_operation_summary(&context, &operation_summary).unwrap_err();
1747        assert_eq!(error, OperationError::NoChanges);
1748    }
1749
1750    #[test]
1751    fn add_annotation_file_creates_operation() {
1752        let context = setup_gen();
1753        let graph_conn = context.graph().conn();
1754        let history_store = DoltHistoryStore::new(graph_conn);
1755
1756        let repo_root = context.workspace().repo_root().unwrap();
1757        let annotation_path = repo_root.join("fixtures").join("annotation.gff3");
1758        fs::create_dir_all(annotation_path.parent().unwrap()).unwrap();
1759        fs::write(&annotation_path, "##gff-version 3\n").unwrap();
1760        let annotation_path_str = annotation_path.to_string_lossy().to_string();
1761
1762        let commit_hash = add_annotation_file(
1763            &context,
1764            &annotation_path_str,
1765            None,
1766            None,
1767            Some("track-1"),
1768            None,
1769            AnnotationFileChecksumOverrides::default(),
1770        )
1771        .unwrap();
1772        assert_eq!(history_store.current_head().unwrap(), Some(commit_hash));
1773
1774        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
1775        asset_refs.sort_by(|left, right| left.role.as_str().cmp(right.role.as_str()));
1776        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
1777        operation_logs.sort_by_key(|operation_log| operation_log.created_on);
1778        assert_eq!(asset_refs.len(), 3);
1779        let annotation_asset = asset_refs
1780            .iter()
1781            .find(|asset| asset.role == AssetRole::Annotation)
1782            .expect("should track the annotation source");
1783        assert_eq!(annotation_asset.name.as_deref(), Some("track-1"));
1784        assert!(
1785            annotation_asset
1786                .logical_path
1787                .as_deref()
1788                .unwrap_or_default()
1789                .ends_with("fixtures/annotation.gff3")
1790        );
1791        assert!(asset_refs.iter().any(|asset| {
1792            asset.role == AssetRole::AnnotationIndex
1793                && asset.upstream_asset_ref_id == Some(annotation_asset.id)
1794        }));
1795        assert!(asset_refs.iter().any(|asset| {
1796            asset.role == AssetRole::Other(ANNOTATION_ATTRIBUTE_INDEX_ROLE.to_string())
1797                && asset.upstream_asset_ref_id == Some(annotation_asset.id)
1798        }));
1799        assert_eq!(operation_logs.len(), 1);
1800        assert_eq!(
1801            operation_logs[0].operation_kind,
1802            OperationKind::AnnotationFile
1803        );
1804        let operation_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
1805        assert_eq!(operation_assets.len(), 3);
1806        assert!(
1807            history_store
1808                .log(None)
1809                .unwrap()
1810                .iter()
1811                .any(|entry| entry.commit_hash == commit_hash
1812                    && entry.message.contains("Add annotation file"))
1813        );
1814
1815        let error = add_annotation_file(
1816            &context,
1817            &annotation_path_str,
1818            None,
1819            None,
1820            Some("track-1"),
1821            None,
1822            AnnotationFileChecksumOverrides::default(),
1823        )
1824        .unwrap_err();
1825        assert!(matches!(
1826            error,
1827            AnnotationFileError::OperationError(OperationError::NoChanges)
1828        ));
1829    }
1830
1831    #[test]
1832    fn test_add_annotation_file_rebuilds_local_gff_indexes_after_sorting() {
1833        let context = setup_gen();
1834        let graph_conn = context.graph().conn();
1835
1836        let repo_root = context
1837            .workspace()
1838            .repo_root()
1839            .expect("should have repo root");
1840        let annotation_path = repo_root
1841            .join("fixtures")
1842            .join("annotation-with-index.gff3");
1843        let index_path = repo_root.join("fixtures").join("annotation-with-index.csi");
1844        let annotation_contents = b"##gff-version 3\n";
1845        let index_contents = b"index";
1846        fs::create_dir_all(
1847            annotation_path
1848                .parent()
1849                .expect("should have annotation parent directory"),
1850        )
1851        .expect("should create fixture directory");
1852        fs::write(&annotation_path, annotation_contents).expect("should write annotation fixture");
1853        fs::write(&index_path, index_contents).expect("should write index fixture");
1854
1855        add_annotation_file(
1856            &context,
1857            annotation_path
1858                .to_str()
1859                .expect("should encode annotation path"),
1860            None,
1861            Some(index_path.to_str().expect("should encode index path")),
1862            Some("track-with-index"),
1863            None,
1864            AnnotationFileChecksumOverrides::default(),
1865        )
1866        .expect("should create annotation file operation");
1867
1868        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
1869        asset_refs.sort_by(|left, right| {
1870            left.role
1871                .as_str()
1872                .cmp(right.role.as_str())
1873                .then_with(|| left.logical_path.cmp(&right.logical_path))
1874        });
1875        assert_eq!(asset_refs.len(), 3);
1876        let annotation_asset = asset_refs
1877            .iter()
1878            .find(|asset| asset.role == AssetRole::Annotation)
1879            .expect("should track the annotation source");
1880        let coordinate_index = asset_refs
1881            .iter()
1882            .find(|asset| asset.role == AssetRole::AnnotationIndex)
1883            .expect("should rebuild a coordinate index");
1884        let attribute_index = asset_refs
1885            .iter()
1886            .find(|asset| {
1887                asset.role == AssetRole::Other(ANNOTATION_ATTRIBUTE_INDEX_ROLE.to_string())
1888            })
1889            .expect("should build an attribute index");
1890        assert_eq!(
1891            coordinate_index.upstream_asset_ref_id,
1892            Some(annotation_asset.id)
1893        );
1894        assert_eq!(
1895            attribute_index.upstream_asset_ref_id,
1896            Some(annotation_asset.id)
1897        );
1898        assert_eq!(
1899            annotation_asset.checksum,
1900            Some(
1901                calculate_file_checksum(
1902                    annotation_asset
1903                        .versioned_store_path(context.workspace())
1904                        .expect("should resolve retained BGZF annotation")
1905                )
1906                .expect("should checksum retained BGZF annotation")
1907            )
1908        );
1909        assert_eq!(
1910            annotation_asset.materialized_checksum,
1911            Some(calculate_reader_checksum(annotation_contents.as_slice()).unwrap())
1912        );
1913        assert!(annotation_asset.uri.ends_with(".gff3.bgz"));
1914        let archive_path = annotation_asset
1915            .versioned_store_path(context.workspace())
1916            .expect("should resolve retained BGZF annotation");
1917        let mut decoded = noodles::bgzf::io::Reader::new(
1918            fs::File::open(archive_path).expect("should open retained BGZF annotation"),
1919        );
1920        let mut decoded_contents = Vec::new();
1921        decoded
1922            .read_to_end(&mut decoded_contents)
1923            .expect("should decompress retained annotation bytes");
1924        assert_eq!(decoded_contents, annotation_contents);
1925        assert_eq!(fs::read(&annotation_path).unwrap(), annotation_contents);
1926        assert_eq!(fs::read(&index_path).unwrap(), index_contents);
1927        assert_eq!(coordinate_index.file_type.as_str(), "tabix");
1928        assert!(coordinate_index.uri.ends_with(".csi"));
1929        assert_eq!(attribute_index.file_type.as_str(), "none");
1930        assert!(attribute_index.uri.ends_with(".gai"));
1931
1932        let err = add_annotation_file(
1933            &context,
1934            annotation_path
1935                .to_str()
1936                .expect("should encode annotation path"),
1937            None,
1938            Some(index_path.to_str().expect("should encode index path")),
1939            Some("track-with-index"),
1940            None,
1941            AnnotationFileChecksumOverrides::default(),
1942        )
1943        .unwrap_err();
1944        assert!(matches!(
1945            err,
1946            AnnotationFileError::OperationError(OperationError::NoChanges)
1947        ));
1948    }
1949
1950    #[test]
1951    fn test_add_annotation_file_sorts_local_gff() {
1952        let context = setup_gen();
1953        let graph_conn = context.graph().conn();
1954        let annotation_path = context
1955            .workspace()
1956            .repo_root()
1957            .unwrap()
1958            .join("features.gff3");
1959        let input = concat!(
1960            "##gff-version 3\n",
1961            "m123\tsource\tgene\t20\t25\t.\t+\t.\tName=Beta-feature\n",
1962            "m123\tsource\tgene\t2\t4\t.\t+\t.\tName=Alpha-feature\n",
1963            "m123\tsource\tgene\t10\t12\t.\t-\t.\tName=Gamma-feature\n",
1964        );
1965        let source_checksum = calculate_reader_checksum(input.as_bytes())
1966            .expect("should checksum original unsorted GFF input");
1967        fs::write(&annotation_path, input).expect("should write unsorted GFF input");
1968
1969        add_annotation_file(
1970            &context,
1971            annotation_path
1972                .to_str()
1973                .expect("should encode annotation path"),
1974            None,
1975            None,
1976            Some("sorted-gff"),
1977            None,
1978            AnnotationFileChecksumOverrides {
1979                annotation: Some(source_checksum),
1980                index: None,
1981            },
1982        )
1983        .expect("should sort and index local GFF input");
1984
1985        assert_eq!(fs::read_to_string(&annotation_path).unwrap(), input);
1986        let assets = AssetRef::all(graph_conn).expect("should load generated annotation assets");
1987        let annotation = assets
1988            .iter()
1989            .find(|asset| asset.role == AssetRole::Annotation)
1990            .expect("should track GFF source");
1991
1992        let source_path = annotation
1993            .versioned_store_path(context.workspace())
1994            .expect("should resolve retained BGZF source");
1995        let retained_bgzf_bytes = fs::read(&source_path).expect("should read retained BGZF bytes");
1996        let archive_checksum = calculate_reader_checksum(retained_bgzf_bytes.as_slice())
1997            .expect("should checksum retained BGZF archive bytes");
1998        assert_eq!(annotation.checksum, Some(archive_checksum));
1999        let mut bgzf_reader = noodles::bgzf::io::Reader::new(
2000            fs::File::open(&source_path).expect("should open retained BGZF source"),
2001        );
2002        let mut sorted_text = String::new();
2003        bgzf_reader
2004            .read_to_string(&mut sorted_text)
2005            .expect("should decode sorted GFF source");
2006        let sorted_checksum = calculate_reader_checksum(sorted_text.as_bytes())
2007            .expect("should checksum sorted annotation content");
2008        assert_eq!(annotation.materialized_checksum, Some(sorted_checksum));
2009        assert_ne!(annotation.materialized_checksum, Some(source_checksum));
2010        let sorted_positions = sorted_text
2011            .lines()
2012            .filter(|line| !line.starts_with('#'))
2013            .map(|line| line.split('\t').nth(3).unwrap())
2014            .collect::<Vec<_>>();
2015        assert_eq!(sorted_positions, ["2", "10", "20"]);
2016    }
2017
2018    #[test]
2019    fn test_add_annotation_file_builds_local_gff_csi() {
2020        let context = setup_gen();
2021        let graph_conn = context.graph().conn();
2022        let annotation_path = context
2023            .workspace()
2024            .repo_root()
2025            .unwrap()
2026            .join("features.gff3");
2027        let input = concat!(
2028            "##gff-version 3\n",
2029            "m123\tsource\tgene\t600000002\t600000004\t.\t+\t.\tName=Alpha-feature\n",
2030            "m123\tsource\tgene\t600000020\t600000025\t.\t+\t.\tName=Beta-feature\n",
2031        );
2032        fs::write(&annotation_path, input).expect("should write sorted GFF input");
2033
2034        add_annotation_file(
2035            &context,
2036            annotation_path
2037                .to_str()
2038                .expect("should encode annotation path"),
2039            None,
2040            None,
2041            Some("indexed-gff"),
2042            None,
2043            AnnotationFileChecksumOverrides::default(),
2044        )
2045        .expect("should index local GFF input");
2046
2047        let assets = AssetRef::all(graph_conn).expect("should load generated annotation assets");
2048        assert_eq!(assets.len(), 3);
2049        let annotation = assets
2050            .iter()
2051            .find(|asset| asset.role == AssetRole::Annotation)
2052            .expect("should track GFF source");
2053        let coordinate_index = assets
2054            .iter()
2055            .find(|asset| asset.role == AssetRole::AnnotationIndex)
2056            .expect("should track CSI coordinate index");
2057        assert!(annotation.uri.ends_with(".gff3.bgz"));
2058        assert!(coordinate_index.uri.ends_with(".csi"));
2059        assert_eq!(coordinate_index.file_type, FileTypes::Tabix.as_str());
2060        assert_eq!(
2061            coordinate_index.upstream_asset_ref_id,
2062            Some(annotation.id),
2063            "CSI metadata should link to its annotation source"
2064        );
2065
2066        let source_path = annotation
2067            .versioned_store_path(context.workspace())
2068            .expect("should resolve retained BGZF source");
2069        let coordinate_index_path = coordinate_index
2070            .versioned_store_path(context.workspace())
2071            .expect("should resolve retained CSI index");
2072        let coordinate_index = noodles::csi::fs::read(&coordinate_index_path)
2073            .expect("should read coordinate index generated from BGZF bytes");
2074        let mut indexed_reader = noodles::csi::io::IndexedReader::new(
2075            File::open(&source_path).unwrap(),
2076            coordinate_index,
2077        );
2078        let region: noodles::core::Region = "m123:600000002-600000002".parse().unwrap();
2079        let records = indexed_reader
2080            .query(&region)
2081            .unwrap()
2082            .map(|result| result.unwrap().as_ref().as_bytes().to_vec())
2083            .collect::<Vec<_>>();
2084        assert_eq!(records.len(), 1);
2085        assert!(String::from_utf8_lossy(&records[0]).contains("Alpha-feature"));
2086    }
2087
2088    #[test]
2089    fn test_add_annotation_file_failure_stops_stage_notifications() {
2090        let context = setup_gen();
2091        let annotation_path = context
2092            .workspace()
2093            .repo_root()
2094            .unwrap()
2095            .join("invalid.gff3");
2096        fs::write(&annotation_path, "not a GFF feature record\n")
2097            .expect("should write invalid GFF input");
2098        let mut progress_events = Vec::new();
2099        let error = {
2100            let mut on_progress = |stage| progress_events.push(stage);
2101            add_annotation_file_with_progress(
2102                &context,
2103                annotation_path
2104                    .to_str()
2105                    .expect("should encode invalid annotation path"),
2106                None,
2107                None,
2108                Some("invalid-gff"),
2109                None,
2110                AnnotationFileAddOptions {
2111                    checksum_overrides: AnnotationFileChecksumOverrides::default(),
2112                    progress: Some(&mut on_progress),
2113                },
2114            )
2115            .expect_err("should reject malformed GFF input while sorting")
2116        };
2117
2118        assert!(matches!(error, AnnotationFileError::GaiError(_)));
2119        assert_eq!(progress_events, [AnnotationFileProgressStage::Sorting]);
2120    }
2121
2122    #[test]
2123    fn test_add_annotation_file_indexes_bed4_names_after_sorting() {
2124        let context = setup_gen();
2125        let annotation_path = context
2126            .workspace()
2127            .repo_root()
2128            .unwrap()
2129            .join("features.bed");
2130        let input = "m123\t10\t16\texon-z\nm123\t1\t5\texon-a\n";
2131        fs::write(&annotation_path, input).expect("should write unsorted BED4 input");
2132        let mut progress_events = Vec::new();
2133        {
2134            let mut on_progress = |stage| progress_events.push(stage);
2135            add_annotation_file_with_progress(
2136                &context,
2137                annotation_path
2138                    .to_str()
2139                    .expect("should encode annotation path"),
2140                None,
2141                None,
2142                Some("search-bed"),
2143                None,
2144                AnnotationFileAddOptions {
2145                    checksum_overrides: AnnotationFileChecksumOverrides::default(),
2146                    progress: Some(&mut on_progress),
2147                },
2148            )
2149            .expect("should sort and index local BED4 input");
2150        }
2151        assert_eq!(
2152            progress_events,
2153            [
2154                AnnotationFileProgressStage::Sorting,
2155                AnnotationFileProgressStage::Compressing,
2156                AnnotationFileProgressStage::BuildingIndex,
2157            ]
2158        );
2159
2160        assert_eq!(fs::read_to_string(&annotation_path).unwrap(), input);
2161        let assets =
2162            AssetRef::all(context.graph().conn()).expect("should load generated annotation assets");
2163        let annotation = assets
2164            .iter()
2165            .find(|asset| asset.role == AssetRole::Annotation)
2166            .expect("should track BED source");
2167        let coordinate_index = assets
2168            .iter()
2169            .find(|asset| asset.role == AssetRole::AnnotationIndex)
2170            .expect("should track BED coordinate index");
2171        let attribute_index = assets
2172            .iter()
2173            .find(|asset| {
2174                asset.role == AssetRole::Other(ANNOTATION_ATTRIBUTE_INDEX_ROLE.to_string())
2175            })
2176            .expect("should track BED name index");
2177        let source_path = annotation
2178            .versioned_store_path(context.workspace())
2179            .expect("should resolve BGZF source");
2180        let coordinate_index_path = coordinate_index
2181            .versioned_store_path(context.workspace())
2182            .expect("should resolve CSI index");
2183        let attribute_index_path = attribute_index
2184            .versioned_store_path(context.workspace())
2185            .expect("should resolve GAI index");
2186        let mut bgzf_reader = bgzf::io::Reader::new(File::open(&source_path).unwrap());
2187        let mut sorted_text = String::new();
2188        bgzf_reader.read_to_string(&mut sorted_text).unwrap();
2189        assert_eq!(
2190            sorted_text.lines().collect::<Vec<_>>(),
2191            ["m123\t1\t5\texon-a", "m123\t10\t16\texon-z"]
2192        );
2193
2194        let mut indexed_source =
2195            gai::IndexedSource::open(&source_path, &coordinate_index_path, &attribute_index_path)
2196                .expect("should open BED source with both indexes");
2197        let hits = indexed_source
2198            .query_with_mode("exon-", gai::MatchMode::Prefix)
2199            .unwrap();
2200        assert_eq!(hits.len(), 2);
2201        assert_eq!(hits[0].raw_line, "m123\t1\t5\texon-a");
2202        assert_eq!(hits[1].raw_line, "m123\t10\t16\texon-z");
2203    }
2204
2205    #[test]
2206    fn test_add_annotation_file_builds_local_gff_attribute_index() {
2207        let context = setup_gen();
2208        let graph_conn = context.graph().conn();
2209        let annotation_path = context
2210            .workspace()
2211            .repo_root()
2212            .unwrap()
2213            .join("features.gff3");
2214        let input = concat!(
2215            "##gff-version 3\n",
2216            "m123\tsource\tgene\t2\t4\t.\t+\t.\tID=id-only-term;Name=Alpha-feature\n",
2217            "m123\tsource\tgene\t10\t12\t.\t-\t.\tID=other-id;Name=Gamma-feature\n",
2218            "m123\tsource\tgene\t20\t25\t.\t+\t.\tID=private-id;Name=Beta-feature;name=foobar;gene=alternate-beta;db_xref=GeneID:123\n",
2219            "m123\tsource\tgene\t30\t35\t.\t+\t.\tID=private-gene-name-only;gene_name=BRCA1\n",
2220        );
2221        fs::write(&annotation_path, input).expect("should write GFF input with searchable names");
2222
2223        add_annotation_file(
2224            &context,
2225            annotation_path
2226                .to_str()
2227                .expect("should encode annotation path"),
2228            None,
2229            None,
2230            Some("indexed-gff"),
2231            None,
2232            AnnotationFileChecksumOverrides::default(),
2233        )
2234        .expect("should index configured GFF attributes");
2235
2236        let assets = AssetRef::all(graph_conn).expect("should load generated annotation assets");
2237        assert_eq!(assets.len(), 3);
2238        let annotation = assets
2239            .iter()
2240            .find(|asset| asset.role == AssetRole::Annotation)
2241            .expect("should track GFF source");
2242        let coordinate_index = assets
2243            .iter()
2244            .find(|asset| asset.role == AssetRole::AnnotationIndex)
2245            .expect("should track CSI coordinate index");
2246        let attribute_index = assets
2247            .iter()
2248            .find(|asset| {
2249                asset.role == AssetRole::Other(ANNOTATION_ATTRIBUTE_INDEX_ROLE.to_string())
2250            })
2251            .expect("should track GAI attribute index");
2252        assert!(attribute_index.uri.ends_with(".gai"));
2253        assert_eq!(attribute_index.file_type, FileTypes::None.as_str());
2254        assert_eq!(
2255            attribute_index.upstream_asset_ref_id,
2256            Some(annotation.id),
2257            "GAI metadata should link to its annotation source"
2258        );
2259
2260        let source_path = annotation
2261            .versioned_store_path(context.workspace())
2262            .expect("should resolve retained BGZF source");
2263        let coordinate_index_path = coordinate_index
2264            .versioned_store_path(context.workspace())
2265            .expect("should resolve retained CSI index");
2266        let attribute_index_path = attribute_index
2267            .versioned_store_path(context.workspace())
2268            .expect("should resolve retained GAI index");
2269        assert_eq!(
2270            gai::inspect_index(&attribute_index_path)
2271                .expect("should inspect retained GAI index")
2272                .attributes,
2273            vec![
2274                "Name".to_string(),
2275                "name".to_string(),
2276                "gene".to_string(),
2277                "gene_name".to_string(),
2278                "db_xref".to_string(),
2279            ]
2280        );
2281        let mut indexed_source =
2282            gai::IndexedSource::open(&source_path, &coordinate_index_path, &attribute_index_path)
2283                .expect("should open retained BGZF, CSI, and GAI files");
2284        assert_eq!(
2285            indexed_source.metadata().attributes,
2286            ["Name", "name", "gene", "gene_name", "db_xref"]
2287        );
2288        for query in ["beta", "alternate", "foobar", "GeneID:123"] {
2289            assert_eq!(
2290                indexed_source
2291                    .query_with_mode(query, gai::MatchMode::Prefix)
2292                    .expect("should query a configured GFF attribute")
2293                    .len(),
2294                1,
2295                "should find the value {query}"
2296            );
2297        }
2298        let gene_name_hits = indexed_source
2299            .query_with_mode("brca1", gai::MatchMode::Prefix)
2300            .expect("should query configured gene_name attribute");
2301        assert_eq!(gene_name_hits.len(), 1);
2302        assert!(gene_name_hits[0].raw_line.contains("gene_name=BRCA1"));
2303        assert!(
2304            indexed_source
2305                .query_with_mode("private-gene-name-only", gai::MatchMode::Prefix)
2306                .expect("should query for a private ID")
2307                .is_empty()
2308                && indexed_source
2309                    .query_with_mode("id-only-term", gai::MatchMode::Prefix)
2310                    .expect("should query for an ID-only term")
2311                    .is_empty(),
2312            "the ID attribute should not be indexed"
2313        );
2314    }
2315
2316    #[test]
2317    fn test_add_annotation_file_does_not_read_remote_assets() {
2318        let context = setup_gen();
2319        let annotation_uri = "http://127.0.0.1:1/annotation.gff3".to_string();
2320        let index_uri = "http://127.0.0.1:1/annotation.gff3.csi".to_string();
2321        let mut progress_events = Vec::new();
2322
2323        {
2324            let mut on_progress = |stage| progress_events.push(stage);
2325            add_annotation_file_with_progress(
2326                &context,
2327                &annotation_uri,
2328                None,
2329                Some(&index_uri),
2330                Some("remote-annotation"),
2331                None,
2332                AnnotationFileAddOptions {
2333                    checksum_overrides: AnnotationFileChecksumOverrides::default(),
2334                    progress: Some(&mut on_progress),
2335                },
2336            )
2337            .expect("should track remote annotation assets");
2338        }
2339        assert!(progress_events.is_empty());
2340
2341        let asset_refs =
2342            AssetRef::all(context.graph().conn()).expect("should load asset references");
2343        assert_eq!(asset_refs.len(), 2);
2344        assert!(
2345            asset_refs
2346                .iter()
2347                .all(|asset_ref| asset_ref.checksum.is_none())
2348        );
2349        assert!(
2350            asset_refs
2351                .iter()
2352                .any(|asset_ref| asset_ref.uri == annotation_uri)
2353        );
2354        assert!(
2355            asset_refs
2356                .iter()
2357                .any(|asset_ref| asset_ref.uri == index_uri)
2358        );
2359    }
2360
2361    #[test]
2362    fn test_add_non_gff_bed_annotation_file_has_no_sort_progress() {
2363        let context = setup_gen();
2364        let annotation_path = context
2365            .workspace()
2366            .repo_root()
2367            .unwrap()
2368            .join("annotation.gb");
2369        fs::write(&annotation_path, "LOCUS       test\n")
2370            .expect("should write non-GFF/BED annotation input");
2371        let mut progress_events = Vec::new();
2372
2373        {
2374            let mut on_progress = |stage| progress_events.push(stage);
2375            add_annotation_file_with_progress(
2376                &context,
2377                annotation_path
2378                    .to_str()
2379                    .expect("should encode non-GFF/BED annotation path"),
2380                None,
2381                None,
2382                Some("genbank-annotation"),
2383                None,
2384                AnnotationFileAddOptions {
2385                    checksum_overrides: AnnotationFileChecksumOverrides::default(),
2386                    progress: Some(&mut on_progress),
2387                },
2388            )
2389            .expect("should add non-GFF/BED annotation without sort progress");
2390        }
2391
2392        assert!(progress_events.is_empty());
2393    }
2394
2395    #[test]
2396    fn test_add_annotation_file_passes_remote_checksum_overrides() {
2397        let context = setup_gen();
2398        let annotation_uri = "http://127.0.0.1:1/annotation.gff3";
2399        let index_uri = "http://127.0.0.1:1/annotation.gff3.csi";
2400        let annotation_checksum = Sha256Hash::convert_str("known annotation contents");
2401        let index_checksum = Sha256Hash::convert_str("known index contents");
2402
2403        add_annotation_file(
2404            &context,
2405            annotation_uri,
2406            None,
2407            Some(index_uri),
2408            Some("remote-annotation"),
2409            None,
2410            AnnotationFileChecksumOverrides {
2411                annotation: Some(annotation_checksum),
2412                index: Some(index_checksum),
2413            },
2414        )
2415        .expect("should track checksummed remote assets without reading them");
2416
2417        let asset_refs =
2418            AssetRef::all(context.graph().conn()).expect("should load asset references");
2419        assert_eq!(asset_refs.len(), 2);
2420        let annotation = asset_refs
2421            .iter()
2422            .find(|asset_ref| asset_ref.role == AssetRole::Annotation)
2423            .expect("should track annotation asset");
2424        let index = asset_refs
2425            .iter()
2426            .find(|asset_ref| asset_ref.role == AssetRole::AnnotationIndex)
2427            .expect("should track annotation index");
2428        assert_eq!(annotation.uri, annotation_uri);
2429        assert_eq!(annotation.checksum, Some(annotation_checksum));
2430        assert_eq!(index.uri, index_uri);
2431        assert_eq!(index.checksum, Some(index_checksum));
2432    }
2433
2434    #[test]
2435    fn test_add_annotation_file_does_not_store_absolute_external_index_path() {
2436        let context = setup_gen();
2437        let graph_conn = context.graph().conn();
2438        let repo_root = context
2439            .workspace()
2440            .repo_root()
2441            .expect("should have repo root");
2442        let annotation_path = repo_root.join("annotation.gff3");
2443        fs::write(&annotation_path, "##gff-version 3\n").expect("should write annotation fixture");
2444
2445        let external_dir = tempfile::tempdir().expect("should create external directory");
2446        let index_path = external_dir.path().join("private-index.csi");
2447        fs::write(&index_path, "private index contents").expect("should write external index");
2448        let index_path = index_path
2449            .to_str()
2450            .expect("should encode external index path");
2451
2452        add_annotation_file(
2453            &context,
2454            annotation_path
2455                .to_str()
2456                .expect("should encode annotation path"),
2457            None,
2458            Some(index_path),
2459            None,
2460            None,
2461            AnnotationFileChecksumOverrides::default(),
2462        )
2463        .expect("should create annotation file operation");
2464
2465        let assets = AssetRef::all(graph_conn).expect("should load asset references");
2466        let index_asset = assets
2467            .iter()
2468            .find(|asset| asset.role == AssetRole::AnnotationIndex)
2469            .expect("should store generated coordinate index asset");
2470        assert_eq!(
2471            index_asset.logical_path.as_deref(),
2472            Some("annotation.gff3.csi")
2473        );
2474        assert!(!index_asset.uri.contains(index_path));
2475        assert!(assets.iter().any(|asset| {
2476            asset.role == AssetRole::Other(ANNOTATION_ATTRIBUTE_INDEX_ROLE.to_string())
2477                && asset
2478                    .logical_path
2479                    .as_deref()
2480                    .is_some_and(|path| path.ends_with(".gai"))
2481        }));
2482        assert!(!assets.iter().any(|asset| asset.uri.contains(index_path)));
2483    }
2484
2485    #[test]
2486    fn test_annotation_and_accession_interval_tree_caches_are_runtime_only() {
2487        let conn = get_connection(None).unwrap();
2488        let annotation_id = HashId::convert_str("cached-annotation");
2489        let accession_id = HashId::convert_str("cached-accession");
2490        let block_group_id = HashId::convert_str("cached-block-group");
2491        let tree: IntervalTree<i64, NodeIntervalBlock> = [(
2492            0..4,
2493            NodeIntervalBlock {
2494                node_id: HashId::convert_str("cached-node"),
2495                start: 0,
2496                end: 4,
2497                sequence_start: 3,
2498                sequence_end: 7,
2499                strand: Strand::Reverse,
2500            },
2501        )]
2502        .into_iter()
2503        .collect();
2504        let shared_tree = Arc::new(tree);
2505        let mut accession = Accession {
2506            id: accession_id,
2507            name: "cached-accession".to_string(),
2508            block_group_id,
2509            parent_accession_id: None,
2510            cached_interval_tree: None,
2511            history_ref: Some("saved-ref".to_string()),
2512        };
2513        accession.set_cached_interval_tree(Some(Arc::clone(&shared_tree)));
2514        let mut annotation = Annotation {
2515            id: annotation_id,
2516            name: "cached-annotation".to_string(),
2517            group: "test".to_string(),
2518            accession_id,
2519            cached_accession: ForeignKeyCache::default(),
2520            cached_interval_tree: None,
2521            history_ref: Some("saved-ref".to_string()),
2522            extra: None,
2523        };
2524        annotation.set_cached_interval_tree(Some(Arc::clone(&shared_tree)));
2525        let shared_accession = Arc::new(accession.clone());
2526        annotation.set_accession(Arc::clone(&shared_accession));
2527
2528        assert!(
2529            Accession::select(&conn)
2530                .id(accession_id)
2531                .load()
2532                .expect("should query absent accession")
2533                .is_empty()
2534        );
2535        assert!(
2536            Annotation::select(&conn)
2537                .id(annotation_id)
2538                .load()
2539                .expect("should query absent annotation")
2540                .is_empty()
2541        );
2542        let annotation_tree = annotation
2543            .intervaltree(&conn)
2544            .expect("should return cached annotation tree without database rows");
2545        let annotation_accession = annotation
2546            .get_accession(&conn)
2547            .expect("should return cached annotation accession without database rows");
2548        let accession_tree = accession
2549            .intervaltree(&conn)
2550            .expect("should return cached accession tree without database rows");
2551        assert!(Arc::ptr_eq(&annotation_tree, &shared_tree));
2552        assert!(Arc::ptr_eq(&annotation_accession, &shared_accession));
2553        assert!(Arc::ptr_eq(&accession_tree, &shared_tree));
2554        let mut annotation_without_tree = annotation.clone();
2555        annotation_without_tree.set_cached_interval_tree(None);
2556        let tree_from_cached_accession = annotation_without_tree
2557            .intervaltree(&conn)
2558            .expect("should load annotation tree from cached accession");
2559        assert!(Arc::ptr_eq(&tree_from_cached_accession, &shared_tree));
2560        assert_eq!(
2561            annotation_without_tree
2562                .length(&conn)
2563                .expect("should get annotation length from cached accession tree"),
2564            4
2565        );
2566        assert_eq!(
2567            accession
2568                .length(&conn)
2569                .expect("should get cached accession length"),
2570            4
2571        );
2572
2573        let cloned_annotation = annotation.clone();
2574        let cloned_accession = accession.clone();
2575        assert!(Arc::ptr_eq(
2576            &annotation_tree,
2577            cloned_annotation
2578                .cached_interval_tree()
2579                .expect("should clone annotation cache")
2580        ));
2581        let cloned_related_accession = cloned_annotation
2582            .cached_accession
2583            .snapshot()
2584            .expect("should clone annotation accession cache");
2585        assert!(Arc::ptr_eq(
2586            &annotation_accession,
2587            &cloned_related_accession
2588        ));
2589        assert!(Arc::ptr_eq(
2590            &accession_tree,
2591            cloned_accession
2592                .cached_interval_tree()
2593                .expect("should clone accession cache")
2594        ));
2595
2596        let mut uncached_annotation = annotation.clone();
2597        uncached_annotation.set_cached_interval_tree(None);
2598        uncached_annotation.cached_accession.replace(None);
2599        assert!(uncached_annotation.cached_accession.snapshot().is_none());
2600        assert!(annotation.cached_accession.snapshot().is_some());
2601        let mut uncached_accession = accession.clone();
2602        uncached_accession.set_cached_interval_tree(None);
2603        assert_eq!(annotation, uncached_annotation);
2604        assert_eq!(accession, uncached_accession);
2605        assert_eq!(
2606            serde_json::to_value(&annotation).expect("should serialize annotation"),
2607            serde_json::to_value(&uncached_annotation)
2608                .expect("should serialize uncached annotation")
2609        );
2610        assert_eq!(
2611            serde_json::to_value(&accession).expect("should serialize accession"),
2612            serde_json::to_value(&uncached_accession).expect("should serialize uncached accession")
2613        );
2614        assert!(
2615            serde_json::to_value(&annotation)
2616                .expect("should serialize annotation")
2617                .get("history_ref")
2618                .is_none()
2619        );
2620        assert!(
2621            serde_json::to_value(&accession)
2622                .expect("should serialize accession")
2623                .get("history_ref")
2624                .is_none()
2625        );
2626        assert!(
2627            serde_json::from_value::<Annotation>(
2628                serde_json::to_value(&annotation).expect("should serialize annotation")
2629            )
2630            .expect("should deserialize annotation")
2631            .cached_interval_tree()
2632            .is_none()
2633        );
2634        assert!(
2635            serde_json::from_value::<Annotation>(
2636                serde_json::to_value(&annotation).expect("should serialize annotation")
2637            )
2638            .expect("should deserialize annotation")
2639            .cached_accession
2640            .snapshot()
2641            .is_none()
2642        );
2643        assert_eq!(
2644            serde_json::from_value::<Annotation>(
2645                serde_json::to_value(&annotation).expect("should serialize annotation")
2646            )
2647            .expect("should deserialize annotation")
2648            .history_ref(),
2649            None
2650        );
2651        assert!(
2652            serde_json::from_value::<Accession>(
2653                serde_json::to_value(&accession).expect("should serialize accession")
2654            )
2655            .expect("should deserialize accession")
2656            .cached_interval_tree()
2657            .is_none()
2658        );
2659    }
2660
2661    #[test]
2662    fn test_annotation_history_ref_loads_historical_accession_nodes() {
2663        let conn = get_connection(None).unwrap();
2664        let (_block_group_id, path) = setup_block_group(&conn);
2665        let accession =
2666            BlockGroup::add_accession(&conn, &path, "history-accession", 0, 10).unwrap();
2667        let annotation =
2668            Annotation::get_or_create(&conn, "history-annotation", "test", &accession.id, None)
2669                .unwrap();
2670        let history_ref: String = conn
2671            .query_row(
2672                "SELECT dolt_commit('-A', '-m', 'save historical annotation accession')",
2673                [],
2674                |row| row.get(0),
2675            )
2676            .unwrap();
2677
2678        conn.execute(
2679            "DELETE FROM accession_nodes WHERE accession_id = ?1",
2680            [accession.id],
2681        )
2682        .unwrap();
2683        assert!(Accession::get_nodes_by_id(&conn, &accession.id, None).is_empty());
2684
2685        let annotation = Annotation::select(&conn)
2686            .id(annotation.id)
2687            .with_ref(history_ref.as_str())
2688            .get()
2689            .unwrap()
2690            .unwrap();
2691        assert_eq!(annotation.history_ref(), Some(history_ref.as_str()));
2692
2693        let accession = annotation.get_accession(&conn).unwrap();
2694        assert_eq!(accession.history_ref(), Some(history_ref.as_str()));
2695        assert_eq!(accession.length(&conn).unwrap(), 10);
2696        assert_eq!(annotation.length(&conn).unwrap(), 10);
2697        assert!(
2698            annotation
2699                .intervaltree(&conn)
2700                .unwrap()
2701                .query(0..10)
2702                .next()
2703                .is_some()
2704        );
2705    }
2706}