Skip to main content

gtars_refget/
seqcol.rs

1//! Seqcol spec operations: comparison, level-based retrieval, attribute search.
2//!
3//! These methods are defined on `RefgetStore` but live in this file for
4//! organizational clarity. They implement the GA4GH Sequence Collections
5//! specification endpoints (level 1/2 retrieval, comparison, attribute search).
6
7use crate::digest::{CollectionLevel1, CollectionLevel2, SeqColComparison, SequenceCollectionMetadata};
8use crate::digest::types::{compare_arrays, level2_to_comparison_arrays};
9use crate::store::{PagedResult, ReadonlyRefgetStore};
10use anyhow::{anyhow, Result};
11
12/// Trait defining the read-only operations a seqcol API server needs from its backend.
13///
14/// This is the canonical interface for seqcol server operations. Any backend
15/// (filesystem-backed `ReadonlyRefgetStore`, Postgres, remote proxy, in-memory mock)
16/// can implement this trait and be used via `Arc<dyn SeqColService>`.
17///
18/// All methods take `&self` and return concrete types, making the trait object-safe.
19pub trait SeqColService {
20    /// Level 1: attribute digests only.
21    fn get_collection_level1(&self, digest: &str) -> Result<CollectionLevel1>;
22
23    /// Level 2: full arrays with values.
24    fn get_collection_level2(&self, digest: &str) -> Result<CollectionLevel2>;
25
26    /// Compare two collections by digest.
27    fn compare(&self, digest_a: &str, digest_b: &str) -> Result<SeqColComparison>;
28
29    /// Compare a stored collection against an externally-provided level-2 body.
30    fn compare_with_level2(
31        &self,
32        digest_a: &str,
33        external: &CollectionLevel2,
34    ) -> Result<SeqColComparison>;
35
36    /// Find collections sharing an attribute digest.
37    fn find_collections_by_attribute(
38        &self,
39        attr_name: &str,
40        attr_digest: &str,
41    ) -> Result<Vec<String>>;
42
43    /// Get the raw attribute array for a given attribute digest.
44    fn get_attribute(
45        &self,
46        attr_name: &str,
47        attr_digest: &str,
48    ) -> Result<Option<serde_json::Value>>;
49
50    /// List collections with pagination and optional attribute filters.
51    fn list_collections(
52        &self,
53        page: usize,
54        page_size: usize,
55        filters: &[(&str, &str)],
56    ) -> Result<PagedResult<SequenceCollectionMetadata>>;
57
58    /// Total number of collections in the store.
59    fn collection_count(&self) -> usize;
60}
61
62/// Check if a collection's metadata matches a single attribute filter.
63/// Returns Err if attr_name is unrecognized.
64pub(crate) fn metadata_matches_attribute(
65    meta: &SequenceCollectionMetadata,
66    attr_name: &str,
67    attr_digest: &str,
68) -> Result<bool> {
69    match attr_name {
70        "names" => Ok(meta.names_digest == attr_digest),
71        "lengths" => Ok(meta.lengths_digest == attr_digest),
72        "sequences" => Ok(meta.sequences_digest == attr_digest),
73        "name_length_pairs" => Ok(meta
74            .name_length_pairs_digest
75            .as_deref()
76            .map_or(false, |d| d == attr_digest)),
77        "sorted_name_length_pairs" => Ok(meta
78            .sorted_name_length_pairs_digest
79            .as_deref()
80            .map_or(false, |d| d == attr_digest)),
81        "sorted_sequences" => Ok(meta
82            .sorted_sequences_digest
83            .as_deref()
84            .map_or(false, |d| d == attr_digest)),
85        _ => Err(anyhow!(
86            "Unknown attribute: '{}'. Supported: names, lengths, sequences, \
87             name_length_pairs, sorted_name_length_pairs, sorted_sequences",
88            attr_name
89        )),
90    }
91}
92
93/// Warn users when brute-force scanning more than this many collections.
94const ATTRIBUTE_SEARCH_WARN_THRESHOLD: usize = 10_000;
95
96/// Error if brute-force scanning would exceed this many collections.
97const ATTRIBUTE_SEARCH_ERROR_THRESHOLD: usize = 100_000;
98
99impl ReadonlyRefgetStore {
100    /// Enable computation and storage of ancillary digests (nlp, snlp, sorted_sequences).
101    pub fn enable_ancillary_digests(&mut self) {
102        self.ancillary_digests = true;
103    }
104
105    /// Disable computation and storage of ancillary digests.
106    pub fn disable_ancillary_digests(&mut self) {
107        self.ancillary_digests = false;
108    }
109
110    /// Returns whether ancillary digests are enabled.
111    pub fn has_ancillary_digests(&self) -> bool {
112        self.ancillary_digests
113    }
114
115    /// Returns whether the on-disk attribute index is enabled.
116    pub fn has_attribute_index(&self) -> bool {
117        self.attribute_index
118    }
119
120    /// Get collection at level 1 representation (attribute digests with spec field names).
121    /// This is a lightweight operation that only reads metadata, no loading needed.
122    pub fn get_collection_level1(&self, digest: &str) -> Result<CollectionLevel1> {
123        let meta = self
124            .get_collection_metadata(digest)
125            .ok_or_else(|| anyhow!("Collection not found: {}", digest))?;
126        Ok(meta.to_level1())
127    }
128
129    /// Get collection at level 2 representation (full arrays, spec format).
130    /// May need to load the collection from disk/remote.
131    pub fn get_collection_level2(&self, digest: &str) -> Result<CollectionLevel2> {
132        // Built straight from the catalog members; no per-member record.
133        let members = self.collection_members(digest).map_err(|_| {
134            anyhow!(
135                "Collection not loaded: {}. Call load_collection() or load_all_collections() first.",
136                digest
137            )
138        })?;
139        let n = members.len();
140        let mut names = Vec::with_capacity(n);
141        let mut lengths = Vec::with_capacity(n);
142        let mut sequences = Vec::with_capacity(n);
143        for m in members {
144            let s = m.seq();
145            names.push(m.name().to_string());
146            lengths.push(s.length());
147            sequences.push(format!("SQ.{}", s.sha512t24u()));
148        }
149        Ok(CollectionLevel2 { names, lengths, sequences })
150    }
151
152    /// Compare two collections by digest. Both must be preloaded.
153    pub fn compare(&self, digest_a: &str, digest_b: &str) -> Result<SeqColComparison> {
154        let coll_a = self.get_collection(digest_a)?;
155        let coll_b = self.get_collection(digest_b)?;
156        Ok(coll_a.compare(&coll_b))
157    }
158
159    /// Match collection-local names by identical sequence content.
160    pub fn match_sequence_names(
161        &self,
162        digest_a: &str,
163        digest_b: &str,
164    ) -> Result<crate::digest::CollectionNameMatch> {
165        let coll_a = self.get_collection(digest_a)?;
166        let coll_b = self.get_collection(digest_b)?;
167        coll_a.match_sequence_names(&coll_b)
168    }
169
170    /// Compare a stored collection (by digest) against an externally-provided level-2 body.
171    ///
172    /// Used for the seqcol spec `POST /comparison/:digest1` endpoint where the client
173    /// submits a local collection as JSON rather than referencing a stored digest.
174    ///
175    /// The returned `SeqColComparison` has `digests.a` set to the stored collection's
176    /// digest and `digests.b` set to `None` because the external collection has no
177    /// server-side digest.
178    pub fn compare_with_level2(
179        &self,
180        digest_a: &str,
181        external: &CollectionLevel2,
182    ) -> Result<SeqColComparison> {
183        let coll_a = self.get_collection(digest_a)?;
184        let arrays_a = coll_a.to_comparison_arrays();
185        let arrays_b = level2_to_comparison_arrays(external);
186        Ok(compare_arrays(
187            arrays_a,
188            arrays_b,
189            Some(coll_a.metadata.digest.clone()),
190            None,
191        ))
192    }
193
194    /// Find all collections with a specific attribute digest.
195    ///
196    /// Dispatches to indexed lookup (if attribute_index enabled) or
197    /// brute-force metadata scan (default).
198    ///
199    /// Supported attr_name values: "names", "lengths", "sequences",
200    /// "name_length_pairs", "sorted_name_length_pairs", "sorted_sequences"
201    pub fn find_collections_by_attribute(
202        &self,
203        attr_name: &str,
204        attr_digest: &str,
205    ) -> Result<Vec<String>> {
206        if self.attribute_index {
207            self.find_collections_by_attribute_indexed(attr_name, attr_digest)
208        } else {
209            self.find_collections_by_attribute_scan(attr_name, attr_digest)
210        }
211    }
212
213    /// Brute-force scan of collection metadata.
214    /// Warns at 10k collections, errors at 100k collections.
215    fn find_collections_by_attribute_scan(
216        &self,
217        attr_name: &str,
218        attr_digest: &str,
219    ) -> Result<Vec<String>> {
220        let count = self.catalog.n_collections();
221
222        if count > ATTRIBUTE_SEARCH_ERROR_THRESHOLD {
223            return Err(anyhow!(
224                "Brute-force attribute search is limited to {} collections ({} in store). \
225                 Indexed attribute lookup is planned for a future release.",
226                ATTRIBUTE_SEARCH_ERROR_THRESHOLD,
227                count
228            ));
229        }
230
231        if count > ATTRIBUTE_SEARCH_WARN_THRESHOLD {
232            eprintln!(
233                "Warning: brute-force attribute search scanning {} collections. \
234                 This may be slow.",
235                count
236            );
237        }
238
239        let mut results = Vec::new();
240        for c in self.catalog.coll_rows() {
241            let meta = self.catalog.coll_meta(c);
242            if metadata_matches_attribute(meta, attr_name, attr_digest)? {
243                results.push(meta.digest.clone());
244            }
245        }
246        Ok(results)
247    }
248
249    /// Get the raw attribute array for a given attribute digest.
250    /// Finds a collection with this attribute (via search), loads it,
251    /// and extracts the array.
252    ///
253    /// Supported attr_name values: "names", "lengths", "sequences",
254    /// "name_length_pairs", "sorted_name_length_pairs", "sorted_sequences"
255    ///
256    /// Returns the array as a serde_json::Value (array of strings or numbers).
257    /// Returns Ok(None) if no collection has this attribute digest.
258    pub fn get_attribute(
259        &self,
260        attr_name: &str,
261        attr_digest: &str,
262    ) -> Result<Option<serde_json::Value>> {
263        let collections = self.find_collections_by_attribute(attr_name, attr_digest)?;
264        if collections.is_empty() {
265            return Ok(None);
266        }
267
268        // Load the first matching collection
269        let collection = self.get_collection(&collections[0])?;
270        let lvl2 = collection.to_level2();
271
272        let value = match attr_name {
273            "names" => serde_json::Value::Array(
274                lvl2.names
275                    .iter()
276                    .map(|s| serde_json::Value::String(s.clone()))
277                    .collect(),
278            ),
279            "lengths" => serde_json::Value::Array(
280                lvl2.lengths
281                    .iter()
282                    .map(|l| serde_json::Value::Number(serde_json::Number::from(*l)))
283                    .collect(),
284            ),
285            "sequences" => serde_json::Value::Array(
286                lvl2.sequences
287                    .iter()
288                    .map(|s| serde_json::Value::String(s.clone()))
289                    .collect(),
290            ),
291            "sorted_sequences" => serde_json::Value::Array(
292                collection
293                    .build_sorted_sequences()
294                    .into_iter()
295                    .map(serde_json::Value::String)
296                    .collect(),
297            ),
298            "name_length_pairs" => {
299                serde_json::Value::Array(collection.build_name_length_pairs())
300            }
301            "sorted_name_length_pairs" => {
302                serde_json::Value::Array(collection.build_sorted_name_length_pairs())
303            }
304            _ => {
305                return Err(anyhow!(
306                    "Unknown attribute: '{}'. Supported: names, lengths, sequences, \
307                     name_length_pairs, sorted_name_length_pairs, sorted_sequences",
308                    attr_name
309                ))
310            }
311        };
312
313        Ok(Some(value))
314    }
315
316    /// Enable indexed attribute lookup (not yet implemented).
317    ///
318    /// Note: The indexed lookup feature is planned for a future release.
319    /// Enabling this will cause `find_collections_by_attribute()` to return
320    /// a "not implemented" error until the feature is complete.
321    pub fn enable_attribute_index(&mut self) {
322        self.attribute_index = true;
323    }
324
325    /// Disable indexed attribute lookup, using brute-force scan instead.
326    pub fn disable_attribute_index(&mut self) {
327        self.attribute_index = false;
328    }
329
330    /// Indexed lookup from on-disk reverse index.
331    /// Stub: not yet implemented. Planned for a future release.
332    fn find_collections_by_attribute_indexed(
333        &self,
334        _attr_name: &str,
335        _attr_digest: &str,
336    ) -> Result<Vec<String>> {
337        Err(anyhow!(
338            "Indexed attribute lookup is not yet implemented. \
339             This feature is planned for a future release. \
340             For now, use the brute-force scan by keeping attribute_index disabled."
341        ))
342    }
343
344    /// Total number of collections in the store.
345    pub fn collection_count(&self) -> usize {
346        self.catalog.n_collections()
347    }
348}
349
350impl SeqColService for ReadonlyRefgetStore {
351    fn get_collection_level1(&self, digest: &str) -> Result<CollectionLevel1> {
352        ReadonlyRefgetStore::get_collection_level1(self, digest)
353    }
354
355    fn get_collection_level2(&self, digest: &str) -> Result<CollectionLevel2> {
356        ReadonlyRefgetStore::get_collection_level2(self, digest)
357    }
358
359    fn compare(&self, digest_a: &str, digest_b: &str) -> Result<SeqColComparison> {
360        ReadonlyRefgetStore::compare(self, digest_a, digest_b)
361    }
362
363    fn compare_with_level2(
364        &self,
365        digest_a: &str,
366        external: &CollectionLevel2,
367    ) -> Result<SeqColComparison> {
368        ReadonlyRefgetStore::compare_with_level2(self, digest_a, external)
369    }
370
371    fn find_collections_by_attribute(
372        &self,
373        attr_name: &str,
374        attr_digest: &str,
375    ) -> Result<Vec<String>> {
376        ReadonlyRefgetStore::find_collections_by_attribute(self, attr_name, attr_digest)
377    }
378
379    fn get_attribute(
380        &self,
381        attr_name: &str,
382        attr_digest: &str,
383    ) -> Result<Option<serde_json::Value>> {
384        ReadonlyRefgetStore::get_attribute(self, attr_name, attr_digest)
385    }
386
387    fn list_collections(
388        &self,
389        page: usize,
390        page_size: usize,
391        filters: &[(&str, &str)],
392    ) -> Result<PagedResult<SequenceCollectionMetadata>> {
393        ReadonlyRefgetStore::list_collections(self, page, page_size, filters)
394    }
395
396    fn collection_count(&self) -> usize {
397        ReadonlyRefgetStore::collection_count(self)
398    }
399}
400
401// Non-filesystem seqcol tests: in-memory store only, no FASTA import.
402#[cfg(test)]
403mod nofs_tests {
404    use crate::store::RefgetStore;
405
406    #[test]
407    fn test_compare_with_level2_unknown_digest_returns_error() {
408        let store = RefgetStore::in_memory();
409        // Build a minimal CollectionLevel2 body
410        use crate::digest::CollectionLevel2;
411        let level2 = CollectionLevel2 {
412            names: vec!["chr1".to_string()],
413            lengths: vec![100],
414            sequences: vec!["SQ.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string()],
415        };
416
417        let result = store.compare_with_level2("nonexistent_digest", &level2);
418        assert!(result.is_err(), "Expected error for unknown digest");
419    }
420}
421
422// The remaining seqcol tests import FASTA via the filesystem-only API.
423#[cfg(all(test, feature = "filesystem"))]
424mod tests {
425    use crate::store::{FastaImportOptions, ReadonlyRefgetStore, RefgetStore};
426    use std::path::PathBuf;
427
428    /// Copy a test FASTA to a temp directory to avoid writing RGSI cache files
429    /// into the test data directory.
430    fn copy_test_fasta(temp_dir: &std::path::Path, name: &str) -> PathBuf {
431        let src = format!("../tests/data/fasta/{}", name);
432        let dst = temp_dir.join(name);
433        std::fs::copy(&src, &dst)
434            .unwrap_or_else(|e| panic!("Failed to copy {} to tempdir: {}", src, e));
435        dst
436    }
437
438    #[test]
439    fn test_ancillary_digests_computed() {
440        let mut store = RefgetStore::in_memory();
441        assert!(store.has_ancillary_digests());
442
443        let (metadata, _) = store
444            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
445            .unwrap();
446
447        // Ancillary digests should be present
448        assert!(metadata.name_length_pairs_digest.is_some());
449        assert!(metadata.sorted_name_length_pairs_digest.is_some());
450        assert!(metadata.sorted_sequences_digest.is_some());
451
452        // The stored collection should also have them
453        let coll_meta = store.get_collection_metadata(&metadata.digest).unwrap();
454        assert!(coll_meta.name_length_pairs_digest.is_some());
455        assert!(coll_meta.sorted_name_length_pairs_digest.is_some());
456        assert!(coll_meta.sorted_sequences_digest.is_some());
457    }
458
459    #[test]
460    fn test_ancillary_digests_disabled() {
461        let mut store = RefgetStore::in_memory();
462        store.disable_ancillary_digests();
463        assert!(!store.has_ancillary_digests());
464
465        let (metadata, _) = store
466            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
467            .unwrap();
468
469        // Ancillary digests should NOT be present
470        assert!(metadata.name_length_pairs_digest.is_none());
471        assert!(metadata.sorted_name_length_pairs_digest.is_none());
472        assert!(metadata.sorted_sequences_digest.is_none());
473    }
474
475    #[test]
476    fn test_collection_level1() {
477        let mut store = RefgetStore::in_memory();
478        let (metadata, _) = store
479            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
480            .unwrap();
481
482        let lvl1 = store.get_collection_level1(&metadata.digest).unwrap();
483        assert_eq!(lvl1.names, metadata.names_digest);
484        assert_eq!(lvl1.lengths, metadata.lengths_digest);
485        assert_eq!(lvl1.sequences, metadata.sequences_digest);
486        assert!(lvl1.name_length_pairs.is_some());
487        assert!(lvl1.sorted_name_length_pairs.is_some());
488        assert!(lvl1.sorted_sequences.is_some());
489    }
490
491    #[test]
492    fn test_collection_level2() {
493        let mut store = RefgetStore::in_memory();
494        let (metadata, _) = store
495            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
496            .unwrap();
497
498        let lvl2 = store.get_collection_level2(&metadata.digest).unwrap();
499        assert_eq!(lvl2.names.len(), 3); // chrX, chr1, chr2
500        assert_eq!(lvl2.lengths.len(), 3);
501        assert_eq!(lvl2.sequences.len(), 3);
502
503        // Check that sequences have SQ. prefix
504        for seq in &lvl2.sequences {
505            assert!(seq.starts_with("SQ."), "Expected SQ. prefix, got: {}", seq);
506        }
507
508        // Check lengths match the FASTA data
509        assert!(lvl2.lengths.contains(&8)); // chrX = TTGGGGAA
510        assert!(lvl2.lengths.contains(&4)); // chr1 = GGAA, chr2 = GCGC
511    }
512
513    #[test]
514    fn test_compare_collections() {
515        let mut store = RefgetStore::in_memory();
516        let (meta_a, _) = store
517            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
518            .unwrap();
519        let (meta_b, _) = store
520            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
521            .unwrap();
522
523        // Self-compare: identical digests, all elements same order
524        let self_result = store.compare(&meta_a.digest, &meta_a.digest).unwrap();
525        assert_eq!(self_result.digests.a, self_result.digests.b);
526        assert_eq!(self_result.attributes.a_and_b.len(), 6); // 3 core + 3 ancillary
527        for attr in &self_result.attributes.a_and_b {
528            assert_eq!(self_result.array_elements.a_and_b_same_order[attr], Some(true));
529        }
530
531        // Cross-compare: different digests, all 6 attributes shared
532        let cross_result = store.compare(&meta_a.digest, &meta_b.digest).unwrap();
533        assert_ne!(cross_result.digests.a, cross_result.digests.b);
534        assert_eq!(cross_result.attributes.a_and_b.len(), 6);
535        assert!(cross_result.attributes.a_only.is_empty());
536        assert!(cross_result.attributes.b_only.is_empty());
537    }
538
539    #[test]
540    fn test_compare_mixed_ancillary() {
541        let mut store = RefgetStore::in_memory();
542        let (meta_a, _) = store
543            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
544            .unwrap();
545        store.disable_ancillary_digests();
546        let (meta_b, _) = store
547            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
548            .unwrap();
549
550        let result = store.compare(&meta_a.digest, &meta_b.digest).unwrap();
551        assert_eq!(result.attributes.a_and_b.len(), 3);
552        assert_eq!(result.attributes.a_only.len(), 3);
553        assert!(result.attributes.b_only.is_empty());
554    }
555
556    #[test]
557    fn test_find_collections_by_attribute() {
558        let mut store = RefgetStore::in_memory();
559        let (metadata, _) = store
560            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
561            .unwrap();
562
563        // Search by names digest should find our collection
564        let results = store
565            .find_collections_by_attribute("names", &metadata.names_digest)
566            .unwrap();
567        assert_eq!(results.len(), 1);
568        assert_eq!(results[0], metadata.digest);
569
570        // Search by lengths digest
571        let results = store
572            .find_collections_by_attribute("lengths", &metadata.lengths_digest)
573            .unwrap();
574        assert_eq!(results.len(), 1);
575
576        // Search by sequences digest
577        let results = store
578            .find_collections_by_attribute("sequences", &metadata.sequences_digest)
579            .unwrap();
580        assert_eq!(results.len(), 1);
581
582        // Search by ancillary digest
583        let nlp = metadata.name_length_pairs_digest.as_ref().unwrap();
584        let results = store
585            .find_collections_by_attribute("name_length_pairs", nlp)
586            .unwrap();
587        assert_eq!(results.len(), 1);
588
589        // Search with nonexistent digest
590        let results = store
591            .find_collections_by_attribute("names", "nonexistent")
592            .unwrap();
593        assert!(results.is_empty());
594
595        // Unknown attribute should error
596        assert!(store
597            .find_collections_by_attribute("unknown", "digest")
598            .is_err());
599    }
600
601    #[test]
602    fn test_get_attribute() {
603        let mut store = RefgetStore::in_memory();
604        let (metadata, _) = store
605            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
606            .unwrap();
607
608        // Get names array
609        let result = store
610            .get_attribute("names", &metadata.names_digest)
611            .unwrap();
612        assert!(result.is_some());
613        let names = result.unwrap();
614        assert!(names.is_array());
615        assert_eq!(names.as_array().unwrap().len(), 3);
616
617        // Get lengths array
618        let result = store
619            .get_attribute("lengths", &metadata.lengths_digest)
620            .unwrap();
621        assert!(result.is_some());
622
623        // Nonexistent digest returns None
624        let result = store.get_attribute("names", "nonexistent").unwrap();
625        assert!(result.is_none());
626    }
627
628    #[test]
629    fn test_get_attribute_sorted_sequences() {
630        let mut store = RefgetStore::in_memory();
631        let (metadata, _) = store
632            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
633            .unwrap();
634
635        let digest = metadata.sorted_sequences_digest.as_ref().unwrap();
636        let result = store.get_attribute("sorted_sequences", digest).unwrap();
637        assert!(result.is_some());
638        let arr = result.unwrap();
639        assert!(arr.is_array());
640        let items = arr.as_array().unwrap();
641        assert_eq!(items.len(), 3);
642
643        // All items should be strings with SQ. prefix
644        for item in items {
645            let s = item.as_str().unwrap();
646            assert!(s.starts_with("SQ."), "Expected SQ. prefix, got: {}", s);
647        }
648
649        // Should be sorted lexicographically
650        let strings: Vec<&str> = items.iter().map(|v| v.as_str().unwrap()).collect();
651        let mut sorted = strings.clone();
652        sorted.sort();
653        assert_eq!(strings, sorted, "sorted_sequences should be in sorted order");
654    }
655
656    #[test]
657    fn test_get_attribute_name_length_pairs() {
658        let mut store = RefgetStore::in_memory();
659        let (metadata, _) = store
660            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
661            .unwrap();
662
663        let digest = metadata.name_length_pairs_digest.as_ref().unwrap();
664        let result = store.get_attribute("name_length_pairs", digest).unwrap();
665        assert!(result.is_some());
666        let arr = result.unwrap();
667        assert!(arr.is_array());
668        let items = arr.as_array().unwrap();
669        assert_eq!(items.len(), 3);
670
671        // Each item should be an object with "name" (string) and "length" (number) keys
672        for item in items {
673            let obj = item.as_object().unwrap();
674            assert!(obj.contains_key("name"), "Expected 'name' key in object");
675            assert!(obj.contains_key("length"), "Expected 'length' key in object");
676            assert!(obj["name"].is_string(), "name should be a string");
677            assert!(obj["length"].is_number(), "length should be a number");
678        }
679    }
680
681    #[test]
682    fn test_get_attribute_sorted_name_length_pairs() {
683        use crate::digest::algorithms::{canonicalize_json, sha512t24u};
684
685        let mut store = RefgetStore::in_memory();
686        let (metadata, _) = store
687            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
688            .unwrap();
689
690        let digest = metadata.sorted_name_length_pairs_digest.as_ref().unwrap();
691        let result = store
692            .get_attribute("sorted_name_length_pairs", digest)
693            .unwrap();
694        assert!(result.is_some());
695        let arr = result.unwrap();
696        assert!(arr.is_array());
697        let items = arr.as_array().unwrap();
698        assert_eq!(items.len(), 3);
699
700        // Each item should be an object with "name" and "length" keys
701        for item in items {
702            let obj = item.as_object().unwrap();
703            assert!(obj.contains_key("name"));
704            assert!(obj.contains_key("length"));
705        }
706
707        // Verify the objects are sorted by their canonical JSON digest
708        let digests: Vec<String> = items
709            .iter()
710            .map(|v| sha512t24u(canonicalize_json(v).as_bytes()))
711            .collect();
712        let mut sorted_digests = digests.clone();
713        sorted_digests.sort();
714        assert_eq!(
715            digests, sorted_digests,
716            "sorted_name_length_pairs objects should be in sorted digest order"
717        );
718    }
719
720    #[test]
721    fn test_get_attribute_ancillary_not_computed() {
722        let mut store = RefgetStore::in_memory();
723        store.disable_ancillary_digests();
724        let (metadata, _) = store
725            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
726            .unwrap();
727
728        // Ancillary digests not present, so search returns empty, get_attribute returns None
729        assert!(metadata.name_length_pairs_digest.is_none());
730        let result = store
731            .get_attribute("name_length_pairs", "some_digest")
732            .unwrap();
733        assert!(
734            result.is_none(),
735            "Expected None when no ancillary digests are computed"
736        );
737    }
738
739    #[test]
740    fn test_rgci_roundtrip_with_ancillary() {
741        let dir = tempfile::tempdir().unwrap();
742        let dir_path = dir.path();
743        let temp_fasta = copy_test_fasta(dir_path, "base.fa");
744
745        // Create and save a store with ancillary digests
746        {
747            let mut store = RefgetStore::on_disk(dir_path).unwrap();
748            store
749                .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
750                .unwrap();
751            store.write().unwrap();
752        }
753
754        // Reload and verify ancillary digests survived
755        {
756            let store = RefgetStore::open_local(dir_path).unwrap();
757            let collections = store.list_collections(0, usize::MAX, &[]).unwrap();
758            assert_eq!(collections.results.len(), 1);
759
760            let meta = &collections.results[0];
761            assert!(meta.name_length_pairs_digest.is_some());
762            assert!(meta.sorted_name_length_pairs_digest.is_some());
763            assert!(meta.sorted_sequences_digest.is_some());
764        }
765    }
766
767    // ================================================================
768    // Compliance tests against Python refget test_fasta_digests.json
769    // To add new test cases, edit tests/data/fasta/test_fasta_digests.json
770    // and add corresponding .fa files to tests/data/fasta/.
771    // ================================================================
772
773    #[test]
774    fn test_compliance_digests_from_fixture() {
775        let fixture_path = "../tests/data/fasta/test_fasta_digests.json";
776        let fixture_str = std::fs::read_to_string(fixture_path)
777            .unwrap_or_else(|e| panic!("Failed to read {}: {}", fixture_path, e));
778        let fixture: serde_json::Value = serde_json::from_str(&fixture_str)
779            .unwrap_or_else(|e| panic!("Failed to parse {}: {}", fixture_path, e));
780
781        let mut store = RefgetStore::in_memory();
782        store.enable_ancillary_digests();
783
784        for (fa_name, bundle) in fixture.as_object().unwrap() {
785            let fasta_path = format!("../tests/data/fasta/{}", fa_name);
786            let (meta, _) = store
787                .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
788                .unwrap_or_else(|e| panic!("{}: {}", fa_name, e));
789
790            let lvl1 = bundle["level1"].as_object().unwrap();
791            let expected_digest = bundle["top_level_digest"].as_str().unwrap();
792
793            assert_eq!(meta.digest, expected_digest, "{}: top_level_digest", fa_name);
794            assert_eq!(meta.names_digest, lvl1["names"].as_str().unwrap(), "{}: names", fa_name);
795            assert_eq!(meta.lengths_digest, lvl1["lengths"].as_str().unwrap(), "{}: lengths", fa_name);
796            assert_eq!(meta.sequences_digest, lvl1["sequences"].as_str().unwrap(), "{}: sequences", fa_name);
797            assert_eq!(
798                meta.sorted_sequences_digest.as_deref(),
799                Some(lvl1["sorted_sequences"].as_str().unwrap()),
800                "{}: sorted_sequences", fa_name
801            );
802            assert_eq!(
803                meta.name_length_pairs_digest.as_deref(),
804                Some(lvl1["name_length_pairs"].as_str().unwrap()),
805                "{}: name_length_pairs", fa_name
806            );
807            assert_eq!(
808                meta.sorted_name_length_pairs_digest.as_deref(),
809                Some(lvl1["sorted_name_length_pairs"].as_str().unwrap()),
810                "{}: sorted_name_length_pairs", fa_name
811            );
812        }
813    }
814
815    #[test]
816    fn test_store_config_persisted() {
817        let dir = tempfile::tempdir().unwrap();
818        let dir_path = dir.path();
819        let temp_fasta = copy_test_fasta(dir_path, "base.fa");
820
821        // Create store with ancillary enabled (default)
822        {
823            let mut store = RefgetStore::on_disk(dir_path).unwrap();
824            assert!(store.has_ancillary_digests());
825            assert!(!store.has_attribute_index());
826            store
827                .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
828                .unwrap();
829            store.write().unwrap();
830        }
831
832        // Reload and verify config
833        {
834            let store = RefgetStore::open_local(dir_path).unwrap();
835            assert!(store.has_ancillary_digests());
836            assert!(!store.has_attribute_index());
837        }
838    }
839
840    // ================================================================
841    // Tests for compare_with_level2
842    // ================================================================
843
844    /// Test 1: compare_with_level2 produces same result as compare when inputs are identical.
845    #[test]
846    fn test_compare_with_level2_self_identical() {
847        let mut store = RefgetStore::in_memory();
848        let (meta, _) = store
849            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
850            .unwrap();
851
852        // Get the level-2 representation of the stored collection
853        let level2 = store.get_collection_level2(&meta.digest).unwrap();
854
855        // Compare the stored collection against its own level-2 body
856        let result = store.compare_with_level2(&meta.digest, &level2).unwrap();
857
858        // digests.a is the stored digest, digests.b is None (no server-side digest for external body)
859        assert_eq!(result.digests.a.as_deref(), Some(meta.digest.as_str()));
860        assert!(result.digests.b.is_none(), "digests.b should be None for external level-2 comparison");
861
862        // All three core attributes should be shared (a_and_b)
863        assert!(result.attributes.a_and_b.contains(&"names".to_string()));
864        assert!(result.attributes.a_and_b.contains(&"lengths".to_string()));
865        assert!(result.attributes.a_and_b.contains(&"sequences".to_string()));
866
867        // All shared core attributes should be in same order
868        for attr in &["names", "lengths", "sequences"] {
869            assert_eq!(
870                result.array_elements.a_and_b_same_order[*attr],
871                Some(true),
872                "{} should be in same order",
873                attr
874            );
875        }
876    }
877
878    /// Test 2: compare_with_level2 with a different external collection produces equivalent
879    /// result to compare(), except digests.b is None instead of Some(digest_b).
880    #[test]
881    fn test_compare_with_level2_cross_compare() {
882        let mut store = RefgetStore::in_memory();
883        let (meta_a, _) = store
884            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
885            .unwrap();
886        let (meta_b, _) = store
887            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
888            .unwrap();
889
890        // Get level-2 of B
891        let level2_b = store.get_collection_level2(&meta_b.digest).unwrap();
892
893        // compare via digest-digest
894        let compare_result = store.compare(&meta_a.digest, &meta_b.digest).unwrap();
895        // compare via digest + external level-2
896        let with_level2_result = store.compare_with_level2(&meta_a.digest, &level2_b).unwrap();
897
898        // digests.b is None in compare_with_level2 result, Some(digest_b) in compare result
899        assert_eq!(compare_result.digests.b, Some(meta_b.digest.clone()));
900        assert!(with_level2_result.digests.b.is_none());
901
902        // Everything else should match
903        assert_eq!(compare_result.digests.a, with_level2_result.digests.a);
904        // The a_and_b core attributes should agree (both compare the same data for core attributes)
905        for attr in &["names", "lengths", "sequences"] {
906            assert!(
907                with_level2_result.attributes.a_and_b.contains(&attr.to_string())
908                    || with_level2_result.attributes.a_only.contains(&attr.to_string())
909                    || with_level2_result.attributes.b_only.contains(&attr.to_string()),
910                "attr {} must appear somewhere",
911                attr
912            );
913        }
914    }
915
916    /// Test 3: compare_with_level2 with an unknown digest returns an error.
917    // `test_compare_with_level2_unknown_digest_returns_error` is non-filesystem;
918    // it lives in the always-compiled `nofs_tests` module above.
919
920    /// Test 4: ancillary attributes from the stored collection appear in a_only when
921    /// the external level-2 body does not contain them.
922    #[test]
923    fn test_compare_with_level2_ancillary_in_a_only() {
924        let mut store = RefgetStore::in_memory();
925        // Import with ancillary digests enabled (default)
926        let (meta, _) = store
927            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
928            .unwrap();
929
930        // Verify ancillary digests were computed
931        assert!(meta.name_length_pairs_digest.is_some());
932        assert!(meta.sorted_name_length_pairs_digest.is_some());
933        assert!(meta.sorted_sequences_digest.is_some());
934
935        // The level-2 body has only the three core attributes — no ancillary
936        let level2 = store.get_collection_level2(&meta.digest).unwrap();
937
938        let result = store.compare_with_level2(&meta.digest, &level2).unwrap();
939
940        // Ancillary attributes that are in stored collection but not in level-2 body
941        // should appear in a_only
942        assert!(
943            result.attributes.a_only.contains(&"sorted_sequences".to_string()),
944            "sorted_sequences should be in a_only"
945        );
946        assert!(
947            result.attributes.a_only.contains(&"name_length_pairs".to_string()),
948            "name_length_pairs should be in a_only"
949        );
950        assert!(
951            result.attributes.a_only.contains(&"sorted_name_length_pairs".to_string()),
952            "sorted_name_length_pairs should be in a_only"
953        );
954
955        // b_only should be empty (level-2 body only has core attributes)
956        assert!(
957            result.attributes.b_only.is_empty(),
958            "b_only should be empty when level-2 has only core attributes"
959        );
960    }
961
962    // =========================================================================
963    // list_collections pagination and filtering tests
964    // =========================================================================
965
966    #[test]
967    fn test_list_collections_paged_no_filters() {
968        let mut store = RefgetStore::in_memory();
969        store
970            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
971            .unwrap();
972        store
973            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
974            .unwrap();
975
976        let result = store.list_collections(0, 2, &[]).unwrap();
977        assert_eq!(result.results.len(), 2);
978        assert_eq!(result.pagination.total, 2);
979        assert_eq!(result.pagination.page, 0);
980        assert_eq!(result.pagination.page_size, 2);
981        // Results should be sorted by digest
982        assert!(result.results[0].digest <= result.results[1].digest);
983    }
984
985    #[test]
986    fn test_list_collections_paged_second_page() {
987        let mut store = RefgetStore::in_memory();
988        store
989            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
990            .unwrap();
991        store
992            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
993            .unwrap();
994
995        // Page 0 with page_size 1
996        let page0 = store.list_collections(0, 1, &[]).unwrap();
997        assert_eq!(page0.results.len(), 1);
998        assert_eq!(page0.pagination.total, 2);
999
1000        // Page 1 with page_size 1
1001        let page1 = store.list_collections(1, 1, &[]).unwrap();
1002        assert_eq!(page1.results.len(), 1);
1003        assert_eq!(page1.pagination.total, 2);
1004
1005        // Different results on different pages
1006        assert_ne!(page0.results[0].digest, page1.results[0].digest);
1007    }
1008
1009    #[test]
1010    fn test_list_collections_paged_beyond_end() {
1011        let mut store = RefgetStore::in_memory();
1012        store
1013            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1014            .unwrap();
1015
1016        let result = store.list_collections(10, 100, &[]).unwrap();
1017        assert!(result.results.is_empty());
1018        assert_eq!(result.pagination.total, 1);
1019    }
1020
1021    #[test]
1022    fn test_list_collections_single_filter() {
1023        let mut store = RefgetStore::in_memory();
1024        let (meta, _) = store
1025            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1026            .unwrap();
1027        store
1028            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
1029            .unwrap();
1030
1031        let result = store.list_collections(0, 100, &[("names", &meta.names_digest)]).unwrap();
1032        assert_eq!(result.results.len(), 1);
1033        assert_eq!(result.results[0].digest, meta.digest);
1034        assert_eq!(result.pagination.total, 1);
1035    }
1036
1037    #[test]
1038    fn test_list_collections_multi_filter_and() {
1039        let mut store = RefgetStore::in_memory();
1040        let (meta, _) = store
1041            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1042            .unwrap();
1043        store
1044            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
1045            .unwrap();
1046
1047        // Filter by both names AND lengths -- should match only base.fa
1048        let result = store.list_collections(0, 100, &[
1049            ("names", &meta.names_digest),
1050            ("lengths", &meta.lengths_digest),
1051        ]).unwrap();
1052        assert_eq!(result.results.len(), 1);
1053        assert_eq!(result.results[0].digest, meta.digest);
1054    }
1055
1056    #[test]
1057    fn test_list_collections_filter_no_match() {
1058        let mut store = RefgetStore::in_memory();
1059        store
1060            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1061            .unwrap();
1062
1063        let result = store.list_collections(0, 100, &[("names", "nonexistent_digest")]).unwrap();
1064        assert!(result.results.is_empty());
1065        assert_eq!(result.pagination.total, 0);
1066    }
1067
1068    #[test]
1069    fn test_list_collections_invalid_attribute() {
1070        let mut store = RefgetStore::in_memory();
1071        store
1072            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1073            .unwrap();
1074
1075        let result = store.list_collections(0, 100, &[("unknown_attr", "digest")]);
1076        assert!(result.is_err());
1077    }
1078
1079    #[test]
1080    fn test_list_collections_filter_with_pagination() {
1081        let mut store = RefgetStore::in_memory();
1082        // base.fa and different_names.fa share the same lengths
1083        let (meta_a, _) = store
1084            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1085            .unwrap();
1086        let (_meta_b, _) = store
1087            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
1088            .unwrap();
1089
1090        // Both collections share lengths -- filter by lengths, page_size=1
1091        let page0 = store.list_collections(0, 1, &[("lengths", &meta_a.lengths_digest)]).unwrap();
1092        assert_eq!(page0.results.len(), 1);
1093        assert_eq!(page0.pagination.total, 2); // both match lengths filter
1094
1095        let page1 = store.list_collections(1, 1, &[("lengths", &meta_a.lengths_digest)]).unwrap();
1096        assert_eq!(page1.results.len(), 1);
1097        assert_eq!(page1.pagination.total, 2);
1098
1099        assert_ne!(page0.results[0].digest, page1.results[0].digest);
1100    }
1101
1102    // =========================================================================
1103    // SeqColService trait tests
1104    // =========================================================================
1105
1106    #[test]
1107    fn test_trait_object_safety() {
1108        use super::SeqColService;
1109        use std::sync::Arc;
1110
1111        let mut store = RefgetStore::in_memory();
1112        let (meta, _) = store
1113            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1114            .unwrap();
1115
1116        let readonly = store.into_readonly();
1117        let service: Arc<dyn SeqColService + Send + Sync> = Arc::new(readonly);
1118
1119        // Call each trait method through the trait object
1120        let lvl1 = service.get_collection_level1(&meta.digest).unwrap();
1121        assert_eq!(lvl1.names, meta.names_digest);
1122
1123        let lvl2 = service.get_collection_level2(&meta.digest).unwrap();
1124        assert_eq!(lvl2.names.len(), 3);
1125
1126        let cmp = service.compare(&meta.digest, &meta.digest).unwrap();
1127        assert_eq!(cmp.digests.a.as_deref(), Some(meta.digest.as_str()));
1128
1129        let cmp2 = service.compare_with_level2(&meta.digest, &lvl2).unwrap();
1130        assert_eq!(cmp2.digests.a.as_deref(), Some(meta.digest.as_str()));
1131
1132        let found = service
1133            .find_collections_by_attribute("names", &meta.names_digest)
1134            .unwrap();
1135        assert_eq!(found.len(), 1);
1136
1137        let attr = service
1138            .get_attribute("names", &meta.names_digest)
1139            .unwrap();
1140        assert!(attr.is_some());
1141
1142        let paged = service.list_collections(0, 10, &[]).unwrap();
1143        assert_eq!(paged.results.len(), 1);
1144
1145        assert_eq!(service.collection_count(), 1);
1146    }
1147
1148    #[test]
1149    fn test_collection_count() {
1150        let mut store = RefgetStore::in_memory();
1151        store
1152            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1153            .unwrap();
1154        store
1155            .add_sequence_collection_from_fasta("../tests/data/fasta/different_names.fa", FastaImportOptions::new())
1156            .unwrap();
1157
1158        assert_eq!(store.collection_count(), 2);
1159    }
1160
1161    #[test]
1162    fn test_trait_methods_match_concrete() {
1163        use super::SeqColService;
1164
1165        let mut store = RefgetStore::in_memory();
1166        let (meta, _) = store
1167            .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
1168            .unwrap();
1169
1170        let readonly = store.into_readonly();
1171
1172        // Call via concrete method
1173        let concrete_lvl1 = ReadonlyRefgetStore::get_collection_level1(&readonly, &meta.digest).unwrap();
1174        // Call via trait
1175        let trait_ref: &dyn SeqColService = &readonly;
1176        let trait_lvl1 = trait_ref.get_collection_level1(&meta.digest).unwrap();
1177
1178        assert_eq!(concrete_lvl1.names, trait_lvl1.names);
1179        assert_eq!(concrete_lvl1.lengths, trait_lvl1.lengths);
1180        assert_eq!(concrete_lvl1.sequences, trait_lvl1.sequences);
1181
1182        // list_collections
1183        let concrete_list = ReadonlyRefgetStore::list_collections(&readonly, 0, 10, &[]).unwrap();
1184        let trait_list = trait_ref.list_collections(0, 10, &[]).unwrap();
1185        assert_eq!(concrete_list.results.len(), trait_list.results.len());
1186        assert_eq!(concrete_list.pagination.total, trait_list.pagination.total);
1187
1188        // collection_count
1189        assert_eq!(
1190            ReadonlyRefgetStore::collection_count(&readonly),
1191            trait_ref.collection_count()
1192        );
1193    }
1194}