Skip to main content

gtars_refget/store/
persistence.rs

1//! Disk I/O for RefgetStore: reading and writing index files,
2//! opening stores from disk, and loading sequences/collections.
3//!
4//! # Commit model
5//!
6//! [`ReadonlyRefgetStore::write_index_files`] is the ONE place the shared,
7//! whole-file store artifacts are published. It is not a "serialize my memory to
8//! disk" operation — it is a DELTA:
9//!
10//! ```text
11//! committed = (rows currently on disk  +  my additions)  \  my removals
12//! ```
13//!
14//! Both halves matter, and for different reasons.
15//!
16//! Reading the rows *currently on disk* is what makes concurrent writers safe. A
17//! store handle holds a snapshot taken at `open_local` time and nothing re-reads
18//! it afterwards; for a FASTA import that snapshot is hours old. A writer that
19//! serialized its own map would silently drop every row another writer committed
20//! in the meantime — which is exactly how a genome went missing from a production
21//! store on 2026-07-23 (its `collections/<digest>.rgsi` was on disk, but no index
22//! referenced it).
23//!
24//! Applying only *my own changes* is what makes deletion safe. The obvious
25//! alternative — union the whole in-memory pile onto what is on disk — cannot
26//! distinguish a row this handle produced from one it merely LOADED so it could
27//! be read (`open_local` loads a stub for every collection in the index). Such a
28//! commit writes back the loaded rows too, so a collection some OTHER process
29//! removed and unlinked comes back from this handle's stale snapshot: index rows
30//! pointing at `.seq` files that no longer exist, an alias resolving to a
31//! collection that cannot be opened. That failure needs no lock race at all —
32//! the removal can have completed before this commit even started. Recording
33//! changes explicitly (see [`super::readonly::PendingChanges`]) removes the
34//! ambiguity, and with it the need for any "not this row" tombstone mechanism.
35//!
36//! Everything expensive stays OUTSIDE the lock: FASTA parsing, digesting, and
37//! every per-`.seq` and per-`collections/*.rgsi` write. Those are
38//! digest-addressed and concurrency-safe by construction (see
39//! [`ReadonlyRefgetStore::write_seq_bytes_to_full_path`]). The exclusive section
40//! is O(index size): parse two TSVs, apply a small delta, publish. Seconds, not
41//! hours. The one deliberate exception is orphan GC — see
42//! [`ReadonlyRefgetStore::remove_collection`].
43
44use super::*;
45use super::readonly::{PendingChanges, ReadonlyRefgetStore};
46use super::alias::AliasKind;
47use super::atomic::{atomic_write, atomic_write_bytes};
48use super::fhr_metadata;
49use super::lock::StoreLock;
50
51use std::collections::{BTreeMap, HashMap, HashSet};
52use std::ffi::OsStr;
53
54use std::fs::{self, File, create_dir_all};
55use std::io::BufRead;
56use std::path::Path;
57
58use anyhow::{anyhow, Context, Result};
59
60use super::catalog::{CollRow, NewMember};
61use sha2::{Sha256, Digest};
62
63use crate::collection::{
64    RgsiHeader,
65    SequenceMetadataExt,
66    read_rgsi_file,
67};
68use crate::digest::{
69    SequenceCollectionMetadata, SequenceMetadata,
70    parse_rgci_line, parse_rgsi_fields, parse_rgsi_line,
71};
72use crate::hashkeyable::{HashKeyable, key_to_digest_string};
73
74use chrono::Utc;
75
76/// Header line of a `sequences.rgsi` file.
77const RGSI_HEADER: &str = "#name\tlength\talphabet\tsha512t24u\tmd5\tdescription";
78
79/// Header line of a `collections.rgci` file.
80const RGCI_HEADER: &str = "#digest\tn_sequences\tnames_digest\tsequences_digest\tlengths_digest\tname_length_pairs_digest\tsorted_name_length_pairs_digest\tsorted_sequences_digest";
81
82fn remove_cached_artifact(path: &Path) -> Result<()> {
83    match fs::symlink_metadata(path) {
84        Ok(metadata) if metadata.is_dir() => fs::remove_dir_all(path)
85            .with_context(|| format!("Failed to remove cached directory {}", path.display())),
86        Ok(_) => fs::remove_file(path)
87            .with_context(|| format!("Failed to remove cached file {}", path.display())),
88        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
89        Err(error) => Err(error)
90            .with_context(|| format!("Failed to inspect cached artifact {}", path.display())),
91    }
92}
93
94fn remove_cached_indexes<'a, I>(cache_path: &Path, paths: I) -> Result<()>
95where
96    I: IntoIterator<Item = &'a str>,
97{
98    let mut seen = HashSet::new();
99    for relative_path in paths {
100        ReadonlyRefgetStore::sanitize_relative_path(relative_path)?;
101        let full_path = cache_path.join(relative_path);
102        if seen.insert(full_path.clone()) {
103            remove_cached_artifact(&full_path)?;
104        }
105    }
106    Ok(())
107}
108
109fn validate_remote_manifest_paths(metadata: &StoreMetadata) -> Result<()> {
110    ReadonlyRefgetStore::sanitize_relative_path(&metadata.seqdata_path_template)?;
111    ReadonlyRefgetStore::sanitize_relative_path(&metadata.collections_path_template)?;
112    ReadonlyRefgetStore::sanitize_relative_path(&metadata.sequence_index)?;
113    if let Some(ref collection_index) = metadata.collection_index {
114        ReadonlyRefgetStore::sanitize_relative_path(collection_index)?;
115    }
116    Ok(())
117}
118
119// ============================================================================
120// ReadonlyRefgetStore disk I/O methods
121// ============================================================================
122
123impl ReadonlyRefgetStore {
124    /// Write a single sequence to disk using the configured path template
125    pub(crate) fn write_sequence_to_disk_single(
126        &self,
127        metadata: &SequenceMetadata,
128        sequence: &[u8],
129    ) -> Result<()> {
130        let template = self
131            .seqdata_path_template
132            .as_ref()
133            .context("seqdata_path_template not set")?;
134        let local_path = self.local_path.as_ref().context("local_path not set")?;
135
136        let seq_file_path = Self::expand_template(&metadata.sha512t24u, template);
137        let full_path = local_path.join(&seq_file_path);
138
139        if let Some(parent) = full_path.parent() {
140            create_dir_all(parent)?;
141        }
142
143        super::atomic::publish_bytes_nosync(&full_path, sequence)
144    }
145
146    /// Write a `.seq` file for a single sequence, given an already-expanded full
147    /// path, skipping `create_dir_all` when the shard directory is known to exist.
148    ///
149    /// Per-digest `.seq` files are independent, so this is safe to call
150    /// concurrently from a writer pool (see [`import`](super::import)). The
151    /// `created_shards` cache holds shard dirs already created in this run so the
152    /// common case avoids a `create_dir_all` syscall per (tiny) sequence -- the
153    /// throughput bottleneck for transcriptomes with hundreds of thousands of
154    /// records.
155    #[cfg_attr(not(feature = "filesystem"), allow(dead_code))]
156    pub(crate) fn write_seq_bytes_to_full_path(
157        full_path: &Path,
158        sequence: &[u8],
159        created_shards: &std::sync::Mutex<HashSet<std::path::PathBuf>>,
160    ) -> Result<()> {
161        if let Some(parent) = full_path.parent() {
162            // Fast path: shard dir already created this run -> skip the syscall.
163            let known = {
164                let guard = created_shards.lock().unwrap();
165                guard.contains(parent)
166            };
167            if !known {
168                create_dir_all(parent)?;
169                created_shards.lock().unwrap().insert(parent.to_path_buf());
170            }
171        }
172
173        // Temp + rename, never an in-place `File::create`: the same digest can
174        // be written by a concurrent process, and truncating a file it already
175        // published (or letting a reader see a partial write) corrupts live data.
176        super::atomic::publish_bytes_nosync(full_path, sequence)
177    }
178
179    /// Write a single collection RGSI file to disk.
180    /// Used when persist_to_disk=true to persist collections incrementally.
181    pub(crate) fn write_collection_to_disk_single<I>(
182        &self,
183        metadata: &SequenceCollectionMetadata,
184        members: I,
185    ) -> Result<()>
186    where
187        I: IntoIterator,
188        I::Item: std::borrow::Borrow<SequenceMetadata>,
189    {
190        let local_path = self.local_path.as_ref().context("local_path not set")?;
191
192        let coll_file_path = format!("collections/{}.rgsi", metadata.digest);
193        let full_path = local_path.join(&coll_file_path);
194
195        if let Some(parent) = full_path.parent() {
196            create_dir_all(parent)?;
197        }
198
199        crate::collection::write_collection_rgsi_rows(&full_path, metadata, members)?;
200
201        Ok(())
202    }
203
204    // =========================================================================
205    // The commit path
206    // =========================================================================
207
208    /// Acquire the store's exclusive writer lock for a commit, unless this store
209    /// already holds one via [`Self::lock_for_batch`].
210    ///
211    /// Returns `Ok(None)` when the lock is already held (re-entrancy: a batch
212    /// guard wrapping several mutations must not deadlock against the
213    /// `write_index_files` each mutation triggers) or when the store is not
214    /// disk-backed (nothing to serialize against).
215    pub(crate) fn acquire_commit_lock(&self, operation: &str) -> Result<Option<StoreLock>> {
216        if self.commit_lock.is_some() {
217            return Ok(None);
218        }
219        let Some(local_path) = self.local_path.as_ref() else {
220            return Ok(None);
221        };
222        Ok(Some(StoreLock::acquire(
223            local_path,
224            operation,
225            self.lock_options.clone(),
226        )?))
227    }
228
229    /// Commit the store's shared index/manifest/alias artifacts.
230    ///
231    /// Applies this handle's [`PendingChanges`] to the index as it is on disk
232    /// RIGHT NOW, rather than serializing the open-time snapshot — see the module
233    /// docs for why both halves of that matter. The publish order is
234    /// load-bearing: indexes and alias files first, `rgstore.json` LAST, because
235    /// the manifest advertises digests of the files it describes. A reader that
236    /// catches the manifest mid-commit would otherwise be told about bytes that
237    /// have not landed.
238    ///
239    /// Called automatically when adding or removing collections in disk-backed
240    /// mode, and by [`Self::write`].
241    pub(crate) fn write_index_files(&self) -> Result<()> {
242        let local_path = self
243            .local_path
244            .as_ref()
245            .context("local_path not set")?
246            .clone();
247        let template = self
248            .seqdata_path_template
249            .as_ref()
250            .context("seqdata_path_template not set")?
251            .clone();
252
253        let _guard = self.acquire_commit_lock("write_index_files")?;
254
255        // Snapshot the pending changes under the store lock, so what gets
256        // applied and what gets cleared afterwards are exactly the same set.
257        let pending = self.pending.lock().unwrap().clone();
258
259        let sequence_index_path = local_path.join("sequences.rgsi");
260        let collection_index_path = local_path.join("collections.rgci");
261
262        // (1) Start from the CURRENT on-disk rows -- not the open-time snapshot
263        // -- and apply only what this handle changed.
264        let mut sequences = read_sequences_rgsi_rows(&sequence_index_path)?;
265        self.apply_pending_sequence_rows(&mut sequences, &pending);
266        let mut collections = read_collections_rgci_rows(&collection_index_path)?;
267        self.apply_pending_collection_rows(&mut collections, &pending);
268
269        // (1b) Refuse to publish a collection whose sequences are not all in
270        // the index we are about to write. Import dedups against rows loaded at
271        // open time and never re-stages those, so if another writer's orphan
272        // GC removed such a row (and its `.seq`) while this import was running,
273        // committing now would publish a collection pointing at missing data.
274        // Under the lock, "row present" implies "file present" (removal drops
275        // both, index first, under this same lock), so this check is enough.
276        for coll_key in &pending.collections {
277            let member_keys = self.loaded_member_seq_keys(&key_to_digest_string(coll_key));
278            if let Some(missing) = member_keys.iter().find(|k| !sequences.contains_key(*k)) {
279                anyhow::bail!(
280                    "cannot commit collection {}: its sequence {} is no longer in the store index. Another writer removed it while this import was in progress. Re-run the import.",
281                    key_to_digest_string(coll_key),
282                    key_to_digest_string(missing),
283                );
284            }
285        }
286
287        // (2) Publish the indexes atomically.
288        write_sequences_rgsi_rows(&sequence_index_path, &sequences)?;
289        write_collections_rgci_rows(&collection_index_path, &collections)?;
290
291        // (2b) Publish the pack sidecar (packed layout only), merging this
292        // handle's pack rows and removals into whatever is on disk now — the
293        // same delta discipline as `sequences.rgsi`.
294        if self.layout == Layout::Packed {
295            self.commit_pack_idx(&local_path, &pending)?;
296            self.invalidate_pack_index();
297        }
298
299        // (3) Publish the alias TSVs this handle touched (same delta rule).
300        self.commit_all_alias_namespaces(&local_path, &pending)?;
301
302        // (4) Recompute manifest fields from what we just wrote -- NOT from
303        // memory, which is neither a superset nor a subset of what is on disk.
304        let logical_bytes: u64 = sequences
305            .values()
306            .map(|m| m.disk_size(&self.mode) as u64)
307            .sum();
308
309        let mut metadata = self.manifest_base(&local_path, &template)?;
310        metadata.sequences_digest = Self::sha256_file(&sequence_index_path).ok();
311        metadata.collections_digest = Self::sha256_file(&collection_index_path).ok();
312        metadata.aliases_digest = self.compute_aliases_digest();
313        metadata.fhr_digest = self.compute_fhr_digest();
314        metadata.logical_sequence_bytes = Some(logical_bytes);
315        let (seq_ns, coll_ns) = published_alias_namespaces(&local_path);
316        metadata.sequence_alias_namespaces = seq_ns;
317        metadata.collection_alias_namespaces = coll_ns;
318
319        // (5) Manifest LAST.
320        write_manifest(&local_path, &metadata)?;
321
322        // (6) These changes are on disk now; forget them.
323        self.pending.lock().unwrap().clear_matching(&pending);
324
325        Ok(())
326    }
327
328    /// Merge and publish `sequences.pack.idx` under the commit lock.
329    ///
330    /// Seals any open incremental session pack first (so its rows are included),
331    /// then applies this handle's `pack_rows` additions and
332    /// `removed_sequences` removals to whatever is on disk now, and republishes
333    /// the sorted sidecar. Mirrors `write_sequences_rgsi_rows`' determinism: the
334    /// same input rows always produce byte-identical output.
335    pub(crate) fn commit_pack_idx(&self, local_path: &Path, pending: &PendingChanges) -> Result<()> {
336        use super::packidx::{read_pack_idx_rows, write_pack_idx, PackRow};
337
338        let idx_path = local_path.join("sequences.pack.idx");
339
340        // Start from the CURRENT on-disk sidecar.
341        let mut rows: BTreeMap<String, PackRow> =
342            read_pack_idx_rows(&super::packidx::load_pack_idx_or_empty(local_path)?)?;
343
344        // Every pack a new row points at must still be on disk. A writer whose
345        // pack had the same content-hash name as an existing one reuses that
346        // file instead of writing its own, and another writer can have
347        // unlinked it since. Removal and compaction unlink packs only under
348        // this lock, so against them a pack present now stays present through
349        // this commit. A failed import or a dropped handle unlinks packs it
350        // created without the lock (see `remove_uncommitted_packs`).
351        let packs_dir = local_path.join("packs");
352        let check_packs = |new_rows: &mut dyn Iterator<Item = &PackRow>| -> Result<()> {
353            let mut seen: HashSet<&str> = HashSet::new();
354            for row in new_rows {
355                if seen.insert(&row.pack) && !packs_dir.join(format!("{}.pack", row.pack)).exists() {
356                    anyhow::bail!(
357                        "cannot commit: pack {} is no longer in the store. Another writer \
358                         removed it while this handle was writing. Reopen the store and \
359                         re-run the import.",
360                        row.pack
361                    );
362                }
363            }
364            Ok(())
365        };
366        check_packs(&mut pending.pack_rows.values())?;
367
368        // Seal any open incremental session pack and fold in its rows.
369        let session_rows = self.seal_open_session_pack()?;
370        check_packs(&mut session_rows.iter().map(|(_, row)| row))?;
371        for (digest, row) in session_rows {
372            rows.insert(digest, row);
373        }
374
375        // Apply this handle's additions.
376        for (key, row) in &pending.pack_rows {
377            rows.insert(key_to_digest_string(key), row.clone());
378        }
379        // Apply this handle's removals.
380        for key in &pending.removed_sequences {
381            rows.remove(&key_to_digest_string(key));
382        }
383
384        write_pack_idx(&idx_path, &rows)
385    }
386
387    /// Apply this handle's pending sequence additions and removals to rows read
388    /// fresh from `sequences.rgsi`.
389    ///
390    /// Additions do NOT overwrite a row already on disk. `length`, `alphabet`,
391    /// and `md5` are determined by the sha512t24u key, so a key collision cannot
392    /// disagree about them — but `name` and `description` are not: the same
393    /// sequence is `chr1` in one collection and `1` in another. Keeping the
394    /// published row makes the outcome stable, at the price of being
395    /// order-dependent across processes: whichever writer commits first sets the
396    /// name.
397    ///
398    /// The honest framing is that `sequences.rgsi`'s `name` column is ADVISORY.
399    /// The authoritative per-collection name mapping lives in each collection's
400    /// members and in each `collections/<digest>.rgsi`. A lexicographic
401    /// tie-break would be order-independent but would silently rename
402    /// sequences on rebuild, which is worse.
403    fn apply_pending_sequence_rows(
404        &self,
405        rows: &mut HashMap<DigestKey, SequenceMetadata>,
406        pending: &PendingChanges,
407    ) {
408        for key in &pending.sequences {
409            if let Some(view) = self.sequence_view(key_to_digest_string(key)) {
410                rows.entry(*key).or_insert_with(|| view.to_metadata());
411            }
412        }
413        for key in &pending.removed_sequences {
414            rows.remove(key);
415        }
416    }
417
418    /// Apply this handle's pending collection additions and removals to rows read
419    /// fresh from `collections.rgci`.
420    ///
421    /// The key is the collection digest and every other column is a digest of the
422    /// collection's CONTENT, so the same key implies the same row. The one
423    /// asymmetry is vintage: rows written by older gtars may have empty ancillary
424    /// columns (`name_length_pairs_digest`, `sorted_name_length_pairs_digest`,
425    /// `sorted_sequences_digest`). Prefer whichever row carries more of them, so
426    /// re-adding a collection upgrades an old row instead of pinning it.
427    fn apply_pending_collection_rows(
428        &self,
429        rows: &mut HashMap<DigestKey, SequenceCollectionMetadata>,
430        pending: &PendingChanges,
431    ) {
432        let ancillary_count = |m: &SequenceCollectionMetadata| {
433            m.name_length_pairs_digest.is_some() as u8
434                + m.sorted_name_length_pairs_digest.is_some() as u8
435                + m.sorted_sequences_digest.is_some() as u8
436        };
437        for key in &pending.collections {
438            let Some(mine) = self.get_collection_metadata(key_to_digest_string(key)) else {
439                continue;
440            };
441            match rows.get(key) {
442                Some(existing) if ancillary_count(existing) >= ancillary_count(mine) => {}
443                _ => {
444                    rows.insert(*key, mine.clone());
445                }
446            }
447        }
448        for key in &pending.removed_collections {
449            rows.remove(key);
450        }
451    }
452
453    /// Build the manifest to publish, preserving fields that must survive a
454    /// commit.
455    ///
456    /// `created_at` is read back from the existing manifest rather than stamped
457    /// with `now()`. It previously meant "last written" (it was overwritten on
458    /// every commit), which made it a duplicate of `modified`; since the commit
459    /// re-reads the manifest under the lock anyway, it can mean what it says.
460    fn manifest_base(&self, local_path: &Path, seqdata_template: &str) -> Result<StoreMetadata> {
461        let now = Utc::now().to_rfc3339();
462        let existing = read_manifest(local_path)?;
463        let created_at = existing
464            .as_ref()
465            .map(|m| m.created_at.clone())
466            .unwrap_or_else(|| now.clone());
467
468        Ok(StoreMetadata {
469            version: 1,
470            seqdata_path_template: seqdata_template.to_string(),
471            collections_path_template: "collections/%s.rgsi".to_string(),
472            sequence_index: "sequences.rgsi".to_string(),
473            collection_index: Some("collections.rgci".to_string()),
474            mode: self.mode,
475            layout: self.layout,
476            created_at,
477            ancillary_digests: self.ancillary_digests,
478            attribute_index: self.attribute_index,
479            sequence_alias_namespaces: self.aliases.sequence_namespaces(),
480            collection_alias_namespaces: self.aliases.collection_namespaces(),
481            modified: Some(now),
482            collections_digest: None,
483            sequences_digest: None,
484            aliases_digest: None,
485            fhr_digest: None,
486            logical_sequence_bytes: None,
487        })
488    }
489
490    /// Write a fresh rgstore.json for an EXPORT to `dir` (a directory this store
491    /// is being copied into, not committed to). No merge, no lock: the caller is
492    /// producing a new store image.
493    pub(crate) fn write_rgstore_json(&self, dir: &Path, seqdata_template: &str) -> Result<()> {
494        let now = Utc::now().to_rfc3339();
495        let metadata = StoreMetadata {
496            version: 1,
497            seqdata_path_template: seqdata_template.to_string(),
498            collections_path_template: "collections/%s.rgsi".to_string(),
499            sequence_index: "sequences.rgsi".to_string(),
500            collection_index: Some("collections.rgci".to_string()),
501            mode: self.mode,
502            // Export always produces a STANDALONE store image (see
503            // `write_store_to_dir`), regardless of the source store's layout.
504            layout: Layout::Standalone,
505            created_at: now.clone(),
506            ancillary_digests: self.ancillary_digests,
507            attribute_index: self.attribute_index,
508            sequence_alias_namespaces: self.aliases.sequence_namespaces(),
509            collection_alias_namespaces: self.aliases.collection_namespaces(),
510            modified: Some(now),
511            collections_digest: None,
512            sequences_digest: None,
513            aliases_digest: None,
514            fhr_digest: None,
515            logical_sequence_bytes: Some(self.logical_sequence_bytes() as u64),
516        };
517        write_manifest(dir, &metadata)
518    }
519
520    /// Refresh only the alias-namespace lists (and aliases_digest) in an existing
521    /// rgstore.json, preserving created_at and the index digests.
522    ///
523    /// This is the cheap manifest update used after an alias is added/removed: it
524    /// re-reads the current manifest and rewrites only the alias-derived fields,
525    /// so we do not rehash the (potentially 60+ MB) sequence/collection indexes
526    /// on every alias mutation. Keeps `sequence_alias_namespaces` /
527    /// `collection_alias_namespaces` in lock-step with what is actually on disk,
528    /// so served stores stay self-describing. No-op if the manifest does not yet
529    /// exist (the next full index write will include the namespaces).
530    ///
531    /// The namespace lists come from a DIRECTORY SCAN of what was just
532    /// published, not from `self.aliases`. Writing memory's view here is how a
533    /// namespace another writer created gets dropped from the manifest: the TSV
534    /// stays on disk but stops being advertised, and over HTTP -- where you
535    /// cannot list a directory -- that makes it unreachable.
536    ///
537    /// Callers must already hold the store lock.
538    pub(crate) fn refresh_manifest_alias_namespaces(&self) -> Result<()> {
539        let local_path = match self.local_path.as_ref() {
540            Some(p) => p,
541            None => return Ok(()),
542        };
543        let Some(mut metadata) = read_manifest(local_path)? else {
544            return Ok(());
545        };
546
547        let (seq_ns, coll_ns) = published_alias_namespaces(local_path);
548        metadata.sequence_alias_namespaces = seq_ns;
549        metadata.collection_alias_namespaces = coll_ns;
550        metadata.aliases_digest = self.compute_aliases_digest();
551        metadata.modified = Some(Utc::now().to_rfc3339());
552
553        write_manifest(local_path, &metadata)
554    }
555
556    // =========================================================================
557    // Whole-store serialization (export paths -- no merge)
558    // =========================================================================
559
560    /// Write this store's in-memory collection metadata to a `.rgci` file.
561    ///
562    /// EXPORT ONLY: serializes exactly what is in memory, which is correct when
563    /// producing a fresh store image in an empty directory. The commit path
564    /// applies a delta to the rows already on disk instead — do not route a
565    /// commit through here, or rows another writer added are lost.
566    pub(crate) fn write_collections_rgci<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
567        let rows: HashMap<DigestKey, SequenceCollectionMetadata> = self
568            .catalog
569            .coll_rows()
570            .map(|c| {
571                let m = self.catalog.coll_meta(c);
572                (m.digest.to_key(), m.clone())
573            })
574            .collect();
575        write_collections_rgci_rows(file_path.as_ref(), &rows)
576    }
577
578    /// Write this store's in-memory sequence metadata to an `.rgsi` file.
579    ///
580    /// EXPORT ONLY — see [`Self::write_collections_rgci`].
581    pub fn write_sequences_rgsi<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
582        let rows: HashMap<DigestKey, SequenceMetadata> = self
583            .sequence_views()
584            .map(|v| (v.sha512t24u().to_key(), v.to_metadata()))
585            .collect();
586        write_sequences_rgsi_rows(file_path.as_ref(), &rows)
587    }
588
589    // =========================================================================
590    // Alias commit
591    // =========================================================================
592
593    /// Publish every alias namespace this handle has TOUCHED. Caller must hold
594    /// the store lock.
595    ///
596    /// Namespaces with no pending change are not rewritten at all — not even
597    /// read. That is the point: the previous implementation visited every
598    /// namespace in memory plus every `*.tsv` on disk and republished each one
599    /// from its own snapshot, which is how an alias another process had just
600    /// removed came back.
601    fn commit_all_alias_namespaces(
602        &self,
603        local_path: &Path,
604        pending: &PendingChanges,
605    ) -> Result<()> {
606        let aliases_dir = local_path.join("aliases");
607        for kind in [AliasKind::Sequence, AliasKind::Collection] {
608            for ns in pending.touched_alias_namespaces(kind) {
609                self.commit_alias_namespace(&aliases_dir, kind, &ns, pending)?;
610            }
611        }
612        Ok(())
613    }
614
615    /// Apply this handle's pending alias changes for ONE namespace to the TSV as
616    /// it is on disk, and publish the result atomically. Deletes the TSV only
617    /// when the resulting map is empty.
618    ///
619    /// Two behaviours here exist because their opposites each destroyed data:
620    ///
621    /// * Only aliases in `pending` are written. Republishing the whole in-memory
622    ///   namespace resurrects entries another writer deleted.
623    /// * Deletion is decided by the RESULT, not by intent. Deleting the TSV
624    ///   because this handle emptied the namespace throws away aliases another
625    ///   writer added to it; deleting it because the namespace is absent from
626    ///   memory is worse still, since `open_local` loads only the namespaces the
627    ///   manifest advertises, so "not in memory" routinely means "not mine".
628    pub(crate) fn commit_alias_namespace(
629        &self,
630        aliases_dir: &Path,
631        kind: AliasKind,
632        namespace: &str,
633        pending: &PendingChanges,
634    ) -> Result<()> {
635        let tsv_path = aliases_dir.join(kind.subdir()).join(format!("{}.tsv", namespace));
636
637        let mut merged = read_alias_tsv(&tsv_path)?;
638
639        for (k, ns, alias) in &pending.aliases {
640            if *k != kind || ns != namespace {
641                continue;
642            }
643            // The alias may have been removed from memory again after being
644            // recorded; nothing to publish then.
645            let Some(digest) = self.aliases.resolve(kind, namespace, alias) else {
646                continue;
647            };
648            match merged.get(alias) {
649                Some(existing) if *existing != digest => {
650                    // A genuine semantic conflict: two writers bound the same
651                    // human-readable name to different content. Silently picking
652                    // one is the failure class that lost a genome in July.
653                    if !self.force_alias && !pending.is_forced(kind, namespace, alias) {
654                        return Err(anyhow::anyhow!(
655                            "alias conflict in {} namespace '{}': '{}' is already published as {} \
656                             on disk but this writer has it as {}. Another writer bound it first. \
657                             Re-run with force-alias enabled (CLI: --force-alias) to overwrite the \
658                             published value.",
659                            kind.subdir(),
660                            namespace,
661                            alias,
662                            key_to_digest_string(existing),
663                            key_to_digest_string(&digest),
664                        ));
665                    }
666                    merged.insert(alias.clone(), digest);
667                }
668                Some(_) => {}
669                None => {
670                    merged.insert(alias.clone(), digest);
671                }
672            }
673        }
674
675        for (k, ns, alias) in &pending.removed_aliases {
676            if *k == kind && ns == namespace {
677                merged.remove(alias);
678            }
679        }
680
681        write_alias_namespace(&tsv_path, &merged)
682    }
683
684    // =========================================================================
685    // Orphan GC support
686    // =========================================================================
687
688    /// The set of sequence digests still referenced by SOME collection on disk,
689    /// excluding `exclude` (the collection being removed).
690    ///
691    /// Derived from disk, not from the loaded collection members. Members are
692    /// loaded only by `load_collections_from_directory`, `ensure_collection_loaded`,
693    /// and the import path, NOT by the normal `open_local` load. On a
694    /// partially-loaded store none are, so a live set derived from them
695    /// says "nothing is referenced" and the GC unlinks sequences other
696    /// collections still need. That difference is invisible from inside the
697    /// function: a partially-loaded store looks exactly like a fully-loaded small
698    /// one.
699    ///
700    /// FAILS CLOSED. If any collection listed in the index has no readable
701    /// `.rgsi` and is not fully resident in memory, this returns `Err` and the
702    /// caller must delete nothing. A missing input must never be read as "nothing
703    /// references this".
704    pub(crate) fn live_sequence_digests_from_disk(
705        &self,
706        exclude: &DigestKey,
707    ) -> Result<HashSet<DigestKey>> {
708        let local_path = self.local_path.as_ref().context("local_path not set")?;
709        let pending = self.pending.lock().unwrap().clone();
710        let index_path = local_path.join("collections.rgci");
711        // The same view the commit will publish: what is on disk now, plus this
712        // handle's uncommitted adds, minus its uncommitted removals.
713        let mut collections = read_collections_rgci_rows(&index_path)?;
714        self.apply_pending_collection_rows(&mut collections, &pending);
715
716        let mut live = HashSet::new();
717        for (key, meta) in &collections {
718            if key == exclude {
719                continue;
720            }
721
722            // Prefer a fully-resident in-memory record; it needs no I/O and is
723            // authoritative for collections that were never persisted.
724            if self.is_collection_loaded(&meta.digest) {
725                live.extend(self.loaded_member_seq_keys(&meta.digest));
726                continue;
727            }
728
729            let rgsi_path = local_path.join(format!("collections/{}.rgsi", meta.digest));
730            let collection = read_rgsi_file(&rgsi_path).with_context(|| {
731                format!(
732                    "refusing to remove orphan sequences: collection {} is listed in \
733                     collections.rgci but {} could not be read. Treating that as \
734                     'references nothing' would delete live sequence data.",
735                    meta.digest,
736                    rgsi_path.display()
737                )
738            })?;
739            for seq in &collection.sequences {
740                live.insert(seq.metadata().sha512t24u.to_key());
741            }
742        }
743        Ok(live)
744    }
745
746    /// The sequence digests belonging to one collection, read from its
747    /// `collections/<digest>.rgsi` (falling back to the in-memory record).
748    pub(crate) fn collection_sequence_digests(&self, digest: &str) -> Result<Vec<DigestKey>> {
749        if self.is_collection_loaded(digest) {
750            return Ok(self.loaded_member_seq_keys(digest));
751        }
752        if let Some(local_path) = self.local_path.as_ref() {
753            let rgsi_path = local_path.join(format!("collections/{}.rgsi", digest));
754            if rgsi_path.exists() {
755                let collection = read_rgsi_file(&rgsi_path)?;
756                return Ok(collection
757                    .sequences
758                    .iter()
759                    .map(|s| s.metadata().sha512t24u.to_key())
760                    .collect());
761            }
762        }
763        // Last resort: nothing is known about this collection's members.
764        Ok(Vec::new())
765    }
766
767    /// Read the store metadata from rgstore.json, returning state digests and timestamp.
768    ///
769    /// Returns a HashMap with keys: modified, collections_digest, sequences_digest,
770    /// aliases_digest, fhr_digest, logical_sequence_bytes. Missing values are omitted
771    /// from the map.
772    pub fn store_metadata(&self) -> Result<HashMap<String, String>> {
773        let local_path = self.local_path.as_ref().context("local_path not set")?;
774        let json = fs::read_to_string(local_path.join("rgstore.json"))
775            .context("Failed to read rgstore.json")?;
776        let metadata: StoreMetadata =
777            serde_json::from_str(&json).context("Failed to parse store metadata")?;
778
779        let mut map = HashMap::new();
780        if let Some(v) = metadata.modified { map.insert("modified".to_string(), v); }
781        if let Some(v) = metadata.collections_digest { map.insert("collections_digest".to_string(), v); }
782        if let Some(v) = metadata.sequences_digest { map.insert("sequences_digest".to_string(), v); }
783        if let Some(v) = metadata.aliases_digest { map.insert("aliases_digest".to_string(), v); }
784        if let Some(v) = metadata.fhr_digest { map.insert("fhr_digest".to_string(), v); }
785        if let Some(v) = metadata.logical_sequence_bytes { map.insert("logical_sequence_bytes".to_string(), v.to_string()); }
786        Ok(map)
787    }
788
789    /// Compute SHA256 digest of a file's contents.
790    fn sha256_file(path: &Path) -> Result<String> {
791        let bytes = fs::read(path)?;
792        let hash = Sha256::digest(&bytes);
793        Ok(format!("{:x}", hash))
794    }
795
796    /// Compute a combined SHA256 digest of all alias namespace files (sorted).
797    /// Alias files live under aliases/sequences/*.tsv and aliases/collections/*.tsv.
798    fn compute_aliases_digest(&self) -> Option<String> {
799        let local_path = self.local_path.as_ref()?;
800        let aliases_dir = local_path.join("aliases");
801        if !aliases_dir.exists() { return None; }
802
803        let mut paths: Vec<_> = Vec::new();
804        for subdir in &["sequences", "collections"] {
805            let sub = aliases_dir.join(subdir);
806            if sub.exists() {
807                if let Ok(entries) = fs::read_dir(&sub) {
808                    for entry in entries.filter_map(|e| e.ok()) {
809                        let p = entry.path();
810                        if p.extension().map_or(false, |e| e == "tsv") {
811                            paths.push(p);
812                        }
813                    }
814                }
815            }
816        }
817        if paths.is_empty() { return None; }
818        paths.sort();
819
820        let mut hasher = Sha256::new();
821        for path in &paths {
822            hasher.update(fs::read(path).ok()?);
823        }
824        Some(format!("{:x}", hasher.finalize()))
825    }
826
827    /// Compute a combined SHA256 digest of all FHR sidecar files (sorted).
828    fn compute_fhr_digest(&self) -> Option<String> {
829        let local_path = self.local_path.as_ref()?;
830        let fhr_dir = local_path.join("fhr");
831        if !fhr_dir.exists() { return None; }
832
833        // Only real sidecars count: a concurrent atomic_write leaves
834        // `.rgstore.tmp.*` files in this directory for a moment, and one left
835        // behind by a crash must not poison every later digest.
836        let mut paths: Vec<_> = fs::read_dir(&fhr_dir).ok()?
837            .filter_map(|e| e.ok())
838            .map(|e| e.path())
839            .filter(|p| {
840                p.file_name()
841                    .and_then(|n| n.to_str())
842                    .map_or(false, |n| n.ends_with(super::fhr_metadata::SIDECAR_EXTENSION))
843            })
844            .collect();
845        if paths.is_empty() { return None; }
846        paths.sort();
847
848        let mut hasher = Sha256::new();
849        for path in paths {
850            hasher.update(fs::read(&path).ok()?);
851        }
852        Some(format!("{:x}", hasher.finalize()))
853    }
854
855    // =========================================================================
856    // Open methods
857    // =========================================================================
858
859    /// Open a local store (internal). Users should use RefgetStore::open_local().
860    pub(crate) fn open_local<P: AsRef<Path>>(path: P) -> Result<Self> {
861        let root_path = path.as_ref();
862
863        let index_path = root_path.join("rgstore.json");
864        let json = fs::read_to_string(&index_path).context(format!(
865            "Failed to read rgstore.json from {}",
866            index_path.display()
867        ))?;
868
869        let metadata: StoreMetadata =
870            serde_json::from_str(&json).context("Failed to parse store metadata")?;
871
872        Self::sanitize_relative_path(&metadata.seqdata_path_template)?;
873        Self::sanitize_relative_path(&metadata.sequence_index)?;
874        if let Some(ref ci) = metadata.collection_index {
875            Self::sanitize_relative_path(ci)?;
876        }
877
878        let mut store = ReadonlyRefgetStore::new(metadata.mode);
879        store.local_path = Some(root_path.to_path_buf());
880        store.seqdata_path_template = Some(metadata.seqdata_path_template.clone());
881        store.persist_to_disk = true;
882        store.layout = metadata.layout;
883        store.ancillary_digests = metadata.ancillary_digests;
884        store.attribute_index = metadata.attribute_index;
885
886        // Invariant: a packed store is never remote-backed.
887        debug_assert!(!(store.layout == Layout::Packed && store.remote_source.is_some()));
888
889        let sequence_index_path = root_path.join(&metadata.sequence_index);
890        if sequence_index_path.exists() {
891            Self::load_sequences_from_index(&mut store, &sequence_index_path)?;
892        }
893
894        if let Some(ref collection_index) = metadata.collection_index {
895            let collection_index_path = root_path.join(collection_index);
896            if collection_index_path.exists() {
897                Self::load_collection_stubs_from_rgci(&mut store, &collection_index_path)?;
898            }
899        }
900
901        if store.catalog.n_collections() == 0 {
902            let collections_dir = root_path.join("collections");
903            Self::load_collections_from_directory(&mut store, &collections_dir)?;
904        }
905
906        // Manifest is the single source of truth: load exactly the alias
907        // namespaces rgstore.json advertises, rather than scanning the aliases/
908        // directory. This unifies local and remote behavior — an alias file the
909        // manifest omits is not loaded, so a stale manifest fails the same way on
910        // disk as it does over HTTP (where directory listing is impossible),
911        // surfacing manifest-write bugs instead of silently masking them.
912        let aliases_dir = root_path.join("aliases");
913        store.aliases.load_namespaces_from_dir(
914            &aliases_dir,
915            &metadata.sequence_alias_namespaces,
916            &metadata.collection_alias_namespaces,
917        )?;
918        store.available_sequence_alias_namespaces = metadata.sequence_alias_namespaces;
919        store.available_collection_alias_namespaces = metadata.collection_alias_namespaces;
920
921        store.fhr_metadata =
922            fhr_metadata::load_sidecars(&root_path.join("fhr"));
923
924        Ok(store)
925    }
926
927    /// Open a remote store (internal). Users should use RefgetStore::open_remote().
928    pub(crate) fn open_remote<P: AsRef<Path>, S: AsRef<str>>(
929        cache_path: P,
930        remote_url: S,
931    ) -> Result<Self> {
932        let cache_path = cache_path.as_ref();
933        let remote_url = remote_url.as_ref().to_string();
934
935        create_dir_all(cache_path)
936            .with_context(|| format!("Failed to create remote cache {}", cache_path.display()))?;
937
938        let origin_path = cache_path.join(".origin");
939        match fs::read_to_string(&origin_path) {
940            Ok(recorded) => {
941                let recorded = recorded.strip_suffix('\n').unwrap_or(&recorded);
942                if recorded != remote_url {
943                    anyhow::bail!(
944                        "Remote cache {} belongs to {}, not requested origin {}",
945                        cache_path.display(),
946                        recorded,
947                        remote_url
948                    );
949                }
950            }
951            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
952                let contents = format!("{}\n", remote_url);
953                atomic_write_bytes(&origin_path, contents.as_bytes()).with_context(|| {
954                    format!("Failed to record remote cache origin in {}", origin_path.display())
955                })?;
956            }
957            Err(error) => {
958                return Err(error).with_context(|| {
959                    format!("Failed to read remote cache origin {}", origin_path.display())
960                });
961            }
962        }
963
964        let manifest_path = cache_path.join("rgstore.json");
965        let cached_json = fs::read_to_string(&manifest_path).ok();
966        let old_metadata = cached_json
967            .as_deref()
968            .and_then(|json| serde_json::from_str::<StoreMetadata>(json).ok())
969            .filter(|metadata| validate_remote_manifest_paths(metadata).is_ok());
970
971        // Refresh the manifest on every open. If the remote is unreachable,
972        // fall back to the cached copy so an earlier-opened store works offline.
973        let json = match Self::fetch_file(
974            &Some(cache_path.to_path_buf()),
975            &Some(remote_url.clone()),
976            "rgstore.json",
977            false,
978            true,
979        ) {
980            Ok(bytes) => {
981                String::from_utf8(bytes).context("Store metadata contains invalid UTF-8")?
982            }
983            Err(error) => match (&old_metadata, cached_json) {
984                (Some(_), Some(json)) => {
985                    eprintln!(
986                        "Could not refresh {} ({}); using cached store metadata",
987                        remote_url, error
988                    );
989                    json
990                }
991                _ => return Err(error),
992            },
993        };
994
995        let metadata: StoreMetadata =
996            serde_json::from_str(&json).context("Failed to parse store metadata")?;
997
998        validate_remote_manifest_paths(&metadata)?;
999
1000        let collections_changed = old_metadata
1001            .as_ref()
1002            .map(|old| old.collections_digest != metadata.collections_digest)
1003            .unwrap_or(true);
1004        let sequences_changed = old_metadata
1005            .as_ref()
1006            .map(|old| old.sequences_digest != metadata.sequences_digest)
1007            .unwrap_or(true);
1008        let aliases_changed = old_metadata
1009            .as_ref()
1010            .map(|old| old.aliases_digest != metadata.aliases_digest)
1011            .unwrap_or(true);
1012        let fhr_changed = old_metadata
1013            .as_ref()
1014            .map(|old| old.fhr_digest != metadata.fhr_digest)
1015            .unwrap_or(true);
1016
1017        if collections_changed {
1018            let old_index = old_metadata
1019                .as_ref()
1020                .and_then(|old| old.collection_index.as_deref())
1021                .unwrap_or("collections.rgci");
1022            let new_index = metadata.collection_index.as_deref().unwrap_or("collections.rgci");
1023            remove_cached_indexes(cache_path, [old_index, new_index])?;
1024            remove_cached_artifact(&cache_path.join("collections"))?;
1025        }
1026        if sequences_changed {
1027            let old_index = old_metadata
1028                .as_ref()
1029                .map(|old| old.sequence_index.as_str())
1030                .unwrap_or("sequences.rgsi");
1031            remove_cached_indexes(cache_path, [old_index, metadata.sequence_index.as_str()])?;
1032        }
1033        if aliases_changed {
1034            remove_cached_artifact(&cache_path.join("aliases"))?;
1035        }
1036        if fhr_changed {
1037            remove_cached_artifact(&cache_path.join("fhr"))?;
1038        }
1039
1040        atomic_write_bytes(&manifest_path, json.as_bytes())
1041            .context("Failed to publish refreshed remote rgstore.json")?;
1042
1043        let mut store = ReadonlyRefgetStore::new(metadata.mode);
1044        store.local_path = Some(cache_path.to_path_buf());
1045        store.remote_source = Some(remote_url.clone());
1046        store.seqdata_path_template = Some(metadata.seqdata_path_template.clone());
1047        store.persist_to_disk = true;
1048        // Cache-asymmetry rule: the remote's layout is recorded separately; the
1049        // local cache stays STANDALONE (sealed packs cannot be appended to).
1050        store.remote_layout = metadata.layout;
1051        store.layout = Layout::Standalone;
1052        store.ancillary_digests = metadata.ancillary_digests;
1053        store.attribute_index = metadata.attribute_index;
1054
1055        // Defer sequence index loading — it can be 66+ MB and is only needed
1056        // when accessing individual sequences, not for browsing collections.
1057        store.sequence_index_loaded = false;
1058        store.sequence_index_path = Some(metadata.sequence_index.clone());
1059
1060        if let Some(ref collection_index) = metadata.collection_index {
1061            if let Ok(collection_index_data) = Self::fetch_file(
1062                &Some(cache_path.to_path_buf()),
1063                &Some(remote_url.clone()),
1064                collection_index,
1065                true,
1066                false,
1067            ) {
1068                let collection_index_str = String::from_utf8(collection_index_data)
1069                    .context("collection index contains invalid UTF-8")?;
1070
1071                Self::load_collection_stubs_from_reader(
1072                    &mut store,
1073                    collection_index_str.as_bytes(),
1074                )?;
1075            }
1076        }
1077
1078        if store.catalog.n_collections() == 0 {
1079            let local_collections_dir = cache_path.join("collections");
1080            create_dir_all(&local_collections_dir)?;
1081            Self::load_collections_from_directory(&mut store, &local_collections_dir)?;
1082        }
1083
1084        for namespace in &metadata.sequence_alias_namespaces {
1085            let relative_path = format!("aliases/sequences/{}.tsv", namespace);
1086            Self::fetch_file(
1087                &store.local_path,
1088                &store.remote_source,
1089                &relative_path,
1090                true,
1091                false,
1092            )
1093            .with_context(|| {
1094                format!(
1095                    "Remote {} advertised sequence alias namespace '{}' but it could not be loaded",
1096                    remote_url, namespace
1097                )
1098            })?;
1099        }
1100        for namespace in &metadata.collection_alias_namespaces {
1101            let relative_path = format!("aliases/collections/{}.tsv", namespace);
1102            Self::fetch_file(
1103                &store.local_path,
1104                &store.remote_source,
1105                &relative_path,
1106                true,
1107                false,
1108            )
1109            .with_context(|| {
1110                format!(
1111                    "Remote {} advertised collection alias namespace '{}' but it could not be loaded",
1112                    remote_url, namespace
1113                )
1114            })?;
1115        }
1116        store.aliases.load_namespaces_from_dir(
1117            &cache_path.join("aliases"),
1118            &metadata.sequence_alias_namespaces,
1119            &metadata.collection_alias_namespaces,
1120        )?;
1121        store.available_sequence_alias_namespaces = metadata.sequence_alias_namespaces;
1122        store.available_collection_alias_namespaces = metadata.collection_alias_namespaces;
1123
1124        Ok(store)
1125    }
1126
1127    // =========================================================================
1128    // Loading helpers
1129    // =========================================================================
1130
1131    /// Parse RGSI lines from a reader straight into catalog sequence rows.
1132    pub(crate) fn load_sequences_from_reader<R: BufRead>(store: &mut ReadonlyRefgetStore, mut reader: R) -> Result<()> {
1133        let mut line = String::new();
1134        loop {
1135            line.clear();
1136            if reader.read_line(&mut line)? == 0 {
1137                break;
1138            }
1139            if line.starts_with('#') {
1140                continue;
1141            }
1142            if let Some(f) = parse_rgsi_fields(&line) {
1143                // A deferred index load may run after a sequence was already
1144                // added (and loaded); dedup keeps that row and its bytes.
1145                store.catalog.add_sequence_parts(f)?;
1146            }
1147        }
1148        Ok(())
1149    }
1150
1151    /// Load sequence metadata from a sequence index file (sequences.rgsi).
1152    pub(crate) fn load_sequences_from_index(store: &mut ReadonlyRefgetStore, index_path: &Path) -> Result<()> {
1153        let file = std::fs::File::open(index_path)?;
1154        let reader = std::io::BufReader::with_capacity(1 << 20, file);
1155        Self::load_sequences_from_reader(store, reader)
1156    }
1157
1158    /// Parse RGCI lines from a reader and register the collections (members
1159    /// not loaded).
1160    pub(crate) fn load_collection_stubs_from_reader<R: BufRead>(
1161        store: &mut ReadonlyRefgetStore,
1162        reader: R,
1163    ) -> Result<()> {
1164        for line in reader.lines() {
1165            let line = line?;
1166
1167            if let Some(metadata) = parse_rgci_line(&line) {
1168                store.catalog.upsert_collection(metadata)?;
1169            }
1170        }
1171
1172        Ok(())
1173    }
1174
1175    /// Load collection stubs from collections.rgci index file (new format).
1176    pub(crate) fn load_collection_stubs_from_rgci(store: &mut ReadonlyRefgetStore, index_path: &Path) -> Result<()> {
1177        let file = std::fs::File::open(index_path)?;
1178        let reader = std::io::BufReader::new(file);
1179        Self::load_collection_stubs_from_reader(store, reader)
1180    }
1181
1182    /// Load full collections from a collections directory (fallback when no RGCI exists).
1183    pub(crate) fn load_collections_from_directory(
1184        store: &mut ReadonlyRefgetStore,
1185        collections_dir: &Path,
1186    ) -> Result<()> {
1187        if !collections_dir.exists() {
1188            return Ok(());
1189        }
1190
1191        for entry in fs::read_dir(collections_dir)? {
1192            let entry = entry?;
1193            let path = entry.path();
1194
1195            if path.is_file() && path.extension() == Some(OsStr::new("rgsi")) {
1196                store.load_collection_rgsi(&path, None)?;
1197            }
1198        }
1199
1200        Ok(())
1201    }
1202
1203    /// Read one `collections/<digest>.rgsi` straight into the catalog: the
1204    /// header becomes the collection row, each data line a member (and a
1205    /// sequence row, if new). No per-line `SequenceMetadata` is built.
1206    ///
1207    /// With `expected`, the file's digest must match it. Files without the
1208    /// level-1 header (older writers) go through [`read_rgsi_file`], which
1209    /// computes the digests from the rows.
1210    pub(crate) fn load_collection_rgsi(&mut self, path: &Path, expected: Option<&str>) -> Result<CollRow> {
1211        let file = std::fs::File::open(path)
1212            .with_context(|| format!("opening {}", path.display()))?;
1213        let mut reader = std::io::BufReader::with_capacity(1 << 20, file);
1214        let mut line = String::new();
1215
1216        let mut header = RgsiHeader::default();
1217        let mut pending_data = false;
1218        loop {
1219            line.clear();
1220            if reader.read_line(&mut line)? == 0 {
1221                break;
1222            }
1223            let l = line.trim_end_matches(['\n', '\r']);
1224            if header.read_line(l) || l.starts_with('#') {
1225                continue;
1226            }
1227            pending_data = true;
1228            break;
1229        }
1230
1231        // `n_sequences` is set once the rows are counted.
1232        let Some(meta) = header.into_metadata(0, path) else {
1233            let collection = read_rgsi_file(path)?;
1234            if let Some(e) = expected {
1235                if collection.metadata.digest != e {
1236                    return Err(anyhow!(
1237                        "Collection digest mismatch: expected {}, got {}",
1238                        e,
1239                        collection.metadata.digest
1240                    ));
1241                }
1242            }
1243            let crate::digest::SequenceCollection { metadata, sequences } = collection;
1244            let members: Vec<SequenceMetadata> =
1245                sequences.iter().map(|s| s.metadata().clone()).collect();
1246            return Ok(self.insert_collection(metadata, &members)?.0);
1247        };
1248        if let Some(e) = expected {
1249            if meta.digest != e {
1250                return Err(anyhow!("Collection digest mismatch: expected {}, got {}", e, meta.digest));
1251            }
1252        }
1253        let c = self.catalog.upsert_collection(meta)?;
1254        self.catalog.start_members(c);
1255
1256        let mut n = 0usize;
1257        let result = (|| -> Result<()> {
1258            loop {
1259                if !pending_data {
1260                    line.clear();
1261                    if reader.read_line(&mut line)? == 0 {
1262                        break;
1263                    }
1264                }
1265                pending_data = false;
1266                if line.starts_with('#') {
1267                    continue;
1268                }
1269                let Some(f) = parse_rgsi_fields(&line) else { continue };
1270                let (name, description) = (f.name, f.description);
1271                let (seq, _) = self.catalog.add_sequence_parts(f)?;
1272                self.catalog.push_member(c, NewMember { seq, name, description, fai: None })?;
1273                n += 1;
1274            }
1275            Ok(())
1276        })();
1277        if let Err(e) = result {
1278            self.catalog.unload_members(c);
1279            return Err(e.context(format!("reading {}", path.display())));
1280        }
1281        self.catalog.set_coll_n_sequences(c, n);
1282        Ok(c)
1283    }
1284}
1285
1286// ============================================================================
1287// Row readers / writers (free functions)
1288//
1289// These read and write index ROWS without touching store state, which is what
1290// makes a delta commit possible: `load_sequences_from_index` and
1291// `load_collection_stubs_from_rgci` mutate a store, so they cannot be used to
1292// look at what is currently on disk during a commit.
1293// ============================================================================
1294
1295/// Read `sequences.rgsi` into digest-keyed rows. A missing file is an empty map
1296/// (a brand-new store), not an error.
1297pub(crate) fn read_sequences_rgsi_rows(path: &Path) -> Result<HashMap<DigestKey, SequenceMetadata>> {
1298    let mut rows = HashMap::new();
1299    let file = match File::open(path) {
1300        Ok(f) => f,
1301        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(rows),
1302        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
1303    };
1304    for line in std::io::BufReader::new(file).lines() {
1305        let line = line?;
1306        if line.starts_with('#') {
1307            continue;
1308        }
1309        if let Some(meta) = parse_rgsi_line(&line) {
1310            rows.insert(meta.sha512t24u.to_key(), meta);
1311        }
1312    }
1313    Ok(rows)
1314}
1315
1316/// Read `collections.rgci` into digest-keyed rows. A missing file is an empty map.
1317pub(crate) fn read_collections_rgci_rows(
1318    path: &Path,
1319) -> Result<HashMap<DigestKey, SequenceCollectionMetadata>> {
1320    let mut rows = HashMap::new();
1321    let file = match File::open(path) {
1322        Ok(f) => f,
1323        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(rows),
1324        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
1325    };
1326    for line in std::io::BufReader::new(file).lines() {
1327        let line = line?;
1328        if let Some(meta) = parse_rgci_line(&line) {
1329            rows.insert(meta.digest.to_key(), meta);
1330        }
1331    }
1332    Ok(rows)
1333}
1334
1335/// Atomically publish `sequences.rgsi` from a row set.
1336///
1337/// Sorted by `sha512t24u` so output is deterministic regardless of build order
1338/// (the row set is a `HashMap`).
1339pub(crate) fn write_sequences_rgsi_rows(
1340    path: &Path,
1341    rows: &HashMap<DigestKey, SequenceMetadata>,
1342) -> Result<()> {
1343    let mut entries: Vec<&SequenceMetadata> = rows.values().collect();
1344    entries.sort_by(|a, b| a.sha512t24u.cmp(&b.sha512t24u));
1345
1346    atomic_write(path, |w| {
1347        writeln!(w, "{}", RGSI_HEADER)?;
1348        for meta in entries {
1349            writeln!(
1350                w,
1351                "{}\t{}\t{}\t{}\t{}\t{}",
1352                meta.name,
1353                meta.length,
1354                meta.alphabet,
1355                meta.sha512t24u,
1356                meta.md5,
1357                meta.description.as_deref().unwrap_or("")
1358            )?;
1359        }
1360        Ok(())
1361    })
1362}
1363
1364/// Atomically publish `collections.rgci` from a row set.
1365///
1366/// Sorted by collection digest for deterministic output.
1367pub(crate) fn write_collections_rgci_rows(
1368    path: &Path,
1369    rows: &HashMap<DigestKey, SequenceCollectionMetadata>,
1370) -> Result<()> {
1371    let mut entries: Vec<&SequenceCollectionMetadata> = rows.values().collect();
1372    entries.sort_by(|a, b| a.digest.cmp(&b.digest));
1373
1374    atomic_write(path, |w| {
1375        writeln!(w, "{}", RGCI_HEADER)?;
1376        for meta in entries {
1377            writeln!(
1378                w,
1379                "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
1380                meta.digest,
1381                meta.n_sequences,
1382                meta.names_digest,
1383                meta.sequences_digest,
1384                meta.lengths_digest,
1385                meta.name_length_pairs_digest.as_deref().unwrap_or(""),
1386                meta.sorted_name_length_pairs_digest.as_deref().unwrap_or(""),
1387                meta.sorted_sequences_digest.as_deref().unwrap_or(""),
1388            )?;
1389        }
1390        Ok(())
1391    })
1392}
1393
1394// ============================================================================
1395// Manifest and alias file helpers
1396// ============================================================================
1397
1398/// Read `<dir>/rgstore.json`, or `None` if it does not exist yet.
1399pub(crate) fn read_manifest(dir: &Path) -> Result<Option<StoreMetadata>> {
1400    let path = dir.join("rgstore.json");
1401    match fs::read_to_string(&path) {
1402        Ok(json) => Ok(Some(serde_json::from_str(&json).with_context(|| {
1403            format!("Failed to parse {}", path.display())
1404        })?)),
1405        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1406        Err(e) => Err(e).with_context(|| format!("Failed to read {}", path.display())),
1407    }
1408}
1409
1410/// Atomically publish `<dir>/rgstore.json`.
1411pub(crate) fn write_manifest(dir: &Path, metadata: &StoreMetadata) -> Result<()> {
1412    let json = serde_json::to_string_pretty(metadata)
1413        .context("Failed to serialize metadata to JSON")?;
1414    super::atomic::atomic_write_bytes(&dir.join("rgstore.json"), json.as_bytes())
1415        .context("Failed to write rgstore.json")
1416}
1417
1418/// Namespace names (file stems) of the `*.tsv` files actually present in `dir`.
1419fn scan_alias_namespaces(dir: &Path) -> Vec<String> {
1420    let Ok(entries) = fs::read_dir(dir) else {
1421        return Vec::new();
1422    };
1423    entries
1424        .filter_map(|e| e.ok())
1425        .map(|e| e.path())
1426        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("tsv"))
1427        .filter_map(|p| p.file_stem().and_then(|s| s.to_str()).map(String::from))
1428        .collect()
1429}
1430
1431/// What the store's alias directory actually advertises, as
1432/// `(sequence_namespaces, collection_namespaces)`.
1433///
1434/// This is the source of truth for the manifest's namespace lists at commit
1435/// time. `open_local` deliberately trusts the MANIFEST rather than the directory
1436/// (so a stale manifest fails identically on disk and over HTTP, surfacing bugs
1437/// instead of masking them) — correct for reading, wrong for writing, where
1438/// trusting a stale snapshot is precisely how namespaces get dropped.
1439pub(crate) fn published_alias_namespaces(local_path: &Path) -> (Vec<String>, Vec<String>) {
1440    let aliases_dir = local_path.join("aliases");
1441    let mut seq = scan_alias_namespaces(&aliases_dir.join(AliasKind::Sequence.subdir()));
1442    let mut coll = scan_alias_namespaces(&aliases_dir.join(AliasKind::Collection.subdir()));
1443    seq.sort();
1444    coll.sort();
1445    (seq, coll)
1446}
1447
1448/// Read one alias namespace TSV. A missing file is an empty map.
1449pub(crate) fn read_alias_tsv(path: &Path) -> Result<HashMap<String, DigestKey>> {
1450    let mut map = HashMap::new();
1451    let file = match File::open(path) {
1452        Ok(f) => f,
1453        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(map),
1454        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
1455    };
1456    for line in std::io::BufReader::new(file).lines() {
1457        let line = line?;
1458        if line.starts_with('#') || line.trim().is_empty() {
1459            continue;
1460        }
1461        if let Some((alias, digest)) = line.split_once('\t') {
1462            map.insert(alias.to_string(), digest.to_key());
1463        }
1464    }
1465    Ok(map)
1466}
1467
1468/// Atomically publish one alias namespace TSV, or delete it if the merged
1469/// namespace is empty.
1470///
1471/// Sorted by alias so the file is deterministic (the map is a `HashMap`), which
1472/// keeps `aliases_digest` stable across writers that committed the same content.
1473pub(crate) fn write_alias_namespace(path: &Path, aliases: &HashMap<String, DigestKey>) -> Result<()> {
1474    if aliases.is_empty() {
1475        match fs::remove_file(path) {
1476            Ok(()) => Ok(()),
1477            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1478            Err(e) => Err(e).with_context(|| format!("removing empty {}", path.display())),
1479        }
1480    } else {
1481        let sorted: BTreeMap<&String, &DigestKey> = aliases.iter().collect();
1482        atomic_write(path, |w| {
1483            for (alias, digest) in sorted {
1484                writeln!(w, "{}\t{}", alias, key_to_digest_string(digest))?;
1485            }
1486            Ok(())
1487        })
1488    }
1489}