Skip to main content

gtars_refget/store/
alias.rs

1//! Alias management for human-readable sequence and collection names.
2//!
3//! Contains AliasManager types, store bridge methods, RefgetStore delegates,
4//! and remote pull methods.
5
6use super::*;
7use super::readonly::ReadonlyRefgetStore;
8use super::core::RefgetStore;
9
10use std::collections::{HashMap, HashSet};
11use std::fs::{self, File, create_dir_all};
12use std::io::{BufRead, BufReader};
13use std::path::Path;
14
15use anyhow::{Context, Result};
16
17use crate::hashkeyable::{DigestKey, HashKeyable, key_to_digest_string};
18
19// =========================================================================
20// Types
21// =========================================================================
22
23/// Identifies whether an alias targets a sequence or a collection.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum AliasKind {
26    Sequence,
27    Collection,
28}
29
30impl AliasKind {
31    /// Returns the subdirectory name for this alias kind.
32    pub fn subdir(&self) -> &'static str {
33        match self {
34            Self::Sequence => "sequences",
35            Self::Collection => "collections",
36        }
37    }
38}
39
40/// Generic alias store: namespace -> { alias -> digest_key }
41type AliasStore = HashMap<String, HashMap<String, DigestKey>>;
42
43/// Manages human-readable aliases for sequences and collections.
44#[derive(Debug)]
45pub struct AliasManager {
46    sequence_aliases: AliasStore,
47    collection_aliases: AliasStore,
48}
49
50// =========================================================================
51// Private helpers (operate on any AliasStore)
52// =========================================================================
53
54/// Error if `namespace` already binds `alias` to a digest other than `digest`,
55/// unless `force`. Read-only: the shared check behind every checked add.
56fn alias_check_existing(
57    store: &AliasStore,
58    kind: AliasKind,
59    namespace: &str,
60    alias: &str,
61    digest: &DigestKey,
62    force: bool,
63) -> Result<()> {
64    match alias_resolve(store, namespace, alias) {
65        Some(existing) if existing != *digest && !force => Err(anyhow::anyhow!(
66            "alias conflict in {} namespace '{}': '{}' already points to {}, \
67             refusing to point it to {}. Aliases must be unique within a namespace; \
68             use force-alias (CLI: --force-alias) only to deliberately re-point it.",
69            kind.subdir(),
70            namespace,
71            alias,
72            key_to_digest_string(&existing),
73            key_to_digest_string(digest),
74        )),
75        _ => Ok(()),
76    }
77}
78
79/// Bind `alias` -> `digest` in `namespace`. Same digest: no-op. Different
80/// digest: error unless `force`. A refused add leaves `store` untouched (no
81/// empty namespace is created).
82fn alias_add(
83    store: &mut AliasStore,
84    kind: AliasKind,
85    namespace: &str,
86    alias: &str,
87    digest: DigestKey,
88    force: bool,
89) -> Result<()> {
90    alias_check_existing(store, kind, namespace, alias, &digest, force)?;
91    store
92        .entry(namespace.to_string())
93        .or_default()
94        .insert(alias.to_string(), digest);
95    Ok(())
96}
97
98fn alias_resolve(store: &AliasStore, namespace: &str, alias: &str) -> Option<DigestKey> {
99    store.get(namespace).and_then(|ns| ns.get(alias)).copied()
100}
101
102fn alias_reverse_scan(store: &AliasStore, digest: &DigestKey) -> Vec<(String, String)> {
103    let mut results = Vec::new();
104    for (namespace, aliases) in store {
105        for (alias, d) in aliases {
106            if d == digest {
107                results.push((namespace.clone(), alias.clone()));
108            }
109        }
110    }
111    results
112}
113
114fn alias_namespaces(store: &AliasStore) -> Vec<String> {
115    store.keys().cloned().collect()
116}
117
118fn alias_list(store: &AliasStore, namespace: &str) -> Option<Vec<String>> {
119    store
120        .get(namespace)
121        .map(|ns| ns.keys().cloned().collect())
122}
123
124fn alias_remove(store: &mut AliasStore, namespace: &str, alias: &str) -> bool {
125    if let Some(ns) = store.get_mut(namespace) {
126        let removed = ns.remove(alias).is_some();
127        if ns.is_empty() {
128            store.remove(namespace);
129        }
130        removed
131    } else {
132        false
133    }
134}
135
136/// Load a user-supplied TSV into `store` under `namespace`, all or nothing.
137/// Returns the distinct alias names bound, in first-seen order.
138///
139/// Returns the names rather than a count because the store-level loaders have to
140/// record each one as a pending change — a commit only publishes aliases this
141/// handle actually touched.
142///
143/// Refuses the whole file, leaving `store` untouched, when:
144/// * the file maps one alias to two different digests. Always an error, even
145///   with `force`: one batch can never mean two things by one name, and letting
146///   the last row win is how per-genome names like `chr1` silently collapsed
147///   onto one genome.
148/// * an alias already in `store` points elsewhere, unless `force`.
149///
150/// Exact duplicate rows are fine and count once.
151fn alias_load_tsv(
152    store: &mut AliasStore,
153    kind: AliasKind,
154    namespace: &str,
155    path: &Path,
156    force: bool,
157) -> Result<Vec<String>> {
158    // Phase 1: parse every row.
159    let file = File::open(path)?;
160    let reader = BufReader::new(file);
161    let mut rows: Vec<(usize, String, DigestKey)> = Vec::new();
162    for (idx, line) in reader.lines().enumerate() {
163        let line = line?;
164        if line.starts_with('#') || line.trim().is_empty() {
165            continue;
166        }
167        let parts: Vec<&str> = line.splitn(2, '\t').collect();
168        if parts.len() == 2 {
169            rows.push((idx + 1, parts[0].to_string(), parts[1].to_key()));
170        }
171    }
172
173    // Phase 2: within this file, one alias must map to one digest.
174    let mut first_seen: HashMap<&str, (DigestKey, usize)> = HashMap::new();
175    let mut distinct: Vec<(&str, DigestKey)> = Vec::new();
176    let mut clashing: HashSet<&str> = HashSet::new();
177    let mut first_clash: Option<(&str, DigestKey, usize, DigestKey, usize)> = None;
178    for (line_no, alias, digest) in &rows {
179        match first_seen.get(alias.as_str()) {
180            None => {
181                first_seen.insert(alias, (*digest, *line_no));
182                distinct.push((alias, *digest));
183            }
184            Some(&(first_digest, first_line)) if first_digest != *digest => {
185                clashing.insert(alias);
186                if first_clash.is_none() {
187                    first_clash = Some((alias, first_digest, first_line, *digest, *line_no));
188                }
189            }
190            Some(_) => {}
191        }
192    }
193    if let Some((alias, digest_a, line_a, digest_b, line_b)) = first_clash {
194        return Err(anyhow::anyhow!(
195            "alias conflict in {} namespace '{}': '{}' maps '{}' to two different digests \
196             ({} on line {}, {} on line {}); {}. A namespace maps each alias to one digest; \
197             per-genome names such as chromosome names are not aliases.",
198            kind.subdir(),
199            namespace,
200            path.display(),
201            alias,
202            key_to_digest_string(&digest_a),
203            line_a,
204            key_to_digest_string(&digest_b),
205            line_b,
206            clash_scale(clashing.len()),
207        ));
208    }
209
210    // Phase 3: no alias may silently re-point an existing binding.
211    for (alias, digest) in &distinct {
212        alias_check_existing(store, kind, namespace, alias, digest, force)?;
213    }
214
215    // Phase 4: apply. Validated above, so nothing below can fail.
216    if !distinct.is_empty() {
217        let ns = store.entry(namespace.to_string()).or_default();
218        for (alias, digest) in &distinct {
219            ns.insert(alias.to_string(), *digest);
220        }
221    }
222    Ok(distinct.into_iter().map(|(alias, _)| alias.to_string()).collect())
223}
224
225/// "N aliases in this file clash", reporting the scale of a clash: thousands
226/// means a design mistake, not a typo.
227fn clash_scale(n: usize) -> String {
228    if n == 1 {
229        "1 alias in this file clashes".to_string()
230    } else {
231        format!("{} aliases in this file clash", n)
232    }
233}
234
235/// Read an alias TSV without clash checks, last row winning. Only for files
236/// gtars wrote itself from a map (so they cannot hold a clash); being strict
237/// here would make a store unopenable over one hand-edited file.
238fn alias_read_tsv_unchecked(store: &mut AliasStore, namespace: &str, path: &Path) -> Result<()> {
239    let map = super::persistence::read_alias_tsv(path)?;
240    if !map.is_empty() {
241        store.entry(namespace.to_string()).or_default().extend(map);
242    }
243    Ok(())
244}
245
246fn load_aliases_from_dir(store: &mut AliasStore, dir: &Path) -> Result<()> {
247    if !dir.exists() {
248        return Ok(());
249    }
250    for entry in fs::read_dir(dir)? {
251        let entry = entry?;
252        let path = entry.path();
253        if path.extension().and_then(|e| e.to_str()) == Some("tsv") {
254            let namespace = path
255                .file_stem()
256                .and_then(|s| s.to_str())
257                .context("Invalid filename")?
258                .to_string();
259            alias_read_tsv_unchecked(store, &namespace, &path)?;
260        }
261    }
262    Ok(())
263}
264
265fn write_all_aliases(store: &AliasStore, dir: &Path) -> Result<()> {
266    if store.is_empty() {
267        return Ok(());
268    }
269    create_dir_all(dir)?;
270    for (namespace, aliases) in store {
271        let tsv_path = dir.join(format!("{}.tsv", namespace));
272        super::persistence::write_alias_namespace(&tsv_path, aliases)?;
273    }
274    Ok(())
275}
276
277// =========================================================================
278// AliasManager public API
279// =========================================================================
280
281impl AliasManager {
282    pub fn new() -> Self {
283        AliasManager {
284            sequence_aliases: HashMap::new(),
285            collection_aliases: HashMap::new(),
286        }
287    }
288
289    pub fn is_empty(&self) -> bool {
290        self.sequence_aliases.is_empty() && self.collection_aliases.is_empty()
291    }
292
293    // --- Sequence aliases ---
294
295    /// Bind a sequence alias. Errors if it already points to a different
296    /// digest, unless `force`.
297    pub fn add_sequence(&mut self, namespace: &str, alias: &str, digest: &str, force: bool) -> Result<()> {
298        let key = digest.to_key();
299        alias_add(&mut self.sequence_aliases, AliasKind::Sequence, namespace, alias, key, force)
300    }
301
302    pub fn resolve_sequence(&self, namespace: &str, alias: &str) -> Option<DigestKey> {
303        alias_resolve(&self.sequence_aliases, namespace, alias)
304    }
305
306    pub fn reverse_lookup_sequence(&self, digest: &str) -> Vec<(String, String)> {
307        let key = digest.to_key();
308        alias_reverse_scan(&self.sequence_aliases, &key)
309    }
310
311    pub fn sequence_namespaces(&self) -> Vec<String> {
312        alias_namespaces(&self.sequence_aliases)
313    }
314
315    pub fn sequence_aliases(&self, namespace: &str) -> Option<Vec<String>> {
316        alias_list(&self.sequence_aliases, namespace)
317    }
318
319    pub fn remove_sequence(&mut self, namespace: &str, alias: &str) -> bool {
320        alias_remove(&mut self.sequence_aliases, namespace, alias)
321    }
322
323    /// Load a TSV of sequence aliases, all or nothing, returning the distinct
324    /// alias names bound. See [`alias_load_tsv`] for what is refused.
325    pub fn load_sequence_tsv(&mut self, namespace: &str, path: &Path, force: bool) -> Result<Vec<String>> {
326        alias_load_tsv(&mut self.sequence_aliases, AliasKind::Sequence, namespace, path, force)
327    }
328
329    // --- Collection aliases ---
330
331    /// Bind a collection alias. Errors if it already points to a different
332    /// digest, unless `force`.
333    pub fn add_collection(&mut self, namespace: &str, alias: &str, digest: &str, force: bool) -> Result<()> {
334        let key = digest.to_key();
335        alias_add(&mut self.collection_aliases, AliasKind::Collection, namespace, alias, key, force)
336    }
337
338    pub fn resolve_collection(&self, namespace: &str, alias: &str) -> Option<DigestKey> {
339        alias_resolve(&self.collection_aliases, namespace, alias)
340    }
341
342    pub fn reverse_lookup_collection(&self, digest: &str) -> Vec<(String, String)> {
343        let key = digest.to_key();
344        alias_reverse_scan(&self.collection_aliases, &key)
345    }
346
347    pub fn collection_namespaces(&self) -> Vec<String> {
348        alias_namespaces(&self.collection_aliases)
349    }
350
351    pub fn collection_aliases(&self, namespace: &str) -> Option<Vec<String>> {
352        alias_list(&self.collection_aliases, namespace)
353    }
354
355    pub fn remove_collection(&mut self, namespace: &str, alias: &str) -> bool {
356        alias_remove(&mut self.collection_aliases, namespace, alias)
357    }
358
359    /// Load a TSV of collection aliases, all or nothing, returning the distinct
360    /// alias names bound. See [`alias_load_tsv`] for what is refused.
361    pub fn load_collection_tsv(&mut self, namespace: &str, path: &Path, force: bool) -> Result<Vec<String>> {
362        alias_load_tsv(&mut self.collection_aliases, AliasKind::Collection, namespace, path, force)
363    }
364
365    // --- Persistence ---
366
367    pub fn load_from_dir(&mut self, aliases_dir: &Path) -> Result<()> {
368        load_aliases_from_dir(&mut self.sequence_aliases, &aliases_dir.join("sequences"))?;
369        load_aliases_from_dir(&mut self.collection_aliases, &aliases_dir.join("collections"))?;
370        Ok(())
371    }
372
373    /// Load only the alias namespaces explicitly listed (the manifest-driven
374    /// path). Unlike `load_from_dir`, which scans the directory for any `*.tsv`
375    /// present, this loads exactly `<aliases_dir>/{sequences,collections}/<ns>.tsv`
376    /// for each listed namespace. This makes `rgstore.json` the single source of
377    /// truth for what a store advertises: an alias file on disk that the manifest
378    /// does not list is simply not loaded, so a stale manifest fails identically
379    /// on a local filesystem and over HTTP (where directory listing is impossible).
380    pub fn load_namespaces_from_dir(
381        &mut self,
382        aliases_dir: &Path,
383        sequence_namespaces: &[String],
384        collection_namespaces: &[String],
385    ) -> Result<()> {
386        let seq_dir = aliases_dir.join("sequences");
387        for ns in sequence_namespaces {
388            let path = seq_dir.join(format!("{}.tsv", ns));
389            if path.exists() {
390                alias_read_tsv_unchecked(&mut self.sequence_aliases, ns, &path)?;
391            }
392        }
393        let coll_dir = aliases_dir.join("collections");
394        for ns in collection_namespaces {
395            let path = coll_dir.join(format!("{}.tsv", ns));
396            if path.exists() {
397                alias_read_tsv_unchecked(&mut self.collection_aliases, ns, &path)?;
398            }
399        }
400        Ok(())
401    }
402
403    pub fn write_to_dir(&self, aliases_dir: &Path) -> Result<()> {
404        write_all_aliases(&self.sequence_aliases, &aliases_dir.join("sequences"))?;
405        write_all_aliases(&self.collection_aliases, &aliases_dir.join("collections"))?;
406        Ok(())
407    }
408
409    // --- Kind-generic accessors (used by the commit path) ---
410
411    /// This manager's in-memory namespaces for one alias kind.
412    pub(crate) fn namespaces_for(&self, kind: AliasKind) -> Vec<String> {
413        alias_namespaces(self.store_for(kind))
414    }
415
416    /// This manager's in-memory `alias -> digest` map for one namespace.
417    /// Empty when the namespace is not in memory — which is NOT the same as
418    /// "the namespace has no aliases on disk"; see
419    /// [`ReadonlyRefgetStore::commit_alias_namespace`](super::readonly::ReadonlyRefgetStore).
420    pub(crate) fn namespace_map(&self, kind: AliasKind, namespace: &str) -> HashMap<String, DigestKey> {
421        self.store_for(kind)
422            .get(namespace)
423            .cloned()
424            .unwrap_or_default()
425    }
426
427    /// Kind-generic single-alias resolve, used by the commit path to look up the
428    /// target of an alias it has recorded as a pending change.
429    pub(crate) fn resolve(&self, kind: AliasKind, namespace: &str, alias: &str) -> Option<DigestKey> {
430        alias_resolve(self.store_for(kind), namespace, alias)
431    }
432
433    fn store_for(&self, kind: AliasKind) -> &AliasStore {
434        match kind {
435            AliasKind::Sequence => &self.sequence_aliases,
436            AliasKind::Collection => &self.collection_aliases,
437        }
438    }
439}
440
441impl Default for AliasManager {
442    fn default() -> Self {
443        Self::new()
444    }
445}
446
447// =========================================================================
448// ReadonlyRefgetStore alias bridge methods
449// =========================================================================
450
451impl ReadonlyRefgetStore {
452    /// Add a sequence alias and persist to disk if applicable.
453    ///
454    /// Re-adding the same binding is a no-op. Pointing an existing alias at a
455    /// different digest errors unless `force_alias` is set; a refused add
456    /// leaves memory, pending changes and disk untouched.
457    pub fn add_sequence_alias(&mut self, namespace: &str, alias: &str, digest: &str) -> Result<()> {
458        self.aliases.add_sequence(namespace, alias, digest, self.force_alias)?;
459        self.record(|p| p.add_alias(AliasKind::Sequence, namespace, alias));
460        self.persist_alias_namespace(AliasKind::Sequence, namespace)?;
461        Ok(())
462    }
463
464    /// Resolve a sequence alias to sequence metadata (no data loading).
465    pub fn get_sequence_metadata_by_alias(&self, namespace: &str, alias: &str) -> Option<crate::digest::SequenceMetadata> {
466        let key = self.aliases.resolve_sequence(namespace, alias)?;
467        self.get_sequence_metadata(key_to_digest_string(&key))
468    }
469
470    /// Resolve a sequence alias and return the sequence record.
471    pub fn get_sequence_by_alias(&self, namespace: &str, alias: &str) -> Result<crate::digest::SequenceRecord> {
472        let key = self.aliases.resolve_sequence(namespace, alias)
473            .ok_or_else(|| anyhow::anyhow!("Sequence alias not found: {}/{}", namespace, alias))?;
474        self.get_sequence(key_to_digest_string(&key))
475            .map_err(|_| anyhow::anyhow!("Sequence not found for alias {}/{}", namespace, alias))
476    }
477
478    /// Reverse lookup: find all aliases pointing to this sequence digest.
479    pub fn get_aliases_for_sequence(&self, digest: &str) -> Vec<(String, String)> {
480        self.aliases.reverse_lookup_sequence(digest)
481    }
482
483    /// List all sequence alias namespaces.
484    pub fn list_sequence_alias_namespaces(&self) -> Vec<String> {
485        self.aliases.sequence_namespaces()
486    }
487
488    /// List all aliases in a sequence alias namespace.
489    pub fn list_sequence_aliases(&self, namespace: &str) -> Option<Vec<String>> {
490        self.aliases.sequence_aliases(namespace)
491    }
492
493    /// Remove a single sequence alias.
494    pub fn remove_sequence_alias(&mut self, namespace: &str, alias: &str) -> Result<bool> {
495        let removed = self.aliases.remove_sequence(namespace, alias);
496        if removed {
497            // Record BEFORE persisting: the commit starts from the TSV on disk,
498            // so without an explicit removal the alias is simply left alone.
499            self.record_alias_removal(AliasKind::Sequence, namespace, alias);
500            self.persist_alias_namespace(AliasKind::Sequence, namespace)?;
501        }
502        Ok(removed)
503    }
504
505    /// Load sequence aliases from a TSV file into a namespace, all or nothing.
506    ///
507    /// Returns the number of distinct aliases bound. Errors, loading nothing,
508    /// if the file maps one alias to two different digests (always, even with
509    /// `force_alias`), or if it would re-point an existing alias (unless
510    /// `force_alias`).
511    pub fn load_sequence_aliases(&mut self, namespace: &str, path: &str) -> Result<usize> {
512        let loaded = self.aliases.load_sequence_tsv(namespace, Path::new(path), self.force_alias)?;
513        self.record(|p| {
514            for alias in &loaded {
515                p.add_alias(AliasKind::Sequence, namespace, alias);
516            }
517        });
518        self.persist_alias_namespace(AliasKind::Sequence, namespace)?;
519        Ok(loaded.len())
520    }
521
522    /// Add a collection alias and persist to disk if applicable.
523    ///
524    /// Re-adding the same binding is a no-op. Pointing an existing alias at a
525    /// different digest errors unless `force_alias` is set; a refused add
526    /// leaves memory, pending changes and disk untouched.
527    pub fn add_collection_alias(&mut self, namespace: &str, alias: &str, digest: &str) -> Result<()> {
528        self.aliases.add_collection(namespace, alias, digest, self.force_alias)?;
529        self.record(|p| p.add_alias(AliasKind::Collection, namespace, alias));
530        self.persist_alias_namespace(AliasKind::Collection, namespace)?;
531        Ok(())
532    }
533
534    /// Check whether an import-time collection alias request would conflict,
535    /// WITHOUT mutating anything.
536    ///
537    /// This is the read-only half of [`Self::register_import_collection_alias`]:
538    /// it returns exactly the error registration would return, so callers can
539    /// validate up front and bail out before committing any part of an import.
540    /// Returns `Ok(())` when `spec` is `None`, when `force` is set, when the
541    /// alias is unused, or when it already points at this same collection (the
542    /// idempotent re-import case).
543    pub(crate) fn check_import_collection_alias(
544        &self,
545        spec: Option<(&str, &str)>,
546        collection_digest: &str,
547        force: bool,
548    ) -> Result<()> {
549        let Some((namespace, alias)) = spec else {
550            return Ok(());
551        };
552        if force {
553            return Ok(());
554        }
555
556        let new_key = collection_digest.to_key();
557        match self.aliases.resolve_collection(namespace, alias) {
558            Some(existing) if existing != new_key => Err(anyhow::anyhow!(
559                "collection alias {}:{} already resolves to collection {} \
560                 but this import would point it at {}; \
561                 pass force to overwrite, or choose a different alias",
562                namespace,
563                alias,
564                key_to_digest_string(&existing),
565                collection_digest,
566            )),
567            _ => Ok(()),
568        }
569    }
570
571    /// Register a collection alias requested at import time.
572    ///
573    /// No-op when `spec` is `None`. Idempotent when the alias already points at
574    /// this digest. Errors on a conflicting existing alias unless `force`,
575    /// because silently remapping a name like `ucsc:hg38` from one assembly to
576    /// another is exactly the misdirection this option exists to prevent.
577    ///
578    /// The alias is recorded as pending and published by the import's final
579    /// `write_index_files`, together with the collection it names.
580    pub(crate) fn register_import_collection_alias(
581        &mut self,
582        spec: Option<(&str, &str)>,
583        collection_digest: &str,
584        force: bool,
585    ) -> Result<()> {
586        let Some((namespace, alias)) = spec else {
587            return Ok(());
588        };
589
590        // Same error, evaluated the same way, as the up-front validation
591        // callers run before mutating anything.
592        self.check_import_collection_alias(spec, collection_digest, force)?;
593
594        let new_key = collection_digest.to_key();
595        match self.aliases.resolve_collection(namespace, alias) {
596            // Same collection: already registered, nothing to do (and no
597            // redundant re-persist). This is what makes re-import idempotent.
598            Some(existing) if existing == new_key => return Ok(()),
599            Some(existing) => {
600                let existing_digest = key_to_digest_string(&existing);
601                if !self.quiet {
602                    println!(
603                        "Warning: remapping collection alias {}:{} from {} to {} (force)",
604                        namespace, alias, existing_digest, collection_digest,
605                    );
606                }
607            }
608            None => {}
609        }
610
611        // Deferred, not published here: the collection itself only reaches
612        // `collections.rgci` in the import's final `write_index_files`, and an
613        // alias visible on disk before its target is a dangling alias to every
614        // concurrent reader (permanently so, if that final commit fails).
615        // Publishing both in the same commit closes that window. `force` is
616        // carried along so the on-disk conflict check honors it too, instead
617        // of only the handle-wide `force_alias` flag. Forced in memory because
618        // the check above already applied this call's own `force`.
619        self.aliases.add_collection(namespace, alias, collection_digest, true)?;
620        self.record(|p| {
621            if force {
622                p.add_forced_alias(AliasKind::Collection, namespace, alias);
623            } else {
624                p.add_alias(AliasKind::Collection, namespace, alias);
625            }
626        });
627        Ok(())
628    }
629
630    /// Check FASTA header-tag sequence aliases `(namespace, alias, digest)`
631    /// from one file, WITHOUT mutating anything, so an import can refuse them
632    /// before it touches any state.
633    ///
634    /// The same alias tagged onto two different sequences in one file is
635    /// always an error (it ignores `force_alias`): that is a per-genome name,
636    /// not an alias. An alias that already points to a different digest
637    /// errors unless `force_alias`.
638    pub(crate) fn check_import_sequence_aliases(
639        &self,
640        aliases: &[(String, String, String)],
641        source: &Path,
642    ) -> Result<()> {
643        let mut first_seen: HashMap<(&str, &str), DigestKey> = HashMap::new();
644        let mut clashing: HashSet<(&str, &str)> = HashSet::new();
645        let mut first_clash: Option<(&str, &str, DigestKey, DigestKey)> = None;
646        for (namespace, alias, digest) in aliases {
647            let key = digest.to_key();
648            match first_seen.get(&(namespace.as_str(), alias.as_str())) {
649                None => {
650                    first_seen.insert((namespace, alias), key);
651                }
652                Some(&first) if first != key => {
653                    clashing.insert((namespace, alias));
654                    if first_clash.is_none() {
655                        first_clash = Some((namespace, alias, first, key));
656                    }
657                }
658                Some(_) => {}
659            }
660        }
661        if let Some((namespace, alias, digest_a, digest_b)) = first_clash {
662            return Err(anyhow::anyhow!(
663                "alias conflict in {} namespace '{}': '{}' tags '{}' onto two different \
664                 sequences ({} and {}); {}. A namespace maps each alias to one digest; \
665                 per-genome names such as chromosome names are not aliases.",
666                AliasKind::Sequence.subdir(),
667                namespace,
668                source.display(),
669                alias,
670                key_to_digest_string(&digest_a),
671                key_to_digest_string(&digest_b),
672                clash_scale(clashing.len()),
673            ));
674        }
675        // In FASTA order, so the error names the first offending header.
676        for (namespace, alias, digest) in aliases {
677            alias_check_existing(
678                &self.aliases.sequence_aliases,
679                AliasKind::Sequence,
680                namespace,
681                alias,
682                &digest.to_key(),
683                self.force_alias,
684            )?;
685        }
686        Ok(())
687    }
688
689    /// Register a sequence alias in memory and mark it pending, WITHOUT
690    /// publishing the namespace TSV. Used by the FASTA import path, which
691    /// commits all of its changes together at the end; publishing per alias
692    /// would rewrite the TSV (and the manifest) once per header.
693    pub(crate) fn add_sequence_alias_pending(&mut self, namespace: &str, alias: &str, digest: &str) -> Result<()> {
694        self.aliases.add_sequence(namespace, alias, digest, self.force_alias)?;
695        self.record(|p| p.add_alias(AliasKind::Sequence, namespace, alias));
696        Ok(())
697    }
698
699    /// Resolve a collection alias to collection metadata.
700    pub fn get_collection_metadata_by_alias(&self, namespace: &str, alias: &str) -> Option<&crate::digest::SequenceCollectionMetadata> {
701        let key = self.aliases.resolve_collection(namespace, alias)?;
702        self.get_collection_metadata(key_to_digest_string(&key))
703    }
704
705    /// Resolve a collection alias and return the loaded collection.
706    pub fn get_collection_by_alias(&self, namespace: &str, alias: &str) -> Result<crate::digest::SequenceCollection> {
707        let key = self.aliases.resolve_collection(namespace, alias)
708            .ok_or_else(|| anyhow::anyhow!("Collection alias not found: {}/{}", namespace, alias))?;
709        let digest_str = key_to_digest_string(&key);
710        self.get_collection(&digest_str)
711    }
712
713    /// Reverse lookup: find all aliases pointing to this collection digest.
714    pub fn get_aliases_for_collection(&self, digest: &str) -> Vec<(String, String)> {
715        self.aliases.reverse_lookup_collection(digest)
716    }
717
718    /// List all collection alias namespaces.
719    pub fn list_collection_alias_namespaces(&self) -> Vec<String> {
720        self.aliases.collection_namespaces()
721    }
722
723    /// List all aliases in a collection alias namespace.
724    pub fn list_collection_aliases(&self, namespace: &str) -> Option<Vec<String>> {
725        self.aliases.collection_aliases(namespace)
726    }
727
728    /// Remove a single collection alias.
729    pub fn remove_collection_alias(&mut self, namespace: &str, alias: &str) -> Result<bool> {
730        let removed = self.aliases.remove_collection(namespace, alias);
731        if removed {
732            self.record_alias_removal(AliasKind::Collection, namespace, alias);
733            self.persist_alias_namespace(AliasKind::Collection, namespace)?;
734        }
735        Ok(removed)
736    }
737
738    /// Load collection aliases from a TSV file into a namespace, all or nothing.
739    ///
740    /// Returns the number of distinct aliases bound. Errors, loading nothing,
741    /// if the file maps one alias to two different digests (always, even with
742    /// `force_alias`), or if it would re-point an existing alias (unless
743    /// `force_alias`).
744    pub fn load_collection_aliases(&mut self, namespace: &str, path: &str) -> Result<usize> {
745        let loaded = self.aliases.load_collection_tsv(namespace, Path::new(path), self.force_alias)?;
746        self.record(|p| {
747            for alias in &loaded {
748                p.add_alias(AliasKind::Collection, namespace, alias);
749            }
750        });
751        self.persist_alias_namespace(AliasKind::Collection, namespace)?;
752        Ok(loaded.len())
753    }
754
755    /// Commit a single alias namespace to disk (if disk-backed).
756    ///
757    /// The cheap alias-mutation path: it applies this handle's pending changes
758    /// for ONE namespace and patches only the manifest's alias-derived fields,
759    /// rather than rehashing the (potentially 60+ MB) sequence and collection
760    /// indexes. Takes the store write lock for the duration, like any other
761    /// commit.
762    pub(crate) fn persist_alias_namespace(&self, kind: AliasKind, namespace: &str) -> Result<()> {
763        if !self.persist_to_disk {
764            return Ok(());
765        }
766        let Some(local_path) = self.local_path.clone() else {
767            return Ok(());
768        };
769
770        let _guard = self.acquire_commit_lock("persist_alias_namespace")?;
771
772        let pending = self.pending.lock().unwrap().clone();
773        let aliases_dir = local_path.join("aliases");
774        self.commit_alias_namespace(&aliases_dir, kind, namespace, &pending)?;
775
776        // Keep rgstore.json in lock-step with the alias files on disk, so a
777        // served store always advertises its true alias namespaces. Without
778        // this, aliases added after the index was written (e.g. a post-build
779        // alias step) leave the manifest stale and remote/HTTP clients —
780        // which cannot list the aliases/ directory — never discover them.
781        self.refresh_manifest_alias_namespaces()?;
782
783        // Only this namespace has been published; leave the rest of the pending
784        // changes for the next full commit.
785        self.pending
786            .lock()
787            .unwrap()
788            .clear_alias_namespace(kind, namespace);
789
790        Ok(())
791    }
792
793    /// Record that an alias was deliberately removed, so the commit drops it
794    /// from the TSV it reads back from disk instead of leaving it alone.
795    pub(crate) fn record_alias_removal(&self, kind: AliasKind, namespace: &str, alias: &str) {
796        let emptied = self.aliases.namespace_map(kind, namespace).is_empty();
797        self.record(|p| {
798            p.remove_alias(kind, namespace, alias);
799            // A namespace that just lost its last in-memory alias is explicitly
800            // emptied, as distinct from "we never loaded it". This only makes
801            // the commit VISIT the namespace; whether the TSV is deleted depends
802            // on the merged result being empty, because another writer may have
803            // added aliases we never saw.
804            if emptied {
805                p.emptied_alias_namespaces
806                    .insert((kind, namespace.to_string()));
807            }
808        });
809    }
810}
811
812// =========================================================================
813// RefgetStore alias delegates
814// =========================================================================
815
816impl RefgetStore {
817    /// Add a sequence alias.
818    pub fn add_sequence_alias(&mut self, namespace: &str, alias: &str, digest: &str) -> Result<()> {
819        self.inner.add_sequence_alias(namespace, alias, digest)
820    }
821
822    /// Remove a single sequence alias.
823    pub fn remove_sequence_alias(&mut self, namespace: &str, alias: &str) -> Result<bool> {
824        self.inner.remove_sequence_alias(namespace, alias)
825    }
826
827    /// Load sequence aliases from a TSV file.
828    pub fn load_sequence_aliases(&mut self, namespace: &str, path: &str) -> Result<usize> {
829        self.inner.load_sequence_aliases(namespace, path)
830    }
831
832    /// Add a collection alias.
833    pub fn add_collection_alias(&mut self, namespace: &str, alias: &str, digest: &str) -> Result<()> {
834        self.inner.add_collection_alias(namespace, alias, digest)
835    }
836
837    /// Remove a single collection alias.
838    pub fn remove_collection_alias(&mut self, namespace: &str, alias: &str) -> Result<bool> {
839        self.inner.remove_collection_alias(namespace, alias)
840    }
841
842    /// Load collection aliases from a TSV file.
843    pub fn load_collection_aliases(&mut self, namespace: &str, path: &str) -> Result<usize> {
844        self.inner.load_collection_aliases(namespace, path)
845    }
846
847    /// Lazy-loading get_collection_by_alias.
848    pub fn get_collection_by_alias(
849        &mut self,
850        namespace: &str,
851        alias: &str,
852    ) -> Result<crate::digest::SequenceCollection> {
853        if let Some(meta) = self.inner.get_collection_metadata_by_alias(namespace, alias) {
854            let digest = meta.digest.clone();
855            if !self.inner.is_collection_loaded(&digest) {
856                self.inner.load_collection(&digest)?;
857            }
858            return self.inner.get_collection_by_alias(namespace, alias);
859        }
860        Err(anyhow::anyhow!("Collection alias not found: {}:{}", namespace, alias))
861    }
862
863    // --- Sidecar pull: aliases ---
864
865    /// Pull alias sidecars from the remote store.
866    pub fn pull_aliases(
867        &mut self,
868        namespace: Option<&str>,
869        strategy: SyncStrategy,
870    ) -> Result<PullResult> {
871        let mut result = PullResult::default();
872
873        let seq_namespaces: Vec<String> = match namespace {
874            Some(ns) => vec![ns.to_string()],
875            None => self.inner.available_sequence_alias_namespaces.clone(),
876        };
877        let coll_namespaces: Vec<String> = match namespace {
878            Some(ns) => vec![ns.to_string()],
879            None => self.inner.available_collection_alias_namespaces.clone(),
880        };
881
882        for ns in &seq_namespaces {
883            self.pull_alias_file(ns, "sequences", &strategy, &mut result)?;
884        }
885
886        for ns in &coll_namespaces {
887            self.pull_alias_file(ns, "collections", &strategy, &mut result)?;
888        }
889
890        if result.pulled > 0 {
891            if let Some(ref local_path) = self.inner.local_path {
892                let aliases_dir = local_path.join("aliases");
893                self.inner.aliases = AliasManager::default();
894                self.inner.aliases.load_from_dir(&aliases_dir)?;
895            }
896        }
897
898        Ok(result)
899    }
900
901    /// Pull a single alias TSV file.
902    fn pull_alias_file(
903        &self,
904        namespace: &str,
905        kind: &str,
906        strategy: &SyncStrategy,
907        result: &mut PullResult,
908    ) -> Result<()> {
909        let relative_path = format!("aliases/{}/{}.tsv", kind, namespace);
910
911        match strategy {
912            SyncStrategy::KeepOurs => {
913                let was_local = self
914                    .inner
915                    .local_path
916                    .as_ref()
917                    .map(|p| p.join(&relative_path).exists())
918                    .unwrap_or(false);
919                match ReadonlyRefgetStore::fetch_file(
920                    &self.inner.local_path,
921                    &self.inner.remote_source,
922                    &relative_path,
923                    self.inner.persist_to_disk,
924                    false,
925                ) {
926                    Ok(_) => {
927                        if was_local {
928                            result.skipped += 1;
929                        } else {
930                            result.pulled += 1;
931                        }
932                    }
933                    Err(_) => {
934                        result.not_found += 1;
935                    }
936                }
937            }
938            SyncStrategy::KeepTheirs => {
939                match ReadonlyRefgetStore::fetch_file(
940                    &self.inner.local_path,
941                    &self.inner.remote_source,
942                    &relative_path,
943                    self.inner.persist_to_disk,
944                    true,
945                ) {
946                    Ok(_) => {
947                        result.pulled += 1;
948                    }
949                    Err(_) => {
950                        result.not_found += 1;
951                    }
952                }
953            }
954            SyncStrategy::Notify => {
955                let local_exists = self
956                    .inner
957                    .local_path
958                    .as_ref()
959                    .map(|p| p.join(&relative_path).exists())
960                    .unwrap_or(false);
961
962                if local_exists {
963                    match ReadonlyRefgetStore::fetch_file(
964                        &None,
965                        &self.inner.remote_source,
966                        &relative_path,
967                        false,
968                        false,
969                    ) {
970                        Ok(remote_data) => {
971                            let local_path = self
972                                .inner
973                                .local_path
974                                .as_ref()
975                                .unwrap()
976                                .join(&relative_path);
977                            let local_data = fs::read(&local_path)?;
978                            if local_data != remote_data {
979                                result.conflicts.push(relative_path);
980                            } else {
981                                result.skipped += 1;
982                            }
983                        }
984                        Err(_) => {
985                            result.not_found += 1;
986                        }
987                    }
988                } else {
989                    result.conflicts.push(relative_path);
990                }
991            }
992        }
993
994        Ok(())
995    }
996}
997
998// =========================================================================
999// Tests
1000// =========================================================================
1001
1002#[cfg(test)]
1003mod tests {
1004    use super::*;
1005    use tempfile::tempdir;
1006
1007    // -----------------------------------------------------------------------
1008    // Minimal HTTP test server helper
1009    // -----------------------------------------------------------------------
1010
1011    /// Spin up a single-threaded HTTP file server on a random port.
1012    ///
1013    /// The server serves files from `serve_dir` for as long as the returned
1014    /// `JoinHandle` is alive (call `drop()` or let it go out of scope, but
1015    /// the thread will block on the next request; `shutdown_flag` is used to
1016    /// stop it cleanly after the test).
1017    ///
1018    /// Returns `(base_url, shutdown_fn)` where `shutdown_fn()` signals the
1019    /// server to stop.
1020    #[cfg(all(feature = "filesystem", feature = "http"))]
1021    fn start_file_server(serve_dir: std::path::PathBuf) -> (String, impl FnOnce()) {
1022        use std::io::{Read as _, Write as _};
1023        use std::net::TcpListener;
1024        use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
1025
1026        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
1027        let port = listener.local_addr().unwrap().port();
1028        let base_url = format!("http://127.0.0.1:{}", port);
1029        let stop = Arc::new(AtomicBool::new(false));
1030        let stop_clone = Arc::clone(&stop);
1031
1032        std::thread::spawn(move || {
1033            listener.set_nonblocking(false).ok();
1034            while !stop_clone.load(Ordering::Relaxed) {
1035                match listener.accept() {
1036                    Ok((mut stream, _)) => {
1037                        let mut buf = [0u8; 4096];
1038                        let n = stream.read(&mut buf).unwrap_or(0);
1039                        let request = std::str::from_utf8(&buf[..n]).unwrap_or("");
1040                        // Parse GET /path HTTP/1.x
1041                        let path = request
1042                            .lines()
1043                            .next()
1044                            .and_then(|l| l.split_whitespace().nth(1))
1045                            .unwrap_or("/");
1046                        // Strip leading '/'
1047                        let rel = path.trim_start_matches('/');
1048                        let file_path = serve_dir.join(rel);
1049                        if file_path.exists() && file_path.is_file() {
1050                            let data = std::fs::read(&file_path).unwrap_or_default();
1051                            let header = format!(
1052                                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1053                                data.len()
1054                            );
1055                            let _ = stream.write_all(header.as_bytes());
1056                            let _ = stream.write_all(&data);
1057                        } else {
1058                            let body = b"Not Found";
1059                            let header = format!(
1060                                "HTTP/1.1 404 Not Found\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1061                                body.len()
1062                            );
1063                            let _ = stream.write_all(header.as_bytes());
1064                            let _ = stream.write_all(body);
1065                        }
1066                    }
1067                    Err(_) => break,
1068                }
1069            }
1070        });
1071
1072        let shutdown = move || {
1073            stop.store(true, Ordering::Relaxed);
1074            // Connect once to unblock the accept() call
1075            let _ = std::net::TcpStream::connect(format!("127.0.0.1:{}", port));
1076        };
1077
1078        (base_url, shutdown)
1079    }
1080
1081    // --- AliasManager unit tests ---
1082
1083    #[test]
1084    fn test_add_and_resolve_sequence() {
1085        let mut mgr = AliasManager::new();
1086        assert!(mgr.is_empty());
1087
1088        mgr.add_sequence("ncbi", "NC_000001.11", "abc123", false).unwrap();
1089        assert!(!mgr.is_empty());
1090
1091        let key = mgr.resolve_sequence("ncbi", "NC_000001.11");
1092        assert!(key.is_some());
1093        assert_eq!(key.unwrap(), "abc123".to_key());
1094
1095        assert!(mgr.resolve_sequence("ncbi", "missing").is_none());
1096        assert!(mgr.resolve_sequence("missing_ns", "NC_000001.11").is_none());
1097    }
1098
1099    #[test]
1100    fn test_reverse_lookup() {
1101        let mut mgr = AliasManager::new();
1102        mgr.add_sequence("ncbi", "NC_000001.11", "digest1", false).unwrap();
1103        mgr.add_sequence("ucsc", "chr1", "digest1", false).unwrap();
1104        mgr.add_sequence("ncbi", "NC_000002.12", "digest2", false).unwrap();
1105
1106        let aliases = mgr.reverse_lookup_sequence("digest1");
1107        assert_eq!(aliases.len(), 2);
1108        assert!(aliases.contains(&("ncbi".to_string(), "NC_000001.11".to_string())));
1109        assert!(aliases.contains(&("ucsc".to_string(), "chr1".to_string())));
1110
1111        let aliases2 = mgr.reverse_lookup_sequence("digest2");
1112        assert_eq!(aliases2.len(), 1);
1113    }
1114
1115    #[test]
1116    fn test_namespaces_and_list() {
1117        let mut mgr = AliasManager::new();
1118        mgr.add_sequence("ncbi", "NC_000001.11", "d1", false).unwrap();
1119        mgr.add_sequence("ucsc", "chr1", "d1", false).unwrap();
1120
1121        let ns = mgr.sequence_namespaces();
1122        assert!(ns.contains(&"ncbi".to_string()));
1123        assert!(ns.contains(&"ucsc".to_string()));
1124
1125        let aliases = mgr.sequence_aliases("ncbi").unwrap();
1126        assert!(aliases.contains(&"NC_000001.11".to_string()));
1127    }
1128
1129    #[test]
1130    fn test_remove() {
1131        let mut mgr = AliasManager::new();
1132        mgr.add_sequence("ncbi", "NC_000001.11", "d1", false).unwrap();
1133
1134        assert!(mgr.remove_sequence("ncbi", "NC_000001.11"));
1135        assert!(mgr.resolve_sequence("ncbi", "NC_000001.11").is_none());
1136        assert!(mgr.sequence_namespaces().is_empty());
1137
1138        assert!(!mgr.remove_sequence("ncbi", "NC_000001.11"));
1139    }
1140
1141    #[test]
1142    fn test_collection_aliases() {
1143        let mut mgr = AliasManager::new();
1144        mgr.add_collection("ucsc", "hg38", "coll_digest", false).unwrap();
1145        mgr.add_collection("gencode", "GRCh38.p14", "coll_digest", false).unwrap();
1146
1147        assert!(mgr.resolve_collection("ucsc", "hg38").is_some());
1148        assert_eq!(mgr.collection_namespaces().len(), 2);
1149
1150        let aliases = mgr.reverse_lookup_collection("coll_digest");
1151        assert_eq!(aliases.len(), 2);
1152
1153        assert!(mgr.remove_collection("ucsc", "hg38"));
1154        assert!(mgr.resolve_collection("ucsc", "hg38").is_none());
1155    }
1156
1157    #[test]
1158    fn test_persistence_roundtrip() {
1159        let dir = tempdir().unwrap();
1160        let aliases_dir = dir.path().join("aliases");
1161
1162        let mut mgr = AliasManager::new();
1163        mgr.add_sequence("ncbi", "NC_000001.11", "seq_digest", false).unwrap();
1164        mgr.add_collection("ucsc", "hg38", "coll_digest", false).unwrap();
1165
1166        mgr.write_to_dir(&aliases_dir).unwrap();
1167
1168        assert!(aliases_dir.join("sequences/ncbi.tsv").exists());
1169        assert!(aliases_dir.join("collections/ucsc.tsv").exists());
1170
1171        let mut mgr2 = AliasManager::new();
1172        mgr2.load_from_dir(&aliases_dir).unwrap();
1173
1174        assert!(mgr2.resolve_sequence("ncbi", "NC_000001.11").is_some());
1175        assert!(mgr2.resolve_collection("ucsc", "hg38").is_some());
1176    }
1177
1178    #[test]
1179    fn test_load_from_missing_dir() {
1180        let mut mgr = AliasManager::new();
1181        mgr.load_from_dir(std::path::Path::new("/nonexistent/aliases")).unwrap();
1182        assert!(mgr.is_empty());
1183    }
1184
1185    #[test]
1186    fn test_write_namespace_single() {
1187        let dir = tempdir().unwrap();
1188        let aliases_dir = dir.path().join("aliases");
1189
1190        let mut mgr = AliasManager::new();
1191        mgr.add_sequence("ncbi", "NC_000001.11", "d1", false).unwrap();
1192        mgr.add_sequence("ucsc", "chr1", "d2", false).unwrap();
1193
1194        let tsv = aliases_dir.join("sequences/ncbi.tsv");
1195        super::super::persistence::write_alias_namespace(
1196            &tsv,
1197            &mgr.namespace_map(AliasKind::Sequence, "ncbi"),
1198        )
1199        .unwrap();
1200
1201        assert!(tsv.exists());
1202        assert!(!aliases_dir.join("sequences/ucsc.tsv").exists());
1203    }
1204
1205    #[test]
1206    fn test_write_namespace_absent_from_memory_does_not_delete() {
1207        // The old `write_namespace` deleted the TSV whenever the namespace was
1208        // missing from memory, which is how another writer's brand-new namespace
1209        // got orphaned: `open_local` loads only what the manifest advertises, so
1210        // "not in memory" routinely means "not mine", not "deleted".
1211        let dir = tempdir().unwrap();
1212        let tsv = dir.path().join("aliases/sequences/ncbi.tsv");
1213        std::fs::create_dir_all(tsv.parent().unwrap()).unwrap();
1214        std::fs::write(&tsv, "NC_000001.11\tother_writers_digest\n").unwrap();
1215
1216        let mgr = AliasManager::new();
1217        let mut merged = super::super::persistence::read_alias_tsv(&tsv).unwrap();
1218        merged.extend(mgr.namespace_map(AliasKind::Sequence, "ncbi"));
1219        super::super::persistence::write_alias_namespace(&tsv, &merged).unwrap();
1220
1221        assert!(tsv.exists(), "another writer's namespace was deleted");
1222        assert_eq!(
1223            std::fs::read_to_string(&tsv).unwrap(),
1224            "NC_000001.11\tother_writers_digest\n"
1225        );
1226    }
1227
1228    #[test]
1229    fn test_empty_write_is_noop() {
1230        let dir = tempdir().unwrap();
1231        let aliases_dir = dir.path().join("aliases");
1232
1233        let mgr = AliasManager::new();
1234        mgr.write_to_dir(&aliases_dir).unwrap();
1235
1236        assert!(!aliases_dir.join("sequences").exists());
1237        assert!(!aliases_dir.join("collections").exists());
1238    }
1239
1240    #[test]
1241    fn test_load_tsv() {
1242        let dir = tempdir().unwrap();
1243        let tsv_path = dir.path().join("ncbi.tsv");
1244        std::fs::write(&tsv_path, "NC_000001.11\tsome_digest\n# comment\n\nNC_000002.12\tanother_digest\n").unwrap();
1245
1246        let mut mgr = AliasManager::new();
1247        let loaded = mgr.load_sequence_tsv("ncbi", &tsv_path, false).unwrap();
1248        assert_eq!(loaded, vec!["NC_000001.11", "NC_000002.12"]);
1249        assert!(mgr.resolve_sequence("ncbi", "NC_000001.11").is_some());
1250        assert!(mgr.resolve_sequence("ncbi", "NC_000002.12").is_some());
1251    }
1252
1253    // --- Store-level alias integration tests ---
1254
1255    #[cfg(feature = "filesystem")]
1256    fn copy_test_fasta(temp_dir: &std::path::Path, name: &str) -> std::path::PathBuf {
1257        let src = format!("../tests/data/fasta/{}", name);
1258        let dst = temp_dir.join(name);
1259        std::fs::copy(&src, &dst)
1260            .unwrap_or_else(|e| panic!("Failed to copy {} to tempdir: {}", src, e));
1261        dst
1262    }
1263
1264    #[test]
1265    fn test_store_sequence_aliases() {
1266        use crate::digest::digest_sequence;
1267
1268        let mut store = RefgetStore::in_memory();
1269        let record = digest_sequence("chr1", b"ACGT");
1270        store.add_sequence_record(record.clone(), false).unwrap();
1271
1272        let digest = record.metadata().sha512t24u.clone();
1273        store.add_sequence_alias("ncbi", "NC_000001.11", &digest).unwrap();
1274        store.add_sequence_alias("ucsc", "chr1", &digest).unwrap();
1275
1276        let found = store.get_sequence_metadata_by_alias("ncbi", "NC_000001.11").unwrap();
1277        assert_eq!(found.name, "chr1");
1278
1279        let aliases = store.get_aliases_for_sequence(&digest);
1280        assert_eq!(aliases.len(), 2);
1281        assert!(aliases.contains(&("ncbi".to_string(), "NC_000001.11".to_string())));
1282        assert!(aliases.contains(&("ucsc".to_string(), "chr1".to_string())));
1283
1284        let ns = store.list_sequence_alias_namespaces();
1285        assert!(ns.contains(&"ncbi".to_string()));
1286        assert!(ns.contains(&"ucsc".to_string()));
1287
1288        let aliases = store.list_sequence_aliases("ncbi").unwrap();
1289        assert!(aliases.contains(&"NC_000001.11".to_string()));
1290    }
1291
1292    #[test]
1293    #[cfg(feature = "filesystem")]
1294    fn test_store_collection_aliases() {
1295        let temp = tempdir().unwrap();
1296        let fasta_path = copy_test_fasta(temp.path(), "base.fa");
1297
1298        let mut store = RefgetStore::in_memory();
1299        let (meta, _) = store
1300            .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
1301            .unwrap();
1302
1303        store.add_collection_alias("ucsc", "hg38", &meta.digest).unwrap();
1304        store.add_collection_alias("gencode", "GRCh38.p14", &meta.digest).unwrap();
1305
1306        let coll = store.get_collection_metadata_by_alias("ucsc", "hg38").unwrap();
1307        assert_eq!(coll.digest, meta.digest);
1308
1309        let aliases = store.get_aliases_for_collection(&meta.digest);
1310        assert_eq!(aliases.len(), 2);
1311    }
1312
1313    #[test]
1314    fn test_store_alias_remove() {
1315        use crate::digest::digest_sequence;
1316
1317        let mut store = RefgetStore::in_memory();
1318        let record = digest_sequence("chr1", b"ACGT");
1319        store.add_sequence_record(record.clone(), false).unwrap();
1320        let digest = record.metadata().sha512t24u.clone();
1321
1322        store.add_sequence_alias("ncbi", "NC_000001.11", &digest).unwrap();
1323        assert!(store.get_sequence_metadata_by_alias("ncbi", "NC_000001.11").is_some());
1324
1325        assert!(store.remove_sequence_alias("ncbi", "NC_000001.11").unwrap());
1326        assert!(store.get_sequence_metadata_by_alias("ncbi", "NC_000001.11").is_none());
1327
1328        assert!(store.list_sequence_alias_namespaces().is_empty());
1329    }
1330
1331    #[test]
1332    #[cfg(feature = "filesystem")]
1333    fn test_store_alias_persistence() {
1334        let dir = tempdir().unwrap();
1335        let store_path = dir.path().join("store");
1336
1337        let fasta_temp = tempdir().unwrap();
1338        let fasta_path = copy_test_fasta(fasta_temp.path(), "base.fa");
1339
1340        let digest: String;
1341        let seq_digest: String;
1342        {
1343            let mut store = RefgetStore::on_disk(&store_path).unwrap();
1344            let (meta, _) = store
1345                .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
1346                .unwrap();
1347            digest = meta.digest.clone();
1348            seq_digest = store.list_sequences().unwrap()[0].sha512t24u.clone();
1349
1350            store.add_sequence_alias("ncbi", "NC_000001.11", &seq_digest).unwrap();
1351            store.add_collection_alias("ucsc", "hg38", &digest).unwrap();
1352        }
1353
1354        {
1355            let store = RefgetStore::open_local(&store_path).unwrap();
1356            assert!(store.get_sequence_metadata_by_alias("ncbi", "NC_000001.11").is_some());
1357            assert!(store.get_collection_metadata_by_alias("ucsc", "hg38").is_some());
1358
1359            assert!(store_path.join("aliases/sequences/ncbi.tsv").exists());
1360            assert!(store_path.join("aliases/collections/ucsc.tsv").exists());
1361        }
1362    }
1363
1364    #[test]
1365    fn test_store_alias_load_tsv() {
1366        use crate::digest::digest_sequence;
1367
1368        let dir = tempdir().unwrap();
1369        let tsv_path = dir.path().join("ncbi.tsv");
1370
1371        let mut store = RefgetStore::in_memory();
1372        let record = digest_sequence("chr1", b"ACGT");
1373        store.add_sequence_record(record.clone(), false).unwrap();
1374        let digest = record.metadata().sha512t24u.clone();
1375
1376        std::fs::write(&tsv_path, format!("NC_000001.11\t{}\n", digest)).unwrap();
1377
1378        let count = store.load_sequence_aliases("ncbi", tsv_path.to_str().unwrap()).unwrap();
1379        assert_eq!(count, 1);
1380        assert!(store.get_sequence_metadata_by_alias("ncbi", "NC_000001.11").is_some());
1381    }
1382
1383    #[test]
1384    fn test_store_alias_reverse_multiple_sequences() {
1385        use crate::digest::digest_sequence;
1386
1387        let mut store = RefgetStore::in_memory();
1388        let r1 = digest_sequence("chr1", b"ACGT");
1389        let r2 = digest_sequence("chr2", b"TTTT");
1390        store.add_sequence_record(r1.clone(), false).unwrap();
1391        store.add_sequence_record(r2.clone(), false).unwrap();
1392
1393        let d1 = r1.metadata().sha512t24u.clone();
1394        let d2 = r2.metadata().sha512t24u.clone();
1395
1396        store.add_sequence_alias("ncbi", "NC_000001.11", &d1).unwrap();
1397        store.add_sequence_alias("ucsc", "chr1", &d1).unwrap();
1398        store.add_sequence_alias("ncbi", "NC_000002.12", &d2).unwrap();
1399
1400        let aliases = store.get_aliases_for_sequence(&d1);
1401        assert_eq!(aliases.len(), 2);
1402
1403        let aliases = store.get_aliases_for_sequence(&d2);
1404        assert_eq!(aliases.len(), 1);
1405    }
1406
1407    #[test]
1408    fn test_store_alias_write_store_to_dir() {
1409        use crate::digest::digest_sequence;
1410
1411        let dir = tempdir().unwrap();
1412        let store_path = dir.path().join("store");
1413
1414        let mut store = RefgetStore::in_memory();
1415        let record = digest_sequence("chr1", b"ACGT");
1416        store.add_sequence_record(record.clone(), false).unwrap();
1417        let digest = record.metadata().sha512t24u.clone();
1418
1419        store.add_sequence_alias("ncbi", "NC_000001.11", &digest).unwrap();
1420
1421        store.write_store_to_dir(&store_path, None).unwrap();
1422
1423        assert!(store_path.join("aliases/sequences/ncbi.tsv").exists());
1424
1425        let store2 = RefgetStore::open_local(&store_path).unwrap();
1426        assert!(store2.get_sequence_metadata_by_alias("ncbi", "NC_000001.11").is_some());
1427    }
1428
1429    #[test]
1430    fn test_get_sequence_metadata_by_alias() {
1431        use crate::digest::digest_sequence;
1432
1433        let mut store = RefgetStore::in_memory();
1434        let record = digest_sequence("chr1", b"ACGT");
1435        store.add_sequence_record(record.clone(), false).unwrap();
1436        let digest = record.metadata().sha512t24u.clone();
1437
1438        store.add_sequence_alias("ncbi", "NC_000001.11", &digest).unwrap();
1439
1440        let meta = store.get_sequence_metadata_by_alias("ncbi", "NC_000001.11").unwrap();
1441        assert_eq!(meta.name, "chr1");
1442        assert_eq!(meta.length, 4);
1443    }
1444
1445    #[test]
1446    fn test_get_sequence_by_alias_loads_data() {
1447        use crate::digest::digest_sequence;
1448
1449        let mut store = RefgetStore::in_memory();
1450        let record = digest_sequence("chr1", b"ACGT");
1451        store.add_sequence_record(record.clone(), false).unwrap();
1452        let digest = record.metadata().sha512t24u.clone();
1453
1454        store.add_sequence_alias("ncbi", "NC_000001.11", &digest).unwrap();
1455
1456        let rec = store.get_sequence_by_alias("ncbi", "NC_000001.11").unwrap();
1457        assert_eq!(rec.metadata().name, "chr1");
1458    }
1459
1460    #[test]
1461    #[cfg(feature = "filesystem")]
1462    fn test_get_collection_metadata_by_alias() {
1463        let temp = tempdir().unwrap();
1464        let fasta_path = copy_test_fasta(temp.path(), "base.fa");
1465
1466        let mut store = RefgetStore::in_memory();
1467        let (meta, _) = store.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new()).unwrap();
1468
1469        store.add_collection_alias("ucsc", "hg38", &meta.digest).unwrap();
1470
1471        let coll_meta = store.get_collection_metadata_by_alias("ucsc", "hg38").unwrap();
1472        assert_eq!(coll_meta.digest, meta.digest);
1473    }
1474
1475    #[test]
1476    #[cfg(feature = "filesystem")]
1477    fn test_get_collection_by_alias_loads() {
1478        let temp = tempdir().unwrap();
1479        let fasta_path = copy_test_fasta(temp.path(), "base.fa");
1480
1481        let mut store = RefgetStore::in_memory();
1482        let (meta, _) = store.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new()).unwrap();
1483
1484        store.add_collection_alias("ucsc", "hg38", &meta.digest).unwrap();
1485
1486        let coll = store.get_collection_by_alias("ucsc", "hg38").unwrap();
1487        assert_eq!(coll.metadata.digest, meta.digest);
1488        assert!(!coll.sequences.is_empty());
1489    }
1490
1491    #[test]
1492    fn test_get_sequence_by_alias_not_found() {
1493        let store = RefgetStore::in_memory();
1494        assert!(store.get_sequence_metadata_by_alias("ncbi", "nonexistent").is_none());
1495    }
1496
1497    #[test]
1498    fn test_get_sequence_by_alias_error_not_found() {
1499        let store = RefgetStore::in_memory();
1500        assert!(store.get_sequence_by_alias("ncbi", "nonexistent").is_err());
1501    }
1502
1503    #[test]
1504    #[cfg(feature = "filesystem")]
1505    fn test_fasta_load_with_namespace_aliases() {
1506        let dir = tempdir().unwrap();
1507        let fasta = dir.path().join("test.fa");
1508        fs::write(
1509            &fasta,
1510            ">chr1 ncbi:NC_000001.11 refseq:NC_000001.11\nACGT\n>chr2 ncbi:NC_000002.12\nTGCA\n",
1511        )
1512        .unwrap();
1513
1514        let mut store = RefgetStore::in_memory();
1515        store
1516            .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().namespaces(&["ncbi", "refseq"]))
1517            .unwrap();
1518
1519        let result = store.get_sequence_by_alias("ncbi", "NC_000001.11");
1520        assert!(result.is_ok());
1521        assert_eq!(result.unwrap().metadata().name, "chr1");
1522
1523        let result = store.get_sequence_by_alias("refseq", "NC_000001.11");
1524        assert!(result.is_ok());
1525
1526        let result = store.get_sequence_by_alias("ncbi", "NC_000002.12");
1527        assert!(result.is_ok());
1528        assert_eq!(result.unwrap().metadata().name, "chr2");
1529
1530        let result = store.get_sequence_by_alias("ncbi", "NC_999999.1");
1531        assert!(result.is_err());
1532    }
1533
1534    #[test]
1535    #[cfg(feature = "filesystem")]
1536    fn test_fasta_load_without_namespaces_no_aliases() {
1537        let dir = tempdir().unwrap();
1538        let fasta = dir.path().join("test.fa");
1539        fs::write(&fasta, ">chr1 ncbi:NC_000001.11\nACGT\n").unwrap();
1540
1541        let mut store = RefgetStore::in_memory();
1542        store
1543            .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
1544            .unwrap();
1545
1546        let result = store.get_sequence_by_alias("ncbi", "NC_000001.11");
1547        assert!(result.is_err());
1548    }
1549
1550    #[test]
1551    #[cfg(feature = "filesystem")]
1552    fn test_remove_collection_cleans_up_aliases() {
1553        let dir = tempdir().unwrap();
1554        let fasta = dir.path().join("test.fa");
1555        fs::write(&fasta, ">chr1\nACGT\n").unwrap();
1556
1557        let mut store = RefgetStore::in_memory();
1558        let (meta, _) = store
1559            .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
1560            .unwrap();
1561        let digest = meta.digest;
1562
1563        store.add_collection_alias("ucsc", "hg38", &digest).unwrap();
1564        assert!(store.get_collection_metadata_by_alias("ucsc", "hg38").is_some());
1565
1566        store.remove_collection(&digest, false).unwrap();
1567        assert!(store.get_collection_metadata_by_alias("ucsc", "hg38").is_none());
1568    }
1569
1570    #[test]
1571    #[cfg(feature = "filesystem")]
1572    fn test_manifest_namespace_roundtrip() {
1573        let dir = tempdir().unwrap();
1574        let store_path = dir.path().join("store");
1575
1576        let mut store = RefgetStore::in_memory();
1577        let fasta_path = dir.path().join("test.fa");
1578        fs::write(&fasta_path, ">seq1\nACGT\n").unwrap();
1579        store
1580            .add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
1581            .unwrap();
1582
1583        let seq_digest = key_to_digest_string(&store.sequence_digests().next().unwrap());
1584        store.add_sequence_alias("ncbi", "NC_000001.11", &seq_digest).unwrap();
1585        let coll_digest = {
1586            let key = store.t_coll_keys()[0];
1587            key_to_digest_string(&key)
1588        };
1589        store.add_collection_alias("ucsc", "hg38", &coll_digest).unwrap();
1590
1591        store.write_store_to_dir(&store_path, None).unwrap();
1592
1593        let json_str = fs::read_to_string(store_path.join("rgstore.json")).unwrap();
1594        let metadata: serde_json::Value = serde_json::from_str(&json_str).unwrap();
1595        assert!(metadata["sequence_alias_namespaces"].as_array().unwrap().iter().any(|v| v.as_str() == Some("ncbi")));
1596        assert!(metadata["collection_alias_namespaces"].as_array().unwrap().iter().any(|v| v.as_str() == Some("ucsc")));
1597
1598        let store2 = RefgetStore::open_local(&store_path).unwrap();
1599        let available = store2.available_alias_namespaces();
1600        assert!(available.sequences.contains(&"ncbi".to_string()));
1601        assert!(available.collections.contains(&"ucsc".to_string()));
1602    }
1603
1604    #[test]
1605    #[cfg(feature = "filesystem")]
1606    fn test_manifest_empty_namespaces_not_serialized() {
1607        let dir = tempdir().unwrap();
1608        let store_path = dir.path().join("store");
1609
1610        let mut store = RefgetStore::in_memory();
1611        let fasta_path = dir.path().join("test.fa");
1612        fs::write(&fasta_path, ">seq1\nACGT\n").unwrap();
1613        store
1614            .add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
1615            .unwrap();
1616        store.write_store_to_dir(&store_path, None).unwrap();
1617
1618        let json_str = fs::read_to_string(store_path.join("rgstore.json")).unwrap();
1619        assert!(!json_str.contains("sequence_alias_namespaces"));
1620        assert!(!json_str.contains("collection_alias_namespaces"));
1621    }
1622
1623    #[test]
1624    #[cfg(feature = "filesystem")]
1625    fn test_old_rgstore_json_without_namespaces() {
1626        let dir = tempdir().unwrap();
1627        let store_path = dir.path().join("store");
1628        fs::create_dir_all(&store_path).unwrap();
1629
1630        let mut store = RefgetStore::in_memory();
1631        let fasta_path = dir.path().join("test.fa");
1632        fs::write(&fasta_path, ">seq1\nACGT\n").unwrap();
1633        store
1634            .add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
1635            .unwrap();
1636        store.write_store_to_dir(&store_path, None).unwrap();
1637
1638        let store2 = RefgetStore::open_local(&store_path).unwrap();
1639        let available = store2.available_alias_namespaces();
1640        assert!(available.sequences.is_empty());
1641        assert!(available.collections.is_empty());
1642    }
1643
1644    /// Fix #1: adding an alias to a disk-backed store re-writes rgstore.json so
1645    /// the served manifest advertises the new namespace (no separate index write
1646    /// required). Previously the alias TSV was persisted but the manifest was
1647    /// left stale, so remote/HTTP clients could never discover the namespace.
1648    #[test]
1649    #[cfg(feature = "filesystem")]
1650    fn test_alias_add_refreshes_manifest() {
1651        let dir = tempdir().unwrap();
1652        let store_path = dir.path().join("store");
1653
1654        let mut store = RefgetStore::on_disk(&store_path).unwrap();
1655        let fasta_path = dir.path().join("test.fa");
1656        fs::write(&fasta_path, ">chr1\nACGT\n").unwrap();
1657        store
1658            .add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
1659            .unwrap();
1660
1661        let seq_digest = key_to_digest_string(&store.sequence_digests().next().unwrap());
1662        // The manifest exists (written when the collection was added) but lists no
1663        // sequence namespaces yet.
1664        let before: serde_json::Value =
1665            serde_json::from_str(&fs::read_to_string(store_path.join("rgstore.json")).unwrap()).unwrap();
1666        assert!(before.get("sequence_alias_namespaces").is_none());
1667
1668        // Adding the alias must refresh the manifest in place.
1669        store.add_sequence_alias("ucsc", "chr1", &seq_digest).unwrap();
1670
1671        let after: serde_json::Value =
1672            serde_json::from_str(&fs::read_to_string(store_path.join("rgstore.json")).unwrap()).unwrap();
1673        assert!(after["sequence_alias_namespaces"]
1674            .as_array()
1675            .unwrap()
1676            .iter()
1677            .any(|v| v.as_str() == Some("ucsc")));
1678
1679        // And a fresh manifest-driven open discovers and resolves it.
1680        let store2 = RefgetStore::open_local(&store_path).unwrap();
1681        assert!(store2.available_alias_namespaces().sequences.contains(&"ucsc".to_string()));
1682        assert!(store2.get_sequence_metadata_by_alias("ucsc", "chr1").is_some());
1683    }
1684
1685    /// Fix #2: with the manifest as the single source of truth, a stale manifest
1686    /// (alias files present on disk but not advertised) yields the SAME result on
1687    /// a local filesystem as over HTTP — the aliases are not discovered and do not
1688    /// resolve. This is the failure that used to be silently masked by scanning
1689    /// the aliases/ directory; making it visible locally is the point.
1690    #[test]
1691    #[cfg(feature = "filesystem")]
1692    fn test_stale_manifest_hides_aliases_locally() {
1693        let dir = tempdir().unwrap();
1694        let store_path = dir.path().join("store");
1695
1696        let mut store = RefgetStore::in_memory();
1697        let fasta_path = dir.path().join("test.fa");
1698        fs::write(&fasta_path, ">chr1\nACGT\n").unwrap();
1699        store
1700            .add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
1701            .unwrap();
1702        let seq_digest = key_to_digest_string(&store.sequence_digests().next().unwrap());
1703        store.add_sequence_alias("ucsc", "chr1", &seq_digest).unwrap();
1704        store.write_store_to_dir(&store_path, None).unwrap();
1705
1706        // The alias TSV is on disk and the manifest correctly lists it.
1707        assert!(store_path.join("aliases/sequences/ucsc.tsv").exists());
1708
1709        // Simulate the stale-manifest bug: drop the advertised namespaces while
1710        // leaving the alias files in place.
1711        let mut metadata: serde_json::Value =
1712            serde_json::from_str(&fs::read_to_string(store_path.join("rgstore.json")).unwrap()).unwrap();
1713        metadata.as_object_mut().unwrap().remove("sequence_alias_namespaces");
1714        fs::write(store_path.join("rgstore.json"), serde_json::to_string_pretty(&metadata).unwrap()).unwrap();
1715
1716        // Manifest-driven open: the un-advertised alias is invisible and unresolvable,
1717        // exactly as it would be for a remote client that cannot list the directory.
1718        let store2 = RefgetStore::open_local(&store_path).unwrap();
1719        assert!(store2.available_alias_namespaces().sequences.is_empty());
1720        assert!(store2.get_sequence_metadata_by_alias("ucsc", "chr1").is_none());
1721    }
1722
1723    // -----------------------------------------------------------------------
1724    // KeepOurs sync strategy tests (regression test for was_local ordering bug)
1725    // -----------------------------------------------------------------------
1726
1727    /// Pull an alias file that does NOT exist locally yet.
1728    /// KeepOurs: first pull should count as `pulled`, second pull as `skipped`.
1729    #[test]
1730    #[cfg(all(feature = "filesystem", feature = "http"))]
1731    fn test_keep_ours_alias_first_pull_counts_as_pulled() {
1732        // "Remote" store: a directory with pre-built alias TSV files.
1733        // pull_aliases(Some("ncbi"), ...) pulls BOTH sequences and collections
1734        // namespace "ncbi", so we create both files on the remote.
1735        let remote_dir = tempdir().unwrap();
1736        let seq_dir = remote_dir.path().join("aliases").join("sequences");
1737        let coll_dir = remote_dir.path().join("aliases").join("collections");
1738        fs::create_dir_all(&seq_dir).unwrap();
1739        fs::create_dir_all(&coll_dir).unwrap();
1740        fs::write(seq_dir.join("ncbi.tsv"), "NC_000001.11\tsome_digest\n").unwrap();
1741        fs::write(coll_dir.join("ncbi.tsv"), "hg38\tcoll_digest\n").unwrap();
1742
1743        // Start a local HTTP server serving the remote_dir.
1744        let (base_url, shutdown) = start_file_server(remote_dir.path().to_path_buf());
1745
1746        // "Local" store: empty disk-backed store that will pull from the server.
1747        let local_dir = tempdir().unwrap();
1748        let local_store_path = local_dir.path().join("store");
1749        fs::create_dir_all(&local_store_path).unwrap();
1750
1751        let mut store = RefgetStore::on_disk(&local_store_path).unwrap();
1752        store.inner.remote_source = Some(base_url);
1753        // Advertise "ncbi" as an available namespace for both sequences and collections.
1754        // pull_aliases(Some("ncbi"), ...) pulls both kinds, so we need both files on remote.
1755        store.inner.available_sequence_alias_namespaces = vec!["ncbi".to_string()];
1756        store.inner.available_collection_alias_namespaces = vec!["ncbi".to_string()];
1757
1758        // First pull: both alias files do not exist locally → both should be pulled.
1759        // pull_aliases(Some("ncbi"), ...) pulls sequences/ncbi.tsv AND collections/ncbi.tsv.
1760        let result = store.pull_aliases(Some("ncbi"), SyncStrategy::KeepOurs).unwrap();
1761        assert_eq!(result.pulled, 2, "first pull should count both files as pulled, not skipped");
1762        assert_eq!(result.skipped, 0, "first pull should not be skipped");
1763        assert_eq!(result.not_found, 0);
1764
1765        // Second pull: both files now exist locally → both should be skipped.
1766        let result2 = store.pull_aliases(Some("ncbi"), SyncStrategy::KeepOurs).unwrap();
1767        assert_eq!(result2.skipped, 2, "second pull should skip both files (already local)");
1768        assert_eq!(result2.pulled, 0, "second pull should not count any files as pulled");
1769
1770        shutdown();
1771    }
1772}