use super::*;
use crate::collection::SequenceCollectionExt;
use crate::digest::types::{
SequenceCollection, SequenceCollectionMetadata, SequenceMetadata, SequenceRecord,
};
use crate::digest::{AlphabetType, md5, sha512t24u};
use crate::hashkeyable::{DigestKey, HashKeyable};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;
use tempfile::tempdir;
use super::catalog::SeqRow;
use super::readonly::ReadonlyRefgetStore;
impl ReadonlyRefgetStore {
pub(crate) fn t_seq<K: AsRef<[u8]>>(&self, digest: K) -> Option<SequenceRecord> {
self.catalog.find_sha(digest).map(|r| self.seq_record(r))
}
pub(crate) fn t_seq_map(&self) -> HashMap<DigestKey, SequenceRecord> {
self.catalog
.seq_rows()
.map(|r| (self.catalog.seq(r).sha512t24u().to_key(), self.seq_record(r)))
.collect()
}
pub(crate) fn t_has_md5<K: AsRef<[u8]>>(&self, md5: K) -> bool {
self.catalog.find_md5(md5).is_some()
}
pub(crate) fn t_coll_keys(&self) -> Vec<DigestKey> {
self.catalog
.coll_rows()
.map(|c| self.catalog.coll_meta(c).digest.to_key())
.collect()
}
pub(crate) fn t_has_coll<K: AsRef<[u8]>>(&self, digest: K) -> bool {
self.catalog.find_coll(digest).is_some()
}
pub(crate) fn t_n_loaded_colls(&self) -> usize {
self.catalog.coll_rows().filter(|&c| self.catalog.is_loaded(c)).count()
}
pub(crate) fn t_names<K: AsRef<[u8]>>(&self, digest: K) -> Vec<String> {
let mut seen = HashSet::new();
self.collection_members(digest)
.map(|ms| {
ms.map(|m| m.name().to_string())
.filter(|n| seen.insert(n.clone()))
.collect()
})
.unwrap_or_default()
}
pub(crate) fn t_name_pairs<K: AsRef<[u8]>>(&self, digest: K) -> Vec<(String, DigestKey)> {
let d = digest.as_ref().to_vec();
self.t_names(&d)
.into_iter()
.map(|n| {
let k = self.member_by_name(&d, &n).unwrap().seq().sha512t24u().to_key();
(n, k)
})
.collect()
}
pub(crate) fn t_clear_sequences(&mut self) {
let rows: Vec<SeqRow> = self.catalog.seq_rows().collect();
self.remove_sequence_rows(&rows);
}
}
fn copy_test_fasta(temp_dir: &std::path::Path, name: &str) -> std::path::PathBuf {
let src = format!("../tests/data/fasta/{}", name);
let dst = temp_dir.join(name);
std::fs::copy(&src, &dst)
.unwrap_or_else(|e| panic!("Failed to copy {} to tempdir: {}", src, e));
dst
}
fn calculate_test_digests(sequence: &[u8]) -> (String, String) {
(sha512t24u(sequence), md5(sequence))
}
fn store_with_one_collection(fasta_content: &str) -> (RefgetStore, String) {
let dir = tempdir().unwrap();
let fasta = dir.path().join("test.fa");
fs::write(&fasta, fasta_content).unwrap();
let mut store = RefgetStore::in_memory();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
(store, meta.digest)
}
fn coll_sel<K: AsRef<[u8]>>(digest: K, names: Option<&[&str]>) -> ExportSelection {
ExportSelection::Collections {
digests: vec![String::from_utf8_lossy(digest.as_ref()).into_owned()],
names: names.map(|n| n.iter().map(|s| s.to_string()).collect()),
}
}
fn name_opts(line_width: usize) -> ExportOptions {
ExportOptions { label: LabelTemplate::parse("{name}").unwrap(), molecule: None, line_width }
}
fn setup_export_test_store(temp_path: &std::path::Path) -> (RefgetStore, DigestKey) {
let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n>chr3\nTTTTCCCC\n";
let temp_fasta_path = temp_path.join("test.fa");
fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.unwrap();
let collections: Vec<_> = store.t_coll_keys().into_iter().collect();
let collection_digest = collections[0];
(store, collection_digest)
}
#[test]
fn test_mode_switching() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n";
let temp_fasta_path = temp_path.join("test.fa");
fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");
let (chr1_sha, _) = calculate_test_digests(b"ATGCATGCATGC");
let chr1_key = chr1_sha.as_bytes().to_key();
{
let mut store = RefgetStore::in_memory();
store.disable_encoding();
store
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.unwrap();
if let Some(SequenceRecord::Full { sequence, .. }) = store.t_seq(&chr1_key) {
assert_eq!(&sequence[..], b"ATGCATGCATGC");
}
let seq_before = store.get_sequence(&chr1_sha).unwrap().decode().unwrap();
store.set_encoding_mode(StorageMode::Encoded).unwrap();
if let Some(SequenceRecord::Full { sequence, .. }) = store.t_seq(&chr1_key) {
assert_eq!(sequence.len(), 3);
}
let seq_after = store.get_sequence(&chr1_sha).unwrap().decode().unwrap();
assert_eq!(seq_before, seq_after);
}
{
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.unwrap();
if let Some(SequenceRecord::Full { sequence, .. }) = store.t_seq(&chr1_key) {
assert_eq!(sequence.len(), 3);
}
let seq_before = store.get_sequence(&chr1_sha).unwrap().decode().unwrap();
store.disable_encoding();
if let Some(SequenceRecord::Full { sequence, .. }) = store.t_seq(&chr1_key) {
assert_eq!(&sequence[..], b"ATGCATGCATGC");
}
let seq_after = store.get_sequence(&chr1_sha).unwrap().decode().unwrap();
assert_eq!(seq_before, seq_after);
}
}
#[test]
fn test_refget_store_retrieve_seq_and_vec() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let fasta_content = "\
>chr1
ATGCATGCATGC
>chr2
GGGGAAAA
";
let temp_fasta_path = temp_path.join("test.fa");
fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.unwrap();
let collection_digest_ref: &str = "uC_UorBNf3YUu1YIDainBhI94CedlNeH";
let bed_content = "\
chr1\t0\t5
chr1\t8\t12
chr2\t0\t4
";
let temp_bed_path = temp_path.join("test.bed");
fs::write(&temp_bed_path, bed_content).expect("Failed to write test BED file");
let temp_output_fa_path = temp_path.join("output.fa");
store
.export_fasta_from_regions(
collection_digest_ref,
temp_bed_path.to_str().unwrap(),
temp_output_fa_path.to_str().unwrap(),
&LabelTemplate::parse("{name}").unwrap(),
)
.expect("export_fasta_from_regions failed");
let output_fa_content =
fs::read_to_string(&temp_output_fa_path).expect("Failed to read output FASTA file");
let expected_fa_content = ">chr1:0-5\nATGCA\n>chr1:8-12\nATGC\n>chr2:0-4\nGGGG\n";
assert_eq!(
output_fa_content.trim(),
expected_fa_content.trim(),
"Output FASTA file content mismatch"
);
let vec_result: Vec<_> = store
.substrings_from_regions(collection_digest_ref, temp_bed_path.to_str().unwrap())
.expect("substrings_from_regions failed")
.collect::<Result<Vec<_>, _>>()
.expect("substrings_from_regions had errors");
let expected_vec = vec![
RetrievedSequence {
sequence: "ATGCA".to_string(),
chrom_name: "chr1".to_string(),
start: 0,
end: 5,
},
RetrievedSequence {
sequence: "ATGC".to_string(),
chrom_name: "chr1".to_string(),
start: 8,
end: 12,
},
RetrievedSequence {
sequence: "GGGG".to_string(),
chrom_name: "chr2".to_string(),
start: 0,
end: 4,
},
];
assert_eq!(vec_result, expected_vec, "Retrieved sequence vector mismatch");
}
#[test]
fn test_substrings_from_region_vectors() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n";
let temp_fasta_path = temp_path.join("test.fa");
fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.unwrap();
let collection_digest_ref: &str = "uC_UorBNf3YUu1YIDainBhI94CedlNeH";
let chroms = ["chr1", "chr1", "chr2"];
let starts = [0u32, 8, 0];
let ends = [5u32, 12, 4];
let vec_result: Vec<_> = store
.substrings_from_region_vectors(collection_digest_ref, &chroms, &starts, &ends)
.expect("substrings_from_region_vectors failed")
.collect::<Result<Vec<_>, _>>()
.expect("substrings_from_region_vectors had errors");
let expected_vec = vec![
RetrievedSequence {
sequence: "ATGCA".to_string(),
chrom_name: "chr1".to_string(),
start: 0,
end: 5,
},
RetrievedSequence {
sequence: "ATGC".to_string(),
chrom_name: "chr1".to_string(),
start: 8,
end: 12,
},
RetrievedSequence {
sequence: "GGGG".to_string(),
chrom_name: "chr2".to_string(),
start: 0,
end: 4,
},
];
assert_eq!(
vec_result, expected_vec,
"Vectors-based retrieval mismatch vs expected"
);
let missing_chroms = ["chrX"];
let missing_starts = [0u32];
let missing_ends = [4u32];
let missing_result: Result<Vec<_>, _> = store
.substrings_from_region_vectors(
collection_digest_ref,
&missing_chroms,
&missing_starts,
&missing_ends,
)
.expect("constructor should succeed for equal-length vectors")
.collect();
let missing_err = missing_result.unwrap_err().to_string();
assert!(
missing_err.contains("Region 1") && missing_err.contains("not found"),
"unexpected missing-sequence error: {missing_err}"
);
}
#[test]
fn test_substrings_from_region_vectors_mismatched_lengths() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n";
let temp_fasta_path = temp_path.join("test.fa");
fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.unwrap();
let collection_digest_ref: &str = "uC_UorBNf3YUu1YIDainBhI94CedlNeH";
let chroms = ["chr1", "chr2"];
let starts = [0u32]; let ends = [5u32, 4];
let result =
store.substrings_from_region_vectors(collection_digest_ref, &chroms, &starts, &ends);
let err_msg = match result {
Ok(_) => panic!("mismatched lengths should error"),
Err(e) => e.to_string(),
};
assert!(
err_msg.contains("Mismatched region vector lengths"),
"unexpected error: {err_msg}"
);
}
#[test]
fn test_negative_bed_coordinates() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n";
let temp_fasta_path = temp_path.join("test.fa");
fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.unwrap();
let collections: Vec<_> = store.t_coll_keys().into_iter().collect();
let collection_digest_ref: &str =
std::str::from_utf8(&collections[0]).expect("invalid collection digest");
let bed_content = "chr1\t-5\t100\n";
let temp_bed_path = temp_path.join("negative.bed");
fs::write(&temp_bed_path, bed_content).expect("Failed to write test BED file");
let result = store.substrings_from_regions(collection_digest_ref, temp_bed_path.to_str().unwrap());
let collected: Result<Vec<_>, _> = result.unwrap().collect();
let error_msg = collected.unwrap_err().to_string();
assert!(error_msg.contains("invalid start or end coordinates"));
let bed_content_neg_end = "chr1\t0\t-10\n";
let temp_bed_path_neg_end = temp_path.join("negative_end.bed");
fs::write(&temp_bed_path_neg_end, bed_content_neg_end).expect("Failed to write test BED file");
let result = store.substrings_from_regions(collection_digest_ref, temp_bed_path_neg_end.to_str().unwrap());
let collected: Result<Vec<_>, _> = result.unwrap().collect();
let error_msg = collected.unwrap_err().to_string();
assert!(error_msg.contains("invalid start or end coordinates"));
}
#[test]
fn test_global_refget_store() {
let sequence = b"ACGT";
let name = "test_seq";
let mut collection = SequenceCollection {
metadata: SequenceCollectionMetadata {
digest: "test_collection".to_string(),
n_sequences: 0,
names_digest: "test".to_string(),
sequences_digest: "test".to_string(),
lengths_digest: "test".to_string(),
name_length_pairs_digest: None,
sorted_name_length_pairs_digest: None,
sorted_sequences_digest: None,
file_path: None,
},
sequences: Vec::new(),
};
let seq_metadata = SequenceMetadata {
name: name.to_string(),
description: None,
length: sequence.len(),
sha512t24u: sha512t24u(sequence),
md5: md5(sequence),
alphabet: AlphabetType::Dna2bit,
fai: None,
};
let record = SequenceRecord::Full {
metadata: seq_metadata.clone(),
sequence: std::sync::Arc::new(sequence.to_vec()),
};
collection.sequences.push(record);
let mut store = RefgetStore::in_memory();
store.add_sequence_collection(collection.clone()).unwrap();
assert!(store.catalog.n_sequences() > 0);
let retrieved_by_name_str = store.get_sequence_by_name(&collection.metadata.digest, name);
assert!(retrieved_by_name_str.is_ok());
let retrieved_record = retrieved_by_name_str.unwrap();
assert_eq!(retrieved_record.metadata().name, name);
let decoded = store
.get_substring(&seq_metadata.sha512t24u, 0, sequence.len())
.unwrap();
assert_eq!(decoded.as_bytes(), sequence);
let retrieved_by_name_key =
store.get_sequence_by_name(collection.metadata.digest.to_key(), name);
assert!(retrieved_by_name_key.is_ok());
let retrieved_by_sha512_str = store.get_sequence(&seq_metadata.sha512t24u);
assert!(retrieved_by_sha512_str.is_ok());
let retrieved_by_sha512_key = store.get_sequence(seq_metadata.sha512t24u.to_key());
assert!(retrieved_by_sha512_key.is_ok());
}
#[test]
fn test_get_substring_by_md5() {
let sequence = b"ACGTACGTAC";
let name = "test_seq";
let mut collection = SequenceCollection {
metadata: SequenceCollectionMetadata {
digest: "test_collection".to_string(),
n_sequences: 0,
names_digest: "test".to_string(),
sequences_digest: "test".to_string(),
lengths_digest: "test".to_string(),
name_length_pairs_digest: None,
sorted_name_length_pairs_digest: None,
sorted_sequences_digest: None,
file_path: None,
},
sequences: Vec::new(),
};
let seq_metadata = SequenceMetadata {
name: name.to_string(),
description: None,
length: sequence.len(),
sha512t24u: sha512t24u(sequence),
md5: md5(sequence),
alphabet: AlphabetType::Dna2bit,
fai: None,
};
collection.sequences.push(SequenceRecord::Full {
metadata: seq_metadata.clone(),
sequence: std::sync::Arc::new(sequence.to_vec()),
});
let mut store = RefgetStore::in_memory();
store.add_sequence_collection(collection).unwrap();
let by_sha = store
.get_substring(&seq_metadata.sha512t24u, 2, 6)
.expect("get_substring by sha512t24u should succeed");
assert_eq!(by_sha.len(), 4);
let by_md5 = store
.get_substring(&seq_metadata.md5, 2, 6)
.expect("get_substring by md5 should succeed");
assert_eq!(by_md5, by_sha);
}
#[test]
fn test_get_substring_zero_length_range() {
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path();
let temp_fasta = copy_test_fasta(temp_path, "base.fa.gz");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let (digest, length) = store
.sequence_metadata()
.find(|m| m.length > 1)
.map(|m| (m.sha512t24u.clone(), m.length))
.expect("expected at least one non-empty sequence");
assert_eq!(
store.get_substring(&digest, 0, 0).unwrap(),
"",
"resident: start == end == 0 should return empty string"
);
assert_eq!(
store.get_substring(&digest, 3, 3).unwrap(),
"",
"resident: interior zero-length range should return empty string"
);
assert_eq!(
store.get_substring(&digest, length, length).unwrap(),
"",
"resident: zero-length range at end should return empty string"
);
assert!(
store.get_substring(&digest, 5, 2).is_err(),
"resident: inverted range (start > end) must error"
);
let batch = store
.get_substrings(&digest, &[(0, 0), (1, 4), (3, 3)])
.unwrap();
assert_eq!(batch.len(), 3);
assert_eq!(batch[0], "");
assert_eq!(batch[1].len(), 3);
assert_eq!(batch[2], "");
assert!(
store.get_substrings(&digest, &[(5, 2)]).is_err(),
"batch: inverted range must error"
);
store
.write_store_to_dir(temp_path, Some("sequences/%s2/%s.seq"))
.unwrap();
let disk_store = RefgetStore::open_local(temp_path).unwrap();
assert!(
!disk_store.is_sequence_loaded(&digest),
"disk-backed sequence should be a stub, not resident"
);
assert_eq!(
disk_store.get_substring(&digest, 0, 0).unwrap(),
"",
"disk: start == end == 0 should return empty string"
);
assert_eq!(
disk_store.get_substring(&digest, 4, 4).unwrap(),
"",
"disk: interior zero-length range should return empty string"
);
assert!(
disk_store.get_substring(&digest, 5, 2).is_err(),
"disk: inverted range (start > end) must error"
);
let disk_batch = disk_store
.get_substrings(&digest, &[(2, 2), (0, 3)])
.unwrap();
assert_eq!(disk_batch[0], "");
assert_eq!(disk_batch[1].len(), 3);
}
#[test]
fn test_resident_overlay_byte_identical_and_evicts() {
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path();
let temp_fasta = copy_test_fasta(temp_path, "base.fa.gz");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
store
.write_store_to_dir(temp_path, Some("sequences/%s2/%s.seq"))
.unwrap();
let disk_store = RefgetStore::open_local(temp_path).unwrap();
let (digest, length) = disk_store
.sequence_metadata()
.find(|m| m.length > 5)
.map(|m| (m.sha512t24u.clone(), m.length))
.expect("expected a non-trivial sequence");
let ranges: Vec<(usize, usize)> = vec![
(0, length.min(4)),
(1, length.min(5)),
(length / 2, (length / 2 + 2).min(length)),
(2, 2),
(length - 1, length),
];
assert!(!disk_store.is_sequence_loaded(&digest));
assert_eq!(disk_store.resident_bytes(), 0);
let disk_single: Vec<String> = ranges
.iter()
.map(|&(s, e)| disk_store.get_substring(&digest, s, e).unwrap())
.collect();
let disk_batch = disk_store.get_substrings(&digest, &ranges).unwrap();
let loaded = disk_store.load_resident(&[digest.clone()]).unwrap();
assert!(loaded > 0, "load_resident should report bytes loaded");
assert_eq!(disk_store.resident_len(), 1);
assert_eq!(disk_store.resident_bytes(), loaded);
assert!(!disk_store.is_sequence_loaded(&digest));
let res_single: Vec<String> = ranges
.iter()
.map(|&(s, e)| disk_store.get_substring(&digest, s, e).unwrap())
.collect();
let res_batch = disk_store.get_substrings(&digest, &ranges).unwrap();
assert_eq!(res_single, disk_single, "overlay get_substring must match disk");
assert_eq!(res_batch, disk_batch, "overlay get_substrings must match disk");
let reloaded = disk_store.load_resident(&[digest.clone()]).unwrap();
assert_eq!(reloaded, 0, "already-resident digest loads 0 new bytes");
disk_store.evict_resident(&[digest.clone()]);
assert_eq!(disk_store.resident_bytes(), 0);
assert_eq!(disk_store.resident_len(), 0);
let after_evict: Vec<String> = ranges
.iter()
.map(|&(s, e)| disk_store.get_substring(&digest, s, e).unwrap())
.collect();
assert_eq!(after_evict, disk_single, "post-evict disk path must match");
disk_store.load_resident(&[digest.clone()]).unwrap();
assert_eq!(disk_store.resident_len(), 1);
disk_store.evict_all_resident();
assert_eq!(disk_store.resident_len(), 0);
}
#[test]
fn test_resident_overlay_concurrent_readers() {
use std::sync::Arc;
use std::thread;
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path();
let temp_fasta = copy_test_fasta(temp_path, "base.fa.gz");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
store
.write_store_to_dir(temp_path, Some("sequences/%s2/%s.seq"))
.unwrap();
let disk_store = RefgetStore::open_local(temp_path).unwrap();
let (digest, length) = disk_store
.sequence_metadata()
.find(|m| m.length > 5)
.map(|m| (m.sha512t24u.clone(), m.length))
.expect("expected a non-trivial sequence");
let expected = disk_store.get_substring(&digest, 0, length.min(6)).unwrap();
let shared = Arc::new(disk_store.into_readonly());
let end = length.min(6);
let mut handles = Vec::new();
for _ in 0..4 {
let s = Arc::clone(&shared);
let d = digest.clone();
let exp = expected.clone();
handles.push(thread::spawn(move || {
for _ in 0..500 {
let got = s.get_substring(&d, 0, end).unwrap();
assert_eq!(got, exp, "reader saw wrong bytes during concurrent load/evict");
}
}));
}
for _ in 0..50 {
shared.load_resident(&[digest.clone()]).unwrap();
shared.evict_resident(&[digest.clone()]);
}
for h in handles {
h.join().unwrap();
}
}
#[test]
fn test_import_fasta() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let test_fa = "../tests/data/fasta/base.fa";
let temp_fa = temp_path.join("base.fa");
std::fs::copy(test_fa, &temp_fa).expect("Failed to copy test FASTA file");
let mut store = RefgetStore::in_memory();
store.add_sequence_collection_from_fasta(temp_fa, FastaImportOptions::new()).unwrap();
assert!(store.catalog.n_sequences() > 0);
let seq_template = "sequences/%s2/%s.seq";
store
.write_store_to_dir(temp_path.to_str().unwrap(), Some(seq_template))
.unwrap();
}
#[test]
fn test_disk_persistence() {
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path();
let temp_fasta = copy_test_fasta(temp_path, "base.fa.gz");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let sequence_keys: Vec<DigestKey> = store.sequence_digests().collect();
assert_eq!(sequence_keys.len(), 3);
let sha512_key1 = sequence_keys[0];
let sha512_key2 = sequence_keys[1];
let original_seq1 = store.t_seq(&sha512_key1).unwrap().clone();
let original_seq2 = store.t_seq(&sha512_key2).unwrap().clone();
let seq_template = "sequences/%s2/%s.seq";
store.write_store_to_dir(temp_path, Some(seq_template)).unwrap();
assert!(temp_path.join("sequences").exists());
assert!(temp_path.join("sequences").read_dir().unwrap().count() > 0);
assert!(temp_path.join("rgstore.json").exists());
assert!(temp_path.join("sequences.rgsi").exists());
assert!(temp_path.join("collections.rgci").exists());
assert!(temp_path.join("collections").exists());
let mut loaded_store = RefgetStore::open_local(temp_path).unwrap();
assert_eq!(loaded_store.catalog.n_sequences(), 3);
assert!(loaded_store.t_seq(&sha512_key1).is_some());
assert!(loaded_store.t_seq(&sha512_key2).is_some());
let loaded_seq1 = loaded_store.t_seq(&sha512_key1).unwrap();
let loaded_seq2 = loaded_store.t_seq(&sha512_key2).unwrap();
assert_eq!(original_seq1.metadata().name, loaded_seq1.metadata().name);
assert_eq!(original_seq1.metadata().length, loaded_seq1.metadata().length);
assert_eq!(original_seq1.metadata().sha512t24u, loaded_seq1.metadata().sha512t24u);
assert_eq!(original_seq1.metadata().md5, loaded_seq1.metadata().md5);
assert_eq!(original_seq2.metadata().name, loaded_seq2.metadata().name);
assert_eq!(original_seq2.metadata().length, loaded_seq2.metadata().length);
assert_eq!(original_seq2.metadata().sha512t24u, loaded_seq2.metadata().sha512t24u);
assert_eq!(original_seq2.metadata().md5, loaded_seq2.metadata().md5);
assert!(!loaded_seq1.is_loaded());
assert!(!loaded_seq2.is_loaded());
assert_eq!(loaded_store.catalog.n_sequences(), 3);
assert_eq!(loaded_store.catalog.n_collections(), store.catalog.n_collections());
loaded_store.load_all_collections().unwrap();
loaded_store.load_all_sequences().unwrap();
for (digest, original_record) in &store.t_seq_map() {
let loaded_record = loaded_store.get_sequence(*digest).unwrap();
assert_eq!(original_record.metadata().name, loaded_record.metadata().name);
assert_eq!(original_record.metadata().length, loaded_record.metadata().length);
if original_record.metadata().length > 0 {
let substring_len = std::cmp::min(5, original_record.metadata().length);
let substring = loaded_store.get_substring(digest, 0, substring_len);
assert!(substring.is_ok());
}
}
}
#[test]
fn test_export_fasta_all_sequences() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let (mut store, collection_digest) = setup_export_test_store(temp_dir.path());
let output_path = temp_dir.path().join("exported_all.fa");
store
.export_fasta(&coll_sel(collection_digest, None), &output_path, &name_opts(80))
.unwrap();
let exported = fs::read_to_string(&output_path).unwrap();
assert!(exported.contains(">chr1") && exported.contains(">chr2") && exported.contains(">chr3"));
assert!(exported.contains("ATGCATGCATGC") && exported.contains("GGGGAAAA") && exported.contains("TTTTCCCC"));
}
#[test]
fn test_export_fasta_subset_sequences() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let (mut store, collection_digest) = setup_export_test_store(temp_dir.path());
let output_path = temp_dir.path().join("exported_subset.fa");
store
.export_fasta(&coll_sel(collection_digest, Some(&["chr1", "chr3"])), &output_path, &name_opts(80))
.unwrap();
let exported = fs::read_to_string(&output_path).unwrap();
assert!(exported.contains(">chr1") && exported.contains(">chr3"));
assert!(!exported.contains(">chr2") && !exported.contains("GGGGAAAA"));
}
#[test]
fn test_export_fasta_roundtrip() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let fasta_content = "\
>seq1
ATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGC
ATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGC
>seq2
GGGGAAAACCCCTTTTGGGGAAAACCCCTTTTGGGGAAAACCCCTTTTGGGGAAAACCCC
";
let temp_fasta_path = temp_path.join("original.fa");
fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");
let mut store1 = RefgetStore::in_memory();
store1
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.unwrap();
let original_digests: Vec<String> = store1
.t_seq_map()
.into_values()
.map(|r| r.metadata().sha512t24u.clone())
.collect();
let collections: Vec<_> = store1.t_coll_keys().into_iter().collect();
let collection_digest = collections[0];
let exported_path = temp_path.join("exported.fa");
store1.export_fasta(&coll_sel(collection_digest, None), &exported_path, &name_opts(60)).expect("Failed to export FASTA");
let mut store2 = RefgetStore::in_memory();
store2
.add_sequence_collection_from_fasta(&exported_path, FastaImportOptions::new())
.unwrap();
let new_digests: Vec<String> = store2
.t_seq_map()
.into_values()
.map(|r| r.metadata().sha512t24u.clone())
.collect();
assert_eq!(original_digests.len(), new_digests.len());
for digest in original_digests {
assert!(new_digests.contains(&digest), "Digest {} should be present after roundtrip", digest);
}
}
#[test]
fn test_export_fasta_by_digests() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let (mut store, _) = setup_export_test_store(temp_dir.path());
let digests: Vec<String> = store
.t_seq_map()
.into_values()
.map(|r| r.metadata().sha512t24u.clone())
.collect();
let output_path = temp_dir.path().join("exported_by_digests.fa");
let opts = ExportOptions { line_width: 80, ..Default::default() };
store.export_fasta(&ExportSelection::SeqDigests(digests.clone()), &output_path, &opts).unwrap();
let exported = fs::read_to_string(&output_path).unwrap();
for d in &digests {
assert!(exported.contains(&format!(">SQ.{}\n", d)), "missing {d}");
}
let prefixed: Vec<String> = digests.iter().map(|d| format!("SQ.{}", d)).collect();
let summary = store
.export_fasta(&ExportSelection::SeqDigests(prefixed), &output_path, &name_opts(80))
.unwrap();
assert_eq!(summary.n_fallbacks, digests.len());
assert_eq!(fs::read_to_string(&output_path).unwrap().matches(">SQ.").count(), digests.len());
}
#[test]
fn test_export_fasta_error_handling() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let (mut store, collection_digest) = setup_export_test_store(temp_dir.path());
let output_path = temp_dir.path().join("should_fail.fa");
let fake_collection = b"fake_collection_digest_12345678";
assert!(store.export_fasta(&coll_sel(fake_collection, None), &output_path, &name_opts(80)).is_err());
assert!(store.export_fasta(&coll_sel(collection_digest, Some(&["nonexistent_chr"])), &output_path, &name_opts(80)).is_err());
}
#[test]
fn test_export_fasta_after_load_local() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let store_path = temp_path.join("store");
let fasta_content = ">chr1\nACGTACGT\n>chr2\nGGGGAAAA\n";
let fasta_path = temp_path.join("test.fa");
fs::write(&fasta_path, fasta_content).unwrap();
let collection_digest: DigestKey;
{
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
.unwrap();
let collections: Vec<_> = store.t_coll_keys().into_iter().collect();
assert_eq!(collections.len(), 1);
collection_digest = collections[0];
}
let mut loaded_store = RefgetStore::open_local(&store_path).unwrap();
assert!(!loaded_store.is_collection_loaded(&collection_digest));
loaded_store.load_all_collections().unwrap();
loaded_store.load_all_sequences().unwrap();
let output_path = temp_path.join("exported.fa");
loaded_store
.export_fasta(&coll_sel(collection_digest, None), &output_path, &name_opts(80))
.expect("export_fasta should work on disk-loaded stores");
let exported = fs::read_to_string(&output_path).unwrap();
assert!(exported.contains(">chr1"));
assert!(exported.contains("ACGTACGT"));
assert!(exported.contains(">chr2"));
assert!(exported.contains("GGGGAAAA"));
}
#[test]
fn test_sequence_names_with_spaces() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let fasta_content = "\
>JAHKSE010000016.1 unmasked:primary_assembly HG002.alt.pat.f1_v2:JAHKSE010000016.1:1:100:1
ATGCATGCATGCATGCATGCATGCATGCATGCATGC
ATGCATGCATGCATGCATGCATGCATGCATGCATGC
>JAHKSE010000012.1 unmasked:primary_assembly HG002.alt.pat.f1_v2:JAHKSE010000012.1:1:100:1
GGGGAAAACCCCTTTTGGGGAAAACCCCTTTTGGGG
GGGGAAAACCCCTTTTGGGGAAAACCCCTTTTGGGG
";
let temp_fasta_path = temp_path.join("spaces_in_names.fa");
fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
.expect("Should parse FASTA headers correctly");
assert_eq!(store.catalog.n_sequences(), 2);
let name1 = "JAHKSE010000016.1";
let name2 = "JAHKSE010000012.1";
let collections: Vec<_> = store.t_coll_keys().into_iter().collect();
assert_eq!(collections.len(), 1);
let collection_digest = collections[0];
{
let seq1 = store.get_sequence_by_name(&collection_digest, name1);
assert!(seq1.is_ok());
let seq1_record = seq1.unwrap();
let seq1_meta = seq1_record.metadata();
assert_eq!(seq1_meta.name, "JAHKSE010000016.1");
assert_eq!(
seq1_meta.description,
Some("unmasked:primary_assembly HG002.alt.pat.f1_v2:JAHKSE010000016.1:1:100:1".to_string())
);
}
{
let seq2 = store.get_sequence_by_name(&collection_digest, name2);
assert!(seq2.is_ok());
}
}
#[test]
fn test_rgsi_filename_with_dots() {
let temp_dir = tempdir().expect("Failed to create temporary directory");
let temp_path = temp_dir.path();
let temp_fasta = copy_test_fasta(temp_path, "HG002.alt.pat.f1_v2.unmasked.fa");
let _seqcol = SequenceCollection::from_path_with_cache(&temp_fasta, false, true)
.expect("Should load FASTA");
let correct_rgsi = temp_path.join("HG002.alt.pat.f1_v2.unmasked.rgsi");
let wrong_rgsi = temp_path.join("HG002.rgsi");
let files: Vec<_> = std::fs::read_dir(temp_path)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().to_string())
.collect();
assert!(correct_rgsi.exists(), "Expected 'HG002.alt.pat.f1_v2.unmasked.rgsi' but found: {:?}", files);
assert!(!wrong_rgsi.exists());
}
#[test]
fn test_on_disk_collection_written_incrementally() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("cache");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let collections_dir = cache_path.join("collections");
assert!(collections_dir.exists());
let rgsi_files: Vec<_> = std::fs::read_dir(&collections_dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().to_string())
.collect();
assert!(!rgsi_files.is_empty());
assert!(rgsi_files.iter().any(|f| f.ends_with(".rgsi")));
}
#[test]
fn test_disk_size_calculation() {
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta("../tests/data/fasta/base.fa.gz", FastaImportOptions::new())
.unwrap();
let disk_size = store.logical_sequence_bytes();
assert!(disk_size > 0);
let manual: usize = store
.list_sequences()
.unwrap()
.iter()
.map(|m| (m.length * m.alphabet.bits_per_symbol()).div_ceil(8))
.sum();
assert_eq!(disk_size, manual);
}
#[test]
fn test_incremental_index_writing() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("store");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
assert!(cache_path.join("rgstore.json").exists());
assert!(cache_path.join("sequences.rgsi").exists());
assert!(cache_path.join("collections.rgci").exists());
let _loaded = RefgetStore::on_disk(&cache_path).unwrap();
}
#[test]
fn test_write_method() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("store");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
store.write().unwrap();
assert!(cache_path.join("rgstore.json").exists());
}
#[test]
fn test_on_disk_smart_constructor() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("store");
let mut store1 = RefgetStore::on_disk(&cache_path).unwrap();
assert_eq!(store1.mode, StorageMode::Encoded);
store1
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let store2 = RefgetStore::on_disk(&cache_path).unwrap();
assert_eq!(store2.catalog.n_sequences(), store1.catalog.n_sequences());
assert_eq!(store2.mode, StorageMode::Encoded);
let cache_path_raw = temp_dir.path().join("store_raw");
let mut store3 = RefgetStore::on_disk(&cache_path_raw).unwrap();
store3.disable_encoding();
assert_eq!(store3.mode, StorageMode::Raw);
store3
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let store4 = RefgetStore::on_disk(&cache_path_raw).unwrap();
assert_eq!(store4.mode, StorageMode::Raw);
let index_path = cache_path_raw.join("rgstore.json");
let json = fs::read_to_string(&index_path).unwrap();
assert!(json.contains("\"mode\":\"Raw\"") || json.contains("\"mode\": \"Raw\""));
}
#[test]
fn test_collection_metadata_methods() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("store");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let collections = store.list_collections(0, usize::MAX, &[]).unwrap();
assert_eq!(collections.results.len(), 1);
let digest = collections.results[0].digest.clone();
let meta = store.get_collection_metadata(&digest);
assert!(meta.is_some());
assert_eq!(meta.unwrap().n_sequences, 3);
assert!(store.is_collection_loaded(&digest));
let stats = store.stats();
assert_eq!(stats.n_collections, 1);
assert_eq!(stats.n_collections_in_memory, 1);
assert_eq!(stats.n_sequences, 3);
}
#[test]
fn test_collection_explicit_loading() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("store");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let digest = store.list_collections(0, usize::MAX, &[]).unwrap().results[0].digest.clone();
drop(store);
let mut loaded_store = RefgetStore::open_local(&cache_path).unwrap();
let meta = loaded_store.get_collection_metadata(&digest);
assert!(meta.is_some());
assert_eq!(meta.unwrap().n_sequences, 3);
assert!(!loaded_store.is_collection_loaded(&digest));
let stats_before = loaded_store.stats();
assert_eq!(stats_before.n_collections, 1);
assert_eq!(stats_before.n_collections_in_memory, 0);
let seq = loaded_store.get_sequence_by_name(&digest, "chr1");
assert!(seq.is_ok());
assert_eq!(seq.unwrap().metadata().name, "chr1");
assert!(loaded_store.is_collection_loaded(&digest));
let stats_after = loaded_store.stats();
assert_eq!(stats_after.n_collections_in_memory, 1);
}
#[test]
fn test_get_collection() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("store");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let digest = store.list_collections(0, usize::MAX, &[]).unwrap().results[0].digest.clone();
drop(store);
let mut loaded_store = RefgetStore::open_local(&cache_path).unwrap();
assert!(!loaded_store.is_collection_loaded(&digest));
let collection = loaded_store.get_collection(&digest).unwrap();
assert!(!collection.sequences.is_empty());
let readonly_store = RefgetStore::open_local(&cache_path).unwrap().into_readonly();
assert!(readonly_store.get_collection(&digest).is_err());
loaded_store.load_all_collections().unwrap();
let collection = loaded_store.get_collection(&digest).unwrap();
assert!(!collection.sequences.is_empty());
assert_eq!(collection.sequences.len(), 3);
let stats_after = loaded_store.stats();
assert_eq!(stats_after.n_sequences_in_memory, 0);
assert_eq!(stats_after.n_collections_in_memory, 1);
for record in loaded_store.t_seq_map().into_values() {
assert!(!record.is_loaded());
}
let seq_digest = collection.sequences[0].metadata().sha512t24u.clone();
loaded_store.load_sequence(&seq_digest).unwrap();
let loaded_seq = loaded_store.get_sequence(&seq_digest).unwrap();
assert!(loaded_seq.is_loaded());
}
#[test]
fn test_get_sequence() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("store");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let seq_digest = store
.t_seq_map()
.into_values()
.next()
.unwrap()
.metadata()
.sha512t24u
.clone();
drop(store);
let mut loaded_store = RefgetStore::open_local(&cache_path).unwrap();
let seq_before = loaded_store.t_seq(&seq_digest.to_key()).unwrap();
assert!(!seq_before.is_loaded());
let loaded_seq = loaded_store.get_sequence(&seq_digest).unwrap();
assert!(loaded_seq.is_loaded());
assert!(loaded_seq.sequence().is_some());
}
#[test]
fn test_get_collection_idempotent() {
let temp_dir = tempdir().unwrap();
let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
let cache_path = temp_dir.path().join("store");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
store
.add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
.unwrap();
let digest = store.list_collections(0, usize::MAX, &[]).unwrap().results[0].digest.clone();
drop(store);
let mut loaded_store = RefgetStore::open_local(&cache_path).unwrap();
loaded_store.load_all_collections().unwrap();
let result1 = loaded_store.get_collection(&digest);
assert!(result1.is_ok());
let result2 = loaded_store.get_collection(&digest);
assert!(result2.is_ok());
assert_eq!(loaded_store.stats().n_collections_in_memory, 1);
}
#[test]
fn test_stale_rgsi_cache_is_ignored() {
use std::io::Write;
let temp_dir = tempdir().unwrap();
let fasta_path = temp_dir.path().join("test.fa");
let mut fasta_file = fs::File::create(&fasta_path).unwrap();
writeln!(fasta_file, ">chr1\nATGCATGC\n>chr2\nGGGGAAAA").unwrap();
let rgsi_path = temp_dir.path().join("test.rgsi");
let mut rgsi_file = fs::File::create(&rgsi_path).unwrap();
writeln!(rgsi_file, "#name\tlength\talphabet\tsha512t24u\tmd5\tdescription").unwrap();
let store_path = temp_dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let result = store.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new());
assert!(result.is_ok(), "Should handle stale cache: {:?}", result.err());
assert_eq!(store.catalog.n_sequences(), 2);
}
#[test]
fn test_add_sequence_record_standalone() {
use crate::digest::digest_sequence;
let mut store = RefgetStore::in_memory();
let record = digest_sequence("test", b"ACGT");
let digest = record.metadata().sha512t24u.clone();
store.add_sequence_record(record, false).unwrap();
let retrieved = store.get_sequence(digest.as_bytes()).unwrap();
assert_eq!(retrieved.metadata().length, 4);
}
#[test]
fn test_add_sequence_record_packed_bytes_in_encoded_mode() {
use crate::digest::{digest_sequence, encode_sequence, lookup_alphabet};
let mut store = RefgetStore::in_memory();
store.set_encoding_mode(StorageMode::Encoded).unwrap();
let record = digest_sequence("test", b"ACGTACGT");
let digest = record.metadata().sha512t24u.clone();
let packed_record = match record {
SequenceRecord::Full { metadata, sequence } => {
let alphabet = lookup_alphabet(&metadata.alphabet);
let encoded = encode_sequence(&*sequence, alphabet).unwrap();
SequenceRecord::Full { metadata, sequence: encoded.into() }
}
other => other,
};
store.add_sequence_record(packed_record, false).unwrap();
let substring = store.get_substring(digest.as_bytes(), 0, 8).unwrap();
assert_eq!(substring, "ACGTACGT");
}
#[test]
fn test_add_sequence_record_raw_ascii_auto_packed_in_encoded_mode() {
use crate::digest::digest_sequence;
let mut store = RefgetStore::in_memory();
assert_eq!(store.storage_mode(), StorageMode::Encoded);
let record = digest_sequence("chr1", b"ACGTACGT");
let digest = record.metadata().sha512t24u.clone();
store.add_sequence_record(record, false).unwrap();
let substring = store.get_substring(digest.as_bytes(), 2, 6).unwrap();
assert_eq!(substring, "GTAC");
}
#[test]
fn test_ingest_sequence_round_trip() {
let mut store = RefgetStore::in_memory();
let digest = store.ingest_sequence("chr1", b"ACGTACGT").unwrap();
let substring = store.get_substring(digest.as_bytes(), 2, 6).unwrap();
assert_eq!(substring, "GTAC");
let digest1 = store.ingest_sequence("chr2", b"A").unwrap();
let substring1 = store.get_substring(digest1.as_bytes(), 0, 1).unwrap();
assert_eq!(substring1, "A");
}
#[test]
fn test_ingest_sequence_disk_backed_round_trip() {
let temp_dir = tempdir().unwrap();
let mut store = RefgetStore::on_disk(temp_dir.path()).unwrap();
let digest = store.ingest_sequence("chr1", b"ACGTACGT").unwrap();
let substring = store.get_substring(digest.as_bytes(), 2, 6).unwrap();
assert_eq!(substring, "GTAC");
}
#[test]
fn test_ingest_sequence_case_parity_with_digest_sequence() {
use crate::digest::digest_sequence;
let mut store = RefgetStore::in_memory();
let digest = store.ingest_sequence("chr1", b"acgt").unwrap();
let expected_digest = digest_sequence("chr1", b"ACGT").metadata().sha512t24u.clone();
assert_eq!(digest, expected_digest);
let substring = store.get_substring(digest.as_bytes(), 0, 4).unwrap();
assert_eq!(substring, "ACGT");
}
#[test]
fn test_get_substring_bytes_matches_get_substring() {
let mut store = RefgetStore::in_memory();
let digest = store.ingest_sequence("chr1", b"ACGTACGT").unwrap();
let bytes = store.get_substring_bytes(digest.as_bytes(), 0, 8).unwrap();
assert_eq!(bytes, b"ACGTACGT".to_vec());
let string = store.get_substring(digest.as_bytes(), 0, 8).unwrap();
assert_eq!(String::from_utf8(bytes).unwrap(), string);
}
#[test]
fn test_get_substrings_bytes_matches_get_substrings() {
let mut store = RefgetStore::in_memory();
let digest = store.ingest_sequence("chr1", b"ACGTACGTACGT").unwrap();
let ranges = [(0usize, 4usize), (4, 8), (8, 12)];
let bytes = store.get_substrings_bytes(digest.as_bytes(), &ranges).unwrap();
let strings = store.get_substrings(digest.as_bytes(), &ranges).unwrap();
assert_eq!(bytes.len(), strings.len());
for (b, s) in bytes.into_iter().zip(strings.into_iter()) {
assert_eq!(String::from_utf8(b).unwrap(), s);
}
}
#[test]
fn test_iter_collections_partial_results_on_missing_rgsi() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta1 = dir.path().join("a.fa");
let fasta2 = dir.path().join("b.fa");
fs::write(&fasta1, ">seq1\nAAAA\n").unwrap();
fs::write(&fasta2, ">seq2\nCCCC\n").unwrap();
let mut store = RefgetStore::in_memory();
let (meta1, _) = store.add_sequence_collection_from_fasta(&fasta1, FastaImportOptions::new()).unwrap();
let (meta2, _) = store.add_sequence_collection_from_fasta(&fasta2, FastaImportOptions::new()).unwrap();
store.write_store_to_dir(&store_path, None).unwrap();
let rgsi1 = store_path.join(format!("collections/{}.rgsi", meta1.digest));
let rgsi2 = store_path.join(format!("collections/{}.rgsi", meta2.digest));
assert!(rgsi1.exists());
assert!(rgsi2.exists());
fs::remove_file(&rgsi1).unwrap();
let mut loaded = RefgetStore::open_local(&store_path).unwrap();
assert_eq!(loaded.catalog.n_collections(), 2);
let result = loaded.load_all_collections();
assert!(result.is_err());
loaded.load_collection(&meta2.digest).unwrap();
let collections: Vec<_> = loaded.iter_collections().collect();
assert_eq!(collections.len(), 1);
assert_eq!(collections[0].metadata.digest, meta2.digest);
}
#[test]
fn test_iter_sequences_returns_stubs_for_unloaded() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta = dir.path().join("test.fa");
fs::write(&fasta, ">seq1\nATGC\n>seq2\nGGGG\n").unwrap();
let mut store = RefgetStore::in_memory();
store.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new()).unwrap();
store.write_store_to_dir(&store_path, None).unwrap();
let seq_digests: Vec<String> = store
.t_seq_map()
.into_values()
.map(|r| r.metadata().sha512t24u.clone())
.collect();
assert_eq!(seq_digests.len(), 2);
let digest_to_delete = &seq_digests[0];
let seq_file = store_path.join(format!(
"sequences/{}/{}.seq",
&digest_to_delete[..2],
digest_to_delete
));
assert!(seq_file.exists());
fs::remove_file(&seq_file).unwrap();
let mut loaded = RefgetStore::open_local(&store_path).unwrap();
assert_eq!(loaded.catalog.n_sequences(), 2);
let sequences: Vec<_> = loaded.iter_sequences().collect();
assert_eq!(sequences.len(), 2);
let loaded_count = sequences.iter().filter(|r| r.is_loaded()).count();
assert_eq!(loaded_count, 0);
let result = loaded.load_all_sequences();
assert!(result.is_err());
let surviving_digest = &seq_digests[1];
loaded.load_sequence(surviving_digest).unwrap();
let sequences: Vec<_> = loaded.iter_sequences().collect();
let loaded_count = sequences.iter().filter(|r| r.is_loaded()).count();
assert_eq!(loaded_count, 1);
}
#[test]
fn test_remove_existing_collection() {
let (mut store, digest) = store_with_one_collection(">chr1\nACGT\n>chr2\nTTTT\n");
assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 1);
let result = store.remove_collection(&digest, false).unwrap();
assert!(result);
assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 0);
assert!(store.get_collection(&digest).is_err());
}
#[test]
fn test_remove_nonexistent_collection() {
let (mut store, _digest) = store_with_one_collection(">chr1\nACGT\n");
let result = store.remove_collection("nonexistent_digest_value", false).unwrap();
assert!(!result);
assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 1);
}
#[test]
fn test_remove_without_orphan_cleanup_keeps_sequences() {
let (mut store, digest) = store_with_one_collection(">chr1\nACGT\n>chr2\nTTTT\n");
assert_eq!(store.list_sequences().unwrap().len(), 2);
store.remove_collection(&digest, false).unwrap();
assert_eq!(store.list_sequences().unwrap().len(), 2);
}
#[test]
fn test_remove_with_orphan_cleanup_removes_sequences() {
let (mut store, digest) = store_with_one_collection(">chr1\nACGT\n>chr2\nTTTT\n");
assert_eq!(store.list_sequences().unwrap().len(), 2);
store.remove_collection(&digest, true).unwrap();
assert_eq!(store.list_sequences().unwrap().len(), 0);
}
#[test]
fn test_remove_with_orphan_cleanup_retains_shared_sequences() {
let dir = tempdir().unwrap();
let fasta1 = dir.path().join("a.fa");
let fasta2 = dir.path().join("b.fa");
fs::write(&fasta1, ">chr1\nACGT\n>chr2\nTTTT\n").unwrap();
fs::write(&fasta2, ">chr1\nACGT\n>chr3\nGGGG\n").unwrap();
let mut store = RefgetStore::in_memory();
let (meta1, _) = store
.add_sequence_collection_from_fasta(&fasta1, FastaImportOptions::new())
.unwrap();
let (meta2, _) = store
.add_sequence_collection_from_fasta(&fasta2, FastaImportOptions::new())
.unwrap();
assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 2);
assert_eq!(store.list_sequences().unwrap().len(), 3);
store.remove_collection(&meta1.digest, true).unwrap();
assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 1);
assert_eq!(store.list_sequences().unwrap().len(), 2);
let coll = store.get_collection(&meta2.digest).unwrap();
assert_eq!(coll.sequences.len(), 2);
}
#[test]
fn test_remove_with_orphan_cleanup_clears_md5_lookup() {
let (mut store, digest) = store_with_one_collection(">chr1\nACGT\n>chr2\nTTTT\n");
assert_eq!(store.list_sequences().unwrap().len(), 2);
assert_eq!(store.catalog.n_sequences(), 2);
store.remove_collection(&digest, true).unwrap();
assert_eq!(store.list_sequences().unwrap().len(), 0);
assert_eq!(store.catalog.n_sequences(), 0);
}
#[test]
fn test_remove_with_orphan_cleanup_md5_lookup_retains_shared_sequences() {
let dir = tempdir().unwrap();
let fasta1 = dir.path().join("a.fa");
let fasta2 = dir.path().join("b.fa");
fs::write(&fasta1, ">chr1\nACGT\n>chr2\nTTTT\n").unwrap();
fs::write(&fasta2, ">chr1\nACGT\n>chr3\nGGGG\n").unwrap();
let mut store = RefgetStore::in_memory();
let (meta1, _) = store
.add_sequence_collection_from_fasta(&fasta1, FastaImportOptions::new())
.unwrap();
let (meta2, _) = store
.add_sequence_collection_from_fasta(&fasta2, FastaImportOptions::new())
.unwrap();
let md5_shared = md5(b"ACGT").to_key(); let md5_orphan = md5(b"TTTT").to_key(); let md5_other = md5(b"GGGG").to_key();
assert_eq!(store.catalog.n_sequences(), 3);
store.remove_collection(&meta1.digest, true).unwrap();
assert!(!store.t_has_md5(&md5_orphan));
assert!(store.t_has_md5(&md5_shared));
assert!(store.t_has_md5(&md5_other));
assert_eq!(store.catalog.n_sequences(), 2);
let coll = store.get_collection(&meta2.digest).unwrap();
assert_eq!(coll.sequences.len(), 2);
assert_eq!(store.list_sequences().unwrap().len(), 2);
}
#[test]
fn test_remove_collection_on_disk() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta = dir.path().join("test.fa");
fs::write(&fasta, ">chr1\nACGT\n>chr2\nTTTT\n").unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = meta.digest.clone();
let rgsi_path = store_path.join(format!("collections/{}.rgsi", digest));
assert!(rgsi_path.exists());
let rgci_path = store_path.join("collections.rgci");
assert!(rgci_path.exists());
let result = store.remove_collection(&digest, false).unwrap();
assert!(result);
assert!(!rgsi_path.exists());
let rgci_content = fs::read_to_string(&rgci_path).unwrap();
assert!(!rgci_content.contains(&digest));
assert!(store_path.join("sequences.rgsi").exists());
assert!(store_path.join("rgstore.json").exists());
}
#[test]
fn test_remove_collection_on_disk_with_orphan_sequences() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta = dir.path().join("test.fa");
fs::write(&fasta, ">chr1\nACGT\n").unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = meta.digest.clone();
let seq_digest = sha512t24u(b"ACGT");
let seq_file = store_path.join(format!("sequences/{}/{}.seq", &seq_digest[..2], seq_digest));
assert!(seq_file.exists());
store.remove_collection(&digest, true).unwrap();
assert!(!seq_file.exists());
let rgsi_content = fs::read_to_string(store_path.join("sequences.rgsi")).unwrap();
let non_comment_lines: Vec<_> = rgsi_content.lines().filter(|l| !l.starts_with('#')).collect();
assert!(non_comment_lines.is_empty());
}
#[test]
fn test_remove_collection_on_disk_cleans_up_empty_shard_dirs() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta = dir.path().join("test.fa");
fs::write(&fasta, ">chr1\nACGT\n>chr2\nTTTT\n>chr3\nGGGG\n").unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = meta.digest.clone();
let seq_files: Vec<PathBuf> = [b"ACGT".as_slice(), b"TTTT".as_slice(), b"GGGG".as_slice()]
.iter()
.map(|seq| {
let d = sha512t24u(seq);
store_path.join(format!("sequences/{}/{}.seq", &d[..2], d))
})
.collect();
for f in &seq_files {
assert!(f.exists(), "expected seq file to exist before removal: {:?}", f);
}
let shard_dirs: std::collections::HashSet<PathBuf> = seq_files
.iter()
.map(|f| f.parent().unwrap().to_path_buf())
.collect();
for d in &shard_dirs {
assert!(d.is_dir(), "expected shard dir to exist before removal: {:?}", d);
}
store.remove_collection(&digest, true).unwrap();
for f in &seq_files {
assert!(!f.exists(), "orphan seq file was not removed: {:?}", f);
}
for d in &shard_dirs {
assert!(
!d.exists(),
"emptied shard dir was not cleaned up (hoisted rmdir pass did not run): {:?}",
d
);
}
assert!(store_path.join("sequences").is_dir());
}
#[test]
fn test_store_exists() {
let dir = tempdir().unwrap();
let path = dir.path();
assert!(!RefgetStore::store_exists(path));
let mut store = RefgetStore::on_disk(path).unwrap();
let fasta_path = dir.path().join("test.fa");
fs::write(&fasta_path, ">seq1\nACGT\n").unwrap();
store
.add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
.unwrap();
store.write().unwrap();
assert!(RefgetStore::store_exists(path));
assert!(!RefgetStore::store_exists("/nonexistent/path/to/store"));
}
#[test]
fn test_clear() {
let dir = tempdir().unwrap();
let fasta_path = dir.path().join("test.fa");
fs::write(&fasta_path, ">seq1\nACGT\n>seq2\nTGCA\n").unwrap();
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
.unwrap();
assert_eq!(store.sequence_digests().count(), 2);
assert_eq!(store.catalog.n_collections(), 1);
let name_count = store.t_n_loaded_colls();
store.clear();
assert_eq!(store.sequence_digests().count(), 2);
assert_eq!(store.stats().n_sequences_in_memory, 0);
assert_eq!(store.catalog.n_collections(), 1);
assert_eq!(store.t_n_loaded_colls(), name_count);
let fasta2 = dir.path().join("test2.fa");
fs::write(&fasta2, ">seq3\nGGGG\n").unwrap();
store
.add_sequence_collection_from_fasta(fasta2.to_str().unwrap(), FastaImportOptions::new())
.unwrap();
assert_eq!(store.sequence_digests().count(), 3);
assert_eq!(store.catalog.n_collections(), 2);
}
#[test]
fn test_rgstore_json_contains_state_digests() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store
.add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
.unwrap();
let json = fs::read_to_string(store_path.join("rgstore.json")).unwrap();
let metadata: serde_json::Value = serde_json::from_str(&json).unwrap();
assert!(metadata.get("modified").is_some(), "modified field should be present");
assert!(metadata.get("collections_digest").is_some(), "collections_digest should be present");
assert!(metadata.get("sequences_digest").is_some(), "sequences_digest should be present");
}
#[test]
fn test_state_digests_change_on_add() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store
.add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
.unwrap();
let meta1 = store.store_metadata().unwrap();
let coll_digest1 = meta1.get("collections_digest").cloned().unwrap();
let fasta2 = dir.path().join("test2.fa");
fs::write(&fasta2, ">seq_new\nTTTTAAAA\n").unwrap();
store
.add_sequence_collection_from_fasta(fasta2.to_str().unwrap(), FastaImportOptions::new())
.unwrap();
let meta2 = store.store_metadata().unwrap();
let coll_digest2 = meta2.get("collections_digest").cloned().unwrap();
assert_ne!(coll_digest1, coll_digest2, "collections_digest should change when a collection is added");
}
#[test]
fn test_aliases_digest_changes_on_alias_add() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
.unwrap();
let meta1 = store.store_metadata().unwrap();
assert!(meta1.get("aliases_digest").is_none(), "no aliases yet");
store.add_sequence_alias("test_ns", "my_alias", &meta.sequences_digest).unwrap();
let fasta2 = dir.path().join("test2.fa");
fs::write(&fasta2, ">alias_test_seq\nAAAACCCC\n").unwrap();
store
.add_sequence_collection_from_fasta(fasta2.to_str().unwrap(), FastaImportOptions::new())
.unwrap();
let meta2 = store.store_metadata().unwrap();
assert!(meta2.get("aliases_digest").is_some(), "aliases_digest should appear after alias + index rewrite");
}
#[test]
fn test_logical_sequence_bytes_persisted_in_manifest() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store
.add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
.unwrap();
let expected = store.logical_sequence_bytes() as u64;
assert!(expected > 0);
let json = fs::read_to_string(store_path.join("rgstore.json")).unwrap();
let manifest: serde_json::Value = serde_json::from_str(&json).unwrap();
assert_eq!(
manifest.get("logical_sequence_bytes").and_then(|v| v.as_u64()),
Some(expected),
"manifest should cache logical_sequence_bytes matching the store"
);
let meta = store.store_metadata().unwrap();
assert_eq!(
meta.get("logical_sequence_bytes").map(|s| s.as_str()),
Some(expected.to_string().as_str())
);
}
#[test]
fn test_logical_sequence_bytes_survives_alias_refresh() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
.unwrap();
let expected = store.logical_sequence_bytes() as u64;
assert!(expected > 0);
store.add_sequence_alias("test_ns", "my_alias", &meta.sequences_digest).unwrap();
let json = fs::read_to_string(store_path.join("rgstore.json")).unwrap();
let manifest: serde_json::Value = serde_json::from_str(&json).unwrap();
assert_eq!(
manifest.get("logical_sequence_bytes").and_then(|v| v.as_u64()),
Some(expected),
"logical_sequence_bytes should survive an alias-only refresh"
);
}
#[test]
fn test_old_rgstore_json_without_state_digests_loads() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
fs::create_dir_all(&store_path).unwrap();
let old_metadata = serde_json::json!({
"version": 1,
"seqdata_path_template": "sequences/%s2/%s.seq",
"collections_path_template": "collections/%s.rgsi",
"sequence_index": "sequences.rgsi",
"collection_index": "collections.rgci",
"mode": "Raw",
"created_at": "2026-01-01T00:00:00Z",
"ancillary_digests": true,
"attribute_index": false
});
fs::write(store_path.join("rgstore.json"), serde_json::to_string_pretty(&old_metadata).unwrap()).unwrap();
fs::write(store_path.join("sequences.rgsi"), "#name\tlength\talphabet\tsha512t24u\tmd5\tdescription\n").unwrap();
fs::write(store_path.join("collections.rgci"), "#digest\tn_sequences\tnames_digest\tsequences_digest\tlengths_digest\tname_length_pairs_digest\tsorted_name_length_pairs_digest\tsorted_sequences_digest\n").unwrap();
let store = RefgetStore::open_local(&store_path).unwrap();
assert_eq!(store.stats().n_sequences, 0);
}
#[test]
fn test_collection_order_preserved_after_roundtrip() {
let fasta_content = "\
>chr1\nACGTACGT\n\
>chr2\nGGGGAAAA\n\
>chr3\nTTTTCCCC\n\
>chr10\nAAAAAAAA\n\
>chr11\nCCCCCCCC\n\
>chr22\nGGGGGGGG\n\
>chrX\nTTTTTTTT\n\
>chrY\nACACACCA\n\
";
let expected_names: Vec<&str> = vec!["chr1","chr2","chr3","chr10","chr11","chr22","chrX","chrY"];
let dir = tempdir().unwrap();
let fasta_path = dir.path().join("order_test.fa");
fs::write(&fasta_path, fasta_content).unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
.unwrap();
let digest = meta.digest.clone();
store.write().unwrap();
store.load_all_collections().unwrap();
let original_collection = store.get_collection(&digest).unwrap();
let original_names: Vec<String> = original_collection
.sequences
.iter()
.map(|s| s.metadata().name.clone())
.collect();
assert_eq!(
original_names,
expected_names,
"Names should match FASTA order before roundtrip"
);
drop(store);
let mut reloaded = RefgetStore::open_local(&store_path).unwrap();
reloaded.load_all_collections().unwrap();
let reloaded_collection = reloaded.get_collection(&digest).unwrap();
let reloaded_names: Vec<String> = reloaded_collection
.sequences
.iter()
.map(|s| s.metadata().name.clone())
.collect();
assert_eq!(
reloaded_names, original_names,
"Sequence order must be identical after save/reload roundtrip"
);
let original_lengths: Vec<usize> = original_collection
.sequences
.iter()
.map(|s| s.metadata().length)
.collect();
let reloaded_lengths: Vec<usize> = reloaded_collection
.sequences
.iter()
.map(|s| s.metadata().length)
.collect();
assert_eq!(
reloaded_lengths, original_lengths,
"Lengths must be in same order after roundtrip"
);
let original_digests: Vec<String> = original_collection
.sequences
.iter()
.map(|s| s.metadata().sha512t24u.clone())
.collect();
let reloaded_digests: Vec<String> = reloaded_collection
.sequences
.iter()
.map(|s| s.metadata().sha512t24u.clone())
.collect();
assert_eq!(
reloaded_digests, original_digests,
"SHA512t24u digests must be in same order after roundtrip"
);
}
#[test]
fn test_shared_sequences_order_preserved_after_disk_roundtrip() {
let fasta_a = ">chrX\nTTGGGGAA\n>chr1\nGGAA\n>chr2\nGCGC\n";
let fasta_b = ">chr1\nGGAA\n>chr2\nGCGC\n>chrX\nTTGGGGAA\n";
let fasta_c = ">chrX\nTTGGGGAA\n>chr2\nGGAA\n>chr1\nGCGC\n";
let dir = tempdir().unwrap();
let fasta_a_path = dir.path().join("a.fa");
let fasta_b_path = dir.path().join("b.fa");
let fasta_c_path = dir.path().join("c.fa");
fs::write(&fasta_a_path, fasta_a).unwrap();
fs::write(&fasta_b_path, fasta_b).unwrap();
fs::write(&fasta_c_path, fasta_c).unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store.set_quiet(true);
let (meta_a, _) = store.add_sequence_collection_from_fasta(&fasta_a_path, FastaImportOptions::new()).unwrap();
let (meta_b, _) = store.add_sequence_collection_from_fasta(&fasta_b_path, FastaImportOptions::new()).unwrap();
let (meta_c, _) = store.add_sequence_collection_from_fasta(&fasta_c_path, FastaImportOptions::new()).unwrap();
let digest_a = meta_a.digest.clone();
let digest_b = meta_b.digest.clone();
let digest_c = meta_c.digest.clone();
store.load_all_collections().unwrap();
let pre_a = store.get_collection_level2(&digest_a).unwrap();
let pre_b = store.get_collection_level2(&digest_b).unwrap();
let pre_c = store.get_collection_level2(&digest_c).unwrap();
assert_eq!(pre_a.names, vec!["chrX", "chr1", "chr2"], "A: names before roundtrip");
assert_eq!(pre_b.names, vec!["chr1", "chr2", "chrX"], "B: names before roundtrip");
assert_eq!(pre_c.names, vec!["chrX", "chr2", "chr1"], "C: names before roundtrip");
store.write().unwrap();
drop(store);
let mut reloaded = RefgetStore::open_local(&store_path).unwrap();
reloaded.load_all_collections().unwrap();
let post_a = reloaded.get_collection_level2(&digest_a).unwrap();
let post_b = reloaded.get_collection_level2(&digest_b).unwrap();
let post_c = reloaded.get_collection_level2(&digest_c).unwrap();
assert_eq!(post_a.names, pre_a.names, "A: names after roundtrip");
assert_eq!(post_b.names, pre_b.names, "B: names after roundtrip");
assert_eq!(post_c.names, pre_c.names, "C: names after roundtrip");
assert_eq!(post_a.lengths, pre_a.lengths, "A: lengths after roundtrip");
assert_eq!(post_b.lengths, pre_b.lengths, "B: lengths after roundtrip");
assert_eq!(post_c.lengths, pre_c.lengths, "C: lengths after roundtrip");
assert_eq!(post_a.sequences, pre_a.sequences, "A: sequences after roundtrip");
assert_eq!(post_b.sequences, pre_b.sequences, "B: sequences after roundtrip");
assert_eq!(post_c.sequences, pre_c.sequences, "C: sequences after roundtrip");
assert_eq!(
post_c.sequences[1], post_a.sequences[1],
"C.chr2 and A.chr1 share GGAA bytes, should have same sequence digest"
);
assert_eq!(
post_c.sequences[2], post_a.sequences[2],
"C.chr1 and A.chr2 share GCGC bytes, should have same sequence digest"
);
}
#[test]
fn test_shared_sequence_different_names() {
let dir = tempdir().unwrap();
let fasta1_content = ">chrX\nTTGGGGAA\n>chr1\nGGAA\n";
let fasta1_path = dir.path().join("subset.fa");
fs::write(&fasta1_path, fasta1_content).unwrap();
let fasta2_content = ">chrX\nTTGGGGAA\n>chr2\nGGAA\n>chr1\nGCGC\n";
let fasta2_path = dir.path().join("swap_wo_coords.fa");
fs::write(&fasta2_path, fasta2_content).unwrap();
let mut store = RefgetStore::in_memory();
let (meta1, _) = store
.add_sequence_collection_from_fasta(&fasta1_path, FastaImportOptions::new())
.unwrap();
let (meta2, _) = store
.add_sequence_collection_from_fasta(&fasta2_path, FastaImportOptions::new())
.unwrap();
let coll1 = store.get_collection(&meta1.digest).unwrap();
let names1: Vec<&str> = coll1.sequences.iter().map(|s| s.metadata().name.as_str()).collect();
assert!(
names1.contains(&"chr1"),
"Collection 1 (subset.fa) should contain 'chr1', got: {:?}",
names1
);
assert!(
!names1.contains(&"chr2"),
"Collection 1 (subset.fa) must NOT contain 'chr2', got: {:?}",
names1
);
let coll2 = store.get_collection(&meta2.digest).unwrap();
let names2: Vec<&str> = coll2.sequences.iter().map(|s| s.metadata().name.as_str()).collect();
assert!(
names2.contains(&"chr2"),
"Collection 2 (swap_wo_coords.fa) should contain 'chr2', got: {:?}",
names2
);
}
fn disk_store_with_one_collection(fasta_content: &str) -> (RefgetStore, String, tempfile::TempDir, tempfile::TempDir) {
let store_dir = tempdir().unwrap();
let fasta_dir = tempdir().unwrap();
let fasta = fasta_dir.path().join("test.fa");
fs::write(&fasta, fasta_content).unwrap();
let mut store = RefgetStore::on_disk(store_dir.path()).unwrap();
store.set_quiet(true);
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = meta.digest.clone();
store.load_all_collections().unwrap();
(store, digest, store_dir, fasta_dir)
}
#[test]
fn test_import_collection_basic() {
let (mut source, digest, _src_dir, _fasta_dir) =
disk_store_with_one_collection(">chr1\nATGC\n>chr2\nGGGG\n");
let target_dir = tempdir().unwrap();
let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
target.import_collection(&mut source, &digest).unwrap();
let coll = target.get_collection(&digest).unwrap();
assert_eq!(coll.sequences.len(), 2);
}
#[test]
fn test_import_collection_copies_sequence_aliases() {
let (mut source, digest, _src_dir, _fasta_dir) =
disk_store_with_one_collection(">chr1\nATGC\n>chr2\nGGGG\n");
let coll = source.get_collection(&digest).unwrap();
let seq0_digest = coll.sequences[0].metadata().sha512t24u.clone();
let seq1_digest = coll.sequences[1].metadata().sha512t24u.clone();
source.add_sequence_alias("ncbi", "NC_000001.1", &seq0_digest).unwrap();
source.add_sequence_alias("ucsc", "chr1", &seq0_digest).unwrap();
source.add_sequence_alias("ncbi", "NC_000002.1", &seq1_digest).unwrap();
let target_dir = tempdir().unwrap();
let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
target.import_collection(&mut source, &digest).unwrap();
let ns = target.list_sequence_alias_namespaces();
assert!(ns.contains(&"ncbi".to_string()), "Missing ncbi namespace: {:?}", ns);
assert!(ns.contains(&"ucsc".to_string()), "Missing ucsc namespace: {:?}", ns);
let resolved = target.get_sequence_metadata_by_alias("ncbi", "NC_000001.1");
assert!(resolved.is_some(), "ncbi alias NC_000001.1 not found in target");
assert_eq!(resolved.unwrap().sha512t24u, seq0_digest);
}
#[test]
fn test_import_collection_copies_collection_aliases() {
let (mut source, digest, _src_dir, _fasta_dir) =
disk_store_with_one_collection(">chr1\nATGC\n>chr2\nGGGG\n");
source.add_collection_alias("insdc", "GCA_000001.1", &digest).unwrap();
source.add_collection_alias("refseq", "GCF_000001.1", &digest).unwrap();
let target_dir = tempdir().unwrap();
let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
target.import_collection(&mut source, &digest).unwrap();
let ns = target.list_collection_alias_namespaces();
assert!(ns.contains(&"insdc".to_string()), "Missing insdc namespace: {:?}", ns);
assert!(ns.contains(&"refseq".to_string()), "Missing refseq namespace: {:?}", ns);
let aliases = target.get_aliases_for_collection(&digest);
assert_eq!(aliases.len(), 2, "Expected 2 collection aliases, got {:?}", aliases);
}
#[test]
fn test_import_collection_copies_fhr_metadata() {
use super::fhr_metadata::FhrMetadata;
let (mut source, digest, _src_dir, _fasta_dir) =
disk_store_with_one_collection(">chr1\nATGC\n");
let fhr = FhrMetadata {
genome: Some("Homo sapiens".to_string()),
..Default::default()
};
source.set_fhr_metadata(&digest, fhr).unwrap();
let target_dir = tempdir().unwrap();
let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
target.import_collection(&mut source, &digest).unwrap();
let fhr = target.get_fhr_metadata(&digest);
assert!(fhr.is_some(), "FHR metadata not copied");
assert_eq!(fhr.unwrap().genome.as_deref(), Some("Homo sapiens"));
}
#[test]
fn test_import_collection_disk_roundtrip_aliases() {
let source_dir = tempdir().unwrap();
let target_dir = tempdir().unwrap();
let fasta_dir = tempdir().unwrap();
let fasta = fasta_dir.path().join("test.fa");
fs::write(&fasta, ">chr1\nATGC\n>chr2\nGGGG\n").unwrap();
let digest;
let seq0_digest;
{
let mut source = RefgetStore::on_disk(source_dir.path()).unwrap();
source.set_quiet(true);
let (meta, _) = source
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
digest = meta.digest.clone();
let coll = source.get_collection(&digest).unwrap();
seq0_digest = coll.sequences[0].metadata().sha512t24u.clone();
source.add_sequence_alias("ncbi", "NC_000001.1", &seq0_digest).unwrap();
source.add_collection_alias("insdc", "GCA_000001.1", &digest).unwrap();
}
let mut source = RefgetStore::on_disk(source_dir.path()).unwrap();
source.load_all_collections().unwrap();
let seq_ns = source.list_sequence_alias_namespaces();
assert!(seq_ns.contains(&"ncbi".to_string()), "Source lost seq aliases after reopen: {:?}", seq_ns);
let coll_ns = source.list_collection_alias_namespaces();
assert!(coll_ns.contains(&"insdc".to_string()), "Source lost coll aliases after reopen: {:?}", coll_ns);
let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
target.import_collection(&mut source, &digest).unwrap();
let ns = target.list_sequence_alias_namespaces();
assert!(ns.contains(&"ncbi".to_string()), "Target missing ncbi seq alias: {:?}", ns);
let resolved = target.get_sequence_metadata_by_alias("ncbi", "NC_000001.1");
assert!(resolved.is_some(), "Alias NC_000001.1 not found in target after disk roundtrip");
assert_eq!(resolved.unwrap().sha512t24u, seq0_digest);
let coll_aliases = target.get_aliases_for_collection(&digest);
assert_eq!(coll_aliases.len(), 1, "Expected 1 collection alias in target: {:?}", coll_aliases);
}
#[test]
fn test_import_collection_file_copy_roundtrip() {
let (mut source, digest, src_dir, _fasta_dir) =
disk_store_with_one_collection(">chr1\nATGC\n>chr2\nGGGG\n");
let target_dir = tempdir().unwrap();
let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
target.import_collection(&mut source, &digest).unwrap();
let src_rgsi = fs::read(
src_dir.path().join(format!("collections/{}.rgsi", digest)),
).unwrap();
let dst_rgsi = fs::read(
target_dir.path().join(format!("collections/{}.rgsi", digest)),
).unwrap();
assert_eq!(src_rgsi, dst_rgsi, "RGSI files should be byte-identical");
let coll = target.get_collection(&digest).unwrap();
for seq in &coll.sequences {
let seq_digest = &seq.metadata().sha512t24u;
let src_seq_path = source.sequence_file_path(seq_digest).unwrap();
let dst_seq_path = target.sequence_file_path(seq_digest).unwrap();
let src_data = fs::read(&src_seq_path).unwrap();
let dst_data = fs::read(&dst_seq_path).unwrap();
assert_eq!(src_data, dst_data, "Sequence file for {} should be byte-identical", seq_digest);
}
let src_coll = source.get_collection(&digest).unwrap();
assert_eq!(coll.metadata.digest, src_coll.metadata.digest);
assert_eq!(coll.sequences.len(), src_coll.sequences.len());
for (src_seq, dst_seq) in src_coll.sequences.iter().zip(coll.sequences.iter()) {
assert_eq!(src_seq.metadata().sha512t24u, dst_seq.metadata().sha512t24u);
assert_eq!(src_seq.metadata().name, dst_seq.metadata().name);
assert_eq!(src_seq.metadata().length, dst_seq.metadata().length);
}
}
#[test]
fn test_import_collection_ancillary_digest_enrichment() {
let source_dir = tempdir().unwrap();
let fasta_dir = tempdir().unwrap();
let fasta = fasta_dir.path().join("test.fa");
fs::write(&fasta, ">chr1\nATGC\n>chr2\nGGGG\n").unwrap();
let mut source = RefgetStore::on_disk(source_dir.path()).unwrap();
source.set_quiet(true);
source.disable_ancillary_digests();
let (meta, _) = source
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = meta.digest.clone();
source.load_all_collections().unwrap();
let src_rgsi_content = fs::read_to_string(
source_dir.path().join(format!("collections/{}.rgsi", digest)),
).unwrap();
assert!(
!src_rgsi_content.contains("name_length_pairs_digest"),
"Source should NOT have ancillary digests",
);
let target_dir = tempdir().unwrap();
let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
target.enable_ancillary_digests();
target.import_collection(&mut source, &digest).unwrap();
let dst_rgsi_content = fs::read_to_string(
target_dir.path().join(format!("collections/{}.rgsi", digest)),
).unwrap();
assert!(
dst_rgsi_content.contains("name_length_pairs_digest"),
"Destination should have ancillary digests. RGSI:\n{}",
dst_rgsi_content,
);
assert!(
dst_rgsi_content.contains("sorted_name_length_pairs_digest"),
"Destination should have sorted_name_length_pairs_digest",
);
assert!(
dst_rgsi_content.contains("sorted_sequences_digest"),
"Destination should have sorted_sequences_digest",
);
let coll_meta = target.get_collection_metadata(&digest).unwrap();
assert!(coll_meta.name_length_pairs_digest.is_some(), "name_length_pairs_digest should be Some");
assert!(coll_meta.sorted_name_length_pairs_digest.is_some(), "sorted_name_length_pairs_digest should be Some");
assert!(coll_meta.sorted_sequences_digest.is_some(), "sorted_sequences_digest should be Some");
}
#[test]
fn test_import_collection_mode_mismatch_error() {
let source_dir = tempdir().unwrap();
let fasta_dir = tempdir().unwrap();
let fasta = fasta_dir.path().join("test.fa");
fs::write(&fasta, ">chr1\nATGC\n").unwrap();
let mut source = RefgetStore::on_disk(source_dir.path()).unwrap();
source.set_quiet(true);
source.disable_encoding();
let (meta, _) = source
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = meta.digest.clone();
source.load_all_collections().unwrap();
let target_dir = tempdir().unwrap();
let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
let result = target.import_collection(&mut source, &digest);
assert!(result.is_err(), "Should fail with mode mismatch");
let err_msg = result.unwrap_err().to_string();
assert!(
err_msg.contains("matching storage modes"),
"Error should mention storage modes: {}",
err_msg,
);
}
fn collect_seq_files(dir: &std::path::Path) -> std::collections::BTreeMap<String, Vec<u8>> {
fn walk(
base: &std::path::Path,
cur: &std::path::Path,
out: &mut std::collections::BTreeMap<String, Vec<u8>>,
) {
for entry in std::fs::read_dir(cur).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
walk(base, &path, out);
} else if path.extension().and_then(|e| e.to_str()) == Some("seq") {
let rel = path.strip_prefix(base).unwrap().to_string_lossy().to_string();
out.insert(rel, std::fs::read(&path).unwrap());
}
}
}
let mut out = std::collections::BTreeMap::new();
let seqdir = dir.join("sequences");
if seqdir.exists() {
walk(dir, &seqdir, &mut out);
}
out
}
const PARITY_FASTA: &str =
">chrX\nTTGGGGAACCCCTTTT\n>chr1\nGGAATTCCGGAATTCC\n>chr2\nACGTACGTACGTACGT\n\
>chrM\nGGGGCCCCAAAATTTT\n>chr10\nTACGTACGTACGTACG\n";
fn build_on_disk_store(dir: &std::path::Path, fasta: &std::path::Path, jobs: usize) -> String {
let mut store = RefgetStore::on_disk(dir).unwrap();
store.set_quiet(true);
let (meta, _) = store
.add_sequence_collection_from_fasta(fasta, FastaImportOptions::new().jobs(jobs))
.unwrap();
meta.digest
}
#[test]
fn test_parallel_equals_serial_on_disk() {
let work = tempdir().unwrap();
let fasta = work.path().join("parity.fa");
fs::write(&fasta, PARITY_FASTA).unwrap();
let dir_serial = tempdir().unwrap();
let dir_parallel = tempdir().unwrap();
let digest_serial = build_on_disk_store(dir_serial.path(), &fasta, 1);
let digest_parallel = build_on_disk_store(dir_parallel.path(), &fasta, 8);
assert_eq!(digest_serial, digest_parallel, "collection digest must match");
let rgsi_serial = fs::read(dir_serial.path().join("sequences.rgsi")).unwrap();
let rgsi_parallel = fs::read(dir_parallel.path().join("sequences.rgsi")).unwrap();
assert_eq!(rgsi_serial, rgsi_parallel, "sequences.rgsi must be byte-identical");
let rgci_serial = fs::read(dir_serial.path().join("collections.rgci")).unwrap();
let rgci_parallel = fs::read(dir_parallel.path().join("collections.rgci")).unwrap();
assert_eq!(rgci_serial, rgci_parallel, "collections.rgci must be byte-identical");
let seqs_serial = collect_seq_files(dir_serial.path());
let seqs_parallel = collect_seq_files(dir_parallel.path());
assert_eq!(
seqs_serial, seqs_parallel,
".seq files must match between serial and parallel builds"
);
assert!(!seqs_serial.is_empty(), "expected some .seq files");
}
#[test]
fn test_parallel_name_lookup_matches_fasta_order() {
let work = tempdir().unwrap();
let fasta = work.path().join("parity.fa");
fs::write(&fasta, PARITY_FASTA).unwrap();
let fasta_order = vec!["chrX", "chr1", "chr2", "chrM", "chr10"];
let dir_serial = tempdir().unwrap();
let dir_parallel = tempdir().unwrap();
let digest = build_on_disk_store(dir_serial.path(), &fasta, 1);
let _ = build_on_disk_store(dir_parallel.path(), &fasta, 8);
let mut serial = RefgetStore::open_local(dir_serial.path()).unwrap();
let mut parallel = RefgetStore::open_local(dir_parallel.path()).unwrap();
serial.load_all_collections().unwrap();
parallel.load_all_collections().unwrap();
let key = digest.to_key();
let serial_names: Vec<String> = serial
.t_names(&key);
let parallel_names: Vec<String> = parallel
.t_names(&key);
assert_eq!(serial_names, fasta_order, "serial name_lookup must follow FASTA order");
assert_eq!(
parallel_names, fasta_order,
"parallel name_lookup must follow FASTA order"
);
}
#[test]
fn test_parallel_equals_serial_in_memory() {
let work = tempdir().unwrap();
let fasta = work.path().join("parity.fa");
fs::write(&fasta, PARITY_FASTA).unwrap();
let mut serial = RefgetStore::in_memory();
serial.set_quiet(true);
let (meta_s, _) = serial
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(1))
.unwrap();
let mut parallel = RefgetStore::in_memory();
parallel.set_quiet(true);
let (meta_p, _) = parallel
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(8))
.unwrap();
assert_eq!(meta_s.digest, meta_p.digest);
let key = meta_s.digest.to_key();
let names_s: Vec<(String, DigestKey)> = serial
.t_name_pairs(&key);
let names_p: Vec<(String, DigestKey)> = parallel
.t_name_pairs(&key);
assert_eq!(names_s, names_p, "name_lookup order+contents must match");
let digs_s: std::collections::BTreeSet<DigestKey> = serial.sequence_digests().collect();
let digs_p: std::collections::BTreeSet<DigestKey> = parallel.sequence_digests().collect();
assert_eq!(digs_s, digs_p, "digest sets must match");
for name in ["chrX", "chr1", "chr2", "chrM", "chr10"] {
let rec_s = serial.get_sequence_by_name(&meta_s.digest, name).unwrap();
let rec_p = parallel.get_sequence_by_name(&meta_p.digest, name).unwrap();
let m_s = rec_s.metadata();
let m_p = rec_p.metadata();
assert_eq!(m_s.sha512t24u, m_p.sha512t24u);
assert_eq!(m_s.md5, m_p.md5);
assert_eq!(m_s.alphabet, m_p.alphabet);
assert_eq!(m_s.length, m_p.length);
let sub_s = serial.get_substring(&m_s.sha512t24u, 0, m_s.length).unwrap();
let sub_p = parallel.get_substring(&m_p.sha512t24u, 0, m_p.length).unwrap();
assert_eq!(sub_s, sub_p, "decoded bytes must match for {}", name);
}
}
#[test]
fn test_parallel_cached_metadata_parity() {
let build_cached = |jobs: usize| -> (tempfile::TempDir, String) {
let src_dir = tempdir().unwrap();
let fasta = src_dir.path().join("cached.fa");
fs::write(&fasta, PARITY_FASTA).unwrap();
let prime_dir = tempdir().unwrap();
let mut prime = RefgetStore::on_disk(prime_dir.path()).unwrap();
prime.set_quiet(true);
prime
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(1))
.unwrap();
assert!(
src_dir.path().join("cached.rgsi").exists(),
"rgsi cache should have been written"
);
let dir = tempdir().unwrap();
let mut store = RefgetStore::on_disk(dir.path()).unwrap();
store.set_quiet(true);
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(jobs))
.unwrap();
(dir, meta.digest)
};
let (dir_serial, digest_serial) = build_cached(1);
let (dir_parallel, digest_parallel) = build_cached(8);
assert_eq!(digest_serial, digest_parallel);
let rgsi_s = fs::read(dir_serial.path().join("sequences.rgsi")).unwrap();
let rgsi_p = fs::read(dir_parallel.path().join("sequences.rgsi")).unwrap();
assert_eq!(rgsi_s, rgsi_p, "cached-path sequences.rgsi must match");
let seqs_s = collect_seq_files(dir_serial.path());
let seqs_p = collect_seq_files(dir_parallel.path());
assert_eq!(seqs_s, seqs_p, "cached-path .seq files must match");
let mut serial = RefgetStore::open_local(dir_serial.path()).unwrap();
let mut parallel = RefgetStore::open_local(dir_parallel.path()).unwrap();
serial.load_all_collections().unwrap();
parallel.load_all_collections().unwrap();
let key = digest_serial.to_key();
let names_s: Vec<String> = serial.t_names(&key);
let names_p: Vec<String> = parallel.t_names(&key);
assert_eq!(names_s, vec!["chrX", "chr1", "chr2", "chrM", "chr10"]);
assert_eq!(names_s, names_p);
}
#[test]
fn test_parallel_duplicate_contig_dedup() {
let fasta_content = ">dupA\nACGTACGTACGT\n>uniq\nGGGGCCCCAAAA\n>dupB\nACGTACGTACGT\n";
let work = tempdir().unwrap();
let fasta = work.path().join("dup.fa");
fs::write(&fasta, fasta_content).unwrap();
let dir = tempdir().unwrap();
let mut store = RefgetStore::on_disk(dir.path()).unwrap();
store.set_quiet(true);
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(8))
.unwrap();
let digs: std::collections::BTreeSet<DigestKey> = store.sequence_digests().collect();
assert_eq!(digs.len(), 2, "duplicate sequence must dedup to 2 entries");
let seqs = collect_seq_files(dir.path());
assert_eq!(seqs.len(), 2, "duplicate sequence must dedup to 2 .seq files");
let key = meta.digest.to_key();
let names = store.t_names(&key);
assert_eq!(names, vec!["dupA", "uniq", "dupB"], "members keep FASTA order");
let sha = |n: &str| store.member_by_name(&meta.digest, n).unwrap().seq().sha512t24u();
assert_eq!(sha("dupA"), sha("dupB"));
assert_ne!(sha("dupA"), sha("uniq"));
}
#[test]
fn test_parallel_determinism_across_runs() {
let work = tempdir().unwrap();
let fasta = work.path().join("parity.fa");
fs::write(&fasta, PARITY_FASTA).unwrap();
let mut prev: Option<Vec<u8>> = None;
for _ in 0..3 {
let dir = tempdir().unwrap();
build_on_disk_store(dir.path(), &fasta, 8);
let rgsi = fs::read(dir.path().join("sequences.rgsi")).unwrap();
if let Some(p) = &prev {
assert_eq!(p, &rgsi, "sequences.rgsi must be identical across parallel runs");
}
prev = Some(rgsi);
}
}
fn collect_store_data_files(
dir: &std::path::Path,
) -> std::collections::BTreeMap<String, Vec<u8>> {
fn walk(
base: &std::path::Path,
cur: &std::path::Path,
out: &mut std::collections::BTreeMap<String, Vec<u8>>,
) {
for entry in std::fs::read_dir(cur).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
walk(base, &path, out);
} else {
let rel = path.strip_prefix(base).unwrap().to_string_lossy().to_string();
if rel == "rgstore.json" {
continue;
}
out.insert(rel, std::fs::read(&path).unwrap());
}
}
}
let mut out = std::collections::BTreeMap::new();
walk(dir, dir, &mut out);
out
}
fn write_gzipped(path: &std::path::Path, content: &str) {
use flate2::write::GzEncoder;
use flate2::Compression;
use std::io::Write;
let f = fs::File::create(path).unwrap();
let mut enc = GzEncoder::new(f, Compression::default());
enc.write_all(content.as_bytes()).unwrap();
enc.finish().unwrap();
}
fn build_multi(
dir: &std::path::Path,
files: &[std::path::PathBuf],
jobs: usize,
) -> Vec<String> {
let mut store = RefgetStore::on_disk(dir).unwrap();
store.set_quiet(true);
let opts = FastaImportOptions::new().jobs(jobs);
store
.add_sequence_collections_from_fastas(files, opts)
.unwrap()
.collections
.into_iter()
.map(|(m, _)| m.digest)
.collect()
}
#[test]
fn test_import_report_per_run_counters() {
let work = tempdir().unwrap();
let fa_a = work.path().join("a.fa");
let fa_b = work.path().join("b.fa");
let fa_c = work.path().join("c.fa");
fs::write(&fa_a, ">chr1\nGGAATTCCGGAATTCC\n>chr2\nACGTACGTACGTACGT\n").unwrap();
fs::write(&fa_b, ">chrX\nTTGGGGAACCCCTTTT\n>chrM\nGGGGCCCCAAAATTTT\n").unwrap();
fs::write(&fa_c, ">altchr1\nGGAATTCCGGAATTCC\n>chr9\nTACGTACGTACGTACG\n").unwrap();
let files = vec![fa_a, fa_b, fa_c];
let store_dir = tempdir().unwrap();
let mut store = RefgetStore::on_disk(store_dir.path()).unwrap();
store.set_quiet(true);
let report = store
.add_sequence_collections_from_fastas(&files, FastaImportOptions::new().jobs(4))
.unwrap();
assert_eq!(report.collections.len(), 3);
assert_eq!(report.n_collections_new, 3);
assert_eq!(report.n_sequences_written, 5);
assert_eq!(report.n_sequences_deduped, 1);
assert_eq!(
report.n_sequences_written + report.n_sequences_deduped,
6,
"written + deduped must equal the records seen"
);
assert_eq!(collect_seq_files(store_dir.path()).len(), 5);
let report2 = store
.add_sequence_collections_from_fastas(&files, FastaImportOptions::new().jobs(4))
.unwrap();
assert_eq!(report2.collections.len(), 3);
assert_eq!(report2.n_collections_new, 0);
assert_eq!(
report2.n_sequences_written, 0,
"a re-import must write no sequence bytes"
);
assert!(report2.collections.iter().all(|(_, was_new)| !*was_new));
assert_eq!(store.stats().n_sequences_in_memory, 0);
let mut mem_store = RefgetStore::in_memory();
mem_store.set_quiet(true);
let mem_report = mem_store
.add_sequence_collections_from_fastas(&files, FastaImportOptions::new().jobs(4))
.unwrap();
assert_eq!(mem_report.n_collections_new, 3);
assert_eq!(mem_report.n_sequences_written, 5);
assert_eq!(mem_report.n_sequences_deduped, 1);
}
#[test]
fn test_multifile_parallel_equals_serial() {
let work = tempdir().unwrap();
let fa_a = work.path().join("a.fa");
let fa_b = work.path().join("b.fa");
let fa_c = work.path().join("c.fa");
fs::write(&fa_a, ">chr1\nGGAATTCCGGAATTCC\n>chr2\nACGTACGTACGTACGT\n").unwrap();
fs::write(&fa_b, ">chrX\nTTGGGGAACCCCTTTT\n>chrM\nGGGGCCCCAAAATTTT\n").unwrap();
fs::write(&fa_c, ">altchr1\nGGAATTCCGGAATTCC\n>chr9\nTACGTACGTACGTACG\n").unwrap();
let files = vec![fa_a.clone(), fa_b.clone(), fa_c.clone()];
let dir_serial = tempdir().unwrap();
let dir_parallel = tempdir().unwrap();
let digests_serial = build_multi(dir_serial.path(), &files, 1);
let digests_parallel = build_multi(dir_parallel.path(), &files, 8);
assert_eq!(
digests_serial, digests_parallel,
"per-file collection digests must match in input order"
);
let serial = collect_store_data_files(dir_serial.path());
let parallel = collect_store_data_files(dir_parallel.path());
assert_eq!(
serial, parallel,
"multi-file parallel store must be byte-identical to serial store"
);
let seqs = collect_seq_files(dir_serial.path());
assert_eq!(seqs.len(), 5, "shared chr1 sequence must be stored once");
}
#[test]
fn test_multifile_parallel_gzipped() {
let work = tempdir().unwrap();
let fa_a = work.path().join("a.fa.gz");
let fa_b = work.path().join("b.fa.gz");
let fa_c = work.path().join("c.fa.gz");
write_gzipped(&fa_a, ">chr1\nGGAATTCCGGAATTCC\n>chr2\nACGTACGTACGTACGT\n");
write_gzipped(&fa_b, ">chrX\nTTGGGGAACCCCTTTT\n>chrM\nGGGGCCCCAAAATTTT\n");
write_gzipped(&fa_c, ">altchr1\nGGAATTCCGGAATTCC\n>chr9\nTACGTACGTACGTACG\n");
let files = vec![fa_a, fa_b, fa_c];
let dir_serial = tempdir().unwrap();
let dir_parallel = tempdir().unwrap();
let digests_serial = build_multi(dir_serial.path(), &files, 1);
let digests_parallel = build_multi(dir_parallel.path(), &files, 8);
assert_eq!(digests_serial, digests_parallel, "gzipped digests must match");
let serial = collect_store_data_files(dir_serial.path());
let parallel = collect_store_data_files(dir_parallel.path());
assert_eq!(
serial, parallel,
"gzipped multi-file parallel store must be byte-identical to serial"
);
}
#[test]
fn test_resume_skips_present_collection_before_decoding_fasta() {
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path();
let fasta_path = temp_path.join("genome.fa");
fs::write(
&fasta_path,
">chr1\nACGTACGTACGTACGT\n>chr2\nTTTTGGGGCCCCAAAA\n",
)
.unwrap();
let cache_path = temp_path.join("store");
let mut store = RefgetStore::on_disk(&cache_path).unwrap();
let (meta_first, was_new_first) = store
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new().jobs(4))
.unwrap();
assert!(was_new_first, "first import must add a new collection");
let rgsi_sidecar = temp_path.join("genome.rgsi");
assert!(
rgsi_sidecar.exists(),
"first import must write the sibling .rgsi cache"
);
let (_meta_forced, was_new_forced) = store
.add_sequence_collection_from_fasta(
&fasta_path,
FastaImportOptions::new().jobs(4).force(true),
)
.expect("forced re-import of an intact FASTA must succeed");
assert!(
was_new_forced,
"--force must bypass the skip and re-process the present collection (was_new = true)"
);
let collections_before: Vec<DigestKey> = {
let mut v: Vec<DigestKey> = store.t_coll_keys().into_iter().collect();
v.sort();
v
};
let sequences_before: Vec<DigestKey> = {
let mut v: Vec<DigestKey> = store.sequence_digests().collect();
v.sort();
v
};
fs::write(&fasta_path, b">totally_bogus_name_not_in_cache\nNNNNNNNN\n").unwrap();
let (meta_resume, was_new_resume) = store
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new().jobs(4))
.expect(
"resume must succeed: a present collection with an intact .rgsi must be skipped \
BEFORE the (now-corrupt) FASTA is opened/decoded",
);
assert!(
!was_new_resume,
"resume of an already-present collection must report was_new = false"
);
assert_eq!(
meta_resume.digest, meta_first.digest,
"resume must report the same collection digest from the cached .rgsi"
);
let collections_after: Vec<DigestKey> = {
let mut v: Vec<DigestKey> = store.t_coll_keys().into_iter().collect();
v.sort();
v
};
let sequences_after: Vec<DigestKey> = {
let mut v: Vec<DigestKey> = store.sequence_digests().collect();
v.sort();
v
};
assert_eq!(
collections_before, collections_after,
"resume must not change the set of collections"
);
assert_eq!(
sequences_before, sequences_after,
"resume must not change the set of sequences"
);
}
fn write_many_tiny_fasta(path: &std::path::Path, n: usize) {
use std::io::Write;
const BASES: [u8; 4] = [b'A', b'C', b'G', b'T'];
let f = fs::File::create(path).unwrap();
let mut w = std::io::BufWriter::new(f);
for i in 0..n {
let mut seq = [b'A'; 16];
let mut v = i;
let mut p = 15usize;
while v > 0 {
seq[p] = BASES[v & 0b11];
v >>= 2;
p = p.wrapping_sub(1);
}
writeln!(w, ">seq{}", i).unwrap();
w.write_all(&seq).unwrap();
w.write_all(b"\n").unwrap();
}
w.flush().unwrap();
}
#[test]
fn test_many_tiny_sequences_throughput() {
let work = tempdir().unwrap();
let fasta = work.path().join("tiny.fa");
let n = 100_000usize;
write_many_tiny_fasta(&fasta, n);
let dir = tempdir().unwrap();
let start = std::time::Instant::now();
let mut store = RefgetStore::on_disk(dir.path()).unwrap();
store.set_quiet(true);
let (meta, was_new) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(4))
.unwrap();
let elapsed = start.elapsed();
assert!(was_new, "collection must be new");
assert_eq!(
meta.n_sequences, n,
"all {} distinct sequences must be registered",
n
);
let seqs = collect_seq_files(dir.path());
assert_eq!(
seqs.len(),
n,
"every distinct tiny sequence must have a .seq file on disk after the barrier"
);
assert!(
elapsed.as_secs() < 60,
"building {} tiny sequences took {:?}; expected well under the single-inserter bound",
n,
elapsed
);
eprintln!(
"throughput: built {} tiny seqs in {:?} ({:.0} seqs/sec)",
n,
elapsed,
n as f64 / elapsed.as_secs_f64()
);
}
fn first_seq_digest(store: &RefgetStore) -> String {
store
.t_seq_map()
.into_values()
.next()
.unwrap()
.metadata()
.sha512t24u
.clone()
}
fn first_seq_length(store: &RefgetStore) -> usize {
store
.t_seq_map()
.into_values()
.next()
.unwrap()
.metadata()
.length
}
fn build_on_disk_store_streaming(mode: StorageMode) -> (tempfile::TempDir, RefgetStore, String, usize) {
let dir = tempdir().unwrap();
let fasta = dir.path().join("test.fa");
fs::write(&fasta, ">chr1\nACGTACGTACGTACGTACGT\n").unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store.set_encoding_mode(mode).unwrap();
store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = first_seq_digest(&store);
let length = first_seq_length(&store);
(dir, store, digest, length)
}
#[test]
fn test_stream_sequence_local_full() {
use std::io::Read;
let (_dir, store, digest, length) = build_on_disk_store_streaming(StorageMode::Encoded);
let mut reader = store.stream_sequence(&digest, None, None).unwrap();
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(out.len(), length);
assert_eq!(&out[..], b"ACGTACGTACGTACGTACGT");
}
#[test]
fn test_stream_sequence_local_substring() {
use std::io::Read;
let (_dir, mut store, digest, length) = build_on_disk_store_streaming(StorageMode::Encoded);
store.load_sequence(&digest).unwrap();
let ranges: Vec<(u64, u64)> = vec![
(0, 4),
(1, 5),
(2, 10),
(5, 6),
(0, length as u64),
(length as u64 - 1, length as u64),
];
for (s, e) in ranges {
let mut reader = store.stream_sequence(&digest, Some(s), Some(e)).unwrap();
let mut streamed = Vec::new();
reader.read_to_end(&mut streamed).unwrap();
let expected = store.get_substring(&digest, s as usize, e as usize).unwrap();
assert_eq!(
String::from_utf8(streamed).unwrap(),
expected,
"mismatch for range {}..{}",
s,
e
);
}
}
fn zstd_test_sequence() -> Vec<u8> {
let mut s = Vec::new();
for _ in 0..2000 {
s.extend_from_slice(b"ACGTAACCGGTT");
}
let motifs: [&[u8]; 4] = [b"GATTACA", b"TTAGGGTT", b"CCCGGGAAA", b"ACGTN"];
for i in 0..1000 {
s.extend_from_slice(motifs[i % motifs.len()]);
}
s
}
fn build_zstd_roundtrip_store(
mode: StorageMode,
name: &str,
ascii: &[u8],
) -> (tempfile::TempDir, RefgetStore, String) {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store.set_encoding_mode(mode).unwrap();
let record = crate::digest::digest_sequence(name, ascii);
let digest = record.metadata().sha512t24u.clone();
let record = if mode == StorageMode::Encoded {
match record {
SequenceRecord::Full { metadata, sequence } => {
let alphabet = crate::digest::lookup_alphabet(&metadata.alphabet);
let packed = crate::digest::encode_sequence(&sequence[..], alphabet).unwrap();
SequenceRecord::Full { metadata, sequence: packed.into() }
}
other => other,
}
} else {
record
};
store.add_sequence_record(record, false).unwrap();
store.write().unwrap();
(dir, store, digest)
}
#[test]
fn test_zstd_roundtrip_matches_encoded() {
let ascii = zstd_test_sequence();
let len = ascii.len();
let (_zdir, zstore, zdigest) =
build_zstd_roundtrip_store(StorageMode::Zstd, "chrZ", &ascii);
let (_edir, estore, edigest) =
build_zstd_roundtrip_store(StorageMode::Encoded, "chrZ", &ascii);
assert_eq!(zdigest, edigest, "digest must be mode-independent");
let windows: Vec<(usize, usize)> = vec![
(0, 1),
(0, 12),
(5, 37),
(11, 24),
(100, 1000),
(len / 2, len / 2 + 4321),
(len - 1, len),
(len - 500, len),
(0, len),
(7, 7), ];
for &(s, e) in &windows {
let z = zstore.get_substring(&zdigest, s, e).unwrap();
let expect = std::str::from_utf8(&ascii[s..e]).unwrap();
assert_eq!(z, expect, "zstd disk get_substring mismatch at {}..{}", s, e);
let en = estore.get_substring(&edigest, s, e).unwrap();
assert_eq!(z, en, "zstd vs encoded mismatch at {}..{}", s, e);
}
let batch: Vec<(usize, usize)> = windows.iter().copied().filter(|&(s, e)| s != e).collect();
let zb = zstore.get_substrings(&zdigest, &batch).unwrap();
for (i, &(s, e)) in batch.iter().enumerate() {
assert_eq!(zb[i], std::str::from_utf8(&ascii[s..e]).unwrap());
}
}
#[test]
fn test_zstd_roundtrip_resident_and_stream() {
use std::io::Read;
let ascii = zstd_test_sequence();
let len = ascii.len();
let (_zdir, mut zstore, zdigest) =
build_zstd_roundtrip_store(StorageMode::Zstd, "chrZ", &ascii);
zstore.load_sequence(&zdigest).unwrap();
let windows: Vec<(usize, usize)> = vec![(0, 12), (11, 5000), (len - 3, len), (0, len)];
for &(s, e) in &windows {
let got = zstore.get_substring(&zdigest, s, e).unwrap();
assert_eq!(got, std::str::from_utf8(&ascii[s..e]).unwrap());
}
for &(s, e) in &windows {
let mut reader = zstore
.stream_sequence(&zdigest, Some(s as u64), Some(e as u64))
.unwrap();
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(&out[..], &ascii[s..e], "zstd stream mismatch at {}..{}", s, e);
}
}
struct XorShift(u64);
impl XorShift {
fn new(seed: u64) -> Self {
XorShift(seed | 1)
}
fn next_u64(&mut self) -> u64 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.0 = x;
x
}
fn range(&mut self, n: usize) -> usize {
(self.next_u64() % n as u64) as usize
}
}
fn multi_seq_fasta() -> String {
let bases = [b'A', b'C', b'G', b'T'];
let mut out = String::new();
for (i, len) in [400usize, 333, 512, 271, 600].iter().enumerate() {
out.push_str(&format!(">seq{}\n", i));
let mut s = String::with_capacity(*len);
for j in 0..*len {
s.push(bases[(i * 7 + j * 3 + (j / 5)) % 4] as char);
}
out.push_str(&s);
out.push('\n');
}
out
}
fn run_fd_cache_eviction_for_mode(raw: bool) {
let temp_dir = tempdir().unwrap();
let fasta_content = multi_seq_fasta();
let fasta = temp_dir.path().join("multi.fa");
fs::write(&fasta, &fasta_content).unwrap();
let store_path = temp_dir.path().join("store");
let mut builder = RefgetStore::on_disk(&store_path).unwrap();
if raw {
builder.disable_encoding();
}
let (coll_meta, _) = builder
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let coll_digest = coll_meta.digest.clone();
drop(builder);
let mut resident = RefgetStore::open_local(&store_path).unwrap();
resident.set_quiet(true);
resident.load_all_collections().unwrap();
resident.load_all_sequences().unwrap();
let mut partial = RefgetStore::open_local(&store_path).unwrap();
partial.set_quiet(true);
partial.load_all_collections().unwrap();
partial.set_seq_fd_cache_cap_for_test(2);
let names: Vec<String> = (0..5).map(|i| format!("seq{}", i)).collect();
let mut seqs: Vec<(String, usize)> = Vec::new();
for name in &names {
let rec = resident.get_sequence_by_name(&coll_digest, name).unwrap();
seqs.push((rec.metadata().sha512t24u.clone(), rec.metadata().length));
}
assert!(seqs.len() > 2, "need >2 sequences to force eviction with cap 2");
let mut rng = XorShift::new(0xC0FFEE_u64 ^ (raw as u64));
for _ in 0..2000 {
let (digest, len) = &seqs[rng.range(seqs.len())];
let len = *len;
let a = rng.range(len);
let b = rng.range(len);
let (start, end) = if a == b {
(a.min(len - 1), a.min(len - 1) + 1)
} else {
(a.min(b), a.max(b))
};
let expected = resident.get_substring(digest, start, end).unwrap();
let got = partial.get_substring(digest, start, end).unwrap();
assert_eq!(
got, expected,
"partial-read mismatch (raw={}) digest={} [{}, {})",
raw, digest, start, end
);
}
}
#[test]
fn test_stream_sequence_raw_mode() {
use std::io::Read;
let (_dir, store, digest, length) = build_on_disk_store_streaming(StorageMode::Raw);
let mut reader = store.stream_sequence(&digest, Some(2), Some(8)).unwrap();
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(&out[..], b"GTACGT");
assert!(length >= 8);
}
#[test]
fn test_stream_sequence_u64_bounds_compile_and_match() {
use std::io::Read;
let (_dir, store, digest, _length) = build_on_disk_store_streaming(StorageMode::Encoded);
let s: u64 = 0;
let e: u64 = 8;
let mut reader = store.stream_sequence(&digest, Some(s), Some(e)).unwrap();
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(out.len(), 8);
}
#[test]
fn test_stream_sequence_zero_length() {
use std::io::Read;
let (_dir, store, digest, _) = build_on_disk_store_streaming(StorageMode::Encoded);
let mut reader = store.stream_sequence(&digest, Some(5), Some(5)).unwrap();
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert!(out.is_empty());
}
#[test]
fn test_stream_sequence_invalid_range() {
let (_dir, store, digest, length) = build_on_disk_store_streaming(StorageMode::Encoded);
assert!(store.stream_sequence(&digest, Some(5), Some(3)).is_err());
assert!(
store
.stream_sequence(&digest, Some(0), Some(length as u64 + 1))
.is_err()
);
}
#[test]
fn test_stream_sequence_bounded_memory() {
use std::io::Read;
let dir = tempdir().unwrap();
let fasta = dir.path().join("big.fa");
let mut content = String::from(">chr1\n");
let bases = [b'A', b'C', b'G', b'T'];
let mut seq = Vec::with_capacity(1_000_000);
for i in 0..1_000_000 {
seq.push(bases[i % 4]);
}
content.push_str(std::str::from_utf8(&seq).unwrap());
content.push('\n');
fs::write(&fasta, &content).unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = first_seq_digest(&store);
let mut reader = store.stream_sequence(&digest, None, None).unwrap();
let mut buf = [0u8; 4096];
let mut collected = Vec::with_capacity(1_000_000);
loop {
let n = reader.read(&mut buf).unwrap();
if n == 0 {
break;
}
collected.extend_from_slice(&buf[..n]);
}
assert_eq!(collected, seq);
}
#[global_allocator]
static PEAK_ALLOC: peak_alloc::PeakAlloc = peak_alloc::PeakAlloc;
static ALLOC_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
#[ignore = "allocation profiling: process-global PeakAlloc; run with --ignored --test-threads=1"]
fn test_stream_sequence_bounded_memory_full_record() {
use std::io::Read;
let _guard = ALLOC_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());
const SEQ_LEN: usize = 1_000_000;
let dir = tempdir().unwrap();
let fasta = dir.path().join("big.fa");
let bases = [b'A', b'C', b'G', b'T'];
let mut seq = Vec::with_capacity(SEQ_LEN);
for i in 0..SEQ_LEN {
seq.push(bases[i % 4]);
}
let mut content = String::from(">chr1\n");
content.push_str(std::str::from_utf8(&seq).unwrap());
content.push('\n');
fs::write(&fasta, &content).unwrap();
let mut store = RefgetStore::in_memory();
store.set_encoding_mode(StorageMode::Raw).unwrap();
store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let digest = first_seq_digest(&store);
{
use crate::hashkeyable::HashKeyable;
let key = digest.to_key();
let rec = store.t_seq(&key).unwrap();
assert!(rec.is_loaded(), "expected Full record for in-memory store");
}
PEAK_ALLOC.reset_peak_usage();
let baseline = PEAK_ALLOC.current_usage();
{
let mut reader = store.stream_sequence(&digest, None, None).unwrap();
let mut chunk = [0u8; 4096];
let mut total = 0usize;
loop {
let n = reader.read(&mut chunk).unwrap();
if n == 0 {
break;
}
total += n;
}
assert_eq!(total, SEQ_LEN);
}
let peak = PEAK_ALLOC.peak_usage();
let peak_delta = peak.saturating_sub(baseline);
let bound: usize = SEQ_LEN / 4; assert!(
peak_delta < bound,
"stream_sequence peak allocation delta {} bytes exceeds bound {} bytes \
(SEQ_LEN={} bytes raw). \
Streaming is cloning the buffer instead of sharing ownership.",
peak_delta,
bound,
SEQ_LEN,
);
}
#[test]
#[ignore = "allocation profiling: process-global PeakAlloc; run with --ignored --test-threads=1"]
fn test_stream_sequence_bounded_memory_stub_record() {
use std::io::Read;
use crate::hashkeyable::HashKeyable;
let _guard = ALLOC_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());
for &SEQ_LEN in &[1_000_000usize, 16_000_000] {
let dir = tempdir().unwrap();
let fasta = dir.path().join("big.fa");
let bases = [b'A', b'C', b'G', b'T'];
let mut seq = Vec::with_capacity(SEQ_LEN);
for i in 0..SEQ_LEN {
seq.push(bases[i % 4]);
}
let mut content = String::from(">chr1\n");
content.push_str(std::str::from_utf8(&seq).unwrap());
content.push('\n');
fs::write(&fasta, &content).unwrap();
let store_path = dir.path().join("store");
let digest;
{
let mut builder = RefgetStore::on_disk(&store_path).unwrap();
builder.set_encoding_mode(StorageMode::Raw).unwrap();
builder
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
digest = first_seq_digest(&builder);
}
let store = RefgetStore::open_local(&store_path).unwrap();
{
let key = digest.to_key();
let rec = store.inner.t_seq(&key).unwrap();
assert!(
!rec.is_loaded(),
"expected Stub record after open_local, got Full"
);
}
PEAK_ALLOC.reset_peak_usage();
let baseline = PEAK_ALLOC.current_usage();
let mut reader = store.stream_sequence(&digest, None, None).unwrap();
let mut scratch = [0u8; 8192];
let mut total = 0usize;
let mut checksum: u64 = 0;
loop {
let n = reader.read(&mut scratch).unwrap();
if n == 0 { break; }
for &b in &scratch[..n] { checksum = checksum.wrapping_add(b as u64); }
total += n;
}
let peak = PEAK_ALLOC.peak_usage();
let peak_delta = peak.saturating_sub(baseline);
assert_eq!(total, SEQ_LEN);
let expected_checksum: u64 = seq.iter().map(|&b| b as u64).sum();
assert_eq!(checksum, expected_checksum);
assert!(
peak_delta < 64 * 1024,
"stream_sequence (Stub path) peak allocation {} bytes exceeds \
64 KiB at SEQ_LEN={} — streaming is not O(1) in sequence size",
peak_delta, SEQ_LEN,
);
}
}
#[test]
fn test_stream_sequence_no_preload_for_stub_record() {
use std::io::Read;
use crate::hashkeyable::HashKeyable;
let (_dir, store, digest, length) = build_on_disk_store_streaming(StorageMode::Encoded);
let mut store = store;
{
let key = digest.to_key();
let row = store.inner.catalog.find_sha(&key).unwrap();
store.inner.loaded.remove(&row);
}
{
let key = digest.to_key();
let rec = store.inner.t_seq(&key).unwrap();
assert!(!rec.is_loaded(), "expected Stub before stream_sequence");
}
let mut reader = store.stream_sequence(&digest, None, None).unwrap();
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(out.len(), length);
assert_eq!(&out[..], b"ACGTACGTACGTACGTACGT");
let key = digest.to_key();
let rec = store.inner.t_seq(&key).unwrap();
assert!(
!rec.is_loaded(),
"stream_sequence must not populate the in-memory Full record"
);
}
#[test]
fn test_list_collections_without_sequence_index() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta_content = ">chr1\nATGCATGC\n>chr2\nGGGGAAAA\n";
let fasta_path = dir.path().join("test.fa");
fs::write(&fasta_path, fasta_content).unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new()).unwrap();
let mut store = RefgetStore::open_local(&store_path).unwrap();
store.inner.t_clear_sequences();
store.inner.sequence_index_loaded = false;
store.inner.sequence_index_path = Some("sequences.rgsi".to_string());
let result = store.list_collections(0, 100, &[]).unwrap();
assert_eq!(result.results.len(), 1, "Should find 1 collection");
assert!(!store.inner.sequence_index_loaded, "Sequence index should NOT be loaded after list_collections");
}
#[test]
fn test_load_all_sequences_triggers_index_load() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta_content = ">chr1\nATGCATGC\n";
let fasta_path = dir.path().join("test.fa");
fs::write(&fasta_path, fasta_content).unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new()).unwrap();
let mut store = RefgetStore::open_local(&store_path).unwrap();
store.inner.t_clear_sequences();
store.inner.sequence_index_loaded = false;
store.inner.sequence_index_path = Some("sequences.rgsi".to_string());
assert!(!store.inner.sequence_index_loaded);
store.load_all_sequences().unwrap();
assert!(store.inner.sequence_index_loaded, "Sequence index should be loaded after load_all_sequences");
assert!(store.inner.catalog.n_sequences() > 0, "Sequences should be populated");
}
#[test]
fn test_lazy_sequence_reads_load_only_requested_records() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta_path = dir.path().join("test.fa");
fs::write(&fasta_path, ">chr1\nATGCATGC\n>chr2\nGGGGAAAA\n").unwrap();
let mut writer = RefgetStore::on_disk(&store_path).unwrap();
let (collection, _) = writer
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
.unwrap();
let first = writer
.get_sequence_by_name(&collection.digest, "chr1")
.unwrap()
.metadata()
.clone();
let second = writer
.get_sequence_by_name(&collection.digest, "chr2")
.unwrap()
.metadata()
.clone();
drop(writer);
let mut store = RefgetStore::open_local(&store_path).unwrap();
store.inner.t_clear_sequences();
store.inner.sequence_index_loaded = false;
store.inner.sequence_index_path = Some("sequences.rgsi".to_string());
let by_name = store
.get_sequence_by_name(&collection.digest, "chr1")
.unwrap();
assert_eq!(by_name.metadata().name, "chr1");
assert!(by_name.is_loaded());
assert!(!store.inner.sequence_index_loaded);
assert!(store.inner.is_sequence_loaded(&first.sha512t24u));
assert!(!store.inner.is_sequence_loaded(&second.sha512t24u));
let listed = store.list_sequences().unwrap();
assert_eq!(listed.len(), 2);
assert!(store.inner.sequence_index_loaded);
assert!(store.inner.is_sequence_loaded(&first.sha512t24u));
assert!(!store.inner.is_sequence_loaded(&second.sha512t24u));
let by_md5 = store.get_sequence(&second.md5).unwrap();
assert!(by_md5.is_loaded());
assert_eq!(by_md5.metadata().name, "chr2");
assert!(store.inner.is_sequence_loaded(&second.sha512t24u));
}
#[test]
fn test_export_fasta_streams_without_loading_from_deferred_state() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta_path = dir.path().join("test.fa");
fs::write(&fasta_path, ">chr1\nATGCATGC\n>chr2\nGGGGAAAA\n").unwrap();
let mut writer = RefgetStore::on_disk(&store_path).unwrap();
let (collection, _) = writer
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
.unwrap();
let first = writer
.get_sequence_by_name(&collection.digest, "chr1")
.unwrap()
.metadata()
.clone();
let second = writer
.get_sequence_by_name(&collection.digest, "chr2")
.unwrap()
.metadata()
.clone();
drop(writer);
let mut store = RefgetStore::open_local(&store_path).unwrap();
store.inner.t_clear_sequences();
store.inner.sequence_index_loaded = false;
store.inner.sequence_index_path = Some("sequences.rgsi".to_string());
assert!(!store.inner.is_sequence_loaded(&first.sha512t24u));
assert!(!store.inner.is_sequence_loaded(&second.sha512t24u));
let output_path = dir.path().join("export_chr1.fa");
store
.export_fasta(&coll_sel(&collection.digest, Some(&["chr1"])), &output_path, &name_opts(80))
.expect("export_fasta should stream the requested sequence");
let exported = fs::read_to_string(&output_path).unwrap();
assert!(exported.contains(">chr1"));
assert!(exported.contains("ATGCATGC"));
assert!(!exported.contains(">chr2"));
assert!(store.inner.sequence_index_loaded);
assert!(
!store.inner.is_sequence_loaded(&first.sha512t24u),
"chr1 should stay unloaded: export streams it"
);
assert!(!store.inner.is_sequence_loaded(&second.sha512t24u));
}
#[test]
fn test_export_fasta_duplicate_named_sequences() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta_path = dir.path().join("dup.fa");
fs::write(&fasta_path, ">dup\nAAAA\n>dup\nCCCC\n").unwrap();
let mut writer = RefgetStore::on_disk(&store_path).unwrap();
let (collection, _) = writer
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
.unwrap();
drop(writer);
let mut store = RefgetStore::open_local(&store_path).unwrap();
let output_path = dir.path().join("dup_out.fa");
let err = store
.export_fasta(&coll_sel(&collection.digest, Some(&["dup"])), &output_path, &name_opts(80))
.unwrap_err()
.to_string();
assert!(err.contains("'dup'") && err.contains("{col}"), "{err}");
store
.export_fasta(&coll_sel(&collection.digest, Some(&["dup"])), &output_path, &ExportOptions::default())
.expect("digest labels are unique");
let out = fs::read_to_string(&output_path).unwrap();
assert_eq!(out.matches(">SQ.").count(), 2);
assert!(out.contains("AAAA") && out.contains("CCCC"));
let bed = dir.path().join("dup.bed");
fs::write(&bed, "dup\t0\t4\n").unwrap();
let out_str = output_path.to_str().unwrap();
store
.export_fasta_from_regions(&collection.digest, bed.to_str().unwrap(), out_str, &LabelTemplate::default())
.unwrap();
let out = fs::read_to_string(&output_path).unwrap();
let (header, bases) = out.trim_end().split_once('\n').unwrap();
let digest = header.trim_start_matches(">SQ.").split(':').next().unwrap();
assert_eq!(bases, "CCCC");
assert_eq!(store.get_substring(digest, 0, 4).unwrap(), bases);
}
#[test]
fn test_open_remote_uses_cached_manifest_when_offline() {
let remote_url = "http://127.0.0.1:1/store";
let dir = tempdir().unwrap();
let cache_path = dir.path().join("cache");
let fasta_path = dir.path().join("test.fa");
fs::write(&fasta_path, ">chr1\nATGCATGC\n").unwrap();
assert!(RefgetStore::open_remote(dir.path().join("empty"), remote_url).is_err());
let mut writer = RefgetStore::on_disk(&cache_path).unwrap();
let (collection, _) = writer
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
.unwrap();
drop(writer);
fs::write(cache_path.join(".origin"), format!("{}\n", remote_url)).unwrap();
let mut store = RefgetStore::open_remote(&cache_path, remote_url)
.expect("a cached remote store should open offline");
let seq = store
.get_sequence_by_name(&collection.digest, "chr1")
.unwrap();
assert!(seq.is_loaded());
}
#[test]
fn test_remote_lookups_accept_prefixed_and_md5_digests() {
let remote_url = "http://127.0.0.1:1/store";
let dir = tempdir().unwrap();
let cache_path = dir.path().join("cache");
let fasta_path = dir.path().join("test.fa");
fs::write(&fasta_path, ">chr1\nATGCATGC\n").unwrap();
let mut writer = RefgetStore::on_disk(&cache_path).unwrap();
writer
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
.unwrap();
drop(writer);
fs::write(cache_path.join(".origin"), format!("{}\n", remote_url)).unwrap();
let (sha_digest, md5_digest) = calculate_test_digests(b"ATGCATGC");
let sq_digest = format!("SQ.{}", sha_digest);
let fresh = || {
let store = RefgetStore::open_remote(&cache_path, remote_url).unwrap();
assert!(!store.inner.sequence_index_loaded);
store
};
let mut store = fresh();
store.load_sequence(&sq_digest).unwrap();
assert!(store.inner.is_sequence_loaded(&sha_digest));
let mut store = fresh();
store.load_sequence(&md5_digest).unwrap();
assert!(store.inner.is_sequence_loaded(&sha_digest));
assert!(fresh().get_sequence(&sq_digest).unwrap().is_loaded());
}
#[test]
fn test_fd_cache_eviction_matches_resident_encoded() {
run_fd_cache_eviction_for_mode(false);
}
#[test]
fn test_fd_cache_eviction_matches_resident_raw() {
run_fd_cache_eviction_for_mode(true);
}
fn run_get_substrings_matches_for_mode(raw: bool) {
let temp_dir = tempdir().unwrap();
let fasta_content = multi_seq_fasta();
let fasta = temp_dir.path().join("multi.fa");
fs::write(&fasta, &fasta_content).unwrap();
let store_path = temp_dir.path().join("store");
let mut builder = RefgetStore::on_disk(&store_path).unwrap();
if raw {
builder.disable_encoding();
}
let (coll_meta, _) = builder
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
let coll_digest = coll_meta.digest.clone();
drop(builder);
let mut resident = RefgetStore::open_local(&store_path).unwrap();
resident.set_quiet(true);
resident.load_all_collections().unwrap();
resident.load_all_sequences().unwrap();
let mut disk = RefgetStore::open_local(&store_path).unwrap();
disk.set_quiet(true);
disk.load_all_collections().unwrap();
let rec = resident.get_sequence_by_name(&coll_digest, "seq0").unwrap();
let digest = rec.metadata().sha512t24u.clone();
let len = rec.metadata().length;
assert_eq!(len, 400);
let sparse: Vec<(usize, usize)> = vec![
(0, 3),
(10, 14),
(50, 51),
(100, 105),
(200, 202),
(399, 400),
];
let sparse_total: usize = sparse.iter().map(|&(s, e)| e - s).sum();
assert!((sparse_total as f64) < 0.125 * (len as f64), "branch A must be partial");
let wide: Vec<(usize, usize)> = vec![
(0, 200),
(100, 350),
(50, 400),
(10, 390),
];
let wide_total: usize = wide.iter().map(|&(s, e)| e - s).sum();
assert!((wide_total as f64) >= 0.125 * (len as f64), "branch B must be whole-decode");
for ranges in [&sparse, &wide] {
let expected_resident: Vec<String> = ranges
.iter()
.map(|&(s, e)| resident.get_substring(&digest, s, e).unwrap())
.collect();
let expected_disk_loop: Vec<String> = ranges
.iter()
.map(|&(s, e)| disk.get_substring(&digest, s, e).unwrap())
.collect();
let batch = disk.get_substrings(&digest, ranges).unwrap();
assert_eq!(
batch, expected_resident,
"batch != resident (raw={}) ranges={:?}",
raw, ranges
);
assert_eq!(
batch, expected_disk_loop,
"batch != disk loop (raw={}) ranges={:?}",
raw, ranges
);
}
let batch_resident = resident.get_substrings(&digest, &wide).unwrap();
let expected: Vec<String> = wide
.iter()
.map(|&(s, e)| resident.get_substring(&digest, s, e).unwrap())
.collect();
assert_eq!(batch_resident, expected, "resident Full-arm batch mismatch (raw={})", raw);
assert!(disk.get_substrings(&digest, &[(0, len + 1)]).is_err());
}
#[test]
fn test_get_substrings_matches_encoded() {
run_get_substrings_matches_for_mode(false);
}
#[test]
fn test_get_substrings_matches_raw() {
run_get_substrings_matches_for_mode(true);
}
#[test]
fn test_import_without_collection_alias_registers_none() {
let dir = tempdir().unwrap();
let fasta = copy_test_fasta(dir.path(), "base.fa");
let mut store = RefgetStore::in_memory();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
assert!(
store.list_collection_alias_namespaces().is_empty(),
"plain import must not create any collection alias namespace"
);
assert!(
store.get_aliases_for_collection(&meta.digest).is_empty(),
"plain import must not name the collection"
);
}
#[test]
fn test_import_without_collection_alias_but_with_namespaces() {
let dir = tempdir().unwrap();
let fasta = dir.path().join("ns.fa");
fs::write(&fasta, ">chr1 ucsc:chr1\nAAAACCCC\n>chr2 ucsc:chr2\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::in_memory();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().namespaces(&["ucsc"]))
.unwrap();
let seq_aliases = store
.list_sequence_aliases("ucsc")
.expect("ucsc sequence alias namespace should exist");
assert!(!seq_aliases.is_empty(), "header aliases should be registered");
assert!(
store.list_collection_alias_namespaces().is_empty(),
"namespaces must not leak into the collection alias index"
);
assert!(store.get_aliases_for_collection(&meta.digest).is_empty());
}
#[test]
fn test_import_with_collection_alias_registers_collection_alias() {
let dir = tempdir().unwrap();
let fasta = copy_test_fasta(dir.path(), "base.fa");
let mut store = RefgetStore::in_memory();
let (meta, _) = store
.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
let resolved = store
.get_collection_metadata_by_alias("ucsc", "hg38")
.expect("ucsc:hg38 should resolve");
assert_eq!(resolved.digest, meta.digest);
assert!(
store.list_sequence_alias_namespaces().is_empty(),
"collection alias must not leak into the sequence alias index"
);
}
#[test]
fn test_collection_alias_without_namespaces() {
let dir = tempdir().unwrap();
let fasta = dir.path().join("bare.fa");
fs::write(&fasta, ">chr1\nAAAACCCC\n>chr2\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::in_memory();
let opts = FastaImportOptions::new().collection_alias("ucsc", "hg38");
assert!(opts.namespaces.is_empty(), "namespaces deliberately unset");
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, opts)
.unwrap();
let resolved = store
.get_collection_metadata_by_alias("ucsc", "hg38")
.expect("ucsc:hg38 should resolve without namespaces set");
assert_eq!(resolved.digest, meta.digest);
}
#[test]
fn test_collection_alias_persists_to_disk() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta = copy_test_fasta(dir.path(), "base.fa");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
store.write().unwrap();
let tsv = store_path.join("aliases").join("collections").join("ucsc.tsv");
assert!(tsv.exists(), "collection alias TSV should be written");
let contents = fs::read_to_string(&tsv).unwrap();
assert!(
contents.contains(&format!("hg38\t{}", meta.digest)),
"TSV should map hg38 to the collection digest, got: {}",
contents
);
let manifest_json: serde_json::Value =
serde_json::from_str(&fs::read_to_string(store_path.join("rgstore.json")).unwrap()).unwrap();
let coll_ns = manifest_json
.get("collection_alias_namespaces")
.and_then(|v| v.as_array())
.expect("rgstore.json should carry collection_alias_namespaces");
assert!(
coll_ns.iter().any(|v| v.as_str() == Some("ucsc")),
"rgstore.json should advertise the ucsc collection alias namespace, got {:?}",
coll_ns
);
assert!(
manifest_json
.get("sequence_alias_namespaces")
.and_then(|v| v.as_array())
.map(|a| a.is_empty())
.unwrap_or(true),
"no sequence alias namespaces should be advertised"
);
let manifest = store.store_metadata().unwrap();
assert!(
manifest.get("aliases_digest").is_some(),
"rgstore.json should carry an aliases_digest"
);
let reopened = RefgetStore::open_local(&store_path).unwrap();
let resolved = reopened
.get_collection_metadata_by_alias("ucsc", "hg38")
.expect("alias should survive a reopen");
assert_eq!(resolved.digest, meta.digest);
}
#[test]
fn test_collection_alias_idempotent_on_reimport() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta = copy_test_fasta(dir.path(), "base.fa");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta1, was_new1) = store
.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
assert!(was_new1);
let (meta2, was_new2) = store
.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
assert!(!was_new2, "second import of the same FASTA is not new");
assert_eq!(meta2.digest, meta1.digest);
assert_eq!(
store
.get_collection_metadata_by_alias("ucsc", "hg38")
.unwrap()
.digest,
meta1.digest
);
store.write().unwrap();
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
let (meta3, was_new3) = reopened
.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
assert!(!was_new3, "already-present collection should be skipped");
assert_eq!(meta3.digest, meta1.digest);
assert_eq!(
reopened
.get_collection_metadata_by_alias("ucsc", "hg38")
.unwrap()
.digest,
meta1.digest
);
}
#[test]
fn test_collection_alias_registered_on_build_side_skip() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta = copy_test_fasta(dir.path(), "base.fa");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
store.write().unwrap();
assert!(store.list_collection_alias_namespaces().is_empty());
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
let (_, was_new) = reopened
.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
assert!(!was_new, "collection was already present");
assert_eq!(
reopened
.get_collection_metadata_by_alias("ucsc", "hg38")
.expect("alias must be registered even on the skip path")
.digest,
meta.digest
);
}
#[test]
fn test_collection_alias_conflict_errors() {
let dir = tempdir().unwrap();
let fasta_a = dir.path().join("a.fa");
fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::in_memory();
let (meta_a, _) = store
.add_sequence_collection_from_fasta(
&fasta_a,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
let err = store
.add_sequence_collection_from_fasta(
&fasta_b,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.expect_err("conflicting alias must error");
let msg = format!("{}", err);
assert!(msg.contains("ucsc"), "error should name the namespace: {}", msg);
assert!(msg.contains("hg38"), "error should name the alias: {}", msg);
assert_eq!(
store
.get_collection_metadata_by_alias("ucsc", "hg38")
.unwrap()
.digest,
meta_a.digest
);
}
#[test]
fn test_collection_alias_conflict_does_not_leak_collection() {
let dir = tempdir().unwrap();
let fasta_a = dir.path().join("a.fa");
fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::in_memory();
let (meta_a, _) = store
.add_sequence_collection_from_fasta(
&fasta_a,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
assert_eq!(store.catalog.n_collections(), 1);
store
.add_sequence_collection_from_fasta(
&fasta_b,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.expect_err("conflicting alias must error");
assert_eq!(
store.catalog.n_collections(),
1,
"a failed import must not leave its collection in the store"
);
assert!(
store.t_has_coll(&meta_a.digest.to_key()),
"the surviving collection should be the one that imported successfully"
);
assert!(
store.t_n_loaded_colls() <= 1,
"no name_lookup entry should be installed for the rejected collection"
);
}
#[test]
fn test_collection_alias_conflict_leaves_no_orphan_on_disk() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta_a = dir.path().join("a.fa");
fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta_a, _) = store
.add_sequence_collection_from_fasta(
&fasta_a,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
store.write().unwrap();
store
.add_sequence_collection_from_fasta(
&fasta_b,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.expect_err("conflicting alias must error");
let coll_dir = store_path.join("collections");
let mut rgsi: Vec<String> = fs::read_dir(&coll_dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".rgsi"))
.collect();
rgsi.sort();
assert_eq!(
rgsi,
vec![format!("{}.rgsi", meta_a.digest)],
"failed import must not leave an orphaned collection .rgsi on disk"
);
assert_eq!(store.catalog.n_collections(), 1);
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
assert_eq!(reopened.catalog.n_collections(), 1);
assert_eq!(
reopened
.get_collection_metadata_by_alias("ucsc", "hg38")
.expect("alias should still resolve after the failed import")
.digest,
meta_a.digest
);
reopened
.get_collection(&meta_a.digest)
.expect("the committed collection must still load");
}
#[test]
fn test_collection_alias_conflict_force_overwrites() {
let dir = tempdir().unwrap();
let fasta_a = dir.path().join("a.fa");
fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::in_memory();
store
.add_sequence_collection_from_fasta(
&fasta_a,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
let (meta_b, _) = store
.add_sequence_collection_from_fasta(
&fasta_b,
FastaImportOptions::new()
.collection_alias("ucsc", "hg38")
.force(true),
)
.unwrap();
assert_eq!(
store
.get_collection_metadata_by_alias("ucsc", "hg38")
.unwrap()
.digest,
meta_b.digest,
"force should remap the alias to the new collection"
);
}
#[test]
fn test_collection_alias_conflict_force_overwrites_on_disk() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta_a = dir.path().join("a.fa");
fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store
.add_sequence_collection_from_fasta(
&fasta_a,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.unwrap();
store.write().unwrap();
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
let (meta_b, _) = reopened
.add_sequence_collection_from_fasta(
&fasta_b,
FastaImportOptions::new()
.collection_alias("ucsc", "hg38")
.force(true),
)
.expect("force must override the alias published on disk");
let fresh = RefgetStore::open_local(&store_path).unwrap();
assert_eq!(
fresh
.get_collection_metadata_by_alias("ucsc", "hg38")
.unwrap()
.digest,
meta_b.digest,
"the remapped alias must be what is on disk"
);
}
#[test]
fn test_failed_import_cleanup_preserves_existing_sequences() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta_a = dir.path().join("a.fa");
fs::write(&fasta_a, ">chr1\nAAAACCCC\n>chr2\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta_a, _) = store
.add_sequence_collection_from_fasta(&fasta_a, FastaImportOptions::new())
.unwrap();
store.write().unwrap();
drop(store);
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
assert!(reopened.t_n_loaded_colls() == 0);
reopened
.add_collection_alias("ucsc", "hg38", &meta_a.digest)
.unwrap();
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_b, ">chrX\nCCCCAAAA\n").unwrap();
reopened
.add_sequence_collection_from_fasta(
&fasta_b,
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.expect_err("conflicting alias must error");
let mut fresh = RefgetStore::open_local(&store_path).unwrap();
let coll = fresh.get_collection(&meta_a.digest).unwrap();
for rec in &coll.sequences {
let digest = rec.metadata().sha512t24u.clone();
fresh
.get_substring(digest.as_str(), 0, rec.metadata().length as usize)
.unwrap_or_else(|e| {
panic!("sequence {} vanished after a failed import: {}", digest, e)
});
}
}
#[cfg(unix)]
#[test]
fn test_standalone_write_failure_does_not_publish_its_collection() {
use std::os::unix::fs::PermissionsExt;
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let seqs = ["AAAACCCCGGGGTTTT", "ACGTACGTACGTACGT", "TTTTGGGGCCCCAAAA"];
let digests: Vec<String> = seqs.iter().map(|s| sha512t24u(s.as_bytes())).collect();
let shards: std::collections::HashSet<&str> = digests.iter().map(|d| &d[..2]).collect();
assert_eq!(shards.len(), seqs.len(), "each sequence needs its own shard directory");
let fasta = dir.path().join("a.fa");
let body: String = seqs.iter().enumerate().map(|(i, s)| format!(">s{i}\n{s}\n")).collect();
fs::write(&fasta, body).unwrap();
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store.set_quiet(true);
let blocked = store_path.join("sequences").join(&digests[2][..2]);
fs::create_dir_all(&blocked).unwrap();
fs::set_permissions(&blocked, fs::Permissions::from_mode(0o555)).unwrap();
if fs::write(blocked.join("probe"), b"x").is_ok() {
fs::set_permissions(&blocked, fs::Permissions::from_mode(0o755)).unwrap();
return;
}
store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(1))
.expect_err("the last .seq write fails");
let _ = fs::set_permissions(&blocked, fs::Permissions::from_mode(0o755));
store.write().unwrap();
drop(store);
let mut fresh = RefgetStore::open_local(&store_path).unwrap();
let collections = fresh.list_collections(0, 10, &[]).unwrap().results;
assert!(collections.is_empty(), "a collection with an unwritten sequence was published");
for m in fresh.list_sequences().unwrap() {
fresh
.get_substring(&m.sha512t24u, 0, m.length)
.unwrap_or_else(|e| panic!("published sequence {} cannot be read: {e}", m.name));
}
}
#[test]
fn test_collection_alias_rejected_for_multiple_files() {
let dir = tempdir().unwrap();
let fasta_a = dir.path().join("a.fa");
fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::in_memory();
let err = store
.add_sequence_collections_from_fastas(
&[fasta_a, fasta_b],
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.expect_err("collection_alias with multiple files must error");
let msg = format!("{}", err);
assert!(
msg.contains("add_collection_alias"),
"error should teach the per-file workaround: {}",
msg
);
assert!(store.catalog.n_sequences() == 0, "no sequences imported");
assert!(store.catalog.n_collections() == 0, "no collections imported");
assert!(store.list_collection_alias_namespaces().is_empty());
assert!(store.list_sequence_alias_namespaces().is_empty());
}
#[test]
fn test_collection_alias_single_element_slice_ok() {
let dir = tempdir().unwrap();
let fasta = dir.path().join("one.fa");
fs::write(&fasta, ">chr1\nAAAACCCC\n").unwrap();
let mut store = RefgetStore::in_memory();
let report = store
.add_sequence_collections_from_fastas(
&[fasta],
FastaImportOptions::new().collection_alias("ucsc", "hg38"),
)
.expect("one-element slice with an alias must succeed");
assert_eq!(report.collections.len(), 1);
assert_eq!(
store
.get_collection_metadata_by_alias("ucsc", "hg38")
.unwrap()
.digest,
report.collections[0].0.digest
);
}
fn add_collection_to_store(store: &mut RefgetStore, dir: &std::path::Path, name: &str, fasta: &str) -> String {
let fasta_path = dir.join(format!("{}.fa", name));
fs::write(&fasta_path, fasta).unwrap();
let (meta, _) = store
.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
.unwrap();
meta.digest
}
#[test]
fn test_interleaved_writers_both_survive() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
let seed_digest = add_collection_to_store(&mut seed, work.path(), "seed", ">chrS\nAAAACCCC\n");
seed.write().unwrap();
drop(seed);
let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();
let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();
let digest_a = add_collection_to_store(&mut writer_a, work.path(), "a", ">chrA\nGGGGTTTT\n");
let digest_b = add_collection_to_store(&mut writer_b, work.path(), "b", ">chrB\nTTTTGGGG\n");
writer_b.write().unwrap();
writer_a.write().unwrap();
drop(writer_a);
drop(writer_b);
let reopened = RefgetStore::open_local(&store_dir).unwrap();
for (label, digest) in [("seed", &seed_digest), ("A", &digest_a), ("B", &digest_b)] {
assert!(
reopened.get_collection_metadata(digest).is_some(),
"collection {} ({}) was dropped from the index by the other writer",
label,
digest
);
}
}
#[test]
fn test_interleaved_writers_preserve_sequence_rows() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
add_collection_to_store(&mut seed, work.path(), "seed", ">chrS\nAAAACCCC\n");
seed.write().unwrap();
drop(seed);
let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();
let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();
add_collection_to_store(&mut writer_a, work.path(), "a", ">chrA\nGGGGTTTT\n");
add_collection_to_store(&mut writer_b, work.path(), "b", ">chrB\nTTTTGGGG\n");
writer_b.write().unwrap();
writer_a.write().unwrap();
drop(writer_a);
drop(writer_b);
let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
let names: std::collections::HashSet<String> = reopened
.list_sequences()
.unwrap()
.iter()
.map(|m| m.name.clone())
.collect();
for expected in ["chrS", "chrA", "chrB"] {
assert!(names.contains(expected), "sequence {} was dropped; have {:?}", expected, names);
}
}
#[test]
fn test_alias_namespace_from_other_writer_survives_commit() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
let seed_digest = add_collection_to_store(&mut seed, work.path(), "seed", ">chrS\nAAAACCCC\n");
seed.write().unwrap();
drop(seed);
let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();
let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();
writer_b
.add_collection_alias("refgenie", "athaliana", &seed_digest)
.unwrap();
drop(writer_b);
add_collection_to_store(&mut writer_a, work.path(), "a", ">chrA\nGGGGTTTT\n");
writer_a.write().unwrap();
drop(writer_a);
assert!(
store_dir.join("aliases/collections/refgenie.tsv").exists(),
"the other writer's alias TSV was deleted"
);
let reopened = RefgetStore::open_local(&store_dir).unwrap();
assert!(
reopened
.get_collection_metadata_by_alias("refgenie", "athaliana")
.is_some(),
"alias stopped resolving after another writer committed"
);
}
#[test]
fn test_removal_is_not_resurrected_by_the_merge() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
let keep = add_collection_to_store(&mut store, work.path(), "keep", ">chrK\nAAAACCCC\n");
let drop_me = add_collection_to_store(&mut store, work.path(), "drop", ">chrD\nGGGGTTTT\n");
store.write().unwrap();
assert!(store.remove_collection(&drop_me, true).unwrap());
drop(store);
let reopened = RefgetStore::open_local(&store_dir).unwrap();
assert!(reopened.get_collection_metadata(&keep).is_some());
assert!(
reopened.get_collection_metadata(&drop_me).is_none(),
"removed collection came back through the merge"
);
}
#[test]
fn test_orphan_gc_keeps_sequences_shared_with_another_collection() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
let coll_a = add_collection_to_store(
&mut store,
work.path(),
"a",
">chrShared\nAAAACCCCGGGGTTTT\n>chrOnlyA\nACACACAC\n",
);
let coll_b = add_collection_to_store(
&mut store,
work.path(),
"b",
">chrShared\nAAAACCCCGGGGTTTT\n>chrOnlyB\nGTGTGTGT\n",
);
store.write().unwrap();
drop(store);
let mut store = RefgetStore::open_local(&store_dir).unwrap();
assert!(
(store.t_n_loaded_colls() == 0),
"precondition: a fresh open must not populate name_lookup"
);
let planned = store.plan_orphan_removal(&coll_a).unwrap();
assert_eq!(
planned.len(),
1,
"only chrOnlyA is an orphan; planned {:?}",
planned
);
assert!(store.remove_collection(&coll_a, true).unwrap());
drop(store);
let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
reopened.load_collection(&coll_b).unwrap();
let collection = reopened.get_collection(&coll_b).unwrap();
assert_eq!(collection.sequences.len(), 2);
for seq in &collection.sequences {
let digest = &seq.metadata().sha512t24u;
assert!(
reopened.get_sequence_metadata(digest).is_some(),
"sequence {} ({}) survived in the index but not in the store",
seq.metadata().name,
digest
);
assert!(
reopened.get_sequence(digest).is_ok(),
"sequence {} ({}) was unlinked from disk by the orphan GC",
seq.metadata().name,
digest
);
}
}
#[test]
fn test_orphan_gc_refuses_when_a_collection_rgsi_is_missing() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
let coll_a = add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
let coll_b = add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
store.write().unwrap();
drop(store);
fs::remove_file(store_dir.join(format!("collections/{}.rgsi", coll_b))).unwrap();
let mut store = RefgetStore::open_local(&store_dir).unwrap();
let err = store.remove_collection(&coll_a, true).unwrap_err();
assert!(
err.to_string().contains("refusing to remove orphan sequences"),
"expected a fail-closed error, got: {}",
err
);
}
#[test]
fn test_orphan_gc_spares_sequences_of_loaded_collections() {
for packed in [false, true] {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let shared = [("s1", "AAAACCCCGGGGTTTT"), ("s2", "ACGTACGTACGTACGT")];
let body = |own: (&str, &str)| -> String {
shared
.iter()
.chain([&own])
.map(|(n, s)| format!(">{n}\n{s}\n"))
.collect()
};
let mut store = if packed {
RefgetStore::on_disk_packed(&store_dir).unwrap()
} else {
RefgetStore::on_disk(&store_dir).unwrap()
};
let coll_a = add_collection_to_store(&mut store, work.path(), "a", &body(("onlyA", "TTTTGGGG")));
let coll_b = add_collection_to_store(&mut store, work.path(), "b", &body(("onlyB", "GGGGAAAA")));
store.write().unwrap();
drop(store);
fs::remove_file(store_dir.join("collections.rgci")).unwrap();
let mut store = RefgetStore::open_local(&store_dir).unwrap();
assert!(store.remove_collection(&coll_a, true).unwrap(), "packed={packed}");
let check = |store: &mut RefgetStore| {
let coll = store.get_collection(&coll_b).unwrap();
assert_eq!(coll.sequences.len(), 3, "packed={packed}");
for rec in &coll.sequences {
let m = rec.metadata();
let want = shared
.iter()
.chain([&("onlyB", "GGGGAAAA")])
.find(|(n, _)| *n == m.name)
.unwrap()
.1;
let got = store
.get_substring(&m.sha512t24u, 0, m.length)
.unwrap_or_else(|e| panic!("packed={packed}: cannot read {}: {e}", m.name));
assert_eq!(got, want, "packed={packed}: {}", m.name);
}
};
check(&mut store);
drop(store);
let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
reopened.load_collection(&coll_b).unwrap();
check(&mut reopened);
}
}
#[test]
fn test_conflicting_alias_errors_unless_forced() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
let coll_a = add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
let coll_b = add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
store.add_collection_alias("ucsc", "hg38", &coll_a).unwrap();
store.write().unwrap();
drop(store);
let mut other = RefgetStore::open_local(&store_dir).unwrap();
let err = other
.add_collection_alias("ucsc", "hg38", &coll_b)
.expect_err("a conflicting alias binding must not be silently resolved");
assert!(err.to_string().contains("alias conflict"), "got: {}", err);
assert_eq!(
fs::read_to_string(store_dir.join("aliases/collections/ucsc.tsv")).unwrap(),
format!("hg38\t{}\n", coll_a)
);
other.set_force_alias(true);
other
.add_collection_alias("ucsc", "hg38", &coll_b)
.expect("force-alias must overwrite the published binding");
drop(other);
let reopened = RefgetStore::open_local(&store_dir).unwrap();
assert_eq!(
reopened
.get_collection_metadata_by_alias("ucsc", "hg38")
.unwrap()
.digest,
coll_b
);
}
fn digests_ab() -> (String, String) {
(sha512t24u(b"AAAACCCC"), sha512t24u(b"GGGGTTTT"))
}
fn write_alias_tsv(dir: &std::path::Path, name: &str, rows: &[(&str, &str)]) -> String {
let path = dir.join(name);
let body: String = rows.iter().map(|(a, d)| format!("{}\t{}\n", a, d)).collect();
fs::write(&path, body).unwrap();
path.to_str().unwrap().to_string()
}
fn has_pending_alias_in(store: &RefgetStore, namespace: &str) -> bool {
store
.pending
.lock()
.unwrap()
.aliases
.iter()
.any(|(_, ns, _)| ns == namespace)
}
#[test]
fn test_alias_load_intra_file_clash_errors() {
let dir = tempdir().unwrap();
let (a, b) = digests_ab();
let tsv = write_alias_tsv(
dir.path(),
"ucsc.tsv",
&[("chr1", &a), ("chr2", &a), ("chr1", &b), ("chr2", &b)],
);
for force in [false, true] {
let mut store = RefgetStore::in_memory();
store.set_force_alias(force);
let err = store
.load_sequence_aliases("ucsc", &tsv)
.expect_err("one alias mapped to two digests must error");
let msg = err.to_string();
assert!(msg.starts_with("alias conflict"), "force={force}: {msg}");
assert!(msg.contains("'chr1'"), "force={force}: error should name the alias: {msg}");
assert!(msg.contains(&a) && msg.contains(&b), "force={force}: error should name both digests: {msg}");
assert!(msg.contains("line 1") && msg.contains("line 3"), "force={force}: error should give line numbers: {msg}");
assert!(store.list_sequence_aliases("ucsc").is_none(), "force={force}: nothing may be loaded");
assert!(!has_pending_alias_in(&store, "ucsc"), "force={force}: nothing may be pending");
}
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store
.load_sequence_aliases("ucsc", &tsv)
.expect_err("one alias mapped to two digests must error on disk too");
assert!(store.list_sequence_aliases("ucsc").is_none());
assert!(!store_path.join("aliases/sequences/ucsc.tsv").exists());
}
#[test]
fn test_alias_load_exact_duplicate_rows_ok() {
let dir = tempdir().unwrap();
let (a, b) = digests_ab();
let tsv = write_alias_tsv(
dir.path(),
"ncbi.tsv",
&[("NC_000001.11", &a), ("NC_000002.12", &b), ("NC_000001.11", &a)],
);
let mut store = RefgetStore::in_memory();
assert_eq!(store.load_sequence_aliases("ncbi", &tsv).unwrap(), 2);
assert_eq!(store.list_sequence_aliases("ncbi").unwrap().len(), 2);
assert_eq!(store.aliases.resolve_sequence("ncbi", "NC_000001.11"), Some(a.to_key()));
assert_eq!(store.load_sequence_aliases("ncbi", &tsv).unwrap(), 2);
}
#[test]
fn test_alias_load_conflicts_with_existing_unless_forced() {
let dir = tempdir().unwrap();
let (a, b) = digests_ab();
let tsv = write_alias_tsv(dir.path(), "ns.tsv", &[("y", &a), ("x", &b)]);
let mut store = RefgetStore::in_memory();
store.add_sequence_alias("ns", "x", &a).unwrap();
let err = store
.load_sequence_aliases("ns", &tsv)
.expect_err("re-pointing an existing alias must error by default");
assert!(err.to_string().starts_with("alias conflict"), "got: {}", err);
assert_eq!(store.aliases.resolve_sequence("ns", "x"), Some(a.to_key()));
assert!(
store.aliases.resolve_sequence("ns", "y").is_none(),
"a refused load must not apply its other rows"
);
store.set_force_alias(true);
assert_eq!(store.load_sequence_aliases("ns", &tsv).unwrap(), 2);
assert_eq!(store.aliases.resolve_sequence("ns", "x"), Some(b.to_key()));
assert_eq!(store.aliases.resolve_sequence("ns", "y"), Some(a.to_key()));
}
#[test]
fn test_add_alias_conflict_in_memory_store() {
let (a, b) = digests_ab();
let mut store = RefgetStore::in_memory();
store.add_sequence_alias("ncbi", "NC_000001.11", &a).unwrap();
store.add_sequence_alias("ncbi", "NC_000001.11", &a).unwrap();
assert_eq!(store.list_sequence_aliases("ncbi").unwrap().len(), 1);
assert_eq!(store.aliases.resolve_sequence("ncbi", "NC_000001.11"), Some(a.to_key()));
store.pending.lock().unwrap().aliases.clear();
let err = store
.add_sequence_alias("ncbi", "NC_000001.11", &b)
.expect_err("a different digest must error by default");
let msg = err.to_string();
assert!(msg.starts_with("alias conflict"), "got: {}", msg);
assert!(msg.contains(&a) && msg.contains(&b), "got: {}", msg);
assert_eq!(store.aliases.resolve_sequence("ncbi", "NC_000001.11"), Some(a.to_key()));
assert!(!has_pending_alias_in(&store, "ncbi"), "a refused add must not be pending");
store.set_force_alias(true);
store
.add_sequence_alias("ncbi", "NC_000001.11", &b)
.expect("force-alias must re-point the alias");
assert_eq!(store.aliases.resolve_sequence("ncbi", "NC_000001.11"), Some(b.to_key()));
}
#[test]
fn test_collection_alias_load_intra_file_clash_errors() {
let dir = tempdir().unwrap();
let (a, b) = digests_ab();
let tsv = write_alias_tsv(dir.path(), "ucsc.tsv", &[("hg38", &a), ("hg38", &b)]);
let mut store = RefgetStore::in_memory();
store.set_force_alias(true);
let err = store
.load_collection_aliases("ucsc", &tsv)
.expect_err("one collection alias mapped to two digests must error");
let msg = err.to_string();
assert!(msg.starts_with("alias conflict in collections"), "got: {}", msg);
assert!(msg.contains("'hg38'"), "got: {}", msg);
assert!(store.list_collection_aliases("ucsc").is_none());
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store.load_collection_aliases("ucsc", &tsv).unwrap_err();
assert!(!store_path.join("aliases/collections/ucsc.tsv").exists());
}
#[test]
fn test_collection_alias_conflict_in_memory_store() {
let (a, b) = digests_ab();
let dir = tempdir().unwrap();
let tsv = write_alias_tsv(dir.path(), "ucsc.tsv", &[("hg38", &b)]);
let mut store = RefgetStore::in_memory();
store.add_collection_alias("ucsc", "hg38", &a).unwrap();
store.add_collection_alias("ucsc", "hg38", &a).expect("same digest is a no-op");
let err = store
.add_collection_alias("ucsc", "hg38", &b)
.expect_err("a different digest must error by default");
assert!(err.to_string().starts_with("alias conflict in collections"), "got: {}", err);
store
.load_collection_aliases("ucsc", &tsv)
.expect_err("a load must not re-point it either");
assert_eq!(store.aliases.resolve_collection("ucsc", "hg38"), Some(a.to_key()));
store.set_force_alias(true);
store.add_collection_alias("ucsc", "hg38", &b).unwrap();
assert_eq!(store.aliases.resolve_collection("ucsc", "hg38"), Some(b.to_key()));
}
#[test]
fn test_import_header_alias_clash_errors() {
let dir = tempdir().unwrap();
let fasta = dir.path().join("clash.fa");
fs::write(&fasta, ">chr1 ucsc:chrX\nAAAACCCC\n>chr2 ucsc:chrX\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::in_memory();
store.set_force_alias(true);
let err = store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().namespaces(&["ucsc"]))
.expect_err("one header alias tagged onto two sequences must error");
let msg = err.to_string();
assert!(msg.starts_with("alias conflict"), "got: {}", msg);
assert!(msg.contains("'chrX'"), "got: {}", msg);
assert!(msg.contains("1 alias in this file clashes"), "got: {}", msg);
assert!(store.catalog.n_collections() == 0, "the rejected collection must not be in the store");
assert!(store.t_n_loaded_colls() == 0);
assert!(store.list_sequence_aliases("ucsc").is_none());
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().namespaces(&["ucsc"]))
.unwrap_err();
assert!(store.catalog.n_collections() == 0);
let orphan_rgsi = fs::read_dir(store_path.join("collections"))
.map(|rd| rd.filter_map(|e| e.ok()).any(|e| e.file_name().to_string_lossy().ends_with(".rgsi")))
.unwrap_or(false);
assert!(!orphan_rgsi, "a rejected import must not leave a collection .rgsi");
assert!(!store_path.join("aliases/sequences/ucsc.tsv").exists());
}
#[test]
fn test_import_header_alias_clash_across_files_errors() {
let dir = tempdir().unwrap();
let fasta_a = dir.path().join("a.fa");
fs::write(&fasta_a, ">chr1 ucsc:chrM\nAAAACCCC\n").unwrap();
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_b, ">chr1 ucsc:chrM\nGGGGTTTT\n").unwrap();
let mut store = RefgetStore::in_memory();
let err = store
.add_sequence_collections_from_fastas(
&[fasta_a.clone(), fasta_b.clone()],
FastaImportOptions::new().namespaces(&["ucsc"]),
)
.expect_err("the same header alias on two genomes must error");
assert!(err.to_string().starts_with("alias conflict"), "got: {:#}", err);
let mut store = RefgetStore::in_memory();
store.set_force_alias(true);
store
.add_sequence_collections_from_fastas(
&[fasta_a, fasta_b],
FastaImportOptions::new().namespaces(&["ucsc"]),
)
.expect("force-alias re-points an alias bound by an earlier file");
}
#[test]
fn test_manifest_digests_match_published_indexes() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
store.write().unwrap();
let metadata = store.store_metadata().unwrap();
let sha = |name: &str| {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(fs::read(store_dir.join(name)).unwrap()))
};
assert_eq!(metadata.get("sequences_digest").unwrap(), &sha("sequences.rgsi"));
assert_eq!(metadata.get("collections_digest").unwrap(), &sha("collections.rgci"));
}
#[test]
fn test_created_at_survives_subsequent_commits() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
store.write().unwrap();
let read_created_at = || -> String {
let json = fs::read_to_string(store_dir.join("rgstore.json")).unwrap();
let v: serde_json::Value = serde_json::from_str(&json).unwrap();
v["created_at"].as_str().unwrap().to_string()
};
let first = read_created_at();
add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
store.write().unwrap();
assert_eq!(read_created_at(), first, "created_at was overwritten by a later commit");
}
#[test]
fn test_batch_lock_is_reentrant_and_exclusive() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
store.write().unwrap();
store.lock_for_batch("test-batch").unwrap();
assert!(store.holds_batch_lock());
add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
store.write().unwrap();
assert!(
super::lock_status(&store_dir).unwrap().is_some(),
"the batch lock should be visible on disk"
);
store.release_batch_lock();
assert!(super::lock_status(&store_dir).unwrap().is_none());
}
#[test]
fn test_commit_leaves_no_transient_files_behind() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
store.write().unwrap();
drop(store);
let leftovers: Vec<String> = fs::read_dir(&store_dir)
.unwrap()
.filter_map(|e| e.ok())
.filter_map(|e| e.file_name().to_str().map(String::from))
.filter(|n| super::is_transient_store_file(n))
.collect();
assert!(leftovers.is_empty(), "transient files left behind: {:?}", leftovers);
}
fn sequence_digests_of(store: &mut RefgetStore, digest: &str) -> Vec<String> {
store.load_collection(digest).unwrap();
store
.get_collection(digest)
.unwrap()
.sequences
.iter()
.map(|s| s.metadata().sha512t24u.clone())
.collect()
}
fn index_contains(store_dir: &std::path::Path, file: &str, needle: &str) -> bool {
fs::read_to_string(store_dir.join(file))
.unwrap()
.lines()
.any(|l| l.contains(needle))
}
#[test]
fn test_stale_handle_does_not_resurrect_a_removed_collection() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
let keep = add_collection_to_store(&mut seed, work.path(), "keep", ">chrK\nAAAACCCC\n");
let victim = add_collection_to_store(
&mut seed,
work.path(),
"victim",
">chrV1\nGGGGTTTT\n>chrV2\nTTTTGGGG\n",
);
seed.add_collection_alias("refgenie", "oluc", &victim).unwrap();
seed.write().unwrap();
let victim_sequences = sequence_digests_of(&mut seed, &victim);
drop(seed);
let mut writer = RefgetStore::open_local(&store_dir).unwrap();
assert!(writer.get_collection_metadata(&victim).is_some());
let mut remover = RefgetStore::open_local(&store_dir).unwrap();
assert!(remover.remove_collection(&victim, true).unwrap());
drop(remover);
assert!(!index_contains(&store_dir, "collections.rgci", &victim));
let added = add_collection_to_store(&mut writer, work.path(), "added", ">chrN\nACACACAC\n");
writer.write().unwrap();
drop(writer);
assert!(
!index_contains(&store_dir, "collections.rgci", &victim),
"the removed collection came back into collections.rgci"
);
for seq in &victim_sequences {
assert!(
!index_contains(&store_dir, "sequences.rgsi", seq),
"orphan sequence {} came back into sequences.rgsi -- its .seq file is gone",
seq
);
}
assert!(
!store_dir.join("aliases/collections/refgenie.tsv").exists(),
"the removed collection's alias namespace came back"
);
let reopened = RefgetStore::open_local(&store_dir).unwrap();
assert!(reopened.get_collection_metadata(&keep).is_some());
assert!(reopened.get_collection_metadata(&added).is_some());
assert!(reopened.get_collection_metadata(&victim).is_none());
assert!(
reopened
.get_collection_metadata_by_alias("refgenie", "oluc")
.is_none(),
"the alias still resolves to a collection that no longer exists"
);
}
#[test]
fn test_no_dangling_sequence_rows_after_a_stale_commit() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
add_collection_to_store(&mut seed, work.path(), "keep", ">chrK\nAAAACCCC\n");
let victim = add_collection_to_store(&mut seed, work.path(), "victim", ">chrV\nGGGGTTTT\n");
seed.write().unwrap();
drop(seed);
let mut writer = RefgetStore::open_local(&store_dir).unwrap();
let mut remover = RefgetStore::open_local(&store_dir).unwrap();
remover.remove_collection(&victim, true).unwrap();
drop(remover);
add_collection_to_store(&mut writer, work.path(), "added", ">chrN\nACACACAC\n");
writer.write().unwrap();
drop(writer);
let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
let digests: Vec<String> = reopened
.list_sequences()
.unwrap()
.iter()
.map(|m| m.sha512t24u.clone())
.collect();
for digest in &digests {
assert!(
reopened.load_sequence(digest).is_ok(),
"sequences.rgsi lists {} but its .seq file is gone",
digest
);
}
}
#[test]
fn test_delta_commit_still_preserves_a_concurrent_addition() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
let seed_digest = add_collection_to_store(&mut seed, work.path(), "seed", ">chrS\nAAAACCCC\n");
seed.write().unwrap();
drop(seed);
let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();
let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();
let digest_a = add_collection_to_store(&mut writer_a, work.path(), "a", ">chrA\nGGGGTTTT\n");
let digest_b = add_collection_to_store(&mut writer_b, work.path(), "b", ">chrB\nTTTTGGGG\n");
writer_b.write().unwrap();
writer_a.write().unwrap();
drop(writer_a);
drop(writer_b);
let reopened = RefgetStore::open_local(&store_dir).unwrap();
for (label, digest) in [("seed", &seed_digest), ("A", &digest_a), ("B", &digest_b)] {
assert!(
reopened.get_collection_metadata(digest).is_some(),
"collection {} ({}) was dropped by the other writer's commit",
label,
digest
);
}
}
#[test]
fn test_removal_reclaims_only_unshared_sequences() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
const SHARED: &str = "AAAACCCCGGGGTTTT";
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
let coll_a = add_collection_to_store(
&mut store,
work.path(),
"a",
&format!(">chrShared\n{}\n>chrOnlyA\nACACACAC\n", SHARED),
);
let coll_b = add_collection_to_store(
&mut store,
work.path(),
"b",
&format!(">chrShared\n{}\n>chrOnlyB\nGTGTGTGT\n", SHARED),
);
store.write().unwrap();
let a_sequences = sequence_digests_of(&mut store, &coll_a);
let b_sequences = sequence_digests_of(&mut store, &coll_b);
drop(store);
let shared: Vec<&String> = a_sequences.iter().filter(|d| b_sequences.contains(d)).collect();
assert_eq!(shared.len(), 1, "precondition: exactly one shared sequence");
let only_a: Vec<&String> = a_sequences.iter().filter(|d| !b_sequences.contains(d)).collect();
assert_eq!(only_a.len(), 1);
let mut store = RefgetStore::open_local(&store_dir).unwrap();
let planned = store.plan_orphan_removal(&coll_a).unwrap();
assert_eq!(planned, vec![only_a[0].clone()], "the dry-run must name exactly chrOnlyA");
assert!(store.remove_collection(&coll_a, true).unwrap());
drop(store);
let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
assert!(
reopened.get_sequence_metadata(only_a[0]).is_none(),
"the unshared sequence was not reclaimed"
);
reopened.load_sequence(shared[0]).unwrap();
assert_eq!(
reopened.get_substring(shared[0], 0, SHARED.len()).unwrap(),
SHARED,
"the shared sequence did not survive intact"
);
}
#[test]
fn test_emptying_a_namespace_spares_another_writers_alias() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
let coll_a = add_collection_to_store(&mut seed, work.path(), "a", ">chrA\nAAAACCCC\n");
let coll_b = add_collection_to_store(&mut seed, work.path(), "b", ">chrB\nGGGGTTTT\n");
seed.add_collection_alias("refgenie", "mine", &coll_a).unwrap();
seed.write().unwrap();
drop(seed);
let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();
let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();
writer_b.add_collection_alias("refgenie", "theirs", &coll_b).unwrap();
drop(writer_b);
assert!(writer_a.remove_collection_alias("refgenie", "mine").unwrap());
drop(writer_a);
let reopened = RefgetStore::open_local(&store_dir).unwrap();
assert!(
reopened
.get_collection_metadata_by_alias("refgenie", "theirs")
.is_some(),
"the other writer's alias was deleted with the namespace"
);
assert!(
reopened
.get_collection_metadata_by_alias("refgenie", "mine")
.is_none(),
"the removed alias came back"
);
}
#[test]
fn test_has_uncommitted_changes_tracks_the_commit() {
let work = tempdir().unwrap();
let store_dir = work.path().join("store");
let mut store = RefgetStore::on_disk(&store_dir).unwrap();
add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
store.write().unwrap();
assert!(!store.has_uncommitted_changes());
store.lock_for_batch("test-batch").unwrap();
let digest = add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
assert!(store.get_collection_metadata(&digest).is_some());
store.write().unwrap();
assert!(
!store.has_uncommitted_changes(),
"a successful commit must clear the pending set"
);
store.release_batch_lock();
}
fn multi_alphabet_fasta() -> String {
format!(
">dna\n{}\n>iupac\n{}\n>prot\n{}\n>asc\n{}\n",
"ACGTACGTACGTACGTACGTACGTACGT",
"ACGTRYMKSWVNACGTRYMKSWVNACGTRYMKSWVN",
"MKTAYIAKQRQISFVKSHFSRQLEERLGLIEVQAPILSRVGDGTQDNLSGAEKAVQVKVKALPDAQFEVVHSLAKWKRQTLGQHDFSAGEGLYTHMKALRPDEDRLSPLHSVYVDQWDWELVMGDGERQFSTLKSTVEAIWAGIKATEAAVSEEFGLAPFLPDQIHFVHSQELLSRYPDLDAKGRERAIAKDLGAVFLVGIGGKLSDGHRHDVRAPDYDDWSTPSELGHAGLNGDILVWNPVLEDAFELSSMGIRVDADTLKHQLALTGDEDRLELEWHQALLRGEMPQTIGGGIGQSRLTMLLLQLPHIGQVQAGVWPAAVRESVPSLL",
"Hello, World! This is plain ASCII text, not a sequence at all: 12345."
)
}
fn build_multi_alphabet_store(
mode: StorageMode,
) -> (tempfile::TempDir, PathBuf, RefgetStore, Vec<(String, String, String)>) {
let dir = tempdir().unwrap();
let fasta = dir.path().join("multi.fa");
fs::write(&fasta, multi_alphabet_fasta()).unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
store.set_encoding_mode(mode).unwrap();
store
.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
.unwrap();
store.write().unwrap();
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
let seqs: Vec<(String, String, String)> = reopened
.list_sequences()
.unwrap()
.into_iter()
.map(|m| (m.name, m.sha512t24u, m.alphabet.to_string()))
.collect();
(dir, store_path, reopened, seqs)
}
fn corrupt_one_byte(path: &std::path::Path) {
let mut bytes = fs::read(path).unwrap();
assert!(!bytes.is_empty(), "cannot corrupt an empty file: {}", path.display());
let mid = bytes.len() / 2;
bytes[mid] ^= 0xFF;
fs::write(path, bytes).unwrap();
}
fn corrupt_one_base_raw(path: &std::path::Path) {
let mut bytes = fs::read(path).unwrap();
assert!(!bytes.is_empty(), "cannot corrupt an empty file: {}", path.display());
let mid = bytes.len() / 2;
bytes[mid] = if bytes[mid] == b'A' { b'C' } else { b'A' };
fs::write(path, bytes).unwrap();
}
fn corrupt_stored_md5(store_path: &std::path::Path, digest: &str, bad_md5: &str) {
let idx_path = store_path.join("sequences.rgsi");
let content = fs::read_to_string(&idx_path).unwrap();
let mut out = String::new();
let mut found = false;
for line in content.lines() {
if line.starts_with('#') || line.trim().is_empty() {
out.push_str(line);
out.push('\n');
continue;
}
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 5 && parts[3] == digest {
found = true;
let mut owned: Vec<String> = parts.iter().map(|s| s.to_string()).collect();
owned[4] = bad_md5.to_string();
out.push_str(&owned.join("\t"));
} else {
out.push_str(line);
}
out.push('\n');
}
assert!(found, "digest {} not found in sequences.rgsi", digest);
fs::write(&idx_path, out).unwrap();
}
fn find_seq<'a>(
seqs: &'a [(String, String, String)],
name: &str,
) -> &'a (String, String, String) {
seqs.iter()
.find(|(n, _, _)| n == name)
.unwrap_or_else(|| panic!("no sequence named {} in test fixture", name))
}
#[test]
fn verify_clean_store_reports_no_failures() {
let (_dir, _store_path, mut store, seqs) = build_multi_alphabet_store(StorageMode::Encoded);
let report = store.verify_sequences(None, &VerifyOptions::default()).unwrap();
assert!(report.is_ok());
assert_eq!(report.n_checked, seqs.len());
assert_eq!(report.n_ok, seqs.len());
assert_eq!(report.n_failed, 0);
assert!(report.failures.is_empty());
let expected_alphabets: std::collections::HashSet<&String> =
seqs.iter().map(|(_, _, a)| a).collect();
assert_eq!(report.by_alphabet.len(), expected_alphabets.len());
for (_, _, alphabet) in &seqs {
let counts = report.by_alphabet.get(alphabet).unwrap();
assert!(counts.checked >= 1);
assert_eq!(counts.failed, 0);
}
}
#[test]
fn verify_clean_store_raw_mode() {
let (_dir, _store_path, mut store, seqs) = build_multi_alphabet_store(StorageMode::Raw);
let report = store.verify_sequences(None, &VerifyOptions::default()).unwrap();
assert!(report.is_ok());
assert_eq!(report.n_checked, seqs.len());
assert_eq!(report.n_failed, 0);
}
#[test]
fn verify_clean_store_zstd_mode() {
let (_dir, _store_path, mut store, seqs) = build_multi_alphabet_store(StorageMode::Zstd);
let report = store.verify_sequences(None, &VerifyOptions::default()).unwrap();
assert!(report.is_ok());
assert_eq!(report.n_checked, seqs.len());
assert_eq!(report.n_failed, 0);
}
#[test]
fn verify_detects_corrupted_encoded_payload() {
let (_dir, store_path, store, seqs) = build_multi_alphabet_store(StorageMode::Encoded);
let (_, target_digest, _) = find_seq(&seqs, "dna").clone();
let seq_path = store.sequence_file_path(&target_digest).unwrap();
drop(store);
corrupt_one_byte(&seq_path);
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
let report = reopened.verify_sequences(None, &VerifyOptions::default()).unwrap();
assert_eq!(report.n_checked, seqs.len());
assert_eq!(report.n_ok, seqs.len() - 1);
assert_eq!(report.n_failed, 1);
assert_eq!(report.failures.len(), 1);
let failure = &report.failures[0];
assert_eq!(failure.digest, target_digest);
assert_eq!(failure.kind, VerifyFailureKind::DigestMismatch);
assert_ne!(failure.computed_sha512t24u.as_deref(), Some(target_digest.as_str()));
assert_eq!(failure.bases_read as usize, failure.length);
}
#[test]
fn verify_detects_corrupted_raw_payload() {
let (_dir, store_path, store, seqs) = build_multi_alphabet_store(StorageMode::Raw);
let (_, target_digest, _) = find_seq(&seqs, "prot").clone();
let seq_path = store.sequence_file_path(&target_digest).unwrap();
drop(store);
corrupt_one_base_raw(&seq_path);
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
let report = reopened.verify_sequences(None, &VerifyOptions::default()).unwrap();
assert_eq!(report.n_failed, 1);
let failure = &report.failures[0];
assert_eq!(failure.digest, target_digest);
assert_eq!(failure.kind, VerifyFailureKind::DigestMismatch);
assert_eq!(report.n_ok, seqs.len() - 1);
}
#[test]
fn verify_reports_truncated_file_as_read_error_and_continues() {
let (_dir, store_path, store, seqs) = build_multi_alphabet_store(StorageMode::Encoded);
let (_, target_digest, _) = find_seq(&seqs, "prot").clone();
let seq_path = store.sequence_file_path(&target_digest).unwrap();
drop(store);
{
let file = std::fs::OpenOptions::new()
.write(true)
.open(&seq_path)
.unwrap();
file.set_len(2).unwrap();
}
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
let report = reopened.verify_sequences(None, &VerifyOptions::default()).unwrap();
assert_eq!(report.n_checked, seqs.len());
assert_eq!(report.n_ok, seqs.len() - 1);
assert_eq!(report.n_failed, 1);
let failure = &report.failures[0];
assert_eq!(failure.digest, target_digest);
assert_eq!(failure.kind, VerifyFailureKind::ReadError);
assert!(failure.error.is_some());
}
#[test]
fn verify_detects_md5_mismatch() {
let (_dir, store_path, _store, seqs) = build_multi_alphabet_store(StorageMode::Encoded);
let (_, target_digest, _) = find_seq(&seqs, "dna").clone();
corrupt_stored_md5(&store_path, &target_digest, "deadbeefdeadbeefdeadbeefdeadbeef");
let mut reopened = RefgetStore::open_local(&store_path).unwrap();
let report = reopened.verify_sequences(None, &VerifyOptions::default()).unwrap();
assert_eq!(report.n_failed, 1);
assert_eq!(report.failures[0].digest, target_digest);
assert_eq!(report.failures[0].kind, VerifyFailureKind::Md5Mismatch);
let mut reopened_no_md5 = RefgetStore::open_local(&store_path).unwrap();
let opts = VerifyOptions {
jobs: 0,
check_md5: false,
};
let report_no_md5 = reopened_no_md5.verify_sequences(None, &opts).unwrap();
assert_eq!(report_no_md5.n_failed, 0);
}
#[test]
fn verify_subset_only_checks_requested() {
let (_dir, _store_path, mut store, seqs) = build_multi_alphabet_store(StorageMode::Encoded);
let two: Vec<String> = seqs.iter().take(2).map(|(_, d, _)| d.clone()).collect();
let report = store
.verify_sequences(Some(&two), &VerifyOptions::default())
.unwrap();
assert_eq!(report.n_checked, 2);
assert_eq!(report.n_failed, 0);
let unknown = vec!["not-a-real-digest".to_string()];
let err = store
.verify_sequences(Some(&unknown), &VerifyOptions::default())
.unwrap_err();
assert!(err.to_string().contains("not-a-real-digest"));
let target = find_seq(&seqs, "dna").clone();
let meta = store
.list_sequences()
.unwrap()
.into_iter()
.find(|m| m.sha512t24u == target.1)
.unwrap();
let md5_subset = vec![meta.md5.clone()];
let report_md5 = store
.verify_sequences(Some(&md5_subset), &VerifyOptions::default())
.unwrap();
assert_eq!(report_md5.n_checked, 1);
assert_eq!(report_md5.n_failed, 0);
}
#[test]
fn verify_collection_limits_to_collection() {
let dir = tempdir().unwrap();
let fasta_a = dir.path().join("a.fa");
let fasta_b = dir.path().join("b.fa");
fs::write(&fasta_a, ">a1\nACGTACGTACGTACGT\n").unwrap();
fs::write(&fasta_b, ">b1\nGGGGCCCCTTTTAAAA\n").unwrap();
let store_path = dir.path().join("store");
let mut store = RefgetStore::on_disk(&store_path).unwrap();
let (meta_a, _) = store
.add_sequence_collection_from_fasta(&fasta_a, FastaImportOptions::new())
.unwrap();
let (meta_b, _) = store
.add_sequence_collection_from_fasta(&fasta_b, FastaImportOptions::new())
.unwrap();
store.write().unwrap();
drop(store);
let mut probe = RefgetStore::open_local(&store_path).unwrap();
let b_digest = probe
.get_collection(&meta_b.digest)
.unwrap()
.sequences[0]
.metadata()
.sha512t24u
.clone();
let seq_path = probe.sequence_file_path(&b_digest).unwrap();
drop(probe);
corrupt_one_byte(&seq_path);
let mut store_a = RefgetStore::open_local(&store_path).unwrap();
let report_a = store_a
.verify_collection(&meta_a.digest, &VerifyOptions::default())
.unwrap();
assert_eq!(report_a.n_failed, 0, "collection A must be unaffected");
let mut store_b = RefgetStore::open_local(&store_path).unwrap();
let report_b = store_b
.verify_collection(&meta_b.digest, &VerifyOptions::default())
.unwrap();
assert_eq!(report_b.n_failed, 1);
assert_eq!(report_b.failures[0].digest, b_digest);
}
#[test]
fn verify_parallel_matches_serial() {
let (_dir, store_path, store, seqs) = build_multi_alphabet_store(StorageMode::Encoded);
let (_, target_digest, _) = find_seq(&seqs, "iupac").clone();
let seq_path = store.sequence_file_path(&target_digest).unwrap();
drop(store);
corrupt_one_byte(&seq_path);
let mut store_serial = RefgetStore::open_local(&store_path).unwrap();
let serial = store_serial
.verify_sequences(
None,
&VerifyOptions {
jobs: 1,
check_md5: true,
},
)
.unwrap();
let mut store_parallel = RefgetStore::open_local(&store_path).unwrap();
let parallel = store_parallel
.verify_sequences(
None,
&VerifyOptions {
jobs: 4,
check_md5: true,
},
)
.unwrap();
assert_eq!(serial.n_checked, parallel.n_checked);
assert_eq!(serial.n_ok, parallel.n_ok);
assert_eq!(serial.n_failed, parallel.n_failed);
assert_eq!(serial.failures.len(), parallel.failures.len());
for (a, b) in serial.failures.iter().zip(parallel.failures.iter()) {
assert_eq!(a.digest, b.digest);
assert_eq!(a.kind, b.kind);
}
assert_eq!(serial.by_alphabet, parallel.by_alphabet);
}
mod packed_layout {
use super::*;
const PACKED_FASTA: &str = ">chrX\nTTGGGGAACCCCTTTTACGTACGT\n\
>chr1\nGGAATTCCGGAATTCCACGT\n\
>chr2\nACGTACGTACGTACGTGGGG\n\
>chrM\nGGGGCCCCAAAATTTTACGTACGTACGT\n\
>chr10\nTACGTACGTACGTACGCCCC\n";
fn collect_packs(dir: &std::path::Path) -> std::collections::BTreeMap<String, Vec<u8>> {
let mut out = std::collections::BTreeMap::new();
let packs = dir.join("packs");
if let Ok(entries) = std::fs::read_dir(&packs) {
for e in entries.filter_map(|e| e.ok()) {
let name = e.file_name().to_string_lossy().into_owned();
if name.ends_with(".pack") {
out.insert(name, std::fs::read(e.path()).unwrap());
}
}
}
out
}
fn seqs(store: &RefgetStore) -> Vec<(String, usize)> {
let mut v: Vec<(String, usize)> = store
.sequence_metadata()
.map(|m| (m.sha512t24u.clone(), m.length))
.collect();
v.sort();
v
}
fn build_packed(
dir: &std::path::Path,
fasta: &std::path::Path,
jobs: usize,
raw: bool,
cap: Option<u64>,
) -> RefgetStore {
let mut s = RefgetStore::on_disk_packed(dir).unwrap();
s.set_quiet(true);
if raw {
s.disable_encoding();
}
if let Some(c) = cap {
s.set_pack_cap_bytes(c);
}
s.add_sequence_collection_from_fasta(fasta, FastaImportOptions::new().jobs(jobs))
.unwrap();
s
}
fn build_standalone(
dir: &std::path::Path,
fasta: &std::path::Path,
raw: bool,
) -> RefgetStore {
let mut s = RefgetStore::on_disk(dir).unwrap();
s.set_quiet(true);
if raw {
s.disable_encoding();
}
s.add_sequence_collection_from_fasta(fasta, FastaImportOptions::new().jobs(1))
.unwrap();
s
}
#[test]
fn parallel_equals_serial_packed() {
let work = tempdir().unwrap();
let fasta = work.path().join("in.fa");
fs::write(&fasta, PACKED_FASTA).unwrap();
let d1 = tempdir().unwrap();
let d4 = tempdir().unwrap();
let d8 = tempdir().unwrap();
let _ = build_packed(d1.path(), &fasta, 1, false, Some(8));
let _ = build_packed(d4.path(), &fasta, 4, false, Some(8));
let _ = build_packed(d8.path(), &fasta, 8, false, Some(8));
let p1 = collect_packs(d1.path());
let p4 = collect_packs(d4.path());
let p8 = collect_packs(d8.path());
assert!(p1.len() > 1, "small cap should produce multiple packs, got {}", p1.len());
assert_eq!(p1, p4, "packs (names + bytes) must match jobs(1) vs jobs(4)");
assert_eq!(p1, p8, "packs must match jobs(1) vs jobs(8)");
let idx1 = fs::read(d1.path().join("sequences.pack.idx")).unwrap();
let idx4 = fs::read(d4.path().join("sequences.pack.idx")).unwrap();
let idx8 = fs::read(d8.path().join("sequences.pack.idx")).unwrap();
assert_eq!(idx1, idx4, "sequences.pack.idx must be byte-identical (1 vs 4)");
assert_eq!(idx1, idx8, "sequences.pack.idx must be byte-identical (1 vs 8)");
let rgsi1 = fs::read(d1.path().join("sequences.rgsi")).unwrap();
let rgsi4 = fs::read(d4.path().join("sequences.rgsi")).unwrap();
assert_eq!(rgsi1, rgsi4, "sequences.rgsi must be byte-identical (regression guard)");
}
#[test]
fn sealing_second_import_leaves_first_packs_untouched() {
let work = tempdir().unwrap();
let fa = work.path().join("a.fa");
let fb = work.path().join("b.fa");
fs::write(&fa, ">a1\nACGTACGTACGT\n>a2\nGGGGCCCCAAAA\n").unwrap();
fs::write(&fb, ">b1\nTTTTACGTACGT\n>b2\nCCCCGGGGACGT\n").unwrap();
let dir = tempdir().unwrap();
{
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
s.add_sequence_collection_from_fasta(&fa, FastaImportOptions::new().jobs(1)).unwrap();
}
let packs_a = collect_packs(dir.path());
{
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
s.add_sequence_collection_from_fasta(&fb, FastaImportOptions::new().jobs(1)).unwrap();
}
let packs_ab = collect_packs(dir.path());
for (name, bytes) in &packs_a {
assert_eq!(packs_ab.get(name), Some(bytes), "A pack {name} changed after import B");
}
assert!(packs_ab.len() > packs_a.len(), "import B must add new packs");
let bases: std::collections::HashMap<&str, &str> = [
("a1", "ACGTACGTACGT"),
("a2", "GGGGCCCCAAAA"),
("b1", "TTTTACGTACGT"),
("b2", "CCCCGGGGACGT"),
]
.into_iter()
.collect();
let mut store = RefgetStore::open_local(dir.path()).unwrap();
let listed = store.list_sequences().unwrap();
assert_eq!(listed.len(), 4);
for m in &listed {
assert_eq!(store.get_substring(&m.sha512t24u, 0, m.length).unwrap(), bases[m.name.as_str()]);
}
}
#[test]
fn count_gate_standalone_only() {
let work = tempdir().unwrap();
let fasta = work.path().join("in.fa");
fs::write(&fasta, ">a\nACGT\n>b\nGGGG\n>c\nTTTT\n").unwrap();
let dir = tempdir().unwrap();
{
let mut s = RefgetStore::on_disk(dir.path()).unwrap();
s.set_quiet(true);
let err = s.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().standalone_file_limit(2),
);
assert!(err.is_err(), "count gate should reject");
}
assert!(collect_seq_files(dir.path()).is_empty(), "no .seq files after gate rejection");
assert!(!dir.path().join("sequences.pack.idx").exists());
{
let mut s = RefgetStore::on_disk(dir.path()).unwrap();
s.set_quiet(true);
let err = s
.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().standalone_file_limit(2).force(true),
)
.expect_err("force must not skip the count gate");
let msg = err.to_string();
assert!(msg.contains("standalone_file_limit"), "{msg}");
assert!(!msg.contains("force"), "the message must not suggest force: {msg}");
}
assert!(collect_seq_files(dir.path()).is_empty(), "no .seq files after a forced rejection");
{
let mut s = RefgetStore::on_disk(dir.path()).unwrap();
s.set_quiet(true);
s.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().standalone_file_limit(3),
)
.unwrap();
}
assert!(!collect_seq_files(dir.path()).is_empty(), "a raised limit should write files");
let pdir = tempdir().unwrap();
{
let mut s = RefgetStore::on_disk_packed(pdir.path()).unwrap();
s.set_quiet(true);
s.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().standalone_file_limit(2),
)
.unwrap();
}
assert!(!collect_packs(pdir.path()).is_empty(), "packed import should succeed");
}
#[test]
fn default_standalone_file_limit_is_500k() {
assert_eq!(FastaImportOptions::new().standalone_file_limit, 500_000);
}
#[test]
fn count_gate_ignores_reimported_sequences() {
let work = tempdir().unwrap();
let fasta = work.path().join("in.fa");
fs::write(&fasta, ">a\nACGT\n>b\nGGGG\n>c\nTTTT\n").unwrap();
let dir = tempdir().unwrap();
let mut s = RefgetStore::on_disk(dir.path()).unwrap();
s.set_quiet(true);
s.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().standalone_file_limit(4),
)
.unwrap();
assert!(work.path().join("in.rgsi").exists(), "first import writes .rgsi");
s.add_sequence_collection_from_fasta(
&fasta,
FastaImportOptions::new().standalone_file_limit(4),
)
.expect("re-import of present sequences must pass the gate");
}
#[test]
fn deletion_dead_bytes_and_compact() {
let work = tempdir().unwrap();
let fa = work.path().join("a.fa");
let fb = work.path().join("b.fa");
fs::write(&fa, ">shared\nACGTACGTACGT\n>a_only\nAAAACCCCGGGG\n").unwrap();
fs::write(&fb, ">shared\nACGTACGTACGT\n>b_only\nTTTTGGGGCCCC\n").unwrap();
let dir = tempdir().unwrap();
let (dig_a, len_a_only, shared_sha, shared_len);
{
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
let (ma, _) = s
.add_sequence_collection_from_fasta(&fa, FastaImportOptions::new().jobs(1))
.unwrap();
s.add_sequence_collection_from_fasta(&fb, FastaImportOptions::new().jobs(1)).unwrap();
dig_a = ma.digest.clone();
len_a_only = 12usize.div_ceil(4) as u64; let sm = s.sequence_metadata().find(|m| m.name == "shared").unwrap();
shared_sha = sm.sha512t24u.clone();
shared_len = sm.length;
let removed = s.remove_collection(&dig_a, true).unwrap();
assert!(removed);
}
let store = RefgetStore::open_local(dir.path()).unwrap();
assert_eq!(store.get_substring(&shared_sha, 0, shared_len).unwrap(), "ACGTACGTACGT");
assert!(
store.sequence_metadata().all(|m| m.name != "a_only"),
"a_only should be gone from the index"
);
let dead = store.packed_dead_bytes().unwrap();
assert_eq!(dead, len_a_only, "dead bytes should equal a_only's encoded length");
let mut store = RefgetStore::open_local(dir.path()).unwrap();
let report = store.compact().unwrap();
assert!(report.bytes_reclaimed >= len_a_only, "compact should reclaim dead bytes");
assert_eq!(store.packed_dead_bytes().unwrap(), 0, "no dead bytes after compact");
assert_eq!(store.get_substring(&shared_sha, 0, shared_len).unwrap(), "ACGTACGTACGT");
}
#[test]
fn compact_keeps_a_batch_lock_the_caller_holds() {
let work = tempdir().unwrap();
let fasta = work.path().join("in.fa");
fs::write(&fasta, PACKED_FASTA).unwrap();
let dir = tempdir().unwrap();
let mut store = build_packed(dir.path(), &fasta, 1, false, None);
store.lock_for_batch("x").unwrap();
store.compact().unwrap();
assert!(store.holds_batch_lock(), "compact released the caller's lock");
store.release_batch_lock();
store.compact().unwrap();
assert!(!store.holds_batch_lock());
}
#[test]
fn compact_prunes_unreferenced_packs_only_on_request() {
let work = tempdir().unwrap();
let fasta = work.path().join("in.fa");
fs::write(&fasta, PACKED_FASTA).unwrap();
let dir = tempdir().unwrap();
drop(build_packed(dir.path(), &fasta, 1, false, None));
let packs = collect_packs(dir.path());
assert_eq!(packs.len(), 1, "the import should commit one pack");
let packs_dir = dir.path().join("packs");
let unlisted = "0123456789abcdef0123456789abcdef.pack";
fs::copy(packs_dir.join(packs.keys().next().unwrap()), packs_dir.join(unlisted)).unwrap();
let temp = ".rgstore.tmp.pack.session.other.0";
fs::write(packs_dir.join(temp), b"another writer's open pack").unwrap();
let mut store = RefgetStore::open_local(dir.path()).unwrap();
let report = store.compact().unwrap();
assert_eq!(report.packs_pruned, 0);
assert!(packs_dir.join(unlisted).exists(), "compact() deleted an unlisted pack");
assert!(store.packed_dead_bytes().unwrap() > 0);
let report = store.compact_with(CompactOptions { prune_unreferenced: true }).unwrap();
assert_eq!(report.packs_pruned, 1);
assert!(!packs_dir.join(unlisted).exists(), "the unlisted pack survived pruning");
assert!(packs_dir.join(temp).exists(), "pruning deleted a temp file");
assert_eq!(store.packed_dead_bytes().unwrap(), 0);
let on_disk: std::collections::BTreeSet<String> =
collect_packs(dir.path()).into_keys().collect();
let indexed: std::collections::BTreeSet<String> =
sidecar_packs(dir.path()).into_iter().map(|p| format!("{p}.pack")).collect();
assert_eq!(on_disk, indexed);
let reopened = RefgetStore::open_local(dir.path()).unwrap();
for record in PACKED_FASTA.split('>').filter(|r| !r.trim().is_empty()) {
let bases: String = record.lines().skip(1).collect();
let sha = sha512t24u(bases.as_bytes());
assert_eq!(reopened.get_substring(&sha, 0, bases.len()).unwrap(), bases);
}
}
#[test]
fn fully_dead_pack_unlinked() {
let work = tempdir().unwrap();
let fa = work.path().join("a.fa");
let fb = work.path().join("b.fa");
fs::write(&fa, ">shared\nACGTACGTACGT\n>a_only\nAAAACCCCGGGG\n").unwrap();
fs::write(&fb, ">shared\nACGTACGTACGT\n>b_only\nTTTTGGGGCCCC\n").unwrap();
let dir = tempdir().unwrap();
let dig_a;
{
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
s.set_pack_cap_bytes(1); let (ma, _) = s
.add_sequence_collection_from_fasta(&fa, FastaImportOptions::new().jobs(1))
.unwrap();
s.add_sequence_collection_from_fasta(&fb, FastaImportOptions::new().jobs(1)).unwrap();
dig_a = ma.digest.clone();
}
let packs_before = collect_packs(dir.path()).len();
{
let mut s = RefgetStore::open_local(dir.path()).unwrap();
s.remove_collection(&dig_a, true).unwrap();
}
let packs_after = collect_packs(dir.path()).len();
assert!(packs_after < packs_before, "a_only's dead pack should be unlinked");
let store = RefgetStore::open_local(dir.path()).unwrap();
assert_eq!(store.packed_dead_bytes().unwrap(), 0, "no dead bytes after eager unlink");
}
#[test]
fn incremental_add_sequence_record() {
use crate::digest::{digest_sequence, encode_sequence, lookup_alphabet};
let dir = tempdir().unwrap();
let (sha1, sha2);
{
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
let pack_encoded = |name: &str, seq: &[u8]| -> SequenceRecord {
match digest_sequence(name, seq) {
SequenceRecord::Full { metadata, sequence } => {
let alphabet = lookup_alphabet(&metadata.alphabet);
let encoded = encode_sequence(&sequence[..], alphabet);
SequenceRecord::Full { metadata, sequence: encoded.unwrap().into() }
}
other => other,
}
};
let r1 = pack_encoded("seg1", b"ACGTACGTACGT");
let r2 = pack_encoded("seg2", b"GGGGCCCCAAAA");
sha1 = r1.metadata().sha512t24u.clone();
sha2 = r2.metadata().sha512t24u.clone();
s.add_sequence_record(r1, false).unwrap();
assert_eq!(s.get_substring(&sha1, 0, 12).unwrap(), "ACGTACGTACGT");
s.add_sequence_record(r2, false).unwrap();
s.write().unwrap();
}
assert!(dir.path().join("sequences.pack.idx").exists());
assert!(!collect_packs(dir.path()).is_empty(), "session pack should be sealed");
let store = RefgetStore::open_local(dir.path()).unwrap();
assert_eq!(store.get_substring(&sha1, 0, 12).unwrap(), "ACGTACGTACGT");
assert_eq!(store.get_substring(&sha2, 0, 12).unwrap(), "GGGGCCCCAAAA");
}
#[test]
fn standalone_unchanged_and_missing_layout_defaults() {
let work = tempdir().unwrap();
let fasta = work.path().join("in.fa");
fs::write(&fasta, PACKED_FASTA).unwrap();
let dir = tempdir().unwrap();
let _ = build_standalone(dir.path(), &fasta, false);
assert!(collect_packs(dir.path()).is_empty());
assert!(!dir.path().join("sequences.pack.idx").exists());
let manifest_path = dir.path().join("rgstore.json");
let mut json: serde_json::Value =
serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap();
json.as_object_mut().unwrap().remove("layout");
fs::write(&manifest_path, serde_json::to_string_pretty(&json).unwrap()).unwrap();
let store = RefgetStore::open_local(dir.path()).unwrap();
assert_eq!(store.inner.layout, Layout::Standalone);
}
#[test]
fn on_disk_packed_rejects_existing_standalone() {
let work = tempdir().unwrap();
let fasta = work.path().join("in.fa");
fs::write(&fasta, ">a\nACGT\n").unwrap();
let dir = tempdir().unwrap();
let _ = build_standalone(dir.path(), &fasta, false);
assert!(RefgetStore::on_disk_packed(dir.path()).is_err());
}
#[test]
fn export_packed_to_standalone_image() {
let work = tempdir().unwrap();
let fasta = work.path().join("in.fa");
fs::write(&fasta, PACKED_FASTA).unwrap();
let pdir = tempdir().unwrap();
let store = build_packed(pdir.path(), &fasta, 4, false, Some(8));
let exported = tempdir().unwrap();
store.write_store_to_dir(exported.path(), None).unwrap();
assert!(!collect_seq_files(exported.path()).is_empty(), "export should write .seq files");
assert!(collect_packs(exported.path()).is_empty(), "export must not write packs");
let manifest = fs::read_to_string(exported.path().join("rgstore.json")).unwrap();
assert!(manifest.contains("\"layout\": \"standalone\""));
let reopened = RefgetStore::open_local(exported.path()).unwrap();
for (sha, len) in seqs(&store) {
assert_eq!(
store.get_substring(&sha, 0, len).unwrap(),
reopened.get_substring(&sha, 0, len).unwrap(),
"exported retrieval must match packed source for {sha}"
);
}
}
fn expected_by_digest(store: &RefgetStore) -> Vec<(String, String)> {
let by_name: std::collections::HashMap<&str, &str> = PACKED_FASTA
.split('>')
.filter(|r| !r.is_empty())
.map(|r| {
let mut it = r.splitn(2, '\n');
(it.next().unwrap(), it.next().unwrap().trim_end())
})
.collect();
let mut v: Vec<(String, String)> = store
.sequence_metadata()
.map(|m| (m.sha512t24u.clone(), by_name[m.name.as_str()].to_string()))
.collect();
v.sort();
v
}
#[test]
fn packed_store_serves_every_mode_through_all_read_paths() {
for mode in [StorageMode::Raw, StorageMode::Encoded, StorageMode::Zstd] {
let dir = tempdir().unwrap();
let fasta = dir.path().join("p.fa");
fs::write(&fasta, PACKED_FASTA).unwrap();
let store_dir = dir.path().join("store");
{
let mut s = RefgetStore::on_disk_packed(&store_dir).unwrap();
s.set_quiet(true);
s.set_encoding_mode(mode).unwrap();
s.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(2))
.unwrap();
s.write().unwrap();
}
assert!(collect_seq_files(&store_dir).is_empty(), "{mode:?}: packed store wrote .seq files");
assert!(!collect_packs(&store_dir).is_empty(), "{mode:?}: packed store has no packs");
let manifest = fs::read_to_string(store_dir.join("rgstore.json")).unwrap();
assert!(manifest.contains("\"layout\": \"packed\""), "{mode:?} manifest: {manifest}");
for cache_mb in [0, 1] {
let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
reopened.set_quiet(true);
reopened.set_pack_cache_mb(cache_mb);
let expected = expected_by_digest(&reopened);
let ro = reopened.into_readonly();
for (sha, want) in &expected {
let n = want.len();
let got = ro.get_substring(sha, 1, n - 1).unwrap();
assert_eq!(got.as_str(), &want[1..n - 1], "{mode:?} cache={cache_mb} substring");
let ranges = [(0, n), (0, 4), (2, 7), (n - 4, n), (1, 1)];
let got = ro.get_substrings(sha, &ranges).unwrap();
let wanted: Vec<&str> = ranges.iter().map(|&(s, e)| &want[s..e]).collect();
assert_eq!(got, wanted, "{mode:?} cache={cache_mb} get_substrings");
let mut r = ro.stream_sequence(sha, Some(2), Some(n as u64)).unwrap();
let mut streamed = String::new();
r.read_to_string(&mut streamed).unwrap();
assert_eq!(streamed, want[2..], "{mode:?} cache={cache_mb} stream");
assert!(ro.verify_sequence(sha, true).unwrap().is_none(), "{mode:?} cache={cache_mb} verify");
}
let cached_blocks = ro.pack_cache.as_ref().map(|c| c.cached_block_count());
match cache_mb {
0 => assert_eq!(cached_blocks, None, "{mode:?}: the cache is off by default"),
_ => assert!(cached_blocks.unwrap() > 0, "{mode:?}: reads did not go through the cache"),
}
let digests: Vec<String> = expected.iter().map(|(d, _)| d.clone()).collect();
assert!(ro.load_resident(&digests).unwrap() > 0, "{mode:?} cache={cache_mb} resident load");
for (sha, want) in &expected {
let got = ro.get_substring(sha, 0, want.len()).unwrap();
assert_eq!(got.as_str(), want.as_str(), "{mode:?} cache={cache_mb} resident read");
}
}
}
}
#[test]
fn packed_store_refuses_mode_switch_once_populated() {
let dir = tempdir().unwrap();
let fasta = dir.path().join("p.fa");
fs::write(&fasta, PACKED_FASTA).unwrap();
let mut s = build_packed(&dir.path().join("store"), &fasta, 1, false, None);
assert!(s.set_encoding_mode(StorageMode::Raw).is_err());
assert_eq!(s.storage_mode(), StorageMode::Encoded);
}
#[test]
fn packed_store_streaming_export_roundtrips() {
for raw in [false, true] {
let dir = tempdir().unwrap();
let fasta = dir.path().join("p.fa");
fs::write(&fasta, PACKED_FASTA).unwrap();
let store_dir = dir.path().join("store");
let digest = {
let s = build_packed(&store_dir, &fasta, 1, raw, Some(8));
s.list_collections(0, 10, &[]).unwrap().results[0].digest.clone()
};
assert!(collect_packs(&store_dir).len() > 1, "small cap should make several packs");
let mut store = RefgetStore::open_local(&store_dir).unwrap();
store.set_quiet(true);
let out = dir.path().join("out.fa");
let opts = ExportOptions {
label: LabelTemplate::parse("{name}").unwrap(),
molecule: None,
line_width: 0,
};
let sel = ExportSelection::Collections { digests: vec![digest], names: None };
store.export_fasta(&sel, &out, &opts).unwrap();
assert_eq!(fs::read_to_string(&out).unwrap(), PACKED_FASTA, "raw={raw}");
}
}
#[test]
fn packed_import_partial_failure_stays_readable() {
let expected: std::collections::HashMap<&str, &str> =
[("a1", "ACGTACGTACGT"), ("a2", "GGGGCCCCAAAA")].into_iter().collect();
for (jobs, cap) in [(1, None), (2, None), (1, Some(1)), (2, Some(1))] {
let work = tempdir().unwrap();
let fa = work.path().join("a.fa");
let fb = work.path().join("b.fa");
fs::write(&fa, ">a1\nACGTACGTACGT\n>a2\nGGGGCCCCAAAA\n").unwrap();
fs::write(&fb, b">b1\nTTTTCCCCAAAAGGGG\n>b2\nCCCCAAAA\n>\xff\nACGT\n").unwrap();
let dir = tempdir().unwrap();
{
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
if let Some(cap) = cap {
s.set_pack_cap_bytes(cap);
}
s.add_sequence_collections_from_fastas(
&[fa.clone(), fb.clone()],
FastaImportOptions::new().jobs(jobs),
)
.expect_err("b.fa is malformed");
s.write().unwrap();
}
let mut store = RefgetStore::open_local(dir.path()).unwrap();
let listed = store.list_sequences().unwrap();
let mut names: Vec<&str> = listed.iter().map(|m| m.name.as_str()).collect();
names.sort();
assert_eq!(names, ["a1", "a2"], "jobs={jobs}");
for m in &listed {
let got = store
.get_substring(&m.sha512t24u, 0, m.length)
.unwrap_or_else(|e| panic!("jobs={jobs}: cannot read {}: {e}", m.name));
assert_eq!(got, expected[m.name.as_str()], "jobs={jobs}: {}", m.name);
}
let idx = fs::read(dir.path().join("sequences.pack.idx")).unwrap();
let rows = crate::store::packidx::read_pack_idx_rows(&idx).unwrap();
let mut indexed: Vec<&String> = rows.keys().collect();
indexed.sort();
let mut published: Vec<&String> = listed.iter().map(|m| &m.sha512t24u).collect();
published.sort();
assert_eq!(indexed, published, "jobs={jobs}: pack rows must match the index");
let referenced: std::collections::BTreeSet<String> =
rows.values().map(|r| format!("{}.pack", r.pack)).collect();
let on_disk: std::collections::BTreeSet<String> =
collect_packs(dir.path()).into_keys().collect();
assert_eq!(on_disk, referenced, "jobs={jobs} cap={cap:?}: unindexed packs left");
}
}
fn lcg_bases(seed: u64, len: usize) -> String {
let mut x = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(0..len)
.map(|_| {
x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
b"ACGT"[(x >> 33) as usize % 4] as char
})
.collect()
}
#[test]
fn two_packed_writers_in_one_process_do_not_share_temp_packs() {
let work = tempdir().unwrap();
let mut expected: std::collections::HashMap<String, String> = Default::default();
let mut fastas = Vec::new();
for (w, prefix) in ["a", "b"].iter().enumerate() {
let mut text = String::new();
for i in 0..40 {
let name = format!("{prefix}{i}");
let bases = lcg_bases((w as u64) * 1_000_000 + i, 400);
text.push_str(&format!(">{name}\n{bases}\n"));
expected.insert(name, bases);
}
let path = work.path().join(format!("{prefix}.fa"));
fs::write(&path, text).unwrap();
fastas.push(path);
}
let dir = tempdir().unwrap();
RefgetStore::on_disk_packed(dir.path()).unwrap().write().unwrap();
let mut handles: Vec<RefgetStore> = (0..2)
.map(|_| {
let mut s = RefgetStore::open_local(dir.path()).unwrap();
s.set_quiet(true);
s.set_pack_cap_bytes(300);
s
})
.collect();
let barrier = std::sync::Barrier::new(2);
std::thread::scope(|scope| {
for (s, fasta) in handles.iter_mut().zip(&fastas) {
let barrier = &barrier;
scope.spawn(move || {
barrier.wait();
s.add_sequence_collection_from_fasta(fasta, FastaImportOptions::new().jobs(2))
.unwrap();
});
}
});
drop(handles);
let leftovers: Vec<String> = fs::read_dir(dir.path().join("packs"))
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with(".rgstore.tmp."))
.collect();
assert!(leftovers.is_empty(), "temp packs left behind: {leftovers:?}");
let mut store = RefgetStore::open_local(dir.path()).unwrap();
let listed = store.list_sequences().unwrap();
assert_eq!(listed.len(), expected.len());
for m in &listed {
let got = store
.get_substring(&m.sha512t24u, 0, m.length)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", m.name));
assert_eq!(got, expected[&m.name], "{}", m.name);
}
}
fn encoded_record(name: &str, seq: &[u8]) -> SequenceRecord {
use crate::digest::{digest_sequence, encode_sequence, lookup_alphabet};
match digest_sequence(name, seq) {
SequenceRecord::Full { metadata, sequence } => {
let encoded = encode_sequence(&sequence[..], lookup_alphabet(&metadata.alphabet));
SequenceRecord::Full { metadata, sequence: encoded.unwrap().into() }
}
other => other,
}
}
fn sidecar_packs(dir: &std::path::Path) -> std::collections::HashSet<String> {
match fs::read(dir.join("sequences.pack.idx")) {
Ok(bytes) => crate::store::packidx::read_pack_idx_rows(&bytes)
.unwrap()
.values()
.map(|r| r.pack.to_string())
.collect(),
Err(_) => Default::default(),
}
}
#[test]
fn dropping_unsealed_session_pack_removes_its_temp() {
let dir = tempdir().unwrap();
{
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
s.add_sequence_record(encoded_record("seg1", b"ACGTACGTACGT"), false).unwrap();
let temps = fs::read_dir(dir.path().join("packs")).unwrap().count();
assert_eq!(temps, 1, "the session pack should be open");
}
assert_eq!(fs::read_dir(dir.path().join("packs")).unwrap().count(), 0);
}
fn writer_with_sealed_uncommitted_pack(
dir: &std::path::Path,
) -> (RefgetStore, Vec<(String, &'static str)>) {
let mut a = RefgetStore::open_local(dir).unwrap();
a.set_quiet(true);
a.set_pack_cap_bytes(1);
let mut held = Vec::new();
for (name, bases) in [("a1", "TTTTGGGGCCCCAAAA"), ("a2", "GGGGAAAATTTTCCCC")] {
let record = encoded_record(name, bases.as_bytes());
held.push((record.metadata().sha512t24u.clone(), bases));
a.add_sequence_record(record, false).unwrap();
}
(a, held)
}
#[test]
fn removal_and_compact_spare_another_writers_uncommitted_pack() {
let work = tempdir().unwrap();
let fx = work.path().join("x.fa");
fs::write(&fx, ">x1\nAAAACCCCGGGGTTTT\n>x2\nACGTACGTACGTACGT\n").unwrap();
let dir = tempdir().unwrap();
let dig_x = {
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
s.set_pack_cap_bytes(1);
let (meta, _) = s
.add_sequence_collection_from_fasta(&fx, FastaImportOptions::new().jobs(1))
.unwrap();
meta.digest
};
let x_packs = sidecar_packs(dir.path());
let (a, held) = writer_with_sealed_uncommitted_pack(dir.path());
let uncommitted: Vec<String> = collect_packs(dir.path())
.into_keys()
.filter(|n| !x_packs.contains(n.trim_end_matches(".pack")))
.collect();
assert_eq!(uncommitted.len(), 1, "A should have sealed one pack: {uncommitted:?}");
{
let mut b = RefgetStore::open_local(dir.path()).unwrap();
b.set_quiet(true);
assert!(b.remove_collection(&dig_x, true).unwrap());
b.compact().unwrap();
}
let packs_after = collect_packs(dir.path());
assert!(packs_after.contains_key(&uncommitted[0]), "B deleted A's uncommitted pack");
for x in &x_packs {
assert!(!packs_after.contains_key(&format!("{x}.pack")), "X's dead pack {x} survived");
}
a.write().unwrap();
drop(a);
let store = RefgetStore::open_local(dir.path()).unwrap();
for (sha, bases) in &held {
assert_eq!(store.get_substring(sha, 0, bases.len()).unwrap(), *bases);
}
}
#[test]
fn commit_refuses_rows_whose_pack_is_gone() {
let dir = tempdir().unwrap();
RefgetStore::on_disk_packed(dir.path()).unwrap().write().unwrap();
let (a, _) = writer_with_sealed_uncommitted_pack(dir.path());
for name in collect_packs(dir.path()).keys() {
fs::remove_file(dir.path().join("packs").join(name)).unwrap();
}
let err = a.write().expect_err("the commit must refuse a missing pack");
assert!(err.to_string().contains("no longer in the store"), "{err}");
assert!(sidecar_packs(dir.path()).is_empty(), "no rows may be published");
}
#[test]
fn dropping_a_handle_removes_its_uncommitted_sealed_packs() {
let dir = tempdir().unwrap();
RefgetStore::on_disk_packed(dir.path()).unwrap().write().unwrap();
let (a, _) = writer_with_sealed_uncommitted_pack(dir.path());
assert_eq!(collect_packs(dir.path()).len(), 1, "a1's pack should be sealed");
drop(a);
let left: Vec<_> = fs::read_dir(dir.path().join("packs"))
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name())
.collect();
assert!(left.is_empty(), "packs/ should be empty: {left:?}");
let (a, mut held) = writer_with_sealed_uncommitted_pack(dir.path());
a.write().unwrap();
drop(a);
let work = tempdir().unwrap();
let fasta = work.path().join("c.fa");
let imported = [("c1", "ACGTTGCAACGTTGCA"), ("c2", "CCCCGGGGAAAATTTT")];
let text: String = imported.iter().map(|(n, b)| format!(">{n}\n{b}\n")).collect();
fs::write(&fasta, text).unwrap();
{
let mut s = RefgetStore::open_local(dir.path()).unwrap();
s.set_quiet(true);
s.set_pack_cap_bytes(1);
s.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(1))
.unwrap();
}
held.extend(imported.iter().map(|(_, b)| (sha512t24u(b.as_bytes()), *b)));
let on_disk: std::collections::BTreeSet<String> =
collect_packs(dir.path()).into_keys().collect();
let indexed: std::collections::BTreeSet<String> =
sidecar_packs(dir.path()).into_iter().map(|p| format!("{p}.pack")).collect();
assert_eq!(on_disk.len(), 4, "one pack per sequence: {on_disk:?}");
assert_eq!(on_disk, indexed);
let store = RefgetStore::open_local(dir.path()).unwrap();
for (sha, bases) in &held {
assert_eq!(store.get_substring(sha, 0, bases.len()).unwrap(), *bases);
}
}
#[cfg(unix)]
#[test]
fn failed_session_seal_keeps_sealed_rows_for_the_next_commit() {
use std::os::unix::fs::PermissionsExt;
let dir = tempdir().unwrap();
RefgetStore::on_disk_packed(dir.path()).unwrap().write().unwrap();
let (a, held) = writer_with_sealed_uncommitted_pack(dir.path());
let packs = dir.path().join("packs");
fs::set_permissions(&packs, fs::Permissions::from_mode(0o555)).unwrap();
if fs::write(packs.join("probe"), b"x").is_ok() {
let _ = fs::remove_file(packs.join("probe"));
fs::set_permissions(&packs, fs::Permissions::from_mode(0o755)).unwrap();
return;
}
let first = a.write();
fs::set_permissions(&packs, fs::Permissions::from_mode(0o755)).unwrap();
first.expect_err("sealing the open pack fails while packs/ is read-only");
a.write().unwrap();
drop(a);
let store = RefgetStore::open_local(dir.path()).unwrap();
for (sha, bases) in &held {
assert_eq!(store.get_substring(sha, 0, bases.len()).unwrap(), *bases);
}
use sha2::Digest as _;
for (name, bytes) in collect_packs(dir.path()) {
let digest = sha2::Sha256::digest(&bytes);
let want: String = digest[..16].iter().map(|b| format!("{:02x}", b)).collect();
assert_eq!(name, format!("{want}.pack"));
}
}
#[cfg(unix)]
#[test]
fn append_after_partial_write_keeps_offsets_and_pack_name() {
use sha2::Digest as _;
use std::io::{Seek as _, SeekFrom, Write as _};
let dir = tempdir().unwrap();
let mut held = Vec::new();
{
let mut s = RefgetStore::on_disk_packed(dir.path()).unwrap();
s.set_quiet(true);
for (i, (name, bases)) in
[("a", "ACGTACGTTTTTGGGGCCCCAAAA"), ("b", "GGGGAAAATTTTCCCC")].into_iter().enumerate()
{
if i == 1 {
let mut guard = s.inner.open_session_pack.lock().unwrap();
let session = guard.as_mut().unwrap();
session.file.seek(SeekFrom::Start(session.len)).unwrap();
session.file.write_all(b"partial write").unwrap();
}
let record = encoded_record(name, bases.as_bytes());
held.push((record.metadata().sha512t24u.clone(), bases));
s.add_sequence_record(record, false).unwrap();
}
s.write().unwrap();
}
let store = RefgetStore::open_local(dir.path()).unwrap();
for (sha, bases) in &held {
assert_eq!(store.get_substring(sha, 0, bases.len()).unwrap(), *bases);
}
let rows = crate::store::packidx::read_pack_idx_rows(
&fs::read(dir.path().join("sequences.pack.idx")).unwrap(),
)
.unwrap();
let packs = collect_packs(dir.path());
assert_eq!(packs.len(), 1);
for (name, bytes) in packs {
let digest = sha2::Sha256::digest(&bytes);
let want: String = digest[..16].iter().map(|b| format!("{:02x}", b)).collect();
assert_eq!(name, format!("{want}.pack"), "pack name must hash its content");
let covered: u64 = rows
.values()
.filter(|r| format!("{}.pack", r.pack) == name)
.map(|r| r.len)
.sum();
assert_eq!(bytes.len() as u64, covered, "{name} holds bytes no row covers");
}
}
#[cfg(unix)]
#[test]
fn failed_record_write_leaves_no_trace() {
use std::os::unix::fs::PermissionsExt;
let listed = |store: &RefgetStore| -> std::collections::BTreeMap<String, String> {
store.sequence_metadata().map(|m| (m.sha512t24u, m.name)).collect()
};
let reads_back = |dir: &std::path::Path, held: &[(String, &str)]| {
let store = RefgetStore::open_local(dir).unwrap();
let names = listed(&store);
let want: std::collections::BTreeSet<&String> = held.iter().map(|(s, _)| s).collect();
assert_eq!(names.keys().collect::<std::collections::BTreeSet<_>>(), want);
for (sha, bases) in held {
assert_eq!(store.get_substring(sha, 0, bases.len()).unwrap(), *bases);
}
names
};
let (kept_bases, failed_bases) = ("ACGTACGTTTTTGGGG", "GGGGAAAATTTTCCCCACGT");
for packed in [true, false] {
let dir = tempdir().unwrap();
let mut s = if packed {
RefgetStore::on_disk_packed(dir.path())
} else {
RefgetStore::on_disk(dir.path())
}
.unwrap();
s.set_quiet(true);
let kept = encoded_record("kept", kept_bases.as_bytes());
let failed = encoded_record("failed", failed_bases.as_bytes());
let mut held = vec![(kept.metadata().sha512t24u.clone(), kept_bases)];
s.add_sequence_record(kept, false).unwrap();
s.write().unwrap();
let data_dir = dir.path().join(if packed { "packs" } else { "sequences" });
fs::create_dir_all(&data_dir).unwrap();
let mut dirs = vec![data_dir.clone()];
dirs.extend(
fs::read_dir(&data_dir)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.is_dir()),
);
let set_mode = |mode: u32| {
for d in &dirs {
fs::set_permissions(d, fs::Permissions::from_mode(mode)).unwrap();
}
};
set_mode(0o555);
if fs::write(data_dir.join("probe"), b"x").is_ok() {
let _ = fs::remove_file(data_dir.join("probe"));
set_mode(0o755);
return;
}
let new_add = s.add_sequence_record(failed.clone(), false);
let renamed = encoded_record("renamed", kept_bases.as_bytes());
let forced_add = s.add_sequence_record(renamed, true);
set_mode(0o755);
new_add.expect_err("adding a record whose bytes cannot be written must fail");
forced_add.expect_err("a forced re-add whose bytes cannot be written must fail");
assert!(s.sequence_metadata().all(|m| m.name != "failed"), "packed={packed}");
s.write().unwrap();
let names = reads_back(dir.path(), &held);
assert_eq!(names[&held[0].0], "kept", "packed={packed}: the failed re-add renamed it");
s.add_sequence_record(failed, false).unwrap();
held.push((sha512t24u(failed_bases.as_bytes()), failed_bases));
s.write().unwrap();
drop(s);
reads_back(dir.path(), &held);
}
}
}
fn reference_record(header: &str, seq: &str, line_width: usize) -> String {
let mut out = format!(">{}\n", header);
if line_width == 0 {
out.push_str(seq);
out.push('\n');
} else {
for line in seq.as_bytes().chunks(line_width) {
out.push_str(std::str::from_utf8(line).unwrap());
out.push('\n');
}
}
out
}
#[test]
fn test_write_fasta_record_chunking_matches_whole_decode() {
use super::export::write_fasta_record;
use crate::digest::{encode_sequence, lookup_alphabet};
let alphabets = [
(AlphabetType::Dna2bit, "ACGT"),
(AlphabetType::Dna3bit, "ACGTN"),
(AlphabetType::DnaIupac, "ACGTRYKMN"),
(AlphabetType::Protein, "ACDEFGHIKLMNPQRSTVWY*"),
];
let chunk_bases = 5;
for (alphabet, letters) in alphabets {
for line_width in [0usize, 1, 3, 7, 80] {
let chunk = if line_width == 0 { chunk_bases } else { (chunk_bases / line_width).max(1) * line_width };
for len in [0, 1, chunk - 1, chunk, chunk + 1, 3 * chunk + 2] {
let seq: String = letters.chars().cycle().take(len).collect();
let meta = SequenceMetadata { length: len, alphabet, ..Default::default() };
let encoded = encode_sequence(&seq, lookup_alphabet(&alphabet)).unwrap();
let zstd = zstd::encode_all(seq.as_bytes(), 3).unwrap();
for (mode, data) in [
(StorageMode::Encoded, encoded.as_slice()),
(StorageMode::Raw, seq.as_bytes()),
(StorageMode::Zstd, zstd.as_slice()),
] {
let mut out: Vec<u8> = Vec::new();
write_fasta_record(&mut out, "h", &meta, data, mode, line_width, chunk_bases).unwrap();
assert_eq!(
String::from_utf8(out).unwrap(),
reference_record("h", &seq, line_width),
"{alphabet:?} {mode:?} len={len} width={line_width}"
);
}
}
}
}
}
#[test]
fn test_export_leaves_no_sequence_loaded() {
let dir = tempdir().unwrap();
let store_path = dir.path().join("store");
let fasta = dir.path().join("t.fa");
fs::write(&fasta, ">chr1\nACGTACGTAC\n>chr2\nGGGGAAAA\n").unwrap();
let digest = {
let mut w = RefgetStore::on_disk(&store_path).unwrap();
w.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new()).unwrap().0.digest
};
let bed = dir.path().join("r.bed");
fs::write(&bed, "chr1\t0\t4\nchr2\t2\t6\n").unwrap();
let mut store = RefgetStore::open_local(&store_path).unwrap();
store.set_quiet(true);
let out = dir.path().join("o.fa");
let all_digests: Vec<String> = store.list_sequences().unwrap().into_iter().map(|m| m.sha512t24u).collect();
let selections = [
coll_sel(&digest, None),
coll_sel(&digest, Some(&["chr2"])),
ExportSelection::SeqDigests(all_digests.clone()),
ExportSelection::All,
];
for sel in &selections {
for opts in [ExportOptions::default(), name_opts(80)] {
store.export_fasta(sel, &out, &opts).unwrap();
for d in &all_digests {
assert!(!store.is_sequence_loaded(d), "{sel:?} left {d} loaded");
}
}
}
let label = LabelTemplate::parse("{name}").unwrap();
store
.export_fasta_from_regions(&digest, bed.to_str().unwrap(), out.to_str().unwrap(), &label)
.unwrap();
assert_eq!(fs::read_to_string(&out).unwrap(), ">chr1:0-4\nACGT\n>chr2:2-6\nGGAA\n");
for d in &all_digests {
assert!(!store.is_sequence_loaded(d));
}
}
struct LabelFixture {
store: RefgetStore,
a: String,
b: String,
s1: String,
orphan: String,
_dir: tempfile::TempDir,
}
fn label_fixture() -> LabelFixture {
let dir = tempdir().unwrap();
let write = |name: &str, body: &str| {
let p = dir.path().join(name);
fs::write(&p, body).unwrap();
p
};
let fa = write("a.fa", ">chr1\nACGTACGT\n>x\nGGGGCCCC\n>onlyA\nTTTTAAAA\n");
let fb = write("b.fa", ">chr1\nACGTACGT\n>y\nGGGGCCCC\n>onlyB\nCCCCAAAA\n");
let fc = write("c.fa", ">c1\nAACCGGTT\n");
let fo = write("o.fa", ">orphan\nTGCATGCA\n");
let mut store = RefgetStore::in_memory();
store.set_quiet(true);
let a = store.add_sequence_collection_from_fasta(&fa, FastaImportOptions::new()).unwrap().0.digest;
let b = store.add_sequence_collection_from_fasta(&fb, FastaImportOptions::new()).unwrap().0.digest;
let c = store.add_sequence_collection_from_fasta(&fc, FastaImportOptions::new()).unwrap().0.digest;
let o = store.add_sequence_collection_from_fasta(&fo, FastaImportOptions::new()).unwrap().0.digest;
let orphan = store.get_sequence_by_name(&o, "orphan").unwrap().metadata().sha512t24u.clone();
store.remove_collection(&o, false).unwrap();
let s1 = store.get_sequence_by_name(&a, "chr1").unwrap().metadata().sha512t24u.clone();
store.add_sequence_alias("refseq", "NC_1", &s1).unwrap();
store.add_sequence_alias("ensembl", "E1", &s1).unwrap();
store.add_collection_alias("ucsc", "genA", &a).unwrap();
store.add_collection_alias("ucsc", "genB", &b).unwrap();
store.add_collection_alias("ucsc", "zzz", &c).unwrap();
store.add_collection_alias("ucsc", "cgen", &c).unwrap();
LabelFixture { store, a, b, s1, orphan, _dir: dir }
}
fn export_headers(store: &mut RefgetStore, sel: &ExportSelection, label: &str) -> anyhow::Result<(Vec<String>, ExportSummary)> {
let dir = tempdir().unwrap();
let out = dir.path().join("o.fa");
let opts = ExportOptions { label: LabelTemplate::parse(label)?, molecule: None, line_width: 80 };
let summary = store.export_fasta(sel, &out, &opts)?;
let headers = fs::read_to_string(&out)
.unwrap()
.lines()
.filter_map(|l| l.strip_prefix('>').map(str::to_string))
.collect();
Ok((headers, summary))
}
#[test]
fn test_label_seq_with_all_writes_each_sequence_once() {
let mut f = label_fixture();
let (headers, summary) = export_headers(&mut f.store, &ExportSelection::All, "{seq}").unwrap();
let mut unique: Vec<String> = f.store.list_sequences().unwrap().into_iter().map(|m| format!("SQ.{}", m.sha512t24u)).collect();
unique.sort();
assert_eq!(headers, unique, "digest order, each once");
assert!(headers.contains(&format!("SQ.{}", f.orphan)));
assert_eq!(summary.n_records, unique.len());
assert_eq!(summary.n_fallbacks, 0);
}
#[test]
fn test_label_collection_name_writes_each_genome_copy() {
let mut f = label_fixture();
let (headers, summary) = export_headers(&mut f.store, &ExportSelection::All, "{col}/{name}").unwrap();
for h in [format!("{}/chr1", f.a), format!("{}/chr1", f.b), format!("{}/x", f.a), format!("{}/y", f.b)] {
assert!(headers.contains(&h), "missing {h}");
}
assert_eq!(summary.n_records, 8);
assert_eq!(headers.last().unwrap(), &format!("SQ.{}", f.orphan));
assert_eq!(summary.n_fallbacks, 1);
let (headers, _) = export_headers(&mut f.store, &ExportSelection::All, "{col:ucsc}/{name}").unwrap();
assert!(headers.contains(&"genA/chr1".to_string()));
assert!(headers.contains(&"genB/chr1".to_string()));
assert!(headers.contains(&"cgen/c1".to_string()));
}
#[test]
fn test_label_alias_fallbacks_are_counted() {
let mut f = label_fixture();
let (headers, summary) = export_headers(&mut f.store, &coll_sel(&f.a, None), "{seq:refseq}").unwrap();
assert_eq!(headers[0], "NC_1");
assert!(headers[1].starts_with("SQ."));
assert_eq!(summary.n_fallbacks, 2);
let err = export_headers(&mut f.store, &coll_sel(&f.a, None), "{seq:nope}").unwrap_err().to_string();
assert!(err.contains("nope") && err.contains("refseq") && err.contains("ensembl"), "{err}");
let err = export_headers(&mut f.store, &coll_sel(&f.a, None), "{col:nope}/{name}").unwrap_err().to_string();
assert!(err.contains("nope") && err.contains("ucsc"), "{err}");
}
#[test]
fn test_label_name_with_all_clash_and_dedup() {
let mut f = label_fixture();
let dir = tempdir().unwrap();
let out = dir.path().join("o.fa");
let (headers, summary) = export_headers(&mut f.store, &coll_sel_many(&[&f.a, &f.b], Some(&["chr1"])), "{name}").unwrap();
assert_eq!(headers, vec!["chr1"]);
assert_eq!(summary.n_deduplicated, 1);
let (_, summary) = export_headers(&mut f.store, &ExportSelection::All, "{name}").unwrap();
assert_eq!(summary.n_deduplicated, 1);
let fd = dir.path().join("d.fa");
fs::write(&fd, ">chr1\nCCCCCCCC\n").unwrap();
f.store.add_sequence_collection_from_fasta(&fd, FastaImportOptions::new()).unwrap();
let opts = ExportOptions { label: LabelTemplate::parse("{name}").unwrap(), ..Default::default() };
let err = f.store.export_fasta(&ExportSelection::All, &out, &opts).unwrap_err().to_string();
assert!(err.contains("'chr1'") && err.contains("collection") && err.contains("{col}"), "{err}");
assert!(!out.exists(), "no output may be written before a label clash error");
}
fn coll_sel_many(digests: &[&str], names: Option<&[&str]>) -> ExportSelection {
ExportSelection::Collections {
digests: digests.iter().map(|d| d.to_string()).collect(),
names: names.map(|n| n.iter().map(|s| s.to_string()).collect()),
}
}
#[test]
fn test_label_same_for_one_collection_or_all() {
let mut f = label_fixture();
for t in ["{seq}", "{col}/{name}", "{col:ucsc}#{name}", "{seq:refseq}"] {
let (one, _) = export_headers(&mut f.store, &coll_sel(&f.b, None), t).unwrap();
let (all, _) = export_headers(&mut f.store, &ExportSelection::All, t).unwrap();
for h in &one {
assert!(all.contains(h), "{t}: {h} missing from All");
}
}
}
#[test]
fn test_label_whitespace_is_an_error() {
let mut f = label_fixture();
f.store.add_sequence_alias("spacey", "has space", &f.s1.clone()).unwrap();
let err = export_headers(&mut f.store, &coll_sel(&f.a, None), "{seq:spacey}").unwrap_err().to_string();
assert!(err.contains("whitespace"), "{err}");
let err = export_headers(&mut f.store, &coll_sel(&f.a, None), "{name} x").unwrap_err().to_string();
assert!(err.contains("whitespace"), "{err}");
}
#[test]
fn test_molecule_filter() {
let dir = tempdir().unwrap();
let fasta = dir.path().join("mix.fa");
fs::write(&fasta, ">dna\nACGTACGT\n>prot\nMKVLAAGIVGEFHW\n").unwrap();
let mut store = RefgetStore::in_memory();
store.set_quiet(true);
let digest = store.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new()).unwrap().0.digest;
let out = dir.path().join("o.fa");
for (molecule, expected) in [
(None, vec!["dna", "prot"]),
(Some(Molecule::Dna), vec!["dna"]),
(Some(Molecule::Protein), vec!["prot"]),
] {
let opts = ExportOptions { label: LabelTemplate::parse("{name}").unwrap(), molecule, line_width: 80 };
store.export_fasta(&coll_sel(&digest, None), &out, &opts).unwrap();
let headers: Vec<String> = fs::read_to_string(&out)
.unwrap()
.lines()
.filter_map(|l| l.strip_prefix('>').map(str::to_string))
.collect();
assert_eq!(headers, expected, "{molecule:?}");
}
assert!("rna".parse::<Molecule>().is_err());
assert_eq!("DNA".parse::<Molecule>().unwrap(), Molecule::Dna);
}