Skip to main content

gen_models/
annotations.rs

1use std::path::{Path, PathBuf};
2
3use gen_core::{
4    DoltHashId, HashId, NodeIntervalBlock, Sha256Hash, calculate_hash,
5    config::Workspace,
6    region::{Region, RegionResolutionError, RegionResolver},
7    traits::Capnp,
8};
9use intervaltree::IntervalTree;
10use rusqlite::{Result as SqlResult, Row, params, types::Type};
11use serde::{Deserialize, Serialize};
12use thiserror::Error;
13
14use crate::{
15    Direction, ModelSelect, ModelSelectError,
16    accession::{Accession, AccessionError, AccessionSelect, AccessionSpan, NewAccession},
17    assets::{AssetRef, AssetRole, OperationKind},
18    db::{DbContext, GraphConnection, max_rows_per_batch},
19    errors::{FileAdditionError, OperationError},
20    file_types::FileTypes,
21    gen_models_capnp::{annotation, annotation_group, annotation_group_sample},
22    history::{HistoryStore, dolt::DoltHistoryStore},
23    operations::{FileAddition, OperationFile, OperationInfo, OperationSummary, track_asset_refs},
24    region::GenRegionError,
25    select::query_models,
26};
27#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
28#[model_select(table = "annotation_groups")]
29pub struct AnnotationGroup {
30    #[model_select(primary_key)]
31    pub name: String,
32}
33
34impl AnnotationGroup {
35    pub fn create(conn: &GraphConnection, name: &str) -> rusqlite::Result<AnnotationGroup> {
36        let mut stmt = conn
37            .prepare("INSERT INTO annotation_groups (name) VALUES (?1) returning (name);")
38            .unwrap();
39        stmt.query_row((name,), |row| Ok(AnnotationGroup { name: row.get(0)? }))
40    }
41
42    pub fn get_or_create(
43        conn: &GraphConnection,
44        name: &str,
45    ) -> Result<AnnotationGroup, AnnotationGroupError> {
46        let mut statement = conn.prepare(
47            "INSERT INTO annotation_groups (name) VALUES (?1) ON CONFLICT(name) DO NOTHING;",
48        )?;
49        statement.execute(params![name])?;
50        Ok(AnnotationGroup {
51            name: name.to_string(),
52        })
53    }
54
55    pub fn query_by_sample(
56        conn: &GraphConnection,
57        sample_name: &str,
58        history_ref: Option<&str>,
59    ) -> Vec<AnnotationGroup> {
60        let samples = AnnotationGroupSample::select(conn)
61            .sample_name(sample_name)
62            .with_ref(history_ref);
63        AnnotationGroup::select(conn)
64            .join_filtered_on(
65                AnnotationGroupSelect::Name,
66                AnnotationGroupSampleSelect::AnnotationGroup,
67                samples,
68            )
69            .order_by(AnnotationGroupSelect::Name, Direction::Asc)
70            .load()
71            .expect("should load annotation groups for sample")
72    }
73}
74
75impl<'a> Capnp<'a> for AnnotationGroup {
76    type Builder = annotation_group::Builder<'a>;
77    type Reader = annotation_group::Reader<'a>;
78
79    fn write_capnp(&self, builder: &mut Self::Builder) {
80        builder.set_name(&self.name);
81    }
82
83    fn read_capnp(reader: Self::Reader) -> Self {
84        AnnotationGroup {
85            name: reader.get_name().unwrap().to_string().unwrap(),
86        }
87    }
88}
89
90#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
91#[model_select(table = "annotations", from_row = annotation_from_row)]
92pub struct Annotation {
93    pub id: HashId,
94    pub name: String,
95    #[model_select(column = "annotation_group")]
96    pub group: String,
97    pub accession_id: HashId,
98    #[model_select(skip)]
99    pub extra: Option<AnnotationExtra>,
100}
101
102fn annotation_from_row(row: &Row) -> SqlResult<Annotation> {
103    Ok(Annotation {
104        id: row.get(0)?,
105        name: row.get(1)?,
106        group: row.get(2)?,
107        accession_id: row.get(3)?,
108        extra: deserialize_annotation_extra(row.get(4)?).map_err(|error| {
109            rusqlite::Error::FromSqlConversionFailure(4, Type::Text, Box::new(error))
110        })?,
111    })
112}
113
114/// For use with create/bulk_create methods.
115#[derive(Clone, Debug)]
116pub struct NewAnnotation<'a> {
117    /// User-facing annotation name.
118    pub name: &'a str,
119    /// Accession covered by this annotation.
120    pub accession_id: HashId,
121    /// Format-specific annotation metadata.
122    pub extra: Option<&'a AnnotationExtra>,
123}
124
125#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
126#[serde(default)]
127pub struct AnnotationExtra {
128    pub genbank: Option<GenBankExtra>,
129    pub gff: Option<GffExtra>,
130    pub bed: Option<BedExtra>,
131}
132
133#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
134#[serde(default)]
135pub struct GenBankExtra {
136    pub kind: String,
137    pub qualifiers: Vec<GenBankQualifier>,
138    pub location_operator: Option<GenBankLocationOperator>,
139}
140
141#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
142#[serde(default)]
143pub struct GenBankQualifier {
144    pub key: String,
145    pub value: Option<String>,
146}
147
148#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
149pub enum GenBankLocationOperator {
150    Join,
151    Order,
152    Bond,
153    OneOf,
154}
155
156#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
157#[serde(default)]
158pub struct GffExtra {
159    pub source: Option<String>,
160    pub ty: String,
161    pub score: Option<String>,
162    pub phase: Option<String>,
163    pub attributes: Vec<GffAttribute>,
164}
165
166#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
167#[serde(default)]
168pub struct GffAttribute {
169    pub key: String,
170    pub values: Vec<String>,
171}
172
173#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
174#[serde(default)]
175pub struct BedExtra {
176    pub score: Option<String>,
177    pub thick_start: Option<i64>,
178    pub thick_end: Option<i64>,
179    pub item_rgb: Option<String>,
180    pub block_count: Option<u64>,
181    pub block_sizes: Option<Vec<i64>>,
182    pub block_starts: Option<Vec<i64>>,
183    pub other_fields: Vec<String>,
184}
185
186fn serialize_annotation_extra(extra: Option<&AnnotationExtra>) -> Result<String, AnnotationError> {
187    serde_json::to_string(extra.unwrap_or(&AnnotationExtra::default()))
188        .map_err(|err| AnnotationError::SerializationError(err.to_string()))
189}
190
191fn deserialize_annotation_extra(
192    value: Option<String>,
193) -> Result<Option<AnnotationExtra>, AnnotationError> {
194    value
195        .map(|value| serde_json::from_str(&value))
196        .transpose()
197        .map(|value| value.filter(|extra| extra != &AnnotationExtra::default()))
198        .map_err(|err| AnnotationError::SerializationError(err.to_string()))
199}
200
201impl<'a> Capnp<'a> for Annotation {
202    type Builder = annotation::Builder<'a>;
203    type Reader = annotation::Reader<'a>;
204
205    fn write_capnp(&self, builder: &mut Self::Builder) {
206        builder.set_id(&self.id.0).unwrap();
207        builder.set_name(&self.name);
208        builder.set_annotation_group(&self.group);
209        builder.set_accession_id(&self.accession_id.0).unwrap();
210        builder.set_extra(
211            serialize_annotation_extra(self.extra.as_ref())
212                .unwrap_or_default()
213                .as_str(),
214        );
215    }
216
217    fn read_capnp(reader: Self::Reader) -> Self {
218        let id = reader
219            .get_id()
220            .unwrap()
221            .as_slice()
222            .unwrap()
223            .try_into()
224            .unwrap();
225        let name = reader.get_name().unwrap().to_string().unwrap();
226        let group = reader.get_annotation_group().unwrap().to_string().unwrap();
227        let accession_id = reader
228            .get_accession_id()
229            .unwrap()
230            .as_slice()
231            .unwrap()
232            .try_into()
233            .unwrap();
234        let extra = deserialize_annotation_extra(
235            reader
236                .get_extra()
237                .ok()
238                .map(|value| value.to_string().unwrap())
239                .filter(|value| !value.is_empty()),
240        )
241        .unwrap_or(None);
242
243        Annotation {
244            id,
245            name,
246            group,
247            accession_id,
248            extra,
249        }
250    }
251}
252
253#[derive(Debug, Error, PartialEq)]
254pub enum AnnotationError {
255    #[error("Database error: {0}")]
256    DatabaseError(#[from] rusqlite::Error),
257    #[error("Selector error: {0}")]
258    ModelSelect(#[from] ModelSelectError),
259    #[error("Annotation group error: {0}")]
260    AnnotationGroupError(#[from] AnnotationGroupError),
261    #[error("Accession error: {0}")]
262    AccessionError(#[from] AccessionError),
263    #[error("Annotation extra serialization error: {0}")]
264    SerializationError(String),
265}
266
267#[derive(Debug, Error)]
268pub enum AddAnnotationError {
269    #[error("Region parse error: {0}")]
270    RegionParse(#[from] gen_core::region::RegionParseError),
271    #[error("Region resolution error: {0}")]
272    RegionResolution(#[from] GenRegionError),
273    #[error("Accession error: {0}")]
274    Accession(#[from] AccessionError),
275    #[error("Annotation error: {0}")]
276    Annotation(#[from] AnnotationError),
277}
278
279impl Annotation {
280    pub fn generate_id(name: &str, group: &str, accession_id: &HashId) -> HashId {
281        HashId(calculate_hash(&format!("{name}:{group}:{accession_id}",)))
282    }
283
284    pub fn create(
285        conn: &GraphConnection,
286        group: &str,
287        annotation: &NewAnnotation<'_>,
288    ) -> Result<Annotation, AnnotationError> {
289        let id = Annotation::generate_id(annotation.name, group, &annotation.accession_id);
290        let query = "INSERT INTO annotations (id, name, annotation_group, accession_id, extra) VALUES (?1, ?2, ?3, ?4, ?5);";
291        let mut stmt = conn.prepare(query)?;
292        let extra_json = serialize_annotation_extra(annotation.extra)?;
293        stmt.execute(params![
294            id,
295            annotation.name,
296            group,
297            annotation.accession_id,
298            extra_json
299        ])?;
300        Ok(Annotation {
301            id,
302            name: annotation.name.to_string(),
303            group: group.to_string(),
304            accession_id: annotation.accession_id,
305            extra: annotation.extra.cloned(),
306        })
307    }
308
309    pub fn get_or_create(
310        conn: &GraphConnection,
311        name: &str,
312        group: &str,
313        accession_id: &HashId,
314        extra: Option<&AnnotationExtra>,
315    ) -> Result<Annotation, AnnotationError> {
316        AnnotationGroup::get_or_create(conn, group)?;
317        let id = Annotation::generate_id(name, group, accession_id);
318        let mut statement = conn.prepare(
319            "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;",
320        )?;
321        let extra_json = serialize_annotation_extra(extra)?;
322        statement.execute(params![id, name, group, accession_id, extra_json])?;
323        Ok(Annotation {
324            id,
325            name: name.to_string(),
326            group: group.to_string(),
327            accession_id: *accession_id,
328            extra: extra.cloned(),
329        })
330    }
331
332    /// Creates annotations for one group, preserving existing rows with matching identities.
333    pub fn bulk_create(
334        conn: &GraphConnection,
335        group: &str,
336        annotations: &[NewAnnotation<'_>],
337    ) -> Result<(), AnnotationError> {
338        if annotations.is_empty() {
339            return Ok(());
340        }
341
342        AnnotationGroup::get_or_create(conn, group)?;
343        let batch_size = max_rows_per_batch(conn, 5);
344        for annotation_batch in annotations.chunks(batch_size) {
345            let mut rows = Vec::with_capacity(annotation_batch.len());
346            let mut parameters: Vec<Box<dyn rusqlite::ToSql>> =
347                Vec::with_capacity(annotation_batch.len() * 5);
348            for annotation in annotation_batch {
349                parameters.push(Box::new(Annotation::generate_id(
350                    annotation.name,
351                    group,
352                    &annotation.accession_id,
353                )));
354                parameters.push(Box::new(annotation.name.to_string()));
355                parameters.push(Box::new(group.to_string()));
356                parameters.push(Box::new(annotation.accession_id));
357                parameters.push(Box::new(serialize_annotation_extra(annotation.extra)?));
358                rows.push("(?, ?, ?, ?, ?)");
359            }
360            let query = format!(
361                "INSERT INTO annotations (id, name, annotation_group, accession_id, extra) VALUES {} ON CONFLICT(accession_id, annotation_group, name) DO NOTHING;",
362                rows.join(",")
363            );
364            conn.execute(&query, rusqlite::params_from_iter(parameters))?;
365        }
366        Ok(())
367    }
368
369    pub fn create_with_samples(
370        conn: &GraphConnection,
371        name: &str,
372        group: &str,
373        accession_id: &HashId,
374        extra: Option<&AnnotationExtra>,
375        sample_names: &[&str],
376    ) -> Result<Annotation, AnnotationError> {
377        let annotation = Annotation::get_or_create(conn, name, group, accession_id, extra)?;
378        annotation.add_samples(conn, sample_names)?;
379        Ok(annotation)
380    }
381
382    pub fn add_samples(
383        &self,
384        conn: &GraphConnection,
385        sample_names: &[&str],
386    ) -> Result<(), AnnotationError> {
387        if sample_names.is_empty() {
388            return Ok(());
389        }
390        AnnotationGroup::get_or_create(conn, &self.group)?;
391        let query = "INSERT INTO annotation_group_samples (annotation_group, sample_name) VALUES (?1, ?2) ON CONFLICT(annotation_group, sample_name) DO NOTHING;";
392        let mut stmt = conn.prepare(query)?;
393        for sample_name in sample_names {
394            stmt.execute(params![self.group, sample_name])?;
395        }
396        Ok(())
397    }
398
399    pub fn get_samples(
400        conn: &GraphConnection,
401        annotation_group: &str,
402    ) -> Result<Vec<String>, AnnotationError> {
403        Ok(AnnotationGroupSample::select(conn)
404            .annotation_group(annotation_group)
405            .only(AnnotationGroupSampleSelect::SampleName)
406            .load()?)
407    }
408
409    pub fn query_by_sample(
410        conn: &GraphConnection,
411        sample_name: &str,
412        history_ref: Option<&str>,
413    ) -> Result<Vec<Annotation>, AnnotationError> {
414        let samples = AnnotationGroupSample::select(conn)
415            .sample_name(sample_name)
416            .with_ref(history_ref);
417        Ok(Annotation::select(conn)
418            .join_filtered_on(
419                AnnotationSelect::Group,
420                AnnotationGroupSampleSelect::AnnotationGroup,
421                samples,
422            )
423            .load()?)
424    }
425
426    pub fn query_by_group(
427        conn: &GraphConnection,
428        group: &str,
429        history_ref: Option<&str>,
430    ) -> Result<Vec<Annotation>, AnnotationError> {
431        let select = Annotation::select(conn).group(group).with_ref(history_ref);
432        Ok(select.load()?)
433    }
434
435    pub fn query_by_group_and_block_group(
436        conn: &GraphConnection,
437        group: &str,
438        block_group_id: &HashId,
439        history_ref: Option<&str>,
440    ) -> Result<Vec<Annotation>, AnnotationError> {
441        let accessions = Accession::select(conn)
442            .block_group_id(*block_group_id)
443            .with_ref(history_ref);
444        Ok(Annotation::select(conn)
445            .group(group)
446            .join_filtered_on(
447                AnnotationSelect::AccessionId,
448                AccessionSelect::Id,
449                accessions,
450            )
451            .load()?)
452    }
453
454    /// List every annotation on a block group, following the sample lineage.
455    ///
456    /// Collects annotations attached to the block group named `block_group_name`
457    /// in `collection_name`, considering `sample_name` together with all of its
458    /// ancestor samples. This mirrors how a block group inherits its parents'
459    /// annotations. Results are de-duplicated by annotation id and ordered from
460    /// the closest sample in the lineage outward. Two annotations that share a
461    /// name but come from different samples (e.g. a parent and child both
462    /// annotating "mreB") are both included, since each is a distinct
463    /// annotation record; unlike [`RegionResolver::resolve`], this is a listing
464    /// operation and does not need to disambiguate by name.
465    ///
466    /// # Arguments
467    ///
468    /// * `collection_name` - Collection the block group belongs to.
469    /// * `sample_name` - Sample whose lineage is walked, including the sample
470    ///   itself.
471    /// * `block_group_name` - Name shared by the block group across the lineage.
472    ///
473    /// # Errors
474    ///
475    /// Returns [`AnnotationError::DatabaseError`] if the query fails.
476    pub fn query_with_lineage(
477        conn: &GraphConnection,
478        collection_name: &str,
479        sample_name: &str,
480        block_group_name: &str,
481    ) -> Result<Vec<Annotation>, AnnotationError> {
482        let query = "WITH RECURSIVE visible_samples(name, depth, path) AS (
483                 SELECT ?2, 0, ',' || ?2 || ','
484                 UNION ALL
485                 SELECT sl.parent_sample_name,
486                        visible.depth + 1,
487                        visible.path || sl.parent_sample_name || ','
488                 FROM sample_lineage sl
489                 JOIN visible_samples visible ON sl.child_sample_name = visible.name
490                 WHERE instr(visible.path, ',' || sl.parent_sample_name || ',') = 0
491             )
492             SELECT a.id,
493                    a.name,
494                    a.annotation_group,
495                    a.accession_id,
496                    a.extra \
497             FROM annotations a \
498             JOIN accessions acc ON a.accession_id = acc.id \
499             JOIN block_groups bg ON acc.block_group_id = bg.id \
500             JOIN visible_samples visible ON bg.sample_name = visible.name \
501             WHERE bg.collection_name = ?1 \
502               AND bg.name = ?3
503             GROUP BY a.id, a.name, a.annotation_group, a.accession_id, a.extra
504             ORDER BY min(visible.depth), a.name, a.id";
505        Ok(query_models::<Annotation, _>(
506            conn,
507            query,
508            params![collection_name, sample_name, block_group_name],
509        )?)
510    }
511
512    pub(crate) fn resolve_candidates(
513        region: &Region,
514        conn: &GraphConnection,
515        collection_name: &str,
516        sample_name: &str,
517    ) -> Result<Vec<Self>, AnnotationError> {
518        query_models::<Annotation, _>(
519            conn,
520            "WITH RECURSIVE visible_samples(name, depth, path) AS (
521                 SELECT ?2, 0, ',' || ?2 || ','
522                 UNION ALL
523                 SELECT sl.parent_sample_name,
524                        visible.depth + 1,
525                        visible.path || sl.parent_sample_name || ','
526                 FROM sample_lineage sl
527                 JOIN visible_samples visible ON sl.child_sample_name = visible.name
528                 WHERE instr(visible.path, ',' || sl.parent_sample_name || ',') = 0
529             ),
530             matching_annotations AS (
531                 SELECT a.id,
532                        a.name,
533                        a.annotation_group,
534                        a.accession_id,
535                        a.extra,
536                        min(visible.depth) AS depth \
537                 FROM annotations a \
538                 JOIN accessions acc ON a.accession_id = acc.id \
539                 JOIN block_groups bg ON acc.block_group_id = bg.id \
540                 JOIN visible_samples visible ON bg.sample_name = visible.name \
541                 WHERE bg.collection_name = ?1 \
542                   AND lower(a.name) = lower(?3)
543                 GROUP BY a.id, a.name, a.annotation_group, a.accession_id, a.extra
544             )
545             SELECT id, name, annotation_group, accession_id, extra \
546             FROM matching_annotations \
547             WHERE depth = (SELECT min(depth) FROM matching_annotations)",
548            params![collection_name, sample_name, region.name],
549        )
550        .map_err(AnnotationError::from)
551    }
552
553    pub fn intervaltree(
554        &self,
555        conn: &GraphConnection,
556    ) -> Result<IntervalTree<i64, NodeIntervalBlock>, AnnotationError> {
557        let accession = Accession::select(conn)
558            .id(self.accession_id)
559            .load()?
560            .into_iter()
561            .next()
562            .ok_or(rusqlite::Error::QueryReturnedNoRows)?;
563        accession.intervaltree(conn).map_err(Into::into)
564    }
565}
566
567impl RegionResolver for Annotation {
568    type Connection = GraphConnection;
569    type Error = AnnotationError;
570
571    fn resolve(
572        region: &Region,
573        conn: &Self::Connection,
574        collection_name: &str,
575        sample_name: &str,
576    ) -> Result<Self, RegionResolutionError<Self::Error>> {
577        let matches = Self::resolve_candidates(region, conn, collection_name, sample_name)?;
578
579        match matches.len() {
580            0 => Err(RegionResolutionError::NotFound(region.name.clone())),
581            1 => Ok(matches.into_iter().next().unwrap()),
582            _ => Err(RegionResolutionError::Ambiguous(format!(
583                "multiple annotations named {}",
584                region.name
585            ))),
586        }
587    }
588}
589
590#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, ModelSelect)]
591#[model_select(
592    table = "annotation_group_samples",
593    default_sort(annotation_group = "asc", sample_name = "asc")
594)]
595pub struct AnnotationGroupSample {
596    #[model_select(primary_key)]
597    pub annotation_group: String,
598    #[model_select(primary_key)]
599    pub sample_name: String,
600}
601
602impl<'a> Capnp<'a> for AnnotationGroupSample {
603    type Builder = annotation_group_sample::Builder<'a>;
604    type Reader = annotation_group_sample::Reader<'a>;
605
606    fn write_capnp(&self, builder: &mut Self::Builder) {
607        builder.set_annotation_group(&self.annotation_group);
608        builder.set_sample_name(&self.sample_name);
609    }
610
611    fn read_capnp(reader: Self::Reader) -> Self {
612        let annotation_group = reader.get_annotation_group().unwrap().to_string().unwrap();
613        let sample_name = reader.get_sample_name().unwrap().to_string().unwrap();
614        AnnotationGroupSample {
615            annotation_group,
616            sample_name,
617        }
618    }
619}
620
621impl AnnotationGroupSample {
622    pub fn create(
623        conn: &GraphConnection,
624        annotation_group: &str,
625        sample_name: &str,
626    ) -> Result<(), AnnotationError> {
627        AnnotationGroup::get_or_create(conn, annotation_group)?;
628        let query = "INSERT INTO annotation_group_samples (annotation_group, sample_name) VALUES (?1, ?2) ON CONFLICT(annotation_group, sample_name) DO NOTHING;";
629        let mut stmt = conn.prepare(query)?;
630        stmt.execute(params![annotation_group, sample_name])?;
631        Ok(())
632    }
633
634    pub fn delete(
635        conn: &GraphConnection,
636        annotation_group: &str,
637        sample_name: &str,
638    ) -> Result<(), AnnotationError> {
639        let query = "DELETE FROM annotation_group_samples WHERE annotation_group = ?1 AND sample_name = ?2;";
640        let mut stmt = conn.prepare(query)?;
641        stmt.execute(params![annotation_group, sample_name])?;
642        Ok(())
643    }
644}
645
646#[derive(Debug, Error, PartialEq)]
647pub enum AnnotationGroupError {
648    #[error("Database error: {0}")]
649    DatabaseError(#[from] rusqlite::Error),
650}
651
652#[derive(Debug, Error)]
653pub enum AnnotationFileError {
654    #[error("Database error: {0}")]
655    DatabaseError(#[from] rusqlite::Error),
656    #[error("File addition error: {0}")]
657    FileAdditionError(#[from] FileAdditionError),
658    #[error("Operation error: {0}")]
659    OperationError(#[from] OperationError),
660    #[error(
661        "Unable to detect annotation file format from the file extension. Use --format to specify it explicitly."
662    )]
663    MissingFileExtension,
664    #[error("Unsupported annotation file type: {0}")]
665    UnsupportedFileType(String),
666}
667
668pub fn parse_annotation_file_type(value: &str) -> Result<FileTypes, AnnotationFileError> {
669    match value.trim().to_ascii_lowercase().as_str() {
670        "gff3" | "gff" => Ok(FileTypes::Gff3),
671        "bed" => Ok(FileTypes::Bed),
672        "genbank" | "gb" => Ok(FileTypes::GenBank),
673        other => Err(AnnotationFileError::UnsupportedFileType(other.to_string())),
674    }
675}
676
677pub fn annotation_file_extension(path: &str) -> Option<String> {
678    let path = Path::new(path);
679    let mut ext = path
680        .extension()
681        .and_then(|ext| ext.to_str())
682        .map(|ext| ext.to_ascii_lowercase());
683    if matches!(ext.as_deref(), Some("gz") | Some("bgz")) {
684        ext = path
685            .file_stem()
686            .and_then(|stem| stem.to_str())
687            .and_then(|stem| Path::new(stem).extension().and_then(|ext| ext.to_str()))
688            .map(|ext| ext.to_ascii_lowercase());
689    }
690    ext
691}
692
693pub fn annotation_index_file_path(
694    workspace: &Workspace,
695    path: &str,
696    explicit_index_path: Option<&str>,
697) -> Option<String> {
698    if let Some(index_path) = explicit_index_path {
699        return Some(index_path.to_string());
700    }
701
702    let mut candidates = vec![format!("{path}.tbi")];
703    let path_buf = PathBuf::from(path);
704    if let Some(extension) = path_buf.extension().and_then(|ext| ext.to_str()) {
705        let mut extension_candidate = path_buf.clone();
706        extension_candidate.set_extension(format!("{extension}.tbi"));
707        let extension_candidate = extension_candidate.to_string_lossy().to_string();
708        if !candidates
709            .iter()
710            .any(|candidate| candidate == &extension_candidate)
711        {
712            candidates.push(extension_candidate);
713        }
714    }
715
716    for candidate in candidates {
717        let exists = if Path::new(&candidate).is_absolute() {
718            Path::new(&candidate).exists()
719        } else {
720            workspace
721                .repo_root()
722                .ok()
723                .is_some_and(|repo_root| repo_root.join(&candidate).exists())
724        };
725        if exists {
726            return Some(candidate);
727        }
728    }
729
730    None
731}
732
733pub fn add_annotation(
734    context: &DbContext,
735    collection: &str,
736    name: &str,
737    group: Option<&str>,
738    sample: &str,
739    region: &str,
740) -> Result<OperationSummary, AddAnnotationError> {
741    let graph_conn = context.graph().conn();
742    let parsed_region = Region::parse(region)?;
743    let resolved_region = crate::region::resolve(&parsed_region, graph_conn, collection, sample)?;
744    let spans = AccessionSpan::from_resolved_region(
745        graph_conn,
746        context.workspace(),
747        &resolved_region,
748        None,
749    )?;
750
751    let accession = Accession::get_or_create(
752        graph_conn,
753        &NewAccession {
754            name: name.to_string(),
755            block_group_id: resolved_region.block_group.id,
756            parent_accession_id: None,
757            spans,
758        },
759    )?;
760
761    let annotation_group = group.unwrap_or("default");
762    let annotation =
763        Annotation::get_or_create(graph_conn, name, annotation_group, &accession.id, None)?;
764    AnnotationGroupSample::create(graph_conn, &annotation.group, sample)?;
765
766    Ok(OperationSummary::new(
767        OperationInfo {
768            files: vec![],
769            description: format!("add annotation {name}"),
770        },
771        format!("add annotation {name}"),
772    ))
773}
774
775/// Optional content checksums collected while annotation assets were already being streamed.
776#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
777pub struct AnnotationFileChecksumOverrides {
778    /// Checksum of the annotation file.
779    pub annotation: Option<Sha256Hash>,
780    /// Checksum of the annotation index.
781    pub index: Option<Sha256Hash>,
782}
783
784/// Adds an annotation asset and optional index to operation history.
785///
786/// Callers pass checksums only when the corresponding remote streams were already consumed for
787/// annotation work. This keeps operation creation independent of remote credentials while local
788/// assets are retained and hashed during preparation.
789pub fn add_annotation_file(
790    context: &DbContext,
791    path: &str,
792    format: Option<&str>,
793    index: Option<&str>,
794    name: Option<&str>,
795    message: Option<&str>,
796    checksum_overrides: AnnotationFileChecksumOverrides,
797) -> Result<DoltHashId, AnnotationFileError> {
798    let workspace = context.workspace();
799    let graph_conn = context.graph().conn();
800
801    let file_type = match format {
802        Some(format) => parse_annotation_file_type(format)?,
803        None => {
804            let ext =
805                annotation_file_extension(path).ok_or(AnnotationFileError::MissingFileExtension)?;
806            parse_annotation_file_type(&ext)?
807        }
808    };
809    let file_addition =
810        FileAddition::prepare(workspace, path, file_type, checksum_overrides.annotation)?;
811    let annotation_logical_path =
812        OperationFile::storage_file_path(workspace, path, file_addition.checksum.as_ref())?;
813    let prepared_index =
814        if let Some(index_path) = annotation_index_file_path(workspace, path, index) {
815            let index_file_type = FileTypes::infer_from_path(&index_path);
816            let file_addition = FileAddition::prepare(
817                workspace,
818                &index_path,
819                index_file_type,
820                checksum_overrides.index,
821            )?;
822            let logical_path = OperationFile::storage_file_path(
823                workspace,
824                &index_path,
825                file_addition.checksum.as_ref(),
826            )?;
827            let name = Path::new(&index_path)
828                .file_name()
829                .and_then(|value| value.to_str())
830                .map(str::to_string);
831            Some((file_addition, logical_path, name))
832        } else {
833            None
834        };
835    let name = name.or_else(|| Path::new(path).file_name().and_then(|value| value.to_str()));
836    let name_value = name.unwrap_or_default();
837    let annotation_asset_ref_id = AssetRef::id_hash(
838        &file_addition.asset_uri,
839        file_addition.file_type.as_str(),
840        file_addition.checksum.as_ref(),
841        &AssetRole::Annotation,
842        Some(&annotation_logical_path),
843        name,
844        None,
845    );
846    let index_file_addition_id = prepared_index
847        .as_ref()
848        .map(|(index_file, _, _)| index_file.id.to_string())
849        .unwrap_or_default();
850    let log_id = HashId(calculate_hash(&format!(
851        "{file_addition_id}:{name_value}:{index_file_addition_id}",
852        file_addition_id = file_addition.id
853    )));
854    let summary = message
855        .map(str::to_string)
856        .unwrap_or_else(|| format!("Add annotation file {path}"));
857    let created_on = chrono::Utc::now()
858        .timestamp_nanos_opt()
859        .expect("should create annotation asset timestamp");
860    let mut tracked_assets = vec![AssetRef::from_file_addition(
861        &file_addition,
862        AssetRole::Annotation,
863        Some(&annotation_logical_path),
864        name,
865        None,
866        created_on,
867    )];
868    if let Some((index_file_addition, index_logical_path, index_name)) = prepared_index.as_ref() {
869        tracked_assets.push(AssetRef::from_file_addition(
870            index_file_addition,
871            AssetRole::AnnotationIndex,
872            Some(index_logical_path),
873            index_name.as_deref(),
874            Some(&annotation_asset_ref_id),
875            created_on,
876        ));
877    }
878    track_asset_refs(
879        graph_conn,
880        Some(&log_id),
881        &OperationKind::AnnotationFile,
882        &summary,
883        &tracked_assets,
884    )?;
885    let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
886    if history_store.status()?.is_empty() {
887        return Err(OperationError::NoChanges.into());
888    }
889
890    let commit_hash = history_store.commit_all(&summary)?;
891
892    Ok(commit_hash)
893}
894
895#[cfg(test)]
896mod tests {
897    use std::{collections::HashSet, fs};
898
899    use gen_core::{HashId, region::RegionResolutionError};
900
901    use super::*;
902    use crate::{
903        assets::{AssetRef, AssetRole, OperationAsset, OperationLog},
904        block_group::{BlockGroup, PathCache},
905        block_group_edge::{BlockGroupEdge, BlockGroupEdgeData},
906        errors::OperationError,
907        operations::{calculate_reader_checksum, commit_operation_summary},
908        path::Path,
909        sample::Sample,
910        sample_lineage::SampleLineage,
911        test_helpers::{create_bg, get_connection, setup_block_group, setup_gen},
912    };
913
914    mod region_resolver {
915        use super::*;
916
917        #[test]
918        fn resolves_annotation_by_name_case_insensitively() {
919            let conn = get_connection(None).unwrap();
920            let (block_group_id, path) = setup_block_group(&conn);
921            let mut cache = PathCache::new(&conn);
922            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
923            let accession =
924                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
925            let annotation =
926                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
927
928            let region = Region::parse("MREB").unwrap();
929            let resolved = Annotation::resolve(&region, &conn, "test", "test").unwrap();
930            assert_eq!(resolved.id, annotation.id);
931        }
932
933        #[test]
934        fn returns_not_found_for_missing_annotation() {
935            let conn = get_connection(None).unwrap();
936            let (_block_group_id, _path) = setup_block_group(&conn);
937
938            let region = Region::parse("missing").unwrap();
939            let err = Annotation::resolve(&region, &conn, "test", "test").unwrap_err();
940            assert!(matches!(
941                err,
942                RegionResolutionError::NotFound(name) if name == "missing"
943            ));
944        }
945
946        #[test]
947        fn returns_ambiguous_for_multiple_matching_annotations() {
948            let conn = get_connection(None).unwrap();
949            let (block_group_id, path) = setup_block_group(&conn);
950            let mut cache = PathCache::new(&conn);
951            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
952            let accession =
953                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
954            let _ = Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
955
956            let other_block_group = create_bg(&conn, "test", "test", "other");
957            let edge_ids = Path::edges_for_path(&conn, &path.id, None)
958                .into_iter()
959                .map(|edge| edge.id)
960                .collect::<Vec<_>>();
961            let block_group_edges = edge_ids
962                .iter()
963                .map(|edge_id| BlockGroupEdgeData {
964                    block_group_id: other_block_group.id,
965                    edge_id: *edge_id,
966                    chromosome_index: 0,
967                    phased: 0,
968                })
969                .collect::<Vec<_>>();
970            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
971            let other_path =
972                Path::create(&conn, "other-path", &other_block_group.id, &edge_ids).unwrap();
973            let other_accession =
974                BlockGroup::add_accession(&conn, &other_path, "ann-accession-2", 0, 5, &mut cache)
975                    .unwrap();
976            let _ = Annotation::get_or_create(&conn, "MREB", "genes", &other_accession.id, None)
977                .unwrap();
978
979            let region = Region::parse("mreB").unwrap();
980            let err = Annotation::resolve(&region, &conn, "test", "test").unwrap_err();
981            assert!(matches!(
982                err,
983                RegionResolutionError::Ambiguous(name) if name == "multiple annotations named mreB"
984            ));
985        }
986
987        #[test]
988        fn resolves_closest_annotation_in_sample_lineage() {
989            let conn = get_connection(None).unwrap();
990            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
991            let mut cache = PathCache::new(&conn);
992            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
993                .unwrap();
994            let parent_accession = BlockGroup::add_accession(
995                &conn,
996                &parent_path,
997                "parent-accession",
998                0,
999                5,
1000                &mut cache,
1001            )
1002            .unwrap();
1003            let _parent_annotation =
1004                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1005                    .unwrap();
1006
1007            let child_block_group = create_bg(&conn, "test", "child", "chr1");
1008            let edge_ids = Path::edges_for_path(&conn, &parent_path.id, None)
1009                .into_iter()
1010                .map(|edge| edge.id)
1011                .collect::<Vec<_>>();
1012            let block_group_edges = edge_ids
1013                .iter()
1014                .map(|edge_id| BlockGroupEdgeData {
1015                    block_group_id: child_block_group.id,
1016                    edge_id: *edge_id,
1017                    chromosome_index: 0,
1018                    phased: 0,
1019                })
1020                .collect::<Vec<_>>();
1021            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1022            let child_path =
1023                Path::create(&conn, "child-path", &child_block_group.id, &edge_ids).unwrap();
1024            let child_accession =
1025                BlockGroup::add_accession(&conn, &child_path, "child-accession", 0, 5, &mut cache)
1026                    .unwrap();
1027            let child_annotation =
1028                Annotation::get_or_create(&conn, "MREB", "genes", &child_accession.id, None)
1029                    .unwrap();
1030            SampleLineage::create(&conn, "test", "child").unwrap();
1031
1032            let region = Region::parse("mreB").unwrap();
1033            let resolved = Annotation::resolve(&region, &conn, "test", "child").unwrap();
1034
1035            assert_eq!(resolved.id, child_annotation.id);
1036        }
1037
1038        #[test]
1039        fn falls_back_to_parent_annotation_when_child_has_none() {
1040            let conn = get_connection(None).unwrap();
1041            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
1042            let mut cache = PathCache::new(&conn);
1043            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
1044                .unwrap();
1045            let parent_accession = BlockGroup::add_accession(
1046                &conn,
1047                &parent_path,
1048                "parent-only-accession",
1049                0,
1050                5,
1051                &mut cache,
1052            )
1053            .unwrap();
1054            let parent_annotation =
1055                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1056                    .unwrap();
1057
1058            let child_block_group = create_bg(&conn, "test", "child", "chr1");
1059            let edge_ids = Path::edges_for_path(&conn, &parent_path.id, None)
1060                .into_iter()
1061                .map(|edge| edge.id)
1062                .collect::<Vec<_>>();
1063            let block_group_edges = edge_ids
1064                .iter()
1065                .map(|edge_id| BlockGroupEdgeData {
1066                    block_group_id: child_block_group.id,
1067                    edge_id: *edge_id,
1068                    chromosome_index: 0,
1069                    phased: 0,
1070                })
1071                .collect::<Vec<_>>();
1072            crate::block_group_edge::BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1073            let _child_path =
1074                Path::create(&conn, "child-path", &child_block_group.id, &edge_ids).unwrap();
1075            SampleLineage::create(&conn, "test", "child").unwrap();
1076
1077            let region = Region::parse("mreB").unwrap();
1078            let resolved = Annotation::resolve(&region, &conn, "test", "child").unwrap();
1079
1080            assert_eq!(resolved.id, parent_annotation.id);
1081        }
1082    }
1083
1084    mod lineage_listing {
1085        use super::*;
1086
1087        /// Attach a block group that shares `parent_path`'s edges, give it its
1088        /// own path and accession, and annotate it. Returns the annotation.
1089        #[expect(clippy::too_many_arguments, reason = "test helper wiring")]
1090        fn annotate_block_group(
1091            conn: &GraphConnection,
1092            parent_path: &Path,
1093            cache: &mut PathCache,
1094            collection_name: &str,
1095            sample_name: &str,
1096            block_group_name: &str,
1097            accession_name: &str,
1098            annotation_name: &str,
1099        ) -> Annotation {
1100            let block_group = create_bg(conn, collection_name, sample_name, block_group_name);
1101            let edge_ids = Path::edges_for_path(conn, &parent_path.id, None)
1102                .into_iter()
1103                .map(|edge| edge.id)
1104                .collect::<Vec<_>>();
1105            let block_group_edges = edge_ids
1106                .iter()
1107                .map(|edge_id| BlockGroupEdgeData {
1108                    block_group_id: block_group.id,
1109                    edge_id: *edge_id,
1110                    chromosome_index: 0,
1111                    phased: 0,
1112                })
1113                .collect::<Vec<_>>();
1114            BlockGroupEdge::bulk_create(conn, &block_group_edges);
1115            let path = Path::create(conn, accession_name, &block_group.id, &edge_ids).unwrap();
1116            let accession =
1117                BlockGroup::add_accession(conn, &path, accession_name, 0, 5, cache).unwrap();
1118            Annotation::get_or_create(conn, annotation_name, "genes", &accession.id, None).unwrap()
1119        }
1120
1121        #[test]
1122        fn test_lists_annotations_on_block_group() {
1123            let conn = get_connection(None).unwrap();
1124            let (block_group_id, path) = setup_block_group(&conn);
1125            let mut cache = PathCache::new(&conn);
1126            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1127            let accession =
1128                BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
1129            let annotation =
1130                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1131
1132            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1133
1134            assert_eq!(listed, vec![annotation]);
1135        }
1136
1137        #[test]
1138        fn test_includes_parent_annotations_via_lineage() {
1139            let conn = get_connection(None).unwrap();
1140            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
1141            let mut cache = PathCache::new(&conn);
1142            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
1143                .unwrap();
1144            let parent_accession = BlockGroup::add_accession(
1145                &conn,
1146                &parent_path,
1147                "parent-accession",
1148                0,
1149                5,
1150                &mut cache,
1151            )
1152            .unwrap();
1153            let parent_annotation =
1154                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1155                    .unwrap();
1156
1157            let child_annotation = annotate_block_group(
1158                &conn,
1159                &parent_path,
1160                &mut cache,
1161                "test",
1162                "child",
1163                "chr1",
1164                "child-accession",
1165                "ftsZ",
1166            );
1167            SampleLineage::create(&conn, "test", "child").unwrap();
1168
1169            let listed = Annotation::query_with_lineage(&conn, "test", "child", "chr1").unwrap();
1170
1171            let ids: HashSet<HashId> = listed.iter().map(|a| a.id).collect();
1172            assert_eq!(
1173                ids,
1174                HashSet::from([parent_annotation.id, child_annotation.id])
1175            );
1176        }
1177
1178        #[test]
1179        fn test_excludes_annotations_on_other_block_group_names() {
1180            let conn = get_connection(None).unwrap();
1181            let (block_group_id, path) = setup_block_group(&conn);
1182            let mut cache = PathCache::new(&conn);
1183            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1184            let accession =
1185                BlockGroup::add_accession(&conn, &path, "chr1-accession", 0, 5, &mut cache)
1186                    .unwrap();
1187            let chr1_annotation =
1188                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1189
1190            let _chr2_annotation = annotate_block_group(
1191                &conn,
1192                &path,
1193                &mut cache,
1194                "test",
1195                "test",
1196                "chr2",
1197                "chr2-accession",
1198                "ftsZ",
1199            );
1200
1201            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1202
1203            assert_eq!(listed, vec![chr1_annotation]);
1204        }
1205
1206        #[test]
1207        fn test_excludes_annotations_from_samples_outside_the_lineage() {
1208            let conn = get_connection(None).unwrap();
1209            let (block_group_id, path) = setup_block_group(&conn);
1210            let mut cache = PathCache::new(&conn);
1211            let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1212            let accession =
1213                BlockGroup::add_accession(&conn, &path, "test-accession", 0, 5, &mut cache)
1214                    .unwrap();
1215            let test_annotation =
1216                Annotation::get_or_create(&conn, "mreB", "genes", &accession.id, None).unwrap();
1217
1218            let _unrelated_annotation = annotate_block_group(
1219                &conn,
1220                &path,
1221                &mut cache,
1222                "test",
1223                "unrelated",
1224                "chr1",
1225                "unrelated-accession",
1226                "ftsZ",
1227            );
1228
1229            let listed = Annotation::query_with_lineage(&conn, "test", "test", "chr1").unwrap();
1230
1231            assert_eq!(listed, vec![test_annotation]);
1232        }
1233
1234        #[test]
1235        fn test_keeps_both_when_parent_and_child_share_an_annotation_name() {
1236            let conn = get_connection(None).unwrap();
1237            let (parent_block_group_id, parent_path) = setup_block_group(&conn);
1238            let mut cache = PathCache::new(&conn);
1239            let _ = PathCache::lookup(&mut cache, &parent_block_group_id, parent_path.name.clone())
1240                .unwrap();
1241            let parent_accession = BlockGroup::add_accession(
1242                &conn,
1243                &parent_path,
1244                "parent-accession",
1245                0,
1246                5,
1247                &mut cache,
1248            )
1249            .unwrap();
1250            let parent_annotation =
1251                Annotation::get_or_create(&conn, "mreB", "genes", &parent_accession.id, None)
1252                    .unwrap();
1253
1254            let child_annotation = annotate_block_group(
1255                &conn,
1256                &parent_path,
1257                &mut cache,
1258                "test",
1259                "child",
1260                "chr1",
1261                "child-accession",
1262                "mreB",
1263            );
1264            SampleLineage::create(&conn, "test", "child").unwrap();
1265
1266            let listed = Annotation::query_with_lineage(&conn, "test", "child", "chr1").unwrap();
1267
1268            // Same name, distinct annotation ids: listing keeps both rather than
1269            // collapsing by name. `resolve` would pick only the child's here
1270            // since it's the closer match (depth 0 vs. depth 1) and error on tie.
1271            assert_eq!(listed, vec![child_annotation, parent_annotation]);
1272        }
1273    }
1274
1275    #[test]
1276    fn annotation_groups_all_lists_groups_in_name_order() {
1277        let conn = get_connection(None).unwrap();
1278        AnnotationGroup::create(&conn, "zebra").unwrap();
1279        AnnotationGroup::create(&conn, "ant").unwrap();
1280
1281        let groups = AnnotationGroup::all(&conn).expect("should load annotation groups");
1282
1283        assert_eq!(
1284            groups,
1285            vec![
1286                AnnotationGroup { name: "ant".into() },
1287                AnnotationGroup {
1288                    name: "zebra".into()
1289                }
1290            ]
1291        );
1292    }
1293
1294    #[test]
1295    fn create_annotation_with_samples() {
1296        let conn = get_connection(None).unwrap();
1297        let (block_group_id, path) = setup_block_group(&conn);
1298
1299        let _ = Sample::create(
1300            &conn,
1301            crate::sample::NewSample {
1302                name: "sample-1",
1303                is_reference: false,
1304            },
1305        )
1306        .unwrap();
1307        let _ = Sample::create(
1308            &conn,
1309            crate::sample::NewSample {
1310                name: "sample-2",
1311                is_reference: false,
1312            },
1313        )
1314        .unwrap();
1315
1316        let mut cache = PathCache::new(&conn);
1317        let _ = PathCache::lookup(&mut cache, &block_group_id, path.name.clone()).unwrap();
1318        let accession =
1319            BlockGroup::add_accession(&conn, &path, "ann-accession", 0, 5, &mut cache).unwrap();
1320
1321        let annotations = [NewAnnotation {
1322            name: "gene-a",
1323            accession_id: accession.id,
1324            extra: None,
1325        }];
1326        Annotation::bulk_create(&conn, "project-tracks", &annotations).unwrap();
1327        AnnotationGroupSample::create(&conn, "project-tracks", "sample-1").unwrap();
1328        AnnotationGroupSample::create(&conn, "project-tracks", "sample-2").unwrap();
1329        let annotation = Annotation::query_by_group(&conn, "project-tracks", None)
1330            .unwrap()
1331            .pop()
1332            .expect("should create annotation");
1333        Annotation::bulk_create(&conn, "project-tracks", &annotations).unwrap();
1334
1335        assert_eq!(
1336            Annotation::query_by_group(&conn, "project-tracks", None).unwrap(),
1337            vec![annotation.clone()]
1338        );
1339
1340        let mut samples = Annotation::get_samples(&conn, &annotation.group).unwrap();
1341        samples.sort();
1342        assert_eq!(
1343            samples,
1344            vec!["sample-1".to_string(), "sample-2".to_string()]
1345        );
1346
1347        let by_sample = Annotation::query_by_sample(&conn, "sample-1", None).unwrap();
1348        assert_eq!(by_sample.len(), 1);
1349        assert_eq!(by_sample[0], annotation);
1350
1351        let by_group = Annotation::query_by_group(&conn, "project-tracks", None).unwrap();
1352        assert_eq!(by_group, vec![annotation]);
1353    }
1354
1355    #[test]
1356    fn deserialize_annotation_extra_defaults_missing_fields() {
1357        // Ensure that if we add new fields to the AnnotationExtra struct, like new_annotation_format we still parse old ones
1358        let extra = deserialize_annotation_extra(Some(r#"{"genbank":{"kind":"CDS"}}"#.to_string()))
1359            .unwrap()
1360            .unwrap();
1361
1362        assert_eq!(
1363            extra.genbank,
1364            Some(GenBankExtra {
1365                kind: "CDS".to_string(),
1366                ..GenBankExtra::default()
1367            })
1368        );
1369        assert_eq!(extra.gff, None);
1370        assert_eq!(extra.bed, None);
1371    }
1372
1373    #[test]
1374    fn deserialize_annotation_extra_ignores_unknown_fields() {
1375        // ensure if we drop a format, removed_top_level key here, we still parse
1376        let extra = deserialize_annotation_extra(Some(
1377            r#"{"genbank":{"kind":"CDS","legacy_field":"value"},"removed_top_level":true}"#
1378                .to_string(),
1379        ))
1380        .unwrap()
1381        .unwrap();
1382
1383        assert_eq!(
1384            extra.genbank,
1385            Some(GenBankExtra {
1386                kind: "CDS".to_string(),
1387                ..GenBankExtra::default()
1388            })
1389        );
1390        assert_eq!(extra.gff, None);
1391        assert_eq!(extra.bed, None);
1392    }
1393
1394    #[test]
1395    fn deserialize_and_reserialize_annotation_extra_keeps_compatible_fields() {
1396        // Ensure that if we parse an older field, we can still reserialize it with the compatible fields kept.
1397        let extra = deserialize_annotation_extra(Some(
1398            r#"{"genbank":{"kind":"CDS","legacy_field":"value"},"removed_top_level":true}"#
1399                .to_string(),
1400        ))
1401        .unwrap()
1402        .unwrap();
1403
1404        let reserialized = serialize_annotation_extra(Some(&extra)).unwrap();
1405        let reparsed: AnnotationExtra = serde_json::from_str(&reserialized).unwrap();
1406
1407        assert_eq!(
1408            reparsed.genbank,
1409            Some(GenBankExtra {
1410                kind: "CDS".to_string(),
1411                ..GenBankExtra::default()
1412            })
1413        );
1414        assert_eq!(reparsed.gff, None);
1415        assert_eq!(reparsed.bed, None);
1416    }
1417
1418    #[test]
1419    fn parse_annotation_file_type_values() {
1420        assert_eq!(parse_annotation_file_type("gff3").unwrap(), FileTypes::Gff3);
1421        assert_eq!(parse_annotation_file_type("GFF").unwrap(), FileTypes::Gff3);
1422        assert_eq!(parse_annotation_file_type("bed").unwrap(), FileTypes::Bed);
1423        assert_eq!(
1424            parse_annotation_file_type("GenBank").unwrap(),
1425            FileTypes::GenBank
1426        );
1427        assert_eq!(
1428            parse_annotation_file_type("gb").unwrap(),
1429            FileTypes::GenBank
1430        );
1431        let err = parse_annotation_file_type("bam").unwrap_err();
1432        assert!(matches!(err, AnnotationFileError::UnsupportedFileType(_)));
1433    }
1434
1435    #[test]
1436    fn add_annotation_creates_annotation() {
1437        let context = setup_gen();
1438        let graph_conn = context.graph().conn();
1439        let history_store = DoltHistoryStore::new(graph_conn);
1440        let _ = setup_block_group(graph_conn);
1441
1442        let operation_summary = add_annotation(
1443            &context,
1444            "test",
1445            "gene-a",
1446            Some("track-1"),
1447            "test",
1448            "chr1:1-5",
1449        )
1450        .unwrap();
1451        let commit_hash = commit_operation_summary(&context, &operation_summary).unwrap();
1452        assert_eq!(history_store.current_head().unwrap(), Some(commit_hash));
1453        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
1454        operation_logs.sort_by_key(|operation_log| std::cmp::Reverse(operation_log.created_on));
1455        assert_eq!(
1456            operation_logs[0].operation_kind,
1457            OperationKind::Other("add annotation gene-a".to_string())
1458        );
1459
1460        let annotations = Annotation::query_by_group(graph_conn, "track-1", None).unwrap();
1461        assert_eq!(annotations.len(), 1);
1462        assert_eq!(annotations[0].name, "gene-a");
1463    }
1464
1465    #[test]
1466    fn test_add_annotation_detects_no_changes() {
1467        let context = setup_gen();
1468        let graph_conn = context.graph().conn();
1469        let _ = setup_block_group(graph_conn);
1470
1471        let operation_summary = add_annotation(
1472            &context,
1473            "test",
1474            "gene-a",
1475            Some("track-1"),
1476            "test",
1477            "chr1:1-5",
1478        )
1479        .unwrap();
1480        commit_operation_summary(&context, &operation_summary).unwrap();
1481
1482        let operation_summary = add_annotation(
1483            &context,
1484            "test",
1485            "gene-a",
1486            Some("track-1"),
1487            "test",
1488            "chr1:1-5",
1489        )
1490        .unwrap();
1491        let err = commit_operation_summary(&context, &operation_summary).unwrap_err();
1492        assert_eq!(err, OperationError::NoChanges);
1493    }
1494
1495    #[test]
1496    fn add_annotation_file_creates_operation() {
1497        let context = setup_gen();
1498        let graph_conn = context.graph().conn();
1499        let history_store = DoltHistoryStore::new(graph_conn);
1500
1501        let repo_root = context.workspace().repo_root().unwrap();
1502        let annotation_path = repo_root.join("fixtures").join("annotation.gff3");
1503        fs::create_dir_all(annotation_path.parent().unwrap()).unwrap();
1504        fs::write(&annotation_path, "##gff-version 3\n").unwrap();
1505        let annotation_path_str = annotation_path.to_string_lossy().to_string();
1506
1507        let commit_hash = add_annotation_file(
1508            &context,
1509            &annotation_path_str,
1510            None,
1511            None,
1512            Some("track-1"),
1513            None,
1514            AnnotationFileChecksumOverrides::default(),
1515        )
1516        .unwrap();
1517        assert_eq!(history_store.current_head().unwrap(), Some(commit_hash));
1518
1519        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
1520        asset_refs.sort_by(|left, right| left.role.as_str().cmp(right.role.as_str()));
1521        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
1522        operation_logs.sort_by_key(|operation_log| operation_log.created_on);
1523        assert_eq!(asset_refs.len(), 1);
1524        assert_eq!(asset_refs[0].role, AssetRole::Annotation);
1525        assert_eq!(asset_refs[0].name.as_deref(), Some("track-1"));
1526        assert!(
1527            asset_refs[0]
1528                .logical_path
1529                .as_deref()
1530                .unwrap_or_default()
1531                .ends_with("fixtures/annotation.gff3")
1532        );
1533        assert_eq!(operation_logs.len(), 1);
1534        assert_eq!(
1535            operation_logs[0].operation_kind,
1536            OperationKind::AnnotationFile
1537        );
1538        let operation_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
1539        assert_eq!(operation_assets.len(), 1);
1540        assert_eq!(operation_assets[0].role, AssetRole::Annotation);
1541        assert!(
1542            history_store
1543                .log(None)
1544                .unwrap()
1545                .iter()
1546                .any(|entry| entry.commit_hash == commit_hash
1547                    && entry.message.contains("Add annotation file"))
1548        );
1549        let err = add_annotation_file(
1550            &context,
1551            &annotation_path_str,
1552            None,
1553            None,
1554            Some("track-1"),
1555            None,
1556            AnnotationFileChecksumOverrides::default(),
1557        )
1558        .unwrap_err();
1559        assert!(matches!(
1560            err,
1561            AnnotationFileError::OperationError(OperationError::NoChanges)
1562        ));
1563    }
1564
1565    #[test]
1566    fn test_add_annotation_file_tracks_explicit_non_tabix_index() {
1567        let context = setup_gen();
1568        let graph_conn = context.graph().conn();
1569
1570        let repo_root = context
1571            .workspace()
1572            .repo_root()
1573            .expect("should have repo root");
1574        let annotation_path = repo_root
1575            .join("fixtures")
1576            .join("annotation-with-index.gff3");
1577        let index_path = repo_root.join("fixtures").join("annotation-with-index.csi");
1578        fs::create_dir_all(
1579            annotation_path
1580                .parent()
1581                .expect("should have annotation parent directory"),
1582        )
1583        .expect("should create fixture directory");
1584        fs::write(&annotation_path, "##gff-version 3\n").expect("should write annotation fixture");
1585        fs::write(&index_path, "index").expect("should write index fixture");
1586
1587        add_annotation_file(
1588            &context,
1589            annotation_path
1590                .to_str()
1591                .expect("should encode annotation path"),
1592            None,
1593            Some(index_path.to_str().expect("should encode index path")),
1594            Some("track-with-index"),
1595            None,
1596            AnnotationFileChecksumOverrides::default(),
1597        )
1598        .expect("should create annotation file operation");
1599
1600        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
1601        asset_refs.sort_by(|left, right| {
1602            left.role
1603                .as_str()
1604                .cmp(right.role.as_str())
1605                .then_with(|| left.logical_path.cmp(&right.logical_path))
1606        });
1607        assert_eq!(asset_refs.len(), 2);
1608        assert_eq!(asset_refs[0].role, AssetRole::Annotation);
1609        assert_eq!(asset_refs[1].role, AssetRole::AnnotationIndex);
1610        assert_eq!(
1611            asset_refs[1].upstream_asset_ref_id,
1612            Some(asset_refs[0].id),
1613            "annotation index should identify its immutable upstream annotation"
1614        );
1615        assert_eq!(
1616            asset_refs[0].checksum,
1617            Some(calculate_reader_checksum("##gff-version 3\n".as_bytes()).unwrap())
1618        );
1619        assert_eq!(
1620            asset_refs[1].checksum,
1621            Some(calculate_reader_checksum("index".as_bytes()).unwrap())
1622        );
1623        assert_eq!(asset_refs[1].file_type.as_str(), "none");
1624        assert_eq!(
1625            asset_refs[1]
1626                .logical_path
1627                .as_deref()
1628                .expect("should store index logical path"),
1629            "fixtures/annotation-with-index.csi"
1630        );
1631    }
1632
1633    #[test]
1634    fn test_add_annotation_file_does_not_read_remote_assets() {
1635        let context = setup_gen();
1636        let annotation_uri = "http://127.0.0.1:1/annotation.gff3".to_string();
1637        let index_uri = "http://127.0.0.1:1/annotation.gff3.csi".to_string();
1638
1639        add_annotation_file(
1640            &context,
1641            &annotation_uri,
1642            None,
1643            Some(&index_uri),
1644            Some("remote-annotation"),
1645            None,
1646            AnnotationFileChecksumOverrides::default(),
1647        )
1648        .expect("should track remote annotation assets");
1649
1650        let asset_refs =
1651            AssetRef::all(context.graph().conn()).expect("should load asset references");
1652        assert_eq!(asset_refs.len(), 2);
1653        assert!(
1654            asset_refs
1655                .iter()
1656                .all(|asset_ref| asset_ref.checksum.is_none())
1657        );
1658        assert!(
1659            asset_refs
1660                .iter()
1661                .any(|asset_ref| asset_ref.uri == annotation_uri)
1662        );
1663        assert!(
1664            asset_refs
1665                .iter()
1666                .any(|asset_ref| asset_ref.uri == index_uri)
1667        );
1668    }
1669
1670    #[test]
1671    fn test_add_annotation_file_passes_remote_checksum_overrides() {
1672        let context = setup_gen();
1673        let annotation_uri = "http://127.0.0.1:1/annotation.gff3";
1674        let index_uri = "http://127.0.0.1:1/annotation.gff3.csi";
1675        let annotation_checksum = Sha256Hash::convert_str("known annotation contents");
1676        let index_checksum = Sha256Hash::convert_str("known index contents");
1677
1678        add_annotation_file(
1679            &context,
1680            annotation_uri,
1681            None,
1682            Some(index_uri),
1683            Some("remote-annotation"),
1684            None,
1685            AnnotationFileChecksumOverrides {
1686                annotation: Some(annotation_checksum),
1687                index: Some(index_checksum),
1688            },
1689        )
1690        .expect("should track checksummed remote assets without reading them");
1691
1692        let asset_refs =
1693            AssetRef::all(context.graph().conn()).expect("should load asset references");
1694        assert_eq!(asset_refs.len(), 2);
1695        let annotation = asset_refs
1696            .iter()
1697            .find(|asset_ref| asset_ref.role == AssetRole::Annotation)
1698            .expect("should track annotation asset");
1699        let index = asset_refs
1700            .iter()
1701            .find(|asset_ref| asset_ref.role == AssetRole::AnnotationIndex)
1702            .expect("should track annotation index");
1703        assert_eq!(annotation.uri, annotation_uri);
1704        assert_eq!(annotation.checksum, Some(annotation_checksum));
1705        assert_eq!(index.uri, index_uri);
1706        assert_eq!(index.checksum, Some(index_checksum));
1707    }
1708
1709    #[test]
1710    fn test_add_annotation_file_does_not_store_absolute_external_index_path() {
1711        let context = setup_gen();
1712        let graph_conn = context.graph().conn();
1713        let repo_root = context
1714            .workspace()
1715            .repo_root()
1716            .expect("should have repo root");
1717        let annotation_path = repo_root.join("annotation.gff3");
1718        fs::write(&annotation_path, "##gff-version 3\n").expect("should write annotation fixture");
1719
1720        let external_dir = tempfile::tempdir().expect("should create external directory");
1721        let index_path = external_dir.path().join("private-index.csi");
1722        fs::write(&index_path, "private index contents").expect("should write external index");
1723        let index_path = index_path
1724            .to_str()
1725            .expect("should encode external index path");
1726
1727        add_annotation_file(
1728            &context,
1729            annotation_path
1730                .to_str()
1731                .expect("should encode annotation path"),
1732            None,
1733            Some(index_path),
1734            None,
1735            None,
1736            AnnotationFileChecksumOverrides::default(),
1737        )
1738        .expect("should create annotation file operation");
1739
1740        let index_asset = AssetRef::all(graph_conn)
1741            .expect("should load asset references")
1742            .into_iter()
1743            .find(|asset| asset.role == AssetRole::AnnotationIndex)
1744            .expect("should store annotation index asset");
1745        let checksum = index_asset
1746            .checksum
1747            .expect("local index asset should have checksum");
1748        let expected_logical_path = format!(".gen/assets/{checksum}.csi");
1749        assert_eq!(
1750            index_asset.logical_path.as_deref(),
1751            Some(expected_logical_path.as_str())
1752        );
1753        assert_ne!(index_asset.logical_path.as_deref(), Some(index_path));
1754        assert!(!index_asset.uri.contains(index_path));
1755    }
1756}