Skip to main content

gtars_refget/store/
readonly.rs

1//! ReadonlyRefgetStore struct definition and core methods.
2
3use super::*;
4use super::alias::AliasManager;
5use super::lock::{LockOptions, StoreLock};
6
7use std::collections::{HashMap, HashSet};
8use std::fmt::{Display, Formatter};
9use std::path::{Path, PathBuf};
10
11use super::catalog::{Catalog, CollRow, MemberView, NewMember, SeqCore, SeqRow, SeqView};
12
13use anyhow::{anyhow, Context, Result};
14
15use crate::collection::SequenceRecordExt;
16use crate::digest::lookup_alphabet;
17use crate::digest::{SequenceCollectionMetadata, SequenceMetadata, SequenceRecord};
18use crate::digest::{decode_string_from_bytes, decode_substring_from_bytes, encode_sequence, StreamingDecoder};
19use crate::digest::{byte_range_for_bases, decode_substring_from_bytes_at_offset};
20use crate::hashkeyable::{DigestKey, HashKeyable, key_to_digest_string};
21use crate::seqcol::metadata_matches_attribute;
22
23use std::fs::{self, create_dir_all, File};
24use std::io::{BufReader, Read, Seek, SeekFrom};
25use std::sync::{Arc, Mutex, RwLock};
26
27/// Fallback capacity for the per-store open-file-descriptor cache, used when
28/// the process's soft `RLIMIT_NOFILE` cannot be read at all (non-unix
29/// targets, or the `getrlimit` syscall failing).
30const SEQ_FD_CACHE_CAP_FLOOR: usize = 256;
31
32/// Ceiling for the adaptive fd-cache capacity. Even under a very high or
33/// unlimited `RLIMIT_NOFILE`, the cache stays bounded so its O(n) LRU eviction
34/// scan (see `FdCache::insert`) stays cheap and a single store instance does
35/// not gratuitously hold an unbounded number of fds open (a process may have
36/// several stores open at once, plus its own stdio/sockets/other files).
37const SEQ_FD_CACHE_CAP_CEILING: usize = 8192;
38
39/// Headroom subtracted from the soft `RLIMIT_NOFILE` when sizing the fd
40/// cache, reserved for the rest of the process (stdio, sockets, other open
41/// files, other store instances).
42const SEQ_FD_CACHE_HEADROOM: usize = 64;
43
44/// Capacity of the per-store open-file-descriptor cache used by the
45/// partial-read path, adapted to the process's soft `RLIMIT_NOFILE`.
46///
47/// A fixed cap of 256 (seqrepo's `fd_cache_size`) is too small: a
48/// genome-scale refget store has tens of thousands of segment `.seq` files
49/// (e.g. ~52k for a human genome at typical segment sizes; a transcriptome
50/// store can have ~122k sequences). A scattered/genome-wide batch of queries
51/// touches far more than 256 distinct files, so a fixed cap thrashes:
52/// nearly every region evicts and reopens its file, costing an extra
53/// `openat`+`close` pair per region. Sizing the cache from the process's own
54/// fd limit lets it hold far more open handles when the ulimit allows it,
55/// while still leaving headroom and an upper bound so it can't exhaust fds or
56/// let LRU eviction get expensive.
57fn default_fd_cache_cap() -> usize {
58    #[cfg(unix)]
59    {
60        let mut rlim = libc::rlimit {
61            rlim_cur: 0,
62            rlim_max: 0,
63        };
64        if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) } == 0 {
65            let soft = rlim.rlim_cur;
66            if soft == libc::RLIM_INFINITY {
67                // No real ceiling to respect; use our own bound.
68                return SEQ_FD_CACHE_CAP_CEILING;
69            }
70            let usable = (soft as usize).saturating_sub(SEQ_FD_CACHE_HEADROOM).max(1);
71            // Never size the cache above what the rlimit (minus headroom)
72            // actually allows, even when that is below the floor -- an
73            // unusually small ulimit must be respected, not overridden by a
74            // "typical minimum". Above the floor, cap at the ceiling.
75            return usable.min(SEQ_FD_CACHE_CAP_CEILING);
76        }
77    }
78    SEQ_FD_CACHE_CAP_FLOOR
79}
80
81/// True when `err` (as returned by [`ReadonlyRefgetStore::get_substring_from_disk`]
82/// / [`ReadonlyRefgetStore::get_cached_seq_file`]) is ultimately caused by the
83/// `.seq` file not existing, as opposed to some other failure (permission
84/// denied, a bad range, a genuine I/O error). Used to fall through to the
85/// remote fallback exactly on a missing file, replacing an upfront
86/// `path.exists()` stat with inspecting the result of an attempted open --
87/// the common case (file present) then costs no extra syscall at all, since
88/// the fd cache would have to open it anyway.
89fn is_missing_seq_file(err: &anyhow::Error) -> bool {
90    err.chain()
91        .any(|cause| matches!(cause.downcast_ref::<std::io::Error>(), Some(io_err) if io_err.kind() == std::io::ErrorKind::NotFound))
92}
93
94/// Error unless `[start, end)` is a non-empty range inside a sequence of
95/// `length` bases.
96fn check_range(start: usize, end: usize, length: usize) -> Result<()> {
97    if start >= length || end > length || start >= end {
98        return Err(anyhow!(
99            "Invalid substring range: start={}, end={}, sequence length={}",
100            start,
101            end,
102            length
103        ));
104    }
105    Ok(())
106}
107
108/// Batch size at which `get_substrings` against a *remote-only* sequence stops
109/// issuing one HTTP byte-range request per range and instead downloads the whole
110/// stored record once (cached locally as a `.seq`, like `load_sequence`), then
111/// serves every range from the local file. Each remote range is a separate
112/// round-trip, so for bulk extraction (e.g. BED region sets) the per-request
113/// latency dominates and a single cached download wins; below the threshold,
114/// fetching only the touched bytes is cheaper than pulling a whole chromosome.
115/// Heuristic, count-based: small/ad-hoc reads stay lean, bulk reads promote.
116const REMOTE_BULK_FETCH_THRESHOLD: usize = 16;
117
118/// Convert decoded sequence bytes into a `String` without re-validating UTF-8.
119///
120/// # Why this exists
121/// gtars sequence bytes are *always* ASCII: the Encoded decoder emits only
122/// bytes drawn from `alphabet.decoding_array` (A/C/G/T/N/IUPAC/protein), and Raw
123/// mode stores one ASCII base per byte per the refget data model. So
124/// `String::from_utf8`'s validation scan can never fail on this data — it is
125/// pure overhead.
126///
127/// # Why it justifies a (single, audited) `unsafe`
128/// Benchmarked (AMD Ryzen 7 3800X, release build): on the whole-sequence Encoded
129/// decode path the `from_utf8` validation scan costs a steady ~6–10% of total
130/// decode-and-convert time — roughly 10–20 ms per 250 Mbp chromosome. That is a
131/// real, repeatable cost on the whole-genome read hot path, so we skip it here.
132///
133/// This is the crate's only `from_utf8_unchecked`. Remote data is validated in
134/// `get_substring_from_remote` before it reaches this conversion.
135///
136/// The `debug_assert` re-validates the ASCII invariant in debug and test builds,
137/// so any future break (a non-ASCII alphabet, an offset bug) fails loudly under
138/// test while release builds stay fast.
139#[inline]
140fn decoded_sequence_to_string(bytes: Vec<u8>) -> String {
141    debug_assert!(
142        bytes.is_ascii(),
143        "decoded sequence bytes must be ASCII (decoder invariant violated)"
144    );
145    // SAFETY: gtars sequence bytes are guaranteed ASCII (see doc above), hence
146    // valid UTF-8, so skipping validation is sound.
147    unsafe { String::from_utf8_unchecked(bytes) }
148}
149
150/// A tiny bounded LRU cache mapping a sequence digest to an open, shared
151/// `.seq` file handle. `.seq` content for a digest is immutable, so a cached
152/// handle never goes stale and needs no invalidation. When the cache is full,
153/// inserting a new handle evicts (closes) the least-recently-used one.
154///
155/// Recency is tracked with a monotonically increasing counter stamped on each
156/// access; eviction scans for the minimum stamp. With a small cap (default 256)
157/// this O(n) eviction is negligible compared to the avoided `open`/`seek`
158/// syscalls on the hot path.
159#[derive(Debug)]
160struct FdCache {
161    cap: usize,
162    tick: u64,
163    /// relative-or-absolute file path -> (shared file handle, last-use stamp).
164    /// Keyed by PATH (not digest) so pack files and `.seq` files share one
165    /// bounded LRU of open handles.
166    entries: HashMap<PathBuf, (Arc<File>, u64)>,
167}
168
169impl FdCache {
170    fn new(cap: usize) -> Self {
171        FdCache {
172            cap: cap.max(1),
173            tick: 0,
174            entries: HashMap::with_capacity(cap.max(1)),
175        }
176    }
177
178    /// Return a cloned handle on hit, bumping recency. `None` on miss.
179    fn get(&mut self, key: &Path) -> Option<Arc<File>> {
180        self.tick += 1;
181        let tick = self.tick;
182        if let Some(slot) = self.entries.get_mut(key) {
183            slot.1 = tick;
184            Some(Arc::clone(&slot.0))
185        } else {
186            None
187        }
188    }
189
190    /// Insert a freshly opened handle, evicting (closing) the LRU entry if full.
191    fn insert(&mut self, key: PathBuf, file: Arc<File>) {
192        self.tick += 1;
193        let tick = self.tick;
194        if !self.entries.contains_key(&key) && self.entries.len() >= self.cap {
195            // Evict the least-recently-used entry. Dropping the Arc closes the
196            // fd once no in-flight read still holds a clone.
197            if let Some(lru_key) = self
198                .entries
199                .iter()
200                .min_by_key(|(_, (_, stamp))| *stamp)
201                .map(|(k, _)| k.clone())
202            {
203                self.entries.remove(&lru_key);
204            }
205        }
206        self.entries.insert(key, (file, tick));
207    }
208}
209
210
211/// A `Read` adapter that yields a byte range from a shared `Arc<Vec<u8>>`
212/// buffer without cloning the backing data.
213///
214/// Used by `stream_sequence` when the target sequence is already resident
215/// in memory as `SequenceRecord::Full`. The alternative of slicing+cloning
216/// would allocate a second copy of the (possibly chromosome-sized) buffer
217/// and defeat the O(1) memory guarantee of streaming.
218pub(crate) struct ArcSliceReader {
219    buf: Arc<Vec<u8>>,
220    pos: usize,
221    end: usize,
222}
223
224impl ArcSliceReader {
225    pub(crate) fn new(buf: Arc<Vec<u8>>, start: usize, end: usize) -> Self {
226        debug_assert!(start <= end);
227        debug_assert!(end <= buf.len());
228        Self { buf, pos: start, end }
229    }
230}
231
232impl Read for ArcSliceReader {
233    fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
234        let remaining = self.end - self.pos;
235        if remaining == 0 {
236            return Ok(0);
237        }
238        let n = remaining.min(out.len());
239        out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
240        self.pos += n;
241        Ok(n)
242    }
243}
244
245/// Open a bounded HTTP byte range against a remote refget store and return
246/// a `Read` yielding exactly `byte_end - byte_start` bytes.
247#[cfg(feature = "http")]
248fn open_remote_range(
249    remote: &str,
250    relpath: &Path,
251    byte_start: u64,
252    byte_end: u64,
253) -> Result<Box<dyn Read + Send>> {
254    let relpath_str = relpath
255        .to_str()
256        .ok_or_else(|| anyhow!("Non-UTF8 sequence path"))?;
257    let url = if remote.ends_with('/') {
258        format!("{}{}", remote, relpath_str)
259    } else {
260        format!("{}/{}", remote, relpath_str)
261    };
262
263    let byte_len = byte_end - byte_start;
264    let last_byte = byte_end.saturating_sub(1);
265    let agent: ureq::Agent = ureq::Agent::config_builder()
266        .timeout_connect(Some(std::time::Duration::from_secs(30)))
267        .timeout_recv_response(Some(std::time::Duration::from_secs(60)))
268        .build()
269        .into();
270    let response = agent
271        .get(&url)
272        .header("Range", &format!("bytes={}-{}", byte_start, last_byte))
273        .call()
274        .map_err(|e| anyhow!("Failed to open remote byte range: {}", e))?;
275
276    // Guard against servers that ignore the Range header and return the full
277    // body with HTTP 200 instead of a 206 Partial Content slice. Wrapping the
278    // full body here would silently produce wrong bases, so refuse outright.
279    let status = response.status();
280    if status.as_u16() != 206 {
281        return Err(anyhow!(
282            "Remote server did not honor Range header (got HTTP {}); \
283             refusing to stream to avoid silent data corruption. URL: {}",
284            status,
285            url
286        ));
287    }
288
289    Ok(Box::new(BufReader::with_capacity(
290        64 * 1024,
291        response.into_body().into_reader().take(byte_len),
292    )))
293}
294
295#[cfg(not(feature = "http"))]
296fn open_remote_range(
297    _remote: &str,
298    _relpath: &Path,
299    _byte_start: u64,
300    _byte_end: u64,
301) -> Result<Box<dyn Read + Send>> {
302    Err(anyhow!(
303        "Remote streaming requires the 'http' feature to be enabled"
304    ))
305}
306
307/// Core refget store with `&self` read methods, suitable for `Arc` sharing in servers.
308///
309/// Mutating methods are used during the setup/loading phase; once wrapped in `Arc`,
310/// only `&self` reads are accessible, making concurrent access thread-safe.
311///
312/// All sequence and collection metadata lives in one columnar [`Catalog`]:
313/// sequences deduplicated store-wide, each collection's members (with their
314/// per-collection names) as a contiguous range, and digest/name lookups as
315/// tables of row numbers. Sequence bytes are never part of the catalog; they
316/// live in [`Self::loaded`] (owned bytes of in-memory stores) or the
317/// evictable `resident` overlay, both keyed by sequence row.
318#[derive(Debug)]
319pub struct ReadonlyRefgetStore {
320    /// Every sequence, membership and collection fact, each stored once.
321    pub(crate) catalog: Catalog,
322    /// Bytes owned by the store: sequences of an in-memory store, or ones
323    /// loaded with `load_sequence`. Keyed by catalog sequence row.
324    pub(crate) loaded: HashMap<SeqRow, Arc<Vec<u8>>>,
325    /// Storage strategy for sequences
326    pub(crate) mode: StorageMode,
327    /// Where the store lives on disk (local store or cache directory)
328    pub(crate) local_path: Option<PathBuf>,
329    /// Where to pull sequences from (if remote-backed)
330    pub(crate) remote_source: Option<String>,
331    /// Template for sequence file paths (e.g., "sequences/%s2/%s.seq")
332    pub(crate) seqdata_path_template: Option<String>,
333    /// Whether to persist sequences to disk (write-through caching)
334    pub(crate) persist_to_disk: bool,
335    /// Whether to suppress progress output
336    pub(crate) quiet: bool,
337    /// Whether to compute ancillary digests (nlp, snlp, sorted_sequences).
338    /// Default: true for new stores.
339    pub(crate) ancillary_digests: bool,
340    /// Whether on-disk attribute reverse index is enabled.
341    /// Default: false.
342    pub(crate) attribute_index: bool,
343    /// Human-readable aliases for sequences and collections.
344    pub(crate) aliases: AliasManager,
345    /// FHR metadata for collections, keyed by collection digest.
346    pub(crate) fhr_metadata: HashMap<DigestKey, super::fhr_metadata::FhrMetadata>,
347    /// Available sequence alias namespaces (from manifest, for remote discovery).
348    pub(crate) available_sequence_alias_namespaces: Vec<String>,
349    /// Available collection alias namespaces (from manifest, for remote discovery).
350    pub(crate) available_collection_alias_namespaces: Vec<String>,
351    /// Bounded LRU cache of open `.seq` file handles for the partial-read path,
352    /// behind a `Mutex` because `get_substring` takes `&self`. Avoids re-opening
353    /// the same chromosome file on every per-region `get_substring` call.
354    seq_fd_cache: Mutex<FdCache>,
355    /// `&self` resident overlay: whole, on-disk-packed `.seq` byte arrays keyed by
356    /// SHA512t24u digest. Populated via [`Self::load_resident`] to promote a
357    /// sequence that is not loaded to RAM without taking `&mut self` (the store is
358    /// `Arc`-shared behind a readonly handle). Consulted in `get_substring` /
359    /// `get_substrings` *before* the on-disk partial-read path: on a hit the
360    /// covering span is decoded from these bytes exactly like loaded bytes, so
361    /// output is byte-identical to the disk path but every region query becomes an
362    /// in-memory decode instead of a positioned read. The bytes are the raw file
363    /// contents (2-bit packed in `Encoded` mode, one byte/base in `Raw`), so a hit
364    /// is mode-agnostic and only the sliced span is ever decoded. `RwLock` so many
365    /// readers proceed concurrently; the `Arc` is cloned out under a brief read
366    /// lock and decoded after the lock is dropped, so decodes never serialize.
367    resident: RwLock<HashMap<SeqRow, Arc<Vec<u8>>>>,
368    /// Whether the sequence index (sequences.rgsi) has been loaded.
369    /// For remote stores, this starts as `false` and is lazily loaded on first
370    /// sequence access, avoiding the costly download when only browsing collections.
371    pub(crate) sequence_index_loaded: bool,
372    /// The relative path to the sequence index file (from rgstore.json),
373    /// stored for deferred loading in remote stores.
374    pub(crate) sequence_index_path: Option<String>,
375    /// What this handle has actually changed since its last successful commit.
376    /// See [`PendingChanges`]. Behind a `Mutex` because the commit path is
377    /// `&self`.
378    pub(crate) pending: Mutex<PendingChanges>,
379    /// A store-directory write lock held across several mutations, set by
380    /// [`Self::lock_for_batch`]. When present, individual commits skip acquiring
381    /// their own lock — otherwise a batch guard would deadlock against the
382    /// `write_index_files` each mutation triggers.
383    pub(crate) commit_lock: Option<Arc<StoreLock>>,
384    /// Timeout/staleness settings used when acquiring the store write lock.
385    pub(crate) lock_options: LockOptions,
386    /// Re-point an existing alias (in memory, or already published on disk) to
387    /// a different target, instead of erroring on the conflict. Off by default:
388    /// binding one human-readable name to different content is a semantic
389    /// conflict, not a merge detail. Never overrides a clash within one load
390    /// (one TSV, or one FASTA's header tags).
391    pub(crate) force_alias: bool,
392
393    // --- Packed layout -------------------------------------------------------
394    /// Physical layout of THIS store's sequence bytes. Invariant:
395    /// `layout == Packed` implies `remote_source == None` (the local cache of a
396    /// remote-backed store is always standalone).
397    pub(crate) layout: Layout,
398    /// Layout of the REMOTE this store caches from (if any). A remote packed
399    /// store is read through its sidecar while the local cache stays standalone.
400    pub(crate) remote_layout: Layout,
401    /// Per-pack size cap in bytes for new packs (default 256 MiB).
402    pub(crate) pack_cap_bytes: u64,
403    /// Optional block cache in front of local pack reads, shared across all
404    /// packs of this store. Off (`None`) by default; see
405    /// [`Self::set_pack_cache_mb`].
406    pub(crate) pack_cache: Option<super::packcache::PackBlockCache>,
407    /// Pack location of each sequence row on the LOCAL side, built lazily from
408    /// the sidecar on the first packed read. Invalidated (set to `None`)
409    /// whenever a commit changes the sidecar or the catalog is renumbered.
410    pub(crate) pack_cols: Mutex<Option<Arc<super::catalog::PackColumns>>>,
411    /// The REMOTE side's `sequences.pack.idx` bytes, fetched whole on the
412    /// first remote packed read and searched by digest. Not row-keyed like
413    /// `pack_cols`, because a remote store's catalog grows after open as
414    /// collections and the sequence index load.
415    pub(crate) remote_pack_index: Mutex<Option<Arc<Vec<u8>>>>,
416    /// Cache of pack file byte lengths (needed to clamp the final block of a
417    /// local block-cache read), keyed by content-hash pack name.
418    pub(crate) pack_lengths: Mutex<HashMap<Arc<str>, u64>>,
419    /// The open, not-yet-sealed pack for an incremental (`add_sequence_record`)
420    /// build session on a packed store. Sealed at cap and always at commit.
421    pub(crate) open_session_pack: Mutex<Option<SessionPack>>,
422}
423
424/// The open, not-yet-sealed pack file a packed store writes new sequences
425/// into, from FASTA import, `add_sequence_record` and `compact`. Bytes are
426/// appended in call order, the content hash is fed the same bytes in the same
427/// order, and the pack is sealed (fsync + rename to its content-hash name) at
428/// the size cap, at the end of an import, and at commit.
429#[derive(Debug)]
430pub(crate) struct SessionPack {
431    /// Directory `packs/` under the store.
432    pub(crate) packs_dir: PathBuf,
433    /// Names this session's temp packs, so no other writer opens the same file.
434    pub(crate) token: String,
435    /// Ordinal of the current open sub-pack (for temp-file naming).
436    pub(crate) ordinal: usize,
437    /// Temp file path `packs/.rgstore.tmp.pack.session.<token>.<ordinal>`.
438    pub(crate) tmp_path: PathBuf,
439    /// Open handle to the temp pack.
440    pub(crate) file: File,
441    /// Running byte length == next offset.
442    pub(crate) len: u64,
443    /// Running content hash of the bytes appended so far.
444    pub(crate) hasher: sha2::Sha256,
445    /// `(digest, offset, len)` rows for sequences appended to THIS open pack.
446    pub(crate) rows: Vec<(String, u64, u64)>,
447    /// Sidecar rows of the packs this session already sealed.
448    pub(crate) sealed: Vec<(String, super::packidx::PackRow)>,
449    /// Names of packs this session renamed into place and has not handed to
450    /// a commit yet. A pack that already existed under the same name is not
451    /// listed: another writer owns it.
452    pub(crate) created: Vec<String>,
453}
454
455impl SessionPack {
456    /// Create the temp file for sub-pack `ordinal`. `create_new`, so a name
457    /// another writer already holds is an error instead of a shared file.
458    fn create_temp(packs_dir: &Path, token: &str, ordinal: usize) -> Result<(PathBuf, File)> {
459        let tmp_path = packs_dir.join(format!(".rgstore.tmp.pack.session.{}.{}", token, ordinal));
460        let file = std::fs::OpenOptions::new()
461            .create_new(true)
462            .read(true)
463            .write(true)
464            .open(&tmp_path)
465            .with_context(|| format!("creating temp pack {}", tmp_path.display()))?;
466        Ok((tmp_path, file))
467    }
468
469    /// Seal the open pack to its content-hash name and open a fresh empty
470    /// temp for continued writing. No-op on an empty pack.
471    ///
472    /// On error the session is unchanged (same open temp, rows and hash), so
473    /// the seal can be retried. The next temp is created before the rename for
474    /// that reason: after the rename nothing can fail.
475    pub(crate) fn seal(&mut self) -> Result<()> {
476        use sha2::Digest as _;
477        if self.len == 0 {
478            return Ok(());
479        }
480        // Cut off bytes past the tracked length (left by a failed append), so
481        // the sealed file is exactly the bytes that were hashed.
482        self.file
483            .set_len(self.len)
484            .context("truncating session pack to its written length")?;
485        let _ = self.file.sync_all();
486        let digest = self.hasher.clone().finalize();
487        let name: String = digest[..16].iter().map(|b| format!("{:02x}", b)).collect();
488        let final_path = self.packs_dir.join(format!("{}.pack", name));
489        let (next_tmp, next_file) =
490            Self::create_temp(&self.packs_dir, &self.token, self.ordinal + 1)?;
491        if final_path.exists() {
492            let _ = std::fs::remove_file(&self.tmp_path);
493        } else if let Err(e) = std::fs::rename(&self.tmp_path, &final_path) {
494            let _ = std::fs::remove_file(&next_tmp);
495            return Err(e).with_context(|| format!("sealing session pack {}", final_path.display()));
496        } else {
497            self.created.push(name.clone());
498        }
499        if let Ok(dir) = File::open(&self.packs_dir) {
500            let _ = dir.sync_all();
501        }
502        let pack: Arc<str> = Arc::from(name.as_str());
503        for (digest, offset, len) in self.rows.drain(..) {
504            let row = super::packidx::PackRow { pack: Arc::clone(&pack), offset, len };
505            self.sealed.push((digest, row));
506        }
507
508        // Continue in the fresh temp.
509        self.ordinal += 1;
510        self.file = next_file;
511        self.tmp_path = next_tmp;
512        self.len = 0;
513        self.hasher = sha2::Sha256::new();
514        Ok(())
515    }
516}
517
518/// A session pack that is dropped without being sealed (the store handle went
519/// away before a commit) leaves no temp file behind. After a seal, `tmp_path`
520/// names the fresh empty temp, or a path already renamed away. The packs it
521/// sealed but never handed to a commit (`created`) are deleted too, since no
522/// row will ever point at them.
523impl Drop for SessionPack {
524    fn drop(&mut self) {
525        let _ = std::fs::remove_file(&self.tmp_path);
526        remove_uncommitted_packs(&self.packs_dir, &self.created, &HashSet::new());
527    }
528}
529
530/// Delete each pack in `created` (packs a writer renamed into place whose
531/// rows never reached a commit) that neither `staged` nor the on-disk
532/// sidecar references. Deletes nothing if the sidecar cannot be read.
533///
534/// Runs without the store lock. Another writer may have reused one of these
535/// packs by name (same content hash). If it has committed, the sidecar lists
536/// the pack and it is kept. If it has not, its commit finds the pack gone and
537/// refuses to publish (see `commit_pack_idx`), a clear error rather than a
538/// bad read. A commit landing between the sidecar read here and the unlink is
539/// not caught: its rows then name a missing pack and their reads fail.
540pub(crate) fn remove_uncommitted_packs(
541    packs_dir: &Path,
542    created: &[String],
543    staged: &HashSet<String>,
544) {
545    if created.is_empty() {
546        return;
547    }
548    let Some(local_path) = packs_dir.parent() else { return };
549    let Ok(listed) = ReadonlyRefgetStore::sidecar_pack_names(local_path) else { return };
550    for name in created {
551        if !staged.contains(name) && !listed.contains(name) {
552            let _ = std::fs::remove_file(packs_dir.join(format!("{}.pack", name)));
553        }
554    }
555}
556
557/// Which side of a (possibly remote-backed) store a resolution targets. The
558/// local cache of a remote packed store is standalone — sealed packs cannot be
559/// appended to — so the two sides can have different layouts.
560#[derive(Clone, Copy, Debug)]
561pub(crate) enum StoreSide {
562    Local,
563    Remote,
564}
565
566/// Path of a sealed pack file, relative to the store root.
567fn pack_relpath(pack: &str) -> PathBuf {
568    PathBuf::from(format!("packs/{}.pack", pack))
569}
570
571/// Result of [`ReadonlyRefgetStore::compact`].
572#[derive(Debug, Clone)]
573pub struct CompactReport {
574    /// Pack files on disk before compaction.
575    pub packs_before: usize,
576    /// Pack files after compaction.
577    pub packs_after: usize,
578    /// Dead bytes reclaimed.
579    pub bytes_reclaimed: u64,
580    /// Unreferenced pack files deleted by
581    /// [`CompactOptions::prune_unreferenced`]; 0 without it.
582    pub packs_pruned: usize,
583}
584
585/// Options for [`ReadonlyRefgetStore::compact_with`].
586#[derive(Debug, Clone, Copy, Default)]
587pub struct CompactOptions {
588    /// Also delete every pack file that the new index does not reference,
589    /// including packs no index ever listed (left by a crashed writer, for
590    /// example). Such a pack can belong to another writer that has sealed it
591    /// but not committed yet, so set this only when no other process is
592    /// writing to the store.
593    pub prune_unreferenced: bool,
594}
595
596/// What this handle has actually created, modified, or deleted since its last
597/// successful commit.
598///
599/// A store handle's in-memory maps hold two different things mixed together:
600/// rows it produced, and rows it merely LOADED so they could be read
601/// (`open_local` loads a stub for every collection in `collections.rgci`, and
602/// every row of `sequences.rgsi`). A commit that cannot tell those apart has to
603/// write the whole pile back — and the pile is an open-time snapshot, which on a
604/// long import is hours stale.
605///
606/// Recording changes explicitly is what makes a commit a DELTA: take the lock,
607/// re-read the index from disk, apply exactly these sets, publish. A row this
608/// handle never touched is never rewritten, so a concurrent writer's additions
609/// cannot be clobbered and its deletions cannot be resurrected.
610///
611/// In-memory only, never written to disk: this describes an intent that is fully
612/// discharged by the commit that applies it, and is cleared as soon as that
613/// commit succeeds. A handle dropped without committing abandons its pending
614/// changes — see [`ReadonlyRefgetStore::has_uncommitted_changes`].
615#[derive(Debug, Default, Clone)]
616pub struct PendingChanges {
617    /// Collection digests to publish into `collections.rgci`.
618    pub(crate) collections: HashSet<DigestKey>,
619    /// Sequence digests to publish into `sequences.rgsi`.
620    pub(crate) sequences: HashSet<DigestKey>,
621    /// `(kind, namespace, alias)` triples to publish into the alias TSVs.
622    pub(crate) aliases: HashSet<(AliasKind, String, String)>,
623    /// Collection digests to drop from `collections.rgci`.
624    pub(crate) removed_collections: HashSet<DigestKey>,
625    /// Sequence digests to drop from `sequences.rgsi`.
626    pub(crate) removed_sequences: HashSet<DigestKey>,
627    /// `(kind, namespace, alias)` triples to drop from the alias TSVs.
628    pub(crate) removed_aliases: HashSet<(AliasKind, String, String)>,
629    /// `(kind, namespace)` pairs this handle explicitly emptied. Recorded so the
630    /// commit visits the namespace at all; whether the TSV is actually deleted
631    /// depends on the MERGED result being empty, not on this handle's intent.
632    pub(crate) emptied_alias_namespaces: HashSet<(AliasKind, String)>,
633    /// Subset of `aliases` the caller asked to force: on commit these overwrite
634    /// a conflicting binding another writer already published, as if
635    /// `force_alias` were set for that one entry.
636    pub(crate) forced_aliases: HashSet<(AliasKind, String, String)>,
637    /// Sidecar rows to publish into `sequences.pack.idx` (packed layout only):
638    /// digest key -> its `(pack, offset, len)` span. Merged and republished
639    /// under the store lock in `write_index_files`.
640    pub(crate) pack_rows: HashMap<DigestKey, super::packidx::PackRow>,
641}
642
643impl PendingChanges {
644    pub(crate) fn is_empty(&self) -> bool {
645        self.collections.is_empty()
646            && self.sequences.is_empty()
647            && self.aliases.is_empty()
648            && self.removed_collections.is_empty()
649            && self.removed_sequences.is_empty()
650            && self.removed_aliases.is_empty()
651            && self.emptied_alias_namespaces.is_empty()
652            && self.pack_rows.is_empty()
653    }
654
655    /// Record a collection this handle added. An add supersedes a pending
656    /// removal of the same digest (and vice versa), so the two sets stay
657    /// disjoint and the commit never has to guess which wins.
658    pub(crate) fn add_collection(&mut self, key: DigestKey) {
659        self.removed_collections.remove(&key);
660        self.collections.insert(key);
661    }
662
663    pub(crate) fn remove_collection(&mut self, key: DigestKey) {
664        self.collections.remove(&key);
665        self.removed_collections.insert(key);
666    }
667
668    pub(crate) fn add_sequence(&mut self, key: DigestKey) {
669        self.removed_sequences.remove(&key);
670        self.sequences.insert(key);
671    }
672
673    pub(crate) fn remove_sequence(&mut self, key: DigestKey) {
674        self.sequences.remove(&key);
675        self.removed_sequences.insert(key);
676    }
677
678    /// Drop sequences from the pending set WITHOUT recording a removal.
679    ///
680    /// For rows that were staged but never published — the failed-import
681    /// cleanup path. Recording a removal instead would be wrong: it would delete
682    /// an identical row another writer had legitimately published, since
683    /// sequence rows are content-addressed and therefore shared.
684    pub(crate) fn forget_sequences(&mut self, keys: &HashSet<DigestKey>) {
685        self.sequences.retain(|k| !keys.contains(k));
686        self.pack_rows.retain(|k, _| !keys.contains(k));
687    }
688
689    pub(crate) fn add_alias(&mut self, kind: AliasKind, namespace: &str, alias: &str) {
690        let entry = (kind, namespace.to_string(), alias.to_string());
691        self.removed_aliases.remove(&entry);
692        self.aliases.insert(entry);
693    }
694
695    pub(crate) fn add_forced_alias(&mut self, kind: AliasKind, namespace: &str, alias: &str) {
696        self.add_alias(kind, namespace, alias);
697        self.forced_aliases
698            .insert((kind, namespace.to_string(), alias.to_string()));
699    }
700
701    pub(crate) fn is_forced(&self, kind: AliasKind, namespace: &str, alias: &str) -> bool {
702        self.forced_aliases
703            .contains(&(kind, namespace.to_string(), alias.to_string()))
704    }
705
706    pub(crate) fn remove_alias(&mut self, kind: AliasKind, namespace: &str, alias: &str) {
707        let entry = (kind, namespace.to_string(), alias.to_string());
708        self.aliases.remove(&entry);
709        self.forced_aliases.remove(&entry);
710        self.removed_aliases.insert(entry);
711    }
712
713    /// Namespaces of one kind this handle has touched — the only ones a commit
714    /// needs to rewrite. Namespaces nobody changed are left alone on disk.
715    pub(crate) fn touched_alias_namespaces(&self, kind: AliasKind) -> HashSet<String> {
716        let mut out = HashSet::new();
717        for (k, ns, _) in self.aliases.iter().chain(self.removed_aliases.iter()) {
718            if *k == kind {
719                out.insert(ns.clone());
720            }
721        }
722        for (k, ns) in &self.emptied_alias_namespaces {
723            if *k == kind {
724                out.insert(ns.clone());
725            }
726        }
727        out
728    }
729
730    /// Drop exactly the changes a completed commit applied.
731    ///
732    /// Set difference, not `clear()`: another thread may have recorded a change
733    /// after the commit snapshotted, and that one still has to be applied.
734    pub(crate) fn clear_matching(&mut self, applied: &PendingChanges) {
735        self.collections.retain(|k| !applied.collections.contains(k));
736        self.sequences.retain(|k| !applied.sequences.contains(k));
737        self.aliases.retain(|k| !applied.aliases.contains(k));
738        self.forced_aliases.retain(|k| !applied.aliases.contains(k));
739        self.removed_collections
740            .retain(|k| !applied.removed_collections.contains(k));
741        self.removed_sequences
742            .retain(|k| !applied.removed_sequences.contains(k));
743        self.removed_aliases
744            .retain(|k| !applied.removed_aliases.contains(k));
745        self.emptied_alias_namespaces
746            .retain(|k| !applied.emptied_alias_namespaces.contains(k));
747        self.pack_rows
748            .retain(|k, _| !applied.pack_rows.contains_key(k));
749    }
750
751    /// Drop the alias changes for one namespace, after the cheap
752    /// single-namespace commit path published it.
753    pub(crate) fn clear_alias_namespace(&mut self, kind: AliasKind, namespace: &str) {
754        self.aliases
755            .retain(|(k, ns, _)| !(*k == kind && ns == namespace));
756        self.forced_aliases
757            .retain(|(k, ns, _)| !(*k == kind && ns == namespace));
758        self.removed_aliases
759            .retain(|(k, ns, _)| !(*k == kind && ns == namespace));
760        self.emptied_alias_namespaces
761            .retain(|(k, ns)| !(*k == kind && ns == namespace));
762    }
763}
764
765impl ReadonlyRefgetStore {
766    /// Generic constructor. Creates a new, empty `ReadonlyRefgetStore`.
767    /// Internal only - users should go through RefgetStore.
768    pub(crate) fn new(mode: StorageMode) -> Self {
769        ReadonlyRefgetStore {
770            catalog: Catalog::new(),
771            loaded: HashMap::new(),
772            mode,
773            local_path: None,
774            remote_source: None,
775            seqdata_path_template: None,
776            persist_to_disk: false,
777            quiet: false,
778            ancillary_digests: true,
779            attribute_index: false,
780            aliases: AliasManager::default(),
781            fhr_metadata: HashMap::new(),
782            available_sequence_alias_namespaces: Vec::new(),
783            available_collection_alias_namespaces: Vec::new(),
784            seq_fd_cache: Mutex::new(FdCache::new(default_fd_cache_cap())),
785            resident: RwLock::new(HashMap::new()),
786            sequence_index_loaded: true,
787            sequence_index_path: None,
788            pending: Mutex::new(PendingChanges::default()),
789            commit_lock: None,
790            lock_options: LockOptions::default(),
791            force_alias: false,
792            layout: Layout::Standalone,
793            remote_layout: Layout::Standalone,
794            pack_cap_bytes: 256 * 1024 * 1024,
795            pack_cache: None,
796            pack_cols: Mutex::new(None),
797            remote_pack_index: Mutex::new(None),
798            pack_lengths: Mutex::new(HashMap::new()),
799            open_session_pack: Mutex::new(None),
800        }
801    }
802
803    // =========================================================================
804    // Catalog access
805    // =========================================================================
806
807    /// Resolve a sequence digest (sha512t24u, `SQ.`-prefixed, or MD5) to its
808    /// catalog row.
809    pub(crate) fn seq_row<K: AsRef<[u8]>>(&self, digest: K) -> Option<SeqRow> {
810        self.catalog.resolve(digest)
811    }
812
813    /// A borrowed view of one sequence's metadata, by any digest form.
814    pub fn sequence_view<K: AsRef<[u8]>>(&self, digest: K) -> Option<SeqView<'_>> {
815        self.seq_row(digest).map(|r| self.catalog.seq(r))
816    }
817
818    /// Views of every sequence in the store, in insertion order.
819    pub fn sequence_views(&self) -> impl Iterator<Item = SeqView<'_>> + '_ {
820        self.catalog.seq_rows().map(|r| self.catalog.seq(r))
821    }
822
823    /// Row of a collection whose member list is loaded; an error if the
824    /// collection is unknown or not loaded.
825    pub(crate) fn loaded_coll_row<K: AsRef<[u8]>>(&self, digest: K) -> Result<CollRow> {
826        let d = digest.as_ref();
827        match self.catalog.find_coll(d) {
828            Some(c) if self.catalog.is_loaded(c) => Ok(c),
829            Some(_) => Err(anyhow!(
830                "Collection {} not loaded. Call load_collection() or load_all_collections() first.",
831                String::from_utf8_lossy(d)
832            )),
833            None => Err(anyhow!("Collection not found: {}", String::from_utf8_lossy(d))),
834        }
835    }
836
837    /// Per-collection members (name, description, sequence) in FASTA order.
838    /// This is the source of truth for names/headers; a sequence's store-wide
839    /// label only names the shared bytes.
840    pub fn collection_members<K: AsRef<[u8]>>(
841        &self,
842        digest: K,
843    ) -> Result<impl ExactSizeIterator<Item = MemberView<'_>> + '_> {
844        let c = self.loaded_coll_row(digest)?;
845        Ok(self.catalog.members(c))
846    }
847
848    /// Borrow the store-owned (loaded) bytes of a sequence, in the store's
849    /// native encoding. `None` if the sequence is unknown or not loaded.
850    pub fn loaded_bytes<K: AsRef<[u8]>>(&self, digest: K) -> Option<&[u8]> {
851        let row = self.seq_row(digest)?;
852        self.loaded.get(&row).map(|b| b.as_slice())
853    }
854
855    /// Store-owned bytes of a sequence, if it is loaded.
856    pub(crate) fn loaded_arc(&self, row: SeqRow) -> Option<Arc<Vec<u8>>> {
857        self.loaded.get(&row).cloned()
858    }
859
860    /// Owned record for a sequence row, with its store-wide label. Bytes are an
861    /// `Arc` bump, not a copy.
862    pub(crate) fn seq_record(&self, row: SeqRow) -> SequenceRecord {
863        let metadata = self.catalog.seq(row).to_metadata();
864        match self.loaded_arc(row) {
865            Some(sequence) => SequenceRecord::Full { metadata, sequence },
866            None => SequenceRecord::Stub(metadata),
867        }
868    }
869
870    /// Owned record for a collection member: THIS collection's name and
871    /// description, the shared bytes.
872    pub(crate) fn member_record(&self, m: MemberView<'_>) -> SequenceRecord {
873        let metadata = m.to_metadata();
874        match self.loaded_arc(m.seq_row()) {
875            Some(sequence) => SequenceRecord::Full { metadata, sequence },
876            None => SequenceRecord::Stub(metadata),
877        }
878    }
879
880    /// Insert (or, with `force`, relabel) a sequence and optionally its bytes.
881    /// Returns the row and whether the store changed (new row or forced).
882    pub(crate) fn insert_sequence(
883        &mut self,
884        meta: &SequenceMetadata,
885        bytes: Option<Arc<Vec<u8>>>,
886        force: bool,
887    ) -> Result<(SeqRow, bool)> {
888        let (row, new) = self.catalog.add_sequence(meta)?;
889        if !new && !force {
890            return Ok((row, false));
891        }
892        if !new {
893            self.catalog.set_sequence_label(row, meta)?;
894        }
895        match bytes {
896            Some(b) => {
897                self.loaded.insert(row, b);
898            }
899            None => {
900                self.loaded.remove(&row);
901            }
902        }
903        Ok((row, true))
904    }
905
906    /// Install a collection with its members (sequences added as needed,
907    /// without bytes). Returns the collection row and the sequence rows that
908    /// were new to the store.
909    pub(crate) fn insert_collection(
910        &mut self,
911        meta: SequenceCollectionMetadata,
912        members: &[SequenceMetadata],
913    ) -> Result<(CollRow, Vec<SeqRow>)> {
914        let mut rows = Vec::with_capacity(members.len());
915        let mut new_rows = Vec::new();
916        for m in members {
917            let (row, new) = self.catalog.add_sequence(m)?;
918            if new {
919                new_rows.push(row);
920            }
921            rows.push(row);
922        }
923        let c = self.catalog.upsert_collection(meta)?;
924        self.catalog.set_members(
925            c,
926            members.iter().zip(&rows).map(|(m, &seq)| NewMember {
927                seq,
928                name: &m.name,
929                description: m.description.as_deref(),
930                fai: m.fai.as_ref(),
931            }),
932        )?;
933        Ok((c, new_rows))
934    }
935
936    /// Tombstone sequences and drop their bytes.
937    pub(crate) fn remove_sequence_rows(&mut self, rows: &[SeqRow]) {
938        let mut resident = self.resident.write().ok();
939        for &r in rows {
940            self.catalog.remove_sequence(r);
941            self.loaded.remove(&r);
942            if let Some(res) = resident.as_mut() {
943                res.remove(&r);
944            }
945        }
946    }
947
948    /// Renumber catalog rows once enough are dead, rekeying the byte maps.
949    pub(crate) fn maybe_compact_catalog(&mut self) {
950        if !self.catalog.needs_compaction() {
951            return;
952        }
953        let remap = self.catalog.compact();
954        let rekey = |m: HashMap<SeqRow, Arc<Vec<u8>>>| -> HashMap<SeqRow, Arc<Vec<u8>>> {
955            m.into_iter()
956                .filter_map(|(r, b)| remap.get(r as usize).copied().flatten().map(|n| (n, b)))
957                .collect()
958        };
959        self.loaded = rekey(std::mem::take(&mut self.loaded));
960        if let Ok(mut res) = self.resident.write() {
961            *res = rekey(std::mem::take(&mut *res));
962        }
963        self.invalidate_pack_index();
964    }
965
966    // =========================================================================
967    // Write locking
968    // =========================================================================
969
970    /// Hold the store's exclusive writer lock across several mutations.
971    ///
972    /// Individual mutations already commit under the lock, so this is only needed
973    /// when a sequence of them must be atomic with respect to other writers — the
974    /// registry's alias step, for instance, which adds many aliases and expects
975    /// them to appear together. The guard is dropped by
976    /// [`Self::release_batch_lock`] or when the store is dropped.
977    ///
978    /// Nested commits are re-entrant: they see the held guard and skip acquiring.
979    pub fn lock_for_batch(&mut self, operation: &str) -> Result<()> {
980        if self.commit_lock.is_some() {
981            return Ok(());
982        }
983        let local_path = self
984            .local_path
985            .as_ref()
986            .context("lock_for_batch requires a disk-backed store")?;
987        let lock = StoreLock::acquire(local_path, operation, self.lock_options.clone())?;
988        self.commit_lock = Some(Arc::new(lock));
989        Ok(())
990    }
991
992    /// Release a lock taken by [`Self::lock_for_batch`].
993    pub fn release_batch_lock(&mut self) {
994        self.commit_lock = None;
995    }
996
997    /// Whether this store currently holds a batch write lock.
998    pub fn holds_batch_lock(&self) -> bool {
999        self.commit_lock.is_some()
1000    }
1001
1002    /// Whether this store has additions or removals that have not yet been
1003    /// committed to the shared index files.
1004    ///
1005    /// Pending changes live only in memory, so dropping a store without
1006    /// committing silently abandons them: added rows never reach
1007    /// `sequences.rgsi`/`collections.rgci`, and removed rows are still on disk.
1008    pub fn has_uncommitted_changes(&self) -> bool {
1009        !self.pending.lock().unwrap().is_empty()
1010    }
1011
1012    /// Record a change this handle made, so the next commit applies it to the
1013    /// index it reads fresh from disk.
1014    pub(crate) fn record<F: FnOnce(&mut PendingChanges)>(&self, f: F) {
1015        f(&mut self.pending.lock().unwrap());
1016    }
1017
1018    /// Override the timeout/staleness settings used when acquiring the write lock.
1019    pub fn set_lock_options(&mut self, options: LockOptions) {
1020        self.lock_options = options;
1021    }
1022
1023    /// Allow re-pointing an existing alias (in memory, or one another writer
1024    /// already published) to a different digest, instead of erroring on the
1025    /// conflict. A load that maps one alias to two digests still errors.
1026    pub fn set_force_alias(&mut self, force: bool) {
1027        self.force_alias = force;
1028    }
1029
1030    /// Test-only: shrink the partial-read fd-cache to a tiny capacity so the
1031    /// eviction/reopen path is exercised deterministically. Only used by the
1032    /// filesystem-gated partial-read tests.
1033    #[cfg(all(test, feature = "filesystem"))]
1034    pub(crate) fn set_seq_fd_cache_cap_for_test(&self, cap: usize) {
1035        let mut cache = self.seq_fd_cache.lock().unwrap();
1036        *cache = FdCache::new(cap);
1037    }
1038
1039    /// Set whether to suppress progress output.
1040    pub fn set_quiet(&mut self, quiet: bool) {
1041        self.quiet = quiet;
1042    }
1043
1044    /// Returns whether the store is in quiet mode.
1045    pub fn is_quiet(&self) -> bool {
1046        self.quiet
1047    }
1048
1049    /// Check whether a valid RefgetStore exists at the given path.
1050    pub fn store_exists<P: AsRef<Path>>(path: P) -> bool {
1051        path.as_ref().join("rgstore.json").exists()
1052    }
1053
1054    /// Change the storage mode, re-encoding/decoding existing sequences as needed.
1055    ///
1056    /// Switching to [`StorageMode::Encoded`] fails if a sequence holds a byte
1057    /// that its stored alphabet cannot represent. That means the store's
1058    /// alphabet metadata is wrong (written by an older gtars) and the store
1059    /// must be re-imported. On error the store is left unchanged.
1060    ///
1061    /// For a disk-backed PACKED store that already holds sequences, changing the
1062    /// mode is refused with an error: the packed bytes on disk are in the
1063    /// current mode, and re-encoding only the resident records would desync
1064    /// them from the packs. Mode is fixed at creation for a populated packed
1065    /// store. (An empty packed store, before any import, may still switch,
1066    /// since there are no packed bytes to desync.)
1067    pub fn set_encoding_mode(&mut self, new_mode: StorageMode) -> Result<()> {
1068        if self.mode == new_mode {
1069            return Ok(());
1070        }
1071        if self.persist_to_disk
1072            && self.layout == Layout::Packed
1073            && self.catalog.n_sequences() > 0
1074        {
1075            return Err(anyhow!(
1076                "refusing to change storage mode on a populated packed store \
1077                 (would desync the packs); mode stays {:?}",
1078                self.mode
1079            ));
1080        }
1081        let old_mode = self.mode;
1082
1083        let encode = |metadata: &SequenceMetadata, ascii: &[u8]| -> Result<Vec<u8>> {
1084            let alphabet = lookup_alphabet(&metadata.alphabet);
1085            encode_sequence(ascii, alphabet).map_err(|e| {
1086                anyhow::anyhow!(
1087                    "cannot encode sequence {} ({}): {e}. The stored alphabet \
1088                     metadata is wrong; re-import this store.",
1089                    metadata.sha512t24u,
1090                    metadata.name
1091                )
1092            })
1093        };
1094
1095        // Convert everything first, then swap in, so an error leaves the store
1096        // untouched rather than half converted.
1097        let mut converted: Vec<(SeqRow, Vec<u8>)> = Vec::new();
1098        for (key, sequence) in self.loaded.iter() {
1099            let owned_meta = self.catalog.seq(*key).to_metadata();
1100            let metadata = &owned_meta;
1101            let new_bytes = match (old_mode, new_mode) {
1102                (StorageMode::Raw, StorageMode::Encoded) => encode(metadata, &sequence[..])?,
1103                (StorageMode::Encoded, StorageMode::Raw) => {
1104                    let alphabet = lookup_alphabet(&metadata.alphabet);
1105                    decode_string_from_bytes(&sequence[..], metadata.length, alphabet)
1106                }
1107                // Zstd conversions: normalize through ASCII. The stored
1108                // body for Zstd is the whole-record zstd frame.
1109                (StorageMode::Raw, StorageMode::Zstd) => {
1110                    zstd::encode_all(&sequence[..], super::ZSTD_STORAGE_LEVEL)
1111                        .expect("zstd encode during mode switch")
1112                }
1113                (StorageMode::Zstd, StorageMode::Raw) => {
1114                    zstd::decode_all(&sequence[..]).expect("zstd decode during mode switch")
1115                }
1116                (StorageMode::Encoded, StorageMode::Zstd) => {
1117                    let alphabet = lookup_alphabet(&metadata.alphabet);
1118                    let ascii =
1119                        decode_string_from_bytes(&sequence[..], metadata.length, alphabet);
1120                    zstd::encode_all(&ascii[..], super::ZSTD_STORAGE_LEVEL)
1121                        .expect("zstd encode during mode switch")
1122                }
1123                (StorageMode::Zstd, StorageMode::Encoded) => {
1124                    let ascii = zstd::decode_all(&sequence[..])
1125                        .expect("zstd decode during mode switch");
1126                    encode(metadata, &ascii[..])?
1127                }
1128                _ => continue,
1129            };
1130            converted.push((*key, new_bytes));
1131        }
1132
1133        for (key, new_bytes) in converted {
1134            self.loaded.insert(key, std::sync::Arc::new(new_bytes));
1135        }
1136
1137        self.mode = new_mode;
1138        Ok(())
1139    }
1140
1141    /// Enable 2-bit encoding for space efficiency.
1142    ///
1143    /// Fails, leaving the store unchanged, if a sequence cannot be encoded
1144    /// with its stored alphabet (see [`set_encoding_mode`](Self::set_encoding_mode)).
1145    pub fn enable_encoding(&mut self) -> Result<()> {
1146        self.set_encoding_mode(StorageMode::Encoded)
1147    }
1148
1149    /// Disable encoding, use raw byte storage.
1150    pub fn disable_encoding(&mut self) {
1151        self.set_encoding_mode(StorageMode::Raw)
1152            .expect("switching to Raw never encodes, so it cannot fail");
1153    }
1154
1155    /// Enable disk persistence for this store.
1156    pub fn enable_persistence<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
1157        let path = path.as_ref();
1158
1159        self.local_path = Some(path.to_path_buf());
1160        self.persist_to_disk = true;
1161        self.seqdata_path_template
1162            .get_or_insert_with(|| DEFAULT_SEQDATA_PATH_TEMPLATE.to_string());
1163
1164        create_dir_all(path.join("sequences"))?;
1165        create_dir_all(path.join("collections"))?;
1166
1167        // Materializing an in-memory store onto disk: EVERYTHING resident is a
1168        // change, because none of it came from this directory. This is the one
1169        // place where "write back the whole in-memory pile" is the correct
1170        // commit, and it is correct precisely because nothing here was loaded.
1171        {
1172            let mut pending = self.pending.lock().unwrap();
1173            for v in self.sequence_views() {
1174                pending.add_sequence(v.sha512t24u().to_key());
1175            }
1176            for c in self.catalog.coll_rows() {
1177                pending.add_collection(self.catalog.coll_meta(c).digest.to_key());
1178            }
1179            for kind in [AliasKind::Sequence, AliasKind::Collection] {
1180                for ns in self.aliases.namespaces_for(kind) {
1181                    for alias in self.aliases.namespace_map(kind, &ns).keys() {
1182                        pending.add_alias(kind, &ns, alias);
1183                    }
1184                }
1185            }
1186        }
1187
1188        let rows: Vec<SeqRow> = self.loaded.keys().copied().collect();
1189        for row in rows {
1190            if let Some(sequence) = self.loaded.remove(&row) {
1191                let metadata = self.catalog.seq(row).to_metadata();
1192                self.write_sequence_to_disk_single(&metadata, &sequence)?;
1193            }
1194        }
1195
1196        for c in self.catalog.coll_rows() {
1197            self.write_collection_to_disk_single(
1198                self.catalog.coll_meta(c),
1199                self.catalog.members(c).map(|m| m.to_metadata()),
1200            )?;
1201        }
1202
1203        self.write_index_files()?;
1204
1205        Ok(())
1206    }
1207
1208    /// Disable disk persistence for this store.
1209    pub fn disable_persistence(&mut self) {
1210        self.persist_to_disk = false;
1211    }
1212
1213    /// Check if persistence to disk is enabled.
1214    pub fn is_persisting(&self) -> bool {
1215        self.persist_to_disk
1216    }
1217
1218    /// Adds a collection, and all sequences in it, to the store.
1219    pub fn add_sequence_collection(
1220        &mut self,
1221        collection: crate::digest::SequenceCollection,
1222    ) -> Result<()> {
1223        self.add_sequence_collection_internal(collection, false)
1224    }
1225
1226    /// Adds a collection, overwriting existing data.
1227    pub fn add_sequence_collection_force(
1228        &mut self,
1229        collection: crate::digest::SequenceCollection,
1230    ) -> Result<()> {
1231        self.add_sequence_collection_internal(collection, true)
1232    }
1233
1234    /// Internal implementation for adding a sequence collection.
1235    pub(crate) fn add_sequence_collection_internal(
1236        &mut self,
1237        collection: crate::digest::SequenceCollection,
1238        force: bool,
1239    ) -> Result<()> {
1240        let coll_digest = collection.metadata.digest.to_key();
1241
1242        if !force && self.catalog.find_coll(&collection.metadata.digest).is_some() {
1243            return Ok(());
1244        }
1245
1246        let crate::digest::SequenceCollection { metadata, sequences } = collection;
1247        let members: Vec<SequenceMetadata> =
1248            sequences.iter().map(|s| s.metadata().clone()).collect();
1249
1250        if self.persist_to_disk && self.local_path.is_some() {
1251            self.write_collection_to_disk_single(&metadata, &members)?;
1252        }
1253
1254        for sequence_record in sequences {
1255            self.add_sequence_record(sequence_record, force)?;
1256        }
1257        self.insert_collection(metadata, &members)?;
1258        self.record(|p| p.add_collection(coll_digest));
1259
1260        if self.persist_to_disk && self.local_path.is_some() {
1261            self.write_index_files()?;
1262        }
1263
1264        Ok(())
1265    }
1266
1267    /// Pack a raw ASCII record when the store uses encoded storage.
1268    ///
1269    /// Raw and packed forms are distinguished by their expected lengths, so a
1270    /// single-base sequence is ambiguous. Use [`ingest_sequence`](Self::ingest_sequence)
1271    /// when the input is known to be raw; it handles that case explicitly.
1272    fn pack_raw_ascii_for_encoded_mode(&self, sr: SequenceRecord) -> Result<SequenceRecord> {
1273        if self.mode != StorageMode::Encoded {
1274            return Ok(sr);
1275        }
1276        match sr {
1277            SequenceRecord::Full { metadata, sequence } => {
1278                let alphabet = lookup_alphabet(&metadata.alphabet);
1279                let bps = alphabet.bits_per_symbol;
1280                let expected_encoded = metadata.length.saturating_mul(bps).div_ceil(8);
1281                let looks_raw = sequence.len() == metadata.length
1282                    && sequence.len() != expected_encoded
1283                    && sequence.is_ascii();
1284                if looks_raw {
1285                    let packed = encode_sequence(&sequence[..], alphabet).with_context(|| {
1286                        format!(
1287                            "encoding sequence {} ({}) with alphabet {}",
1288                            metadata.sha512t24u, metadata.name, metadata.alphabet
1289                        )
1290                    })?;
1291                    Ok(SequenceRecord::Full {
1292                        metadata,
1293                        sequence: std::sync::Arc::new(packed),
1294                    })
1295                } else {
1296                    Ok(SequenceRecord::Full { metadata, sequence })
1297                }
1298            }
1299            stub @ SequenceRecord::Stub(_) => Ok(stub),
1300        }
1301    }
1302
1303    /// Digest and insert raw bytes using the store's native encoding.
1304    ///
1305    /// Because the input is known to be raw, this method also handles
1306    /// single-base sequences, whose raw and packed lengths are identical.
1307    /// Input is normalized in the same way as `digest_sequence`.
1308    pub fn ingest_sequence(&mut self, name: &str, bytes: &[u8]) -> Result<String> {
1309        let record = crate::digest::digest_sequence(name, bytes);
1310        let digest = record.metadata().sha512t24u.clone();
1311
1312        let record = match record {
1313            SequenceRecord::Full { metadata, sequence } if self.mode == StorageMode::Encoded => {
1314                let alphabet = lookup_alphabet(&metadata.alphabet);
1315                let packed = encode_sequence(&sequence[..], alphabet).with_context(|| {
1316                    format!("encoding sequence {} ({})", metadata.sha512t24u, metadata.name)
1317                })?;
1318                SequenceRecord::Full {
1319                    metadata,
1320                    sequence: std::sync::Arc::new(packed),
1321                }
1322            }
1323            other => other,
1324        };
1325
1326        self.add_sequence_record(record, false)?;
1327        Ok(digest)
1328    }
1329
1330    /// Adds a SequenceRecord directly to the store without collection association.
1331    ///
1332    /// Raw ASCII records are packed when the store uses encoded storage.
1333    /// Already-packed records are stored unchanged.
1334    pub fn add_sequence_record(&mut self, sr: SequenceRecord, force: bool) -> Result<()> {
1335        let sr = self.pack_raw_ascii_for_encoded_mode(sr)?;
1336
1337        let metadata = sr.metadata();
1338        let key = metadata.sha512t24u.to_key();
1339
1340        // Records must now match the store's native representation: ASCII in
1341        // Raw mode or the alphabet's packed size in Encoded mode.
1342        debug_assert!(
1343            match &sr {
1344                SequenceRecord::Full { metadata, sequence } => match self.mode {
1345                    StorageMode::Raw => sequence.is_ascii(),
1346                    StorageMode::Encoded => {
1347                        let bps = lookup_alphabet(&metadata.alphabet).bits_per_symbol;
1348                        sequence.len() == metadata.length.saturating_mul(bps).div_ceil(8)
1349                    }
1350                    StorageMode::Zstd => true, // zstd bytes have no simple invariant to check
1351                },
1352                SequenceRecord::Stub(_) => true,
1353            },
1354            "add_sequence_record: sequence bytes must be stored in the store's native encoding (ASCII in Raw mode, packed to the alphabet's encoded size in Encoded mode)"
1355        );
1356
1357        // A dedup hit records NOTHING: the row is already in memory, which for a
1358        // disk-backed store means it is already in `sequences.rgsi`. Re-asserting
1359        // it would put a row this handle did not produce back into the delta.
1360        if !force && self.catalog.find_sha(&metadata.sha512t24u).is_some() {
1361            return Ok(());
1362        }
1363
1364        // In Zstd mode the caller passes the ASCII record body (per contract,
1365        // "do not 2-bit pre-pack, let zstd own the entropy"); the store owns the
1366        // whole-record zstd compression here so the on-disk / in-memory body is
1367        // the compressed frame. Reads decompress the whole frame and slice.
1368        let sr = self.compress_record_for_storage(sr)?;
1369        let (metadata, bytes) = match sr {
1370            SequenceRecord::Full { metadata, sequence } => (metadata, Some(sequence)),
1371            SequenceRecord::Stub(metadata) => (metadata, None),
1372        };
1373
1374        let writes_bytes = self.persist_to_disk && self.local_path.is_some() && bytes.is_some();
1375        // What the insert below changes, so a failed byte write can put it
1376        // back: the prior label and bytes of a sequence already in the catalog
1377        // (only a forced re-add gets here with one), and whether this handle
1378        // had already staged the sequence or a removal of it.
1379        let undo = writes_bytes.then(|| {
1380            let prior = self
1381                .catalog
1382                .find_sha(&metadata.sha512t24u)
1383                .map(|r| (self.catalog.seq(r).to_metadata(), self.loaded.get(&r).cloned()));
1384            let p = self.pending.lock().unwrap();
1385            (prior, p.sequences.contains(&key), p.removed_sequences.contains(&key))
1386        });
1387
1388        let (row, _) = self.insert_sequence(&metadata, bytes.clone(), true)?;
1389        self.record(|p| p.add_sequence(key));
1390
1391        if let (Some(sequence), Some((prior, was_staged, was_removed))) = (&bytes, undo) {
1392            let packed = self.layout == Layout::Packed;
1393            let written = if packed {
1394                // Packed incremental write (panget's path): append to the open
1395                // session pack. The bytes stay loaded so mid-session reads are
1396                // served from RAM; on reopen the sequence is resolved through
1397                // the sidecar.
1398                self.session_pack_append(&metadata.sha512t24u, sequence)
1399            } else {
1400                self.write_sequence_to_disk_single(&metadata, sequence)
1401            };
1402            if let Err(e) = written {
1403                // Undo the insert, so a later commit publishes no row whose
1404                // bytes are not on disk. A sequence this call added is
1405                // removed; one already in the catalog keeps its row and gets
1406                // its prior label and bytes back.
1407                match prior {
1408                    None => self.remove_sequence_rows(&[row]),
1409                    Some((meta, prior_bytes)) => {
1410                        let _ = self.catalog.set_sequence_label(row, &meta);
1411                        match prior_bytes {
1412                            Some(b) => self.loaded.insert(row, b),
1413                            None => self.loaded.remove(&row),
1414                        };
1415                    }
1416                }
1417                let mut p = self.pending.lock().unwrap();
1418                if !was_staged {
1419                    p.sequences.remove(&key);
1420                }
1421                if was_removed {
1422                    p.removed_sequences.insert(key);
1423                }
1424                return Err(e);
1425            }
1426            if !packed {
1427                self.loaded.remove(&row);
1428            }
1429        }
1430        Ok(())
1431    }
1432
1433    /// For a `Zstd`-mode store, compress a `Full` record's ASCII body into a zstd
1434    /// frame (the stored representation). A no-op for every other mode and for
1435    /// `Stub` records. `metadata.length` stays the logical (ASCII) base count.
1436    fn compress_record_for_storage(&self, sr: SequenceRecord) -> Result<SequenceRecord> {
1437        if self.mode != StorageMode::Zstd {
1438            return Ok(sr);
1439        }
1440        match sr {
1441            SequenceRecord::Full { metadata, sequence } => {
1442                let compressed = zstd::encode_all(&sequence[..], super::ZSTD_STORAGE_LEVEL)
1443                    .context("zstd compression of sequence record failed")?;
1444                Ok(SequenceRecord::Full {
1445                    metadata,
1446                    sequence: std::sync::Arc::new(compressed),
1447                })
1448            }
1449            other => Ok(other),
1450        }
1451    }
1452
1453    /// Inserter-side half of [`add_sequence_record`](Self::add_sequence_record)
1454    /// for the parallel streaming import: do the FAST in-memory dedup decision
1455    /// and catalog insert here (single inserter, so no race on the
1456    /// dedup truth), but DO NOT write the bytes to disk. Instead return the
1457    /// expanded full path + bytes, so the caller can dispatch the (independent,
1458    /// per-digest) `.seq` write to a bounded writer pool, or append the bytes
1459    /// to the session pack of a packed store.
1460    ///
1461    /// Returns `Some((full_path, bytes))` when a write must be performed
1462    /// (disk-backed store, `Full` record, and either a first occurrence or a
1463    /// forced overwrite), or `None` when nothing needs to be written to disk
1464    /// (in-memory mode, a `Stub`, or a dedup hit). The in-memory state is fully
1465    /// updated before returning, so dedup stays the single source of truth on
1466    /// the inserter thread.
1467    #[cfg_attr(not(feature = "filesystem"), allow(dead_code))]
1468    pub(crate) fn add_sequence_record_deferred_write(
1469        &mut self,
1470        sr: SequenceRecord,
1471        force: bool,
1472    ) -> Result<Option<(PathBuf, Vec<u8>)>> {
1473        let metadata = sr.metadata();
1474        let key = metadata.sha512t24u.to_key();
1475
1476        // Dedup hit: nothing inserted, so nothing to record. See
1477        // [`Self::add_sequence_record`].
1478        if !force && self.catalog.find_sha(&metadata.sha512t24u).is_some() {
1479            return Ok(None);
1480        }
1481
1482        if self.persist_to_disk && self.local_path.is_some() {
1483            match sr {
1484                SequenceRecord::Full { metadata, sequence } => {
1485                    // Insert the metadata NOW (reserve), so the dedup
1486                    // decision is committed on the inserter thread. The caller
1487                    // does the actual byte write.
1488                    let full_path = self
1489                        .sequence_file_path(&metadata.sha512t24u)
1490                        .context("seqdata_path_template/local_path not set")?;
1491                    self.insert_sequence(&metadata, None, true)?;
1492                    self.record(|p| p.add_sequence(key));
1493                    // INVARIANT: strong_count == 1 here — the Arc was just
1494                    // constructed in the import pipeline (Arc::new in import.rs)
1495                    // and no other owner exists at the point of this call, so
1496                    // try_unwrap always succeeds and reclaims the buffer with zero
1497                    // copy. The clone fallback is dead code / future-proofing only.
1498                    debug_assert_eq!(
1499                        std::sync::Arc::strong_count(&sequence),
1500                        1,
1501                        "sequence Arc must be uniquely owned for zero-copy reclaim"
1502                    );
1503                    let bytes = std::sync::Arc::try_unwrap(sequence)
1504                        .unwrap_or_else(|arc| (*arc).clone());
1505                    // Zstd mode: the caller handed us the ASCII body; compress the
1506                    // whole record so the zstd frame is what gets written.
1507                    let bytes = if self.mode == StorageMode::Zstd {
1508                        zstd::encode_all(&bytes[..], super::ZSTD_STORAGE_LEVEL)
1509                            .context("zstd compression of sequence record failed")?
1510                    } else {
1511                        bytes
1512                    };
1513                    return Ok(Some((full_path, bytes)));
1514                }
1515                SequenceRecord::Stub(s) => {
1516                    self.insert_sequence(&s, None, true)?;
1517                    self.record(|p| p.add_sequence(key));
1518                    return Ok(None);
1519                }
1520            }
1521        }
1522
1523        // In-memory (non-disk-backed): keep the resident body in the store's
1524        // native form, so a Zstd store holds the compressed frame just like the
1525        // disk-backed path returns compressed bytes above.
1526        let (metadata, bytes) = match self.compress_record_for_storage(sr)? {
1527            SequenceRecord::Full { metadata, sequence } => (metadata, Some(sequence)),
1528            SequenceRecord::Stub(metadata) => (metadata, None),
1529        };
1530        self.insert_sequence(&metadata, bytes, true)?;
1531        self.record(|p| p.add_sequence(key));
1532        Ok(None)
1533    }
1534
1535    // =========================================================================
1536    // Sequence query methods
1537    // =========================================================================
1538
1539    /// Returns an iterator over all sequence digests in the store
1540    pub fn sequence_digests(&self) -> impl Iterator<Item = DigestKey> + '_ {
1541        self.sequence_views().map(|v| v.sha512t24u().to_key())
1542    }
1543
1544    /// Returns an iterator over (owned) sequence metadata for all sequences in
1545    /// the store. Use [`Self::sequence_views`] to avoid the per-item copy.
1546    pub fn sequence_metadata(&self) -> impl Iterator<Item = SequenceMetadata> + '_ {
1547        self.sequence_views().map(|v| v.to_metadata())
1548    }
1549
1550    /// Logical size in bytes of all sequence *payloads*, computed from metadata
1551    /// (length x storage mode). Cheap: O(n_sequences) arithmetic, no I/O, no walk,
1552    /// works on stubs. Does NOT include index files, sidecars, or rgstore.json.
1553    /// This is the value cached in the manifest at write time (see write path); for
1554    /// the exact full on-disk footprint use `actual_disk_usage()` (walks the dir).
1555    pub fn logical_sequence_bytes(&self) -> usize {
1556        self.sequence_views().map(|v| v.disk_size(&self.mode)).sum()
1557    }
1558
1559    /// Exact on-disk footprint of the store: recursively walks the store directory
1560    /// and sums every file's byte length (`.seq` data, `.rgsi`/`.rgci` indexes, FHR
1561    /// sidecars, alias data, `rgstore.json`). Accurate and complete, but does I/O on
1562    /// every call. Use this when an exact footprint is needed; for the cheap cached
1563    /// sequence-content size use `logical_sequence_bytes()`.
1564    pub fn actual_disk_usage(&self) -> usize {
1565        let Some(path) = &self.local_path else {
1566            return 0;
1567        };
1568
1569        fn dir_size(path: &std::path::Path) -> usize {
1570            let mut total = 0;
1571            if let Ok(entries) = std::fs::read_dir(path) {
1572                for entry in entries.flatten() {
1573                    let path = entry.path();
1574                    if path.is_file() {
1575                        total += entry.metadata().map(|m| m.len() as usize).unwrap_or(0);
1576                    } else if path.is_dir() {
1577                        total += dir_size(&path);
1578                    }
1579                }
1580            }
1581            total
1582        }
1583
1584        dir_size(path)
1585    }
1586
1587    // =========================================================================
1588    // Collection API
1589    // =========================================================================
1590
1591    /// List collections with pagination and optional attribute filtering.
1592    pub fn list_collections(
1593        &self,
1594        page: usize,
1595        page_size: usize,
1596        filters: &[(&str, &str)],
1597    ) -> Result<PagedResult<SequenceCollectionMetadata>> {
1598        let mut filtered: Vec<SequenceCollectionMetadata> = Vec::new();
1599        for c in self.catalog.coll_rows() {
1600            let meta = self.catalog.coll_meta(c);
1601            let mut passes = true;
1602            for &(attr_name, attr_digest) in filters {
1603                if !metadata_matches_attribute(meta, attr_name, attr_digest)? {
1604                    passes = false;
1605                    break;
1606                }
1607            }
1608            if passes {
1609                filtered.push(meta.clone());
1610            }
1611        }
1612
1613        filtered.sort_by(|a, b| a.digest.cmp(&b.digest));
1614
1615        let total = filtered.len();
1616        let start = page * page_size;
1617        let results = if start < total {
1618            filtered.into_iter().skip(start).take(page_size).collect()
1619        } else {
1620            Vec::new()
1621        };
1622
1623        Ok(PagedResult {
1624            results,
1625            pagination: Pagination {
1626                page,
1627                page_size,
1628                total,
1629            },
1630        })
1631    }
1632
1633    /// Get metadata for a single collection by digest (no sequence data).
1634    pub fn get_collection_metadata<K: AsRef<[u8]>>(
1635        &self,
1636        collection_digest: K,
1637    ) -> Option<&SequenceCollectionMetadata> {
1638        self.catalog
1639            .find_coll(collection_digest)
1640            .map(|c| self.catalog.coll_meta(c))
1641    }
1642
1643    /// Get a collection with all its sequences loaded.
1644    pub fn get_collection(&self, collection_digest: &str) -> Result<crate::digest::SequenceCollection> {
1645        let c = self.loaded_coll_row(collection_digest)?;
1646        // Each result carries the per-collection name AND description, not the
1647        // first-imported store-wide label of a sequence shared across
1648        // collections. Only the bytes (and `fai`, if the member lacks it) come
1649        // from the sequence row.
1650        let sequences: Vec<SequenceRecord> =
1651            self.catalog.members(c).map(|m| self.member_record(m)).collect();
1652        Ok(crate::digest::SequenceCollection {
1653            metadata: self.catalog.coll_meta(c).clone(),
1654            sequences,
1655        })
1656    }
1657
1658    /// Dry-run of [`Self::remove_collection`]'s orphan cleanup: the sequence
1659    /// digests that WOULD be deleted, without touching anything.
1660    ///
1661    /// Uses the same disk-derived live set as the real thing, so it fails with the
1662    /// same error if the store is not in a state where orphan GC is safe.
1663    ///
1664    /// # Advisory, by design
1665    ///
1666    /// This takes NO lock. It exists for confirmation prompts ("this will free
1667    /// 21 sequences, proceed?"), where blocking every concurrent writer for the
1668    /// length of a full-store scan to answer a question the user may say no to
1669    /// would be absurd. The authoritative scan runs again inside
1670    /// `remove_collection`, under the lock, and the two can legitimately differ:
1671    /// a collection committed in between makes some planned orphan live again,
1672    /// and the real removal will correctly spare it. Callers comparing the two
1673    /// should treat a shortfall as normal concurrency, not corruption.
1674    pub fn plan_orphan_removal(&self, digest: &str) -> Result<Vec<String>> {
1675        let key = digest.to_key();
1676        let candidates = self.orphan_candidates(digest)?;
1677        let live = self.live_sequence_set(&key)?;
1678        Ok(candidates
1679            .into_iter()
1680            .filter(|k| !live.contains(k))
1681            .map(|k| key_to_digest_string(&k))
1682            .collect())
1683    }
1684
1685    /// Sequence digests belonging to the collection being removed.
1686    fn orphan_candidates(&self, digest: &str) -> Result<Vec<DigestKey>> {
1687        if self.local_path.is_some() {
1688            self.collection_sequence_digests(digest)
1689        } else {
1690            Ok(self.loaded_member_seq_keys(digest))
1691        }
1692    }
1693
1694    /// Sequence digest keys of a loaded collection's members (empty if the
1695    /// collection is unknown or not loaded).
1696    pub(crate) fn loaded_member_seq_keys(&self, digest: &str) -> Vec<DigestKey> {
1697        match self.catalog.find_coll(digest) {
1698            Some(c) => self
1699                .catalog
1700                .members(c)
1701                .map(|m| m.seq().sha512t24u().to_key())
1702                .collect(),
1703            None => Vec::new(),
1704        }
1705    }
1706
1707    /// Sequence digests still referenced by some OTHER collection.
1708    ///
1709    /// Disk-backed stores derive this from disk. Only a pure in-memory store
1710    /// (`local_path == None`) falls back to the loaded collection members:
1711    /// there, the in-memory catalog is all there is, so it is authoritative.
1712    fn live_sequence_set(&self, exclude: &DigestKey) -> Result<HashSet<DigestKey>> {
1713        if self.local_path.is_some() {
1714            return self.live_sequence_digests_from_disk(exclude);
1715        }
1716        let mut live = HashSet::new();
1717        for c in self.catalog.coll_rows() {
1718            if self.catalog.coll_meta(c).digest.to_key() == *exclude {
1719                continue;
1720            }
1721            live.extend(self.catalog.members(c).map(|m| m.seq().sha512t24u().to_key()));
1722        }
1723        Ok(live)
1724    }
1725
1726    /// Remove a collection from the store.
1727    ///
1728    /// When `remove_orphan_sequences` is true, the orphan-cleanup path is
1729    /// O(sequences + collections): each orphan is one catalog lookup, never a
1730    /// scan. Do not reintroduce a per-orphan scan here; on large stores that is
1731    /// quadratic and effectively unbounded.
1732    ///
1733    /// The live set is derived from DISK, not from the loaded members; see
1734    /// [`Self::live_sequence_digests_from_disk`] for why that distinction is the
1735    /// difference between a GC and a data-loss bug.
1736    ///
1737    /// # The lock is held across the orphan scan, deliberately
1738    ///
1739    /// The scan is the expensive part — on the plantref store (147 collections,
1740    /// ~1.5M sequence digests) it reads every `collections/*.rgsi` and takes
1741    /// roughly a minute. Everywhere else in this module the rule is "do the
1742    /// expensive work outside the lock"; here that rule is wrong. Computing the
1743    /// live set before taking the lock leaves a window in which another writer
1744    /// commits a collection referencing one of the digests the scan just
1745    /// classified as an orphan, and the unlink that follows deletes live data.
1746    /// Removals are rare and hand-run, so blocking concurrent builds for a
1747    /// minute is the cheap side of that trade.
1748    pub fn remove_collection(
1749        &mut self,
1750        digest: &str,
1751        remove_orphan_sequences: bool,
1752    ) -> Result<bool> {
1753        let key = digest.to_key();
1754
1755        if self.catalog.find_coll(digest).is_none() {
1756            return Ok(false);
1757        }
1758
1759        // Take the lock BEFORE the orphan scan and hold it through the scan, the
1760        // index commit, and the unlinks. All three have to see the same store: a
1761        // collection another writer adds in between would make an "orphan" live
1762        // again, and we would unlink it anyway. The nested `write_index_files`
1763        // sees the guard and does not re-acquire.
1764        let acquired = self.acquire_commit_lock("remove_collection")?;
1765        let restore = match acquired {
1766            Some(lock) => {
1767                let previous = self.commit_lock.replace(Arc::new(lock));
1768                Some(previous)
1769            }
1770            // Already inside a caller's `lock_for_batch`; leave it alone.
1771            None => None,
1772        };
1773
1774        let result = self.remove_collection_locked(digest, key, remove_orphan_sequences);
1775
1776        if let Some(previous) = restore {
1777            self.commit_lock = previous;
1778        }
1779        result
1780    }
1781
1782    fn remove_collection_locked(
1783        &mut self,
1784        digest: &str,
1785        key: DigestKey,
1786        remove_orphan_sequences: bool,
1787    ) -> Result<bool> {
1788        // Compute both sets BEFORE mutating anything: the candidates come from
1789        // the collection's own `.rgsi`, which the cleanup below unlinks.
1790        let orphan_candidates: Vec<DigestKey> = if remove_orphan_sequences {
1791            self.orphan_candidates(digest)?
1792        } else {
1793            Vec::new()
1794        };
1795        let still_referenced: HashSet<DigestKey> = if remove_orphan_sequences {
1796            self.live_sequence_set(&key)?
1797        } else {
1798            HashSet::new()
1799        };
1800
1801        if let Some(c) = self.catalog.find_coll(digest) {
1802            self.catalog.remove_collection(c);
1803        }
1804        self.fhr_metadata.remove(&key);
1805        self.record(|p| p.remove_collection(key));
1806
1807        // Remove collection aliases pointing to this digest. The in-memory
1808        // alias table is an open-time snapshot; an alias another process
1809        // published for this collection since then is only on disk, and
1810        // leaving it behind makes it resolve to nothing. Under the lock, also
1811        // scan the published TSVs for every entry targeting this digest.
1812        let mut alias_pairs = self.aliases.reverse_lookup_collection(digest);
1813        if self.persist_to_disk {
1814            if let Some(local_path) = &self.local_path {
1815                let dir = local_path.join("aliases").join(AliasKind::Collection.subdir());
1816                if let Ok(entries) = fs::read_dir(&dir) {
1817                    for entry in entries.filter_map(|e| e.ok()) {
1818                        let path = entry.path();
1819                        if path.extension().map_or(true, |e| e != "tsv") {
1820                            continue;
1821                        }
1822                        let Some(ns) = path.file_stem().and_then(|s| s.to_str()) else {
1823                            continue;
1824                        };
1825                        for (alias, target) in super::persistence::read_alias_tsv(&path)? {
1826                            if target == key {
1827                                alias_pairs.push((ns.to_string(), alias));
1828                            }
1829                        }
1830                    }
1831                }
1832            }
1833        }
1834        alias_pairs.sort();
1835        alias_pairs.dedup();
1836        let affected_namespaces: HashSet<String> = alias_pairs
1837            .iter()
1838            .map(|(ns, _)| ns.clone())
1839            .collect();
1840        for (ns, alias) in &alias_pairs {
1841            self.aliases.remove_collection(ns, alias);
1842            self.record_alias_removal(AliasKind::Collection, ns, alias);
1843        }
1844        for ns in &affected_namespaces {
1845            self.persist_alias_namespace(AliasKind::Collection, ns)?;
1846        }
1847
1848        // Which sequences to unlink, decided under the lock from the live set
1849        // computed under the same lock. A sequence that a loaded collection
1850        // still uses is kept even when the on-disk index does not list that
1851        // collection: the removed collection's members are already dropped
1852        // above, so any remaining reference comes from another collection.
1853        let orphans: Vec<DigestKey> = if remove_orphan_sequences {
1854            orphan_candidates
1855                .into_iter()
1856                .filter(|k| !still_referenced.contains(k))
1857                .filter(|k| {
1858                    self.catalog
1859                        .find_sha(key_to_digest_string(k))
1860                        .is_none_or(|r| self.catalog.seq_refcount(r) == 0)
1861                })
1862                .collect()
1863        } else {
1864            Vec::new()
1865        };
1866
1867        if !orphans.is_empty() {
1868            {
1869                let mut pending = self.pending.lock().unwrap();
1870                for orphan_key in &orphans {
1871                    pending.remove_sequence(*orphan_key);
1872                }
1873            }
1874
1875            let rows: Vec<SeqRow> = orphans
1876                .iter()
1877                .filter_map(|k| self.catalog.find_sha(key_to_digest_string(k)))
1878                .collect();
1879            self.remove_sequence_rows(&rows);
1880        }
1881        self.maybe_compact_catalog();
1882
1883        // INDEX FIRST, FILES SECOND. Both orderings can be interrupted by a
1884        // crash; only one of the two resulting states is recoverable. Rows gone,
1885        // files present is garbage on disk that a later GC can reclaim. Rows
1886        // present, files gone is a store that lies: `get_substring` raises,
1887        // `get_collection` cannot open its sequences, and an alias resolves to a
1888        // collection that no longer exists.
1889        if self.persist_to_disk {
1890            // The packs the sidecar lists before this commit, read under the
1891            // lock this removal holds: the only packs it may unlink.
1892            let packs_before = match (&self.local_path, self.layout) {
1893                (Some(local_path), Layout::Packed) => Self::sidecar_pack_names(local_path)?,
1894                _ => HashSet::new(),
1895            };
1896            self.write_index_files()?;
1897
1898            if self.layout == Layout::Packed {
1899                // Packed: no per-`.seq` unlink. Orphan rows were already dropped
1900                // from the sidecar by the commit above; here we eagerly unlink
1901                // any listed pack that no live sidecar row references any more.
1902                if let Some(local_path) = self.local_path.clone() {
1903                    self.remove_fully_dead_packs(&local_path, &packs_before)?;
1904                }
1905            } else {
1906                self.remove_seq_files(&orphans);
1907            }
1908
1909            if let Some(local_path) = &self.local_path {
1910                let rgsi_path = local_path.join(format!("collections/{}.rgsi", digest));
1911                let _ = fs::remove_file(&rgsi_path);
1912                let fhr_path = local_path.join(format!("fhr/{}.fhr.json", digest));
1913                let _ = fs::remove_file(&fhr_path);
1914            }
1915        }
1916
1917        Ok(true)
1918    }
1919
1920    /// Remove every sequence this handle staged (and its `.seq` file on disk)
1921    /// that no collection in the catalog references.
1922    ///
1923    /// Used as a best-effort cleanup after a failed import:
1924    /// [`add_sequence_collections_from_fastas`](Self::add_sequence_collections_from_fastas)
1925    /// may have inserted sequences for a partially-built collection that never
1926    /// received an `End` message (and was therefore never registered). Those
1927    /// sequences are orphans, with no owning collection, and this method
1928    /// removes them so the store stays internally consistent. The operation is
1929    /// O(sequences + collections): each orphan is one catalog lookup.
1930    ///
1931    /// Sequences shared with a successfully-finalized collection are preserved.
1932    ///
1933    /// Only sequences THIS import staged (still pending, never committed) are
1934    /// candidates. Anything already in the on-disk index is out of bounds:
1935    /// `open_local` loads every sequence row but no collection members, so
1936    /// "a sequence no loaded collection references" describes the entire
1937    /// pre-existing store, not an orphan. Deriving candidates from that would
1938    /// unlink every published `.seq` file after one failed import into a
1939    /// reopened store.
1940    #[cfg_attr(not(feature = "filesystem"), allow(dead_code))]
1941    pub(crate) fn remove_orphan_seq_files(&mut self) {
1942        // Build the set of all sequence digest keys that are referenced by at
1943        // least one surviving (finalized) collection.
1944        let mut referenced: std::collections::HashSet<DigestKey> =
1945            std::collections::HashSet::new();
1946        for c in self.catalog.coll_rows() {
1947            referenced.extend(self.catalog.members(c).map(|m| m.seq().sha512t24u().to_key()));
1948        }
1949
1950        // Candidates: staged by this handle and not yet published.
1951        let staged: Vec<DigestKey> = self
1952            .pending
1953            .lock()
1954            .unwrap()
1955            .sequences
1956            .iter()
1957            .copied()
1958            .collect();
1959
1960        // Collect the orphan keys (staged but not referenced).
1961        let orphans: Vec<DigestKey> = staged
1962            .into_iter()
1963            .filter(|k| !referenced.contains(k))
1964            .collect();
1965
1966        if orphans.is_empty() {
1967            return;
1968        }
1969
1970        // Remove from in-memory structures.
1971        let rows: Vec<SeqRow> = orphans
1972            .iter()
1973            .filter_map(|k| self.catalog.find_sha(key_to_digest_string(k)))
1974            .collect();
1975        self.remove_sequence_rows(&rows);
1976        let orphan_set: std::collections::HashSet<DigestKey> = orphans.iter().copied().collect();
1977
1978        // FORGET these, do not tombstone them. They were staged by an import
1979        // that failed before its single commit, so no row of ours was ever
1980        // published; recording a removal would delete the identical row a
1981        // different writer legitimately published, since sequence rows are
1982        // content-addressed and therefore shared between collections.
1983        self.record(|p| p.forget_sequences(&orphan_set));
1984        self.forget_staged_aliases(AliasKind::Sequence, &orphan_set);
1985
1986        // Best-effort remove on-disk `.seq` files.
1987        if self.persist_to_disk {
1988            self.remove_seq_files(&orphans);
1989        }
1990    }
1991
1992    /// Best-effort unlink of the standalone `.seq` files of `keys`, then of
1993    /// each shard directory they leave empty.
1994    ///
1995    /// Collect parent shard dirs while unlinking, then rmdir them ONCE at the
1996    /// end. Do NOT move the rmdir back into the loop: `.seq` files are sharded
1997    /// over ~4096 two-char prefix dirs, so a per-file rmdir issues N syscalls
1998    /// (nearly all failing with ENOTEMPTY) to remove at most ~4096 dirs,
1999    /// roughly doubling the syscall count in a loop that is filesystem-metadata
2000    /// bound. The rmdir pass must run AFTER all unlinks, or dirs that only
2001    /// become empty later would be skipped.
2002    fn remove_seq_files(&self, keys: &[DigestKey]) {
2003        let (Some(local_path), Some(template)) = (&self.local_path, &self.seqdata_path_template)
2004        else {
2005            return;
2006        };
2007        let mut parent_dirs: HashSet<PathBuf> = HashSet::new();
2008        for key in keys {
2009            let full = local_path.join(Self::expand_template(&key_to_digest_string(key), template));
2010            let _ = fs::remove_file(&full);
2011            if let Some(parent) = full.parent() {
2012                parent_dirs.insert(parent.to_path_buf());
2013            }
2014        }
2015        for parent in &parent_dirs {
2016            let _ = fs::remove_dir(parent); // ignore if non-empty
2017        }
2018    }
2019
2020    /// Drop every collection this handle staged that has a member in `seqs`,
2021    /// with the collection aliases staged for it, without recording a removal.
2022    ///
2023    /// Used after a failed import for sequences whose bytes never reached disk
2024    /// (no sealed pack, or no `.seq` file): a collection that names them cannot
2025    /// be committed.
2026    /// [`Self::remove_orphan_seq_files`] then drops the sequences themselves.
2027    #[cfg_attr(not(feature = "filesystem"), allow(dead_code))]
2028    pub(crate) fn forget_collections_using(&mut self, seqs: &HashSet<DigestKey>) {
2029        let staged = self.pending.lock().unwrap().collections.clone();
2030        let doomed: Vec<CollRow> = self
2031            .catalog
2032            .coll_rows()
2033            .filter(|&c| staged.contains(&self.catalog.coll_meta(c).digest.to_key()))
2034            .filter(|&c| {
2035                self.catalog
2036                    .members(c)
2037                    .any(|m| seqs.contains(&m.seq().sha512t24u().to_key()))
2038            })
2039            .collect();
2040        let keys: HashSet<DigestKey> = doomed
2041            .iter()
2042            .map(|&c| self.catalog.coll_meta(c).digest.to_key())
2043            .collect();
2044        for c in doomed {
2045            self.catalog.remove_collection(c);
2046        }
2047        self.pending
2048            .lock()
2049            .unwrap()
2050            .collections
2051            .retain(|k| !keys.contains(k));
2052        self.forget_staged_aliases(AliasKind::Collection, &keys);
2053
2054        // Each collection's `.rgsi` was written when it finalized. Remove it
2055        // unless the published index lists the collection (another writer
2056        // committed the same one): a store whose index lists no collections
2057        // loads them from `collections/` on open.
2058        if let (true, Some(local_path)) = (self.persist_to_disk, &self.local_path) {
2059            let index = local_path.join("collections.rgci");
2060            if let Ok(published) = super::persistence::read_collections_rgci_rows(&index) {
2061                for key in keys.iter().filter(|k| !published.contains_key(*k)) {
2062                    let rgsi = format!("collections/{}.rgsi", key_to_digest_string(key));
2063                    let _ = fs::remove_file(local_path.join(rgsi));
2064                }
2065            }
2066        }
2067    }
2068
2069    /// Unbind the aliases of `kind` this handle staged but never published whose
2070    /// target is in `targets`, without recording a removal.
2071    fn forget_staged_aliases(&mut self, kind: AliasKind, targets: &HashSet<DigestKey>) {
2072        let mut pending = self.pending.lock().unwrap();
2073        let doomed: Vec<(AliasKind, String, String)> = pending
2074            .aliases
2075            .iter()
2076            .filter(|(k, ns, alias)| {
2077                *k == kind
2078                    && match kind {
2079                        AliasKind::Sequence => self.aliases.resolve_sequence(ns, alias),
2080                        AliasKind::Collection => self.aliases.resolve_collection(ns, alias),
2081                    }
2082                    .is_some_and(|t| targets.contains(&t))
2083            })
2084            .cloned()
2085            .collect();
2086        for entry in doomed {
2087            match kind {
2088                AliasKind::Sequence => self.aliases.remove_sequence(&entry.1, &entry.2),
2089                AliasKind::Collection => self.aliases.remove_collection(&entry.1, &entry.2),
2090            };
2091            pending.forced_aliases.remove(&entry);
2092            pending.aliases.remove(&entry);
2093        }
2094    }
2095
2096    // =========================================================================
2097    // Import from another store
2098    // =========================================================================
2099
2100    /// Import a single collection (with all its sequences, aliases, and FHR
2101    /// metadata) from another store into this store.
2102    ///
2103    /// Both stores must be disk-backed with matching storage modes.
2104    /// The source store must have the collection loaded (call
2105    /// `load_collection()` or `load_all_collections()` first).
2106    pub fn import_collection(&mut self, source: &ReadonlyRefgetStore, digest: &str) -> Result<()> {
2107        // Store-to-store copy does not handle packed stores.
2108        if self.layout == Layout::Packed || source.layout == Layout::Packed {
2109            return Err(anyhow!(
2110                "import_collection does not support packed stores: copying a \
2111                 collection into or out of a packed store is not implemented. \
2112                 Export it to FASTA and import that instead."
2113            ));
2114        }
2115        // Both stores must be disk-backed with same mode
2116        if source.local_path.is_none() || self.local_path.is_none() || !self.persist_to_disk {
2117            return Err(anyhow!("import_collection requires both stores to be disk-backed"));
2118        }
2119        if source.mode != self.mode {
2120            return Err(anyhow!(
2121                "import_collection requires matching storage modes (source={:?}, dest={:?})",
2122                source.mode,
2123                self.mode,
2124            ));
2125        }
2126
2127        self.import_collection_file_copy(source, digest)?;
2128
2129        // Copy sequence aliases for every sequence in the imported collection
2130        for seq_key in source.loaded_member_seq_keys(digest) {
2131            let seq_digest = key_to_digest_string(&seq_key);
2132            for (ns, alias) in source.aliases.reverse_lookup_sequence(&seq_digest) {
2133                self.add_sequence_alias(&ns, &alias, &seq_digest)?;
2134            }
2135        }
2136
2137        // Copy collection aliases
2138        for (ns, alias) in source.aliases.reverse_lookup_collection(digest) {
2139            self.add_collection_alias(&ns, &alias, digest)?;
2140        }
2141
2142        // Copy FHR metadata
2143        if let Some(fhr) = source.get_fhr_metadata(digest) {
2144            self.set_fhr_metadata(digest, fhr.clone())?;
2145        }
2146
2147        Ok(())
2148    }
2149
2150    /// File-copy based import: copies RGSI and .seq files directly from
2151    /// source to destination, then registers the collection in memory.
2152    fn import_collection_file_copy(
2153        &mut self,
2154        source: &ReadonlyRefgetStore,
2155        digest: &str,
2156    ) -> Result<()> {
2157        use crate::collection::read_rgsi_file;
2158
2159        // 1. Read the source RGSI file to get collection metadata
2160        let src_rgsi_path = source
2161            .collection_file_path(digest)
2162            .ok_or_else(|| anyhow!("Source store has no local path for collection {}", digest))?;
2163        let collection = read_rgsi_file(&src_rgsi_path)
2164            .with_context(|| format!("Failed to read source RGSI file: {}", src_rgsi_path.display()))?;
2165
2166        let mut metadata = collection.metadata.clone();
2167
2168        // 2. Handle ancillary digests and copy/write the RGSI file
2169        let dst_rgsi_path = self
2170            .collection_file_path(digest)
2171            .ok_or_else(|| anyhow!("Dest store has no local path for collection {}", digest))?;
2172        if let Some(parent) = dst_rgsi_path.parent() {
2173            create_dir_all(parent)?;
2174        }
2175
2176        let needs_ancillary_rewrite = self.ancillary_digests
2177            && metadata.name_length_pairs_digest.is_none();
2178
2179        if needs_ancillary_rewrite {
2180            // Source lacks ancillary digests but destination wants them --
2181            // compute them and write a new RGSI file.
2182            metadata.compute_ancillary_digests(&collection.sequences);
2183            crate::collection::write_collection_rgsi_rows(
2184                &dst_rgsi_path,
2185                &metadata,
2186                collection.sequences.iter().map(|s| s.metadata()),
2187            )?;
2188        } else {
2189            // Byte-for-byte copy of the RGSI file
2190            fs::copy(&src_rgsi_path, &dst_rgsi_path)
2191                .with_context(|| format!(
2192                    "Failed to copy RGSI {} -> {}",
2193                    src_rgsi_path.display(),
2194                    dst_rgsi_path.display(),
2195                ))?;
2196        }
2197
2198        // 3. Copy sequence data files
2199        for seq_record in &collection.sequences {
2200            let seq_meta = seq_record.metadata();
2201            let seq_digest = &seq_meta.sha512t24u;
2202
2203            let src_seq_path = source
2204                .sequence_file_path(seq_digest)
2205                .ok_or_else(|| anyhow!("Source has no path for sequence {}", seq_digest))?;
2206            let dst_seq_path = self
2207                .sequence_file_path(seq_digest)
2208                .ok_or_else(|| anyhow!("Dest has no path for sequence {}", seq_digest))?;
2209
2210            // Skip if destination already has this sequence (dedup across collections)
2211            if dst_seq_path.exists() {
2212                // Still need to register in memory below
2213            } else {
2214                if let Some(parent) = dst_seq_path.parent() {
2215                    create_dir_all(parent)?;
2216                }
2217                fs::copy(&src_seq_path, &dst_seq_path).with_context(|| {
2218                    format!(
2219                        "Failed to copy sequence {} -> {}",
2220                        src_seq_path.display(),
2221                        dst_seq_path.display(),
2222                    )
2223                })?;
2224            }
2225        }
2226
2227        // 4. Register in memory (sequences deduped against the catalog).
2228        let coll_key = digest.to_key();
2229        let members: Vec<SequenceMetadata> =
2230            collection.sequences.iter().map(|s| s.metadata().clone()).collect();
2231        let (_, new_rows) = self.insert_collection(metadata.clone(), &members)?;
2232        self.record(|p| p.add_collection(coll_key));
2233        for row in new_rows {
2234            let seq_key = self.catalog.seq(row).sha512t24u().to_key();
2235            self.record(|p| p.add_sequence(seq_key));
2236        }
2237
2238        // 5. Update index files
2239        self.write_index_files()?;
2240
2241        Ok(())
2242    }
2243
2244    // =========================================================================
2245    // Sequence API
2246    // =========================================================================
2247
2248    /// List all sequences in the store (metadata only, no sequence data).
2249    pub fn list_sequences(&self) -> Vec<SequenceMetadata> {
2250        let mut result: Vec<_> = self.sequence_metadata().collect();
2251        result.sort_by(|a, b| a.sha512t24u.cmp(&b.sha512t24u));
2252        result
2253    }
2254
2255    /// Get metadata for a single sequence by digest (no sequence data).
2256    /// Accepts sha512t24u (bare or `SQ.`-prefixed) or MD5.
2257    pub fn get_sequence_metadata<K: AsRef<[u8]>>(
2258        &self,
2259        seq_digest: K,
2260    ) -> Option<SequenceMetadata> {
2261        self.sequence_view(seq_digest).map(|v| v.to_metadata())
2262    }
2263
2264    /// Get a sequence by its SHA512t24u (or MD5) digest. Bytes, if loaded, are
2265    /// shared (`Arc`), not copied.
2266    pub fn get_sequence<K: AsRef<[u8]>>(&self, seq_digest: K) -> Result<SequenceRecord> {
2267        let row = self.seq_row(seq_digest.as_ref()).ok_or_else(|| {
2268            anyhow!(
2269                "Sequence not found: {}",
2270                String::from_utf8_lossy(seq_digest.as_ref())
2271            )
2272        })?;
2273        Ok(self.seq_record(row))
2274    }
2275
2276    /// Clear sequence data from the store to free memory.
2277    ///
2278    /// Drops every sequence's loaded bytes. Metadata is preserved: sequences,
2279    /// collections, name lookups, MD5 lookups, aliases, and FHR metadata
2280    /// remain intact.
2281    ///
2282    /// For on-disk stores, data on disk is unaffected.
2283    pub fn clear(&mut self) {
2284        self.loaded.clear();
2285        if let Ok(mut cache) = self.seq_fd_cache.lock() {
2286            cache.entries.clear();
2287        }
2288    }
2289
2290    /// Check whether a sequence's bytes are loaded (owned by the store) rather
2291    /// than metadata only.
2292    pub fn is_sequence_loaded<K: AsRef<[u8]>>(&self, seq_digest: K) -> bool {
2293        self.seq_row(seq_digest)
2294            .is_some_and(|r| self.loaded.contains_key(&r))
2295    }
2296
2297    /// Get a sequence by collection digest and name.
2298    ///
2299    /// The returned record carries THIS collection's name and description for
2300    /// the sequence, not the first-imported label of a sequence shared across
2301    /// collections. Bytes (and `fai`, if the member lacks it) come from the
2302    /// sequence row; the bytes are an `Arc` bump, not a copy.
2303    pub fn get_sequence_by_name<K: AsRef<[u8]>>(
2304        &self,
2305        collection_digest: K,
2306        sequence_name: &str,
2307    ) -> Result<SequenceRecord> {
2308        let m = self.member_by_name(collection_digest, sequence_name)?;
2309        Ok(self.member_record(m))
2310    }
2311
2312    /// The member of a loaded collection named `sequence_name`.
2313    pub fn member_by_name<K: AsRef<[u8]>>(
2314        &self,
2315        collection_digest: K,
2316        sequence_name: &str,
2317    ) -> Result<MemberView<'_>> {
2318        let c = self.loaded_coll_row(collection_digest)?;
2319        self.catalog
2320            .member_by_name(c, sequence_name)
2321            .ok_or_else(|| anyhow!("Sequence '{}' not found in collection", sequence_name))
2322    }
2323
2324    // =========================================================================
2325    // Loading methods
2326    // =========================================================================
2327
2328    /// Ensure the sequence index (sequences.rgsi) is loaded.
2329    /// For remote stores this is deferred until first sequence access.
2330    /// Returns Ok(()) immediately if already loaded.
2331    pub(crate) fn ensure_sequence_index_loaded(&mut self) -> Result<()> {
2332        if self.sequence_index_loaded {
2333            return Ok(());
2334        }
2335
2336        let seq_index_path = self.sequence_index_path.clone()
2337            .ok_or_else(|| anyhow!("No sequence_index_path set for deferred loading"))?;
2338
2339        if !self.quiet {
2340            eprintln!("Downloading sequence index {}...", seq_index_path);
2341        }
2342
2343        let data = Self::fetch_file(
2344            &self.local_path,
2345            &self.remote_source,
2346            &seq_index_path,
2347            true,
2348            false,
2349        )?;
2350        let data_str = String::from_utf8(data)
2351            .context("sequence index contains invalid UTF-8")?;
2352
2353        Self::load_sequences_from_reader(self, data_str.as_bytes())?;
2354        self.sequence_index_loaded = true;
2355        Ok(())
2356    }
2357
2358    /// Explicitly load the sequence index. For servers that want to preload
2359    /// all data during startup before converting to `ReadonlyRefgetStore`.
2360    pub fn load_sequence_index(&mut self) -> Result<()> {
2361        self.ensure_sequence_index_loaded()
2362    }
2363
2364    /// Load the member lists of all collections.
2365    pub fn load_all_collections(&mut self) -> Result<()> {
2366        let digests: Vec<String> = self
2367            .catalog
2368            .coll_rows()
2369            .map(|c| self.catalog.coll_meta(c).digest.clone())
2370            .collect();
2371        for d in digests {
2372            self.ensure_collection_loaded(&d)?;
2373        }
2374        self.catalog.shrink_to_fit();
2375        Ok(())
2376    }
2377
2378    /// Eagerly load the bytes of every sequence.
2379    pub fn load_all_sequences(&mut self) -> Result<()> {
2380        let rows: Vec<SeqRow> = self.catalog.seq_rows().collect();
2381        for row in rows {
2382            self.ensure_sequence_loaded(row)?;
2383        }
2384        Ok(())
2385    }
2386
2387    /// Load a single collection by digest.
2388    pub fn load_collection(&mut self, digest: &str) -> Result<()> {
2389        self.ensure_collection_loaded(digest)
2390    }
2391
2392    /// Load a single sequence by digest.
2393    pub fn load_sequence(&mut self, digest: &str) -> Result<()> {
2394        let row = self
2395            .seq_row(digest)
2396            .ok_or_else(|| anyhow!("Sequence not found in store"))?;
2397        self.ensure_sequence_loaded(row)
2398    }
2399
2400    // =========================================================================
2401    // Resident overlay (&self): promote whole `.seq` files to RAM without &mut
2402    // =========================================================================
2403
2404    /// Promote a set of sequences to the `&self` resident overlay, reading each
2405    /// whole `.seq` file into RAM as its raw on-disk (packed) bytes.
2406    ///
2407    /// Unlike [`load_sequence`](Self::load_sequence) / [`load_all_sequences`](
2408    /// Self::load_all_sequences) — which take `&mut self` and are therefore
2409    /// unusable once the store is wrapped in an `Arc` — this takes `&self` and
2410    /// stores into an `RwLock`-guarded overlay consulted by `get_substring` /
2411    /// `get_substrings` before the on-disk partial-read path.
2412    ///
2413    /// The loads are made cheap and predictable: digests are deduped (md5 aliases
2414    /// resolved), any already loaded or already resident are skipped, and the rest
2415    /// are **sorted by `.seq` path** so the reads walk the sequence directory in
2416    /// order rather than in `HashMap` hash order (the pathology of
2417    /// [`load_all_sequences`](Self::load_all_sequences)). Each file is one
2418    /// `File::open` + `read_to_end` (a few large sequential reads), not a scatter
2419    /// of positioned reads.
2420    ///
2421    /// Returns the number of bytes newly loaded into the overlay by this call
2422    /// (already resident or loaded skips contribute 0), for RAM-budget accounting.
2423    pub fn load_resident(&self, digests: &[String]) -> Result<u64> {
2424        let template = self.seqdata_path_template.as_ref().ok_or_else(|| {
2425            anyhow!("Resident load requires a sequence data path template")
2426        })?;
2427
2428        // Plan: resolve to canonical keys, skip loaded / already-resident, dedupe.
2429        let mut plan: Vec<(SeqRow, String)> = Vec::new();
2430        let mut seen: HashSet<SeqRow> = HashSet::new();
2431        {
2432            let resident = self
2433                .resident
2434                .read()
2435                .map_err(|_| anyhow!("resident overlay lock poisoned"))?;
2436            for d in digests {
2437                match self.seq_row(d) {
2438                    Some(key) if !seen.insert(key) => continue, // duplicate in this request
2439                    Some(key) if resident.contains_key(&key) => continue, // already resident
2440                    Some(key) if self.loaded.contains_key(&key) => continue, // already loaded
2441                    Some(key) => {
2442                        let digest_str = self.catalog.seq(key).sha512t24u();
2443                        let relpath = Self::expand_template(&digest_str, template)
2444                            .to_string_lossy()
2445                            .into_owned();
2446                        plan.push((key, relpath));
2447                    }
2448                    None => {
2449                        return Err(anyhow!(
2450                            "Cannot load resident: sequence not found: {}",
2451                            d
2452                        ));
2453                    }
2454                }
2455            }
2456        }
2457
2458        // Ordered, coalesced whole-file reads: sort by on-disk path so the
2459        // directory is walked in order, not in hash order.
2460        plan.sort_by(|a, b| a.1.cmp(&b.1));
2461
2462        let mut loaded: Vec<(SeqRow, Arc<Vec<u8>>)> = Vec::with_capacity(plan.len());
2463        let mut total: u64 = 0;
2464        for (key, _) in plan {
2465            let data = self.read_stored_bytes(key, self.persist_to_disk)?;
2466            total += data.len() as u64;
2467            loaded.push((key, data));
2468        }
2469
2470        // Publish into the overlay under a single write lock.
2471        {
2472            let mut resident = self
2473                .resident
2474                .write()
2475                .map_err(|_| anyhow!("resident overlay lock poisoned"))?;
2476            for (key, arc) in loaded {
2477                resident.insert(key, arc);
2478            }
2479        }
2480
2481        Ok(total)
2482    }
2483
2484    /// Drop the given digests from the resident overlay. Subsequent queries for
2485    /// them fall back to the on-disk partial-read path. Unknown / non-resident
2486    /// digests are ignored.
2487    pub fn evict_resident(&self, digests: &[String]) {
2488        if let Ok(mut resident) = self.resident.write() {
2489            for d in digests {
2490                if let Some(key) = self.seq_row(d) {
2491                    resident.remove(&key);
2492                }
2493            }
2494        }
2495    }
2496
2497    /// Drop the entire resident overlay.
2498    pub fn evict_all_resident(&self) {
2499        if let Ok(mut resident) = self.resident.write() {
2500            resident.clear();
2501        }
2502    }
2503
2504    /// Total bytes currently held in the resident overlay (sum of the packed
2505    /// `.seq` byte arrays). Used for RAM-budget accounting.
2506    pub fn resident_bytes(&self) -> u64 {
2507        self.resident
2508            .read()
2509            .map(|r| r.values().map(|b| b.len() as u64).sum())
2510            .unwrap_or(0)
2511    }
2512
2513    /// Number of sequences currently resident.
2514    pub fn resident_len(&self) -> usize {
2515        self.resident.read().map(|r| r.len()).unwrap_or(0)
2516    }
2517
2518    /// Estimate, from in-memory metadata only (no I/O), the additional bytes
2519    /// [`load_resident`](Self::load_resident) would pull into RAM for `digests`.
2520    /// Already loaded or already resident digests, and duplicates, contribute 0.
2521    /// Used for RAM-budget planning before committing to a load.
2522    pub fn resident_estimate_bytes(&self, digests: &[String]) -> u64 {
2523        let resident = self.resident.read().ok();
2524        let mut seen: HashSet<SeqRow> = HashSet::new();
2525        let mut total: u64 = 0;
2526        for d in digests {
2527            let Some(key) = self.seq_row(d) else { continue };
2528            if !seen.insert(key) {
2529                continue;
2530            }
2531            if let Some(r) = &resident {
2532                if r.contains_key(&key) {
2533                    continue;
2534                }
2535            }
2536            if self.loaded.contains_key(&key) {
2537                continue;
2538            }
2539            // Zstd: compressed size varies; disk_size uses uncompressed as an
2540            // upper bound.
2541            total += self.catalog.seq(key).disk_size(&self.mode) as u64;
2542        }
2543        total
2544    }
2545
2546    /// Clone the resident packed bytes for `key`, if present. The `Arc` is cloned
2547    /// out under a brief read lock so the lock is released before the caller
2548    /// decodes -- decodes therefore never serialize against each other.
2549    fn resident_lookup(&self, key: SeqRow) -> Option<Arc<Vec<u8>>> {
2550        self.resident.read().ok().and_then(|r| r.get(&key).cloned())
2551    }
2552
2553    /// Decode `[start, end)` from a whole stored sequence buffer (loaded or
2554    /// resident bytes), after the bounds check.
2555    fn decode_full_span(
2556        &self,
2557        metadata: &SeqCore,
2558        sequence: &[u8],
2559        start: usize,
2560        end: usize,
2561    ) -> Result<Vec<u8>> {
2562        check_range(start, end, metadata.length)?;
2563        match self.mode {
2564            StorageMode::Encoded => {
2565                let alphabet = lookup_alphabet(&metadata.alphabet);
2566                Ok(decode_substring_from_bytes(sequence, start, end, alphabet))
2567            }
2568            StorageMode::Raw => Ok(sequence[start..end].to_vec()),
2569            StorageMode::Zstd => {
2570                let ascii = zstd::decode_all(sequence)
2571                    .context("zstd decompression of sequence record failed")?;
2572                Ok(ascii[start..end].to_vec())
2573            }
2574        }
2575    }
2576
2577    /// Iterate over all collections with their sequences loaded.
2578    pub fn iter_collections(&self) -> impl Iterator<Item = crate::digest::SequenceCollection> + '_ {
2579        let mut digests: Vec<String> = self
2580            .catalog
2581            .coll_rows()
2582            .map(|c| self.catalog.coll_meta(c).digest.clone())
2583            .collect();
2584        digests.sort();
2585
2586        digests.into_iter().filter_map(move |digest| {
2587            self.get_collection(&digest).ok()
2588        })
2589    }
2590
2591    /// Iterate over all sequences with their data loaded.
2592    pub fn iter_sequences(&self) -> impl Iterator<Item = SequenceRecord> + '_ {
2593        let mut rows: Vec<SeqRow> = self.catalog.seq_rows().collect();
2594        rows.sort_by_key(|&r| self.catalog.seq(r).sha512t24u());
2595        rows.into_iter().map(move |r| self.seq_record(r))
2596    }
2597
2598    /// Check if a collection is fully loaded.
2599    pub fn is_collection_loaded<K: AsRef<[u8]>>(&self, collection_digest: K) -> bool {
2600        self.catalog
2601            .find_coll(collection_digest)
2602            .is_some_and(|c| self.catalog.is_loaded(c))
2603    }
2604
2605    /// Returns the local path where the store is located (if any)
2606    pub fn local_path(&self) -> Option<&PathBuf> {
2607        self.local_path.as_ref()
2608    }
2609
2610    /// Returns the remote source URL (if any)
2611    pub fn remote_source(&self) -> Option<&str> {
2612        self.remote_source.as_deref()
2613    }
2614
2615    /// Returns the storage mode used by this store
2616    pub fn storage_mode(&self) -> StorageMode {
2617        self.mode
2618    }
2619
2620    /// Returns the physical layout of this store's sequence bytes, fixed when
2621    /// the store was created.
2622    pub fn layout(&self) -> Layout {
2623        self.layout
2624    }
2625
2626    // =========================================================================
2627    // Substring retrieval
2628    // =========================================================================
2629
2630    /// Retrieves a substring from an encoded sequence by its SHA512t24u digest.
2631    ///
2632    /// Thin `String` wrapper over [`get_substring_bytes`](Self::get_substring_bytes);
2633    /// see it for the actual retrieval logic.
2634    pub fn get_substring<K: AsRef<[u8]>>(
2635        &self,
2636        sha512_digest: K,
2637        start: usize,
2638        end: usize,
2639    ) -> Result<String> {
2640        self.get_substring_bytes(sha512_digest, start, end)
2641            .map(decoded_sequence_to_string)
2642    }
2643
2644    /// Retrieves a substring from an encoded sequence by its SHA512t24u digest,
2645    /// as raw bytes rather than a `String`.
2646    pub fn get_substring_bytes<K: AsRef<[u8]>>(
2647        &self,
2648        sha512_digest: K,
2649        start: usize,
2650        end: usize,
2651    ) -> Result<Vec<u8>> {
2652        let actual_key = self.seq_row(sha512_digest.as_ref()).ok_or_else(|| {
2653            anyhow!(
2654                "Sequence not found: {}",
2655                String::from_utf8_lossy(sha512_digest.as_ref())
2656            )
2657        })?;
2658
2659        // Zero-length range: a request for `[start, start)` is a well-formed
2660        // empty interval, so return an empty result instead of erroring. This
2661        // is the natural substring semantics, matches the wasm/JS
2662        // `RemoteRefgetStore.getSubstring` contract, and is what bulk/region
2663        // callers expect for an empty interval. Handling it here, before record
2664        // resolution, means every downstream path (loaded or resident bytes,
2665        // on-disk, remote) agrees without each needing its own guard.
2666        // Inverted ranges are rejected by the bounds checks below.
2667        if start == end {
2668            return Ok(Vec::new());
2669        }
2670
2671        let core = self.catalog.seq(actual_key).core();
2672        // Loaded bytes, or the resident overlay (whole `.seq` promoted to RAM
2673        // via `load_resident`): decode the covering span from memory, with no
2674        // disk read.
2675        if let Some(bytes) = self.loaded_arc(actual_key).or_else(|| self.resident_lookup(actual_key)) {
2676            return self.decode_full_span(&core, &bytes, start, end);
2677        }
2678        // Not in memory: for a disk-backed store, read only the bytes covering
2679        // [start, end) instead of loading the whole sequence into RAM. This is
2680        // the random-access extract path: sparse region extraction touches a
2681        // tiny fraction of each sequence, so a per-query partial read avoids
2682        // the cost of `load_sequence` pulling entire chromosomes into memory.
2683        //
2684        // Local `.seq` (if present) -> remote byte-range (if configured).
2685        // Attempt the disk read directly rather than `path.exists()`-ing
2686        // first: the fd cache already amortizes opens across queries, so a
2687        // pre-check would be a pure-overhead `statx` on the overwhelmingly
2688        // common case (the file exists). A missing local file still falls
2689        // through to the remote fallback rather than erroring, detected from
2690        // the open failing with `NotFound`.
2691        if self.local_path.is_some() && self.seqdata_path_template.is_some() {
2692            match self.get_substring_from_disk(&core, start, end) {
2693                Ok(s) => return Ok(s),
2694                Err(e) if is_missing_seq_file(&e) => {} // fall through to remote below
2695                Err(e) => return Err(e),
2696            }
2697        }
2698        if self.remote_source.is_some() {
2699            return self.get_substring_from_remote(&core, start, end);
2700        }
2701        Err(anyhow!("Sequence data not loaded (stub only)"))
2702    }
2703
2704    /// Batch substring retrieval for many ranges of ONE sequence.
2705    ///
2706    /// Resolves the record once and validates all ranges up front, then:
2707    /// - **Loaded or resident**: decode/slice each range from the bytes in RAM.
2708    /// - **Disk-backed, not loaded**: partial-read each range independently via the
2709    ///   fd-cached [`get_substring_from_disk`](Self::get_substring_from_disk)
2710    ///   path (reads only the bytes covering each range; reuses the open `.seq`
2711    ///   handle across ranges).
2712    ///
2713    /// The main benefit over a loop of [`get_substring`](Self::get_substring) is
2714    /// for FFI callers (e.g. the Python binding): resolving the record once and
2715    /// crossing the boundary once per sequence instead of once per range.
2716    ///
2717    /// A whole-sequence "decode once, slice all" strategy was tried for
2718    /// wide/overlapping range sets but measured *slower* on real chromosome-scale
2719    /// sequences (decoding a 250 Mbp chromosome into one buffer, plus the large
2720    /// allocation, outweighs the avoided re-decode of scattered spans), so the
2721    /// partial path is used uniformly. Callers wanting resident behavior should
2722    /// load the sequence (`load_sequence`) first; the in-memory arm then serves it.
2723    ///
2724    /// Output strings are byte-identical to a loop of
2725    /// [`get_substring`](Self::get_substring).
2726    ///
2727    /// Thin `String` wrapper over
2728    /// [`get_substrings_bytes`](Self::get_substrings_bytes); see it for the
2729    /// actual retrieval logic.
2730    pub fn get_substrings<K: AsRef<[u8]>>(
2731        &self,
2732        sha512_digest: K,
2733        ranges: &[(usize, usize)],
2734    ) -> Result<Vec<String>> {
2735        self.get_substrings_bytes(sha512_digest, ranges).map(|v| {
2736            v.into_iter().map(decoded_sequence_to_string).collect()
2737        })
2738    }
2739
2740    /// Batch substring retrieval for many ranges of ONE sequence, as raw bytes
2741    /// rather than `String`s. See [`get_substrings`](Self::get_substrings) for
2742    /// the full behavior description.
2743    pub fn get_substrings_bytes<K: AsRef<[u8]>>(
2744        &self,
2745        sha512_digest: K,
2746        ranges: &[(usize, usize)],
2747    ) -> Result<Vec<Vec<u8>>> {
2748        let actual_key = self.seq_row(sha512_digest.as_ref()).ok_or_else(|| {
2749            anyhow!(
2750                "Sequence not found: {}",
2751                String::from_utf8_lossy(sha512_digest.as_ref())
2752            )
2753        })?;
2754
2755        let meta = &self.catalog.seq(actual_key).core();
2756        let seq_length = meta.length;
2757
2758        // Validate every range up front (same rule as get_substring). A
2759        // zero-length range (`start == end`) is a valid empty interval that
2760        // yields "" (see get_substring); only an inverted range (`start > end`)
2761        // or an out-of-bounds end is rejected. `start == seq_length` is allowed
2762        // only when it is also an empty range (start == end == seq_length).
2763        for &(start, end) in ranges {
2764            if start != end || end > seq_length {
2765                check_range(start, end, seq_length)?;
2766            }
2767        }
2768
2769        match self.loaded_arc(actual_key).or_else(|| self.resident_lookup(actual_key)) {
2770            // Loaded bytes, or the resident overlay (whole `.seq` promoted to
2771            // RAM via `load_resident`): decode every range from memory.
2772            Some(sequence) => {
2773                let seq: &[u8] = sequence.as_slice();
2774                let mut out = Vec::with_capacity(ranges.len());
2775                match self.mode {
2776                    StorageMode::Encoded => {
2777                        let alphabet = lookup_alphabet(&meta.alphabet);
2778                        for &(start, end) in ranges {
2779                            out.push(decode_substring_from_bytes(seq, start, end, alphabet));
2780                        }
2781                    }
2782                    StorageMode::Raw => {
2783                        for &(start, end) in ranges {
2784                            out.push(seq[start..end].to_vec());
2785                        }
2786                    }
2787                    StorageMode::Zstd => {
2788                        // Decompress the whole record once, slice every range.
2789                        let ascii = zstd::decode_all(seq)
2790                            .context("zstd decompression of sequence record failed")?;
2791                        for &(start, end) in ranges {
2792                            out.push(ascii[start..end].to_vec());
2793                        }
2794                    }
2795                }
2796                Ok(out)
2797            }
2798            None => {
2799                // Resolve once for the whole batch: local `.seq` (if present) ->
2800                // remote byte-range (if configured). Whether the local file
2801                // exists is determined lazily below from an actual open/read
2802                // attempt rather than a `path.exists()` stat here -- the fd
2803                // cache already amortizes opens, so pre-checking existence is
2804                // pure overhead on the common (file present) case. A missing
2805                // local file still falls through to the remote fallback rather
2806                // than erroring.
2807                let has_local_path = self.local_path.is_some() && self.seqdata_path_template.is_some();
2808                let has_remote = self.remote_source.is_some();
2809                if !has_local_path && !has_remote {
2810                    return Err(anyhow!("Sequence data not loaded (stub only)"));
2811                }
2812
2813                // No remote fallback configured: there is nothing to branch on,
2814                // so read every range straight from disk without ever stat-ing
2815                // for existence -- an open failure has nowhere else to fall
2816                // back to anyway and simply propagates. This is the common path
2817                // for local (non-remote) batch extraction.
2818                if !has_remote {
2819                    let mut out = Vec::with_capacity(ranges.len());
2820                    for &(start, end) in ranges {
2821                        if start == end {
2822                            out.push(Vec::new());
2823                        } else {
2824                            out.push(self.get_substring_from_disk(meta, start, end)?);
2825                        }
2826                    }
2827                    return Ok(out);
2828                }
2829
2830                // A remote fallback exists, so we do need to know up front
2831                // whether the file is already cached locally in order to pick
2832                // between the on-disk and (possibly bulk-downloaded) remote
2833                // path below. This stat is paid once per batch call for this
2834                // sequence, not once per range.
2835                let local_seq_exists = has_local_path
2836                    && self
2837                        .sequence_file_path(&meta.sha512t24u)
2838                        .map(|p| p.exists())
2839                        .unwrap_or(false);
2840
2841                // Bulk remote extraction: one HTTP round-trip per range is slow
2842                // for large batches. Past REMOTE_BULK_FETCH_THRESHOLD, fetch the
2843                // whole stored record once, from the remote `.seq` or its span
2844                // in a remote pack, and cache it as a local `.seq` (needs a
2845                // local cache dir + path template to write into), then read
2846                // every range from that file. Single / small-batch reads fall
2847                // through to pure byte-range.
2848                if !local_seq_exists
2849                    && self.local_path.is_some()
2850                    && self.seqdata_path_template.is_some()
2851                    && ranges.len() >= REMOTE_BULK_FETCH_THRESHOLD
2852                {
2853                    self.read_stored_bytes(actual_key, true)?;
2854                    let mut out = Vec::with_capacity(ranges.len());
2855                    for &(start, end) in ranges {
2856                        // Zero-length range -> "" (see get_substring). Short-circuit
2857                        // before the partial-read path, which rejects start == end.
2858                        if start == end {
2859                            out.push(Vec::new());
2860                        } else {
2861                            out.push(self.get_substring_from_disk(meta, start, end)?);
2862                        }
2863                    }
2864                    return Ok(out);
2865                }
2866
2867                let mut out = Vec::with_capacity(ranges.len());
2868                for &(start, end) in ranges {
2869                    // Zero-length range -> "" (see get_substring). Short-circuit
2870                    // before the partial-read paths, which reject start == end.
2871                    if start == end {
2872                        out.push(Vec::new());
2873                    } else if local_seq_exists {
2874                        out.push(self.get_substring_from_disk(meta, start, end)?);
2875                    } else {
2876                        out.push(self.get_substring_from_remote(meta, start, end)?);
2877                    }
2878                }
2879                Ok(out)
2880            }
2881        }
2882    }
2883
2884    /// Read a substring directly from the on-disk `.seq` file, fetching only the
2885    /// bytes that cover `[start, end)`.
2886    ///
2887    /// `.seq` files are headerless raw byte arrays (bit-packed in Encoded mode,
2888    /// one ASCII byte per base in Raw mode), so byte offsets map directly to base
2889    /// positions. We compute the covering byte range with [`byte_range_for_bases`],
2890    /// read just that window with a positioned read, and decode it with
2891    /// [`decode_substring_from_bytes_at_offset`]. This is the partial-read path
2892    /// that makes random-access extraction cheap: it never materializes the whole
2893    /// sequence in memory.
2894    fn get_substring_from_disk(
2895        &self,
2896        metadata: &SeqCore,
2897        start: usize,
2898        end: usize,
2899    ) -> Result<Vec<u8>> {
2900        check_range(start, end, metadata.length)?;
2901
2902        // Zstd: there is no base->byte mapping into a compressed frame, so read
2903        // the whole stored frame (a small CDC chunk), decompress once, and slice
2904        // the ASCII. Whole-frame decompress of a <=256 KiB chunk is microseconds.
2905        if self.mode == StorageMode::Zstd {
2906            let compressed = match self.pack_row(&metadata.sha512t24u, StoreSide::Local)? {
2907                Some(row) => self.read_pack_bytes_local(&row.pack, row.offset, row.offset + row.len)?,
2908                None => {
2909                    let file = self.get_cached_seq_file(&metadata.sha512t24u)?;
2910                    let file_len = file
2911                        .metadata()
2912                        .context("failed to stat zstd seq file")?
2913                        .len() as usize;
2914                    crate::posread::read_exact_window(&file, 0, file_len)?
2915                }
2916            };
2917            let ascii = zstd::decode_all(&compressed[..])
2918                .context("zstd decompression of seq file failed")?;
2919            return Ok(ascii[start..end].to_vec());
2920        }
2921
2922        // Compute the covering byte window (identity under Raw). This math is
2923        // layout-independent; narrowing falls out of adding the pack offset to
2924        // an already-narrow window.
2925        let (byte_start, byte_end) = match self.mode {
2926            StorageMode::Encoded => {
2927                let alphabet = lookup_alphabet(&metadata.alphabet);
2928                byte_range_for_bases(start, end, alphabet.bits_per_symbol)
2929            }
2930            StorageMode::Raw => (start, end),
2931            StorageMode::Zstd => unreachable!("handled above"),
2932        };
2933
2934        // Resolve where the bytes live and read only the covering window.
2935        let buf = match self.pack_row(&metadata.sha512t24u, StoreSide::Local)? {
2936            Some(row) => {
2937                // Add the pack offset to the already-narrow window; block-cache
2938                // read of the absolute range.
2939                let abs_start = row.offset + byte_start as u64;
2940                let abs_end = row.offset + byte_end as u64;
2941                self.read_pack_bytes_local(&row.pack, abs_start, abs_end)?
2942            }
2943            None => {
2944                // Fetch (or open + cache) the shared `.seq` file handle. The
2945                // critical section is tiny; the positioned read is outside the
2946                // lock, so concurrent reads are never serialized by the cache.
2947                let file = self.get_cached_seq_file(&metadata.sha512t24u)?;
2948                crate::posread::read_exact_window(&file, byte_start, byte_end - byte_start)?
2949            }
2950        };
2951
2952        let decoded: Vec<u8> = match self.mode {
2953            StorageMode::Encoded => {
2954                let alphabet = lookup_alphabet(&metadata.alphabet);
2955                decode_substring_from_bytes_at_offset(&buf, byte_start, start, end, alphabet)
2956            }
2957            StorageMode::Raw => buf,
2958            StorageMode::Zstd => unreachable!("handled above"),
2959        };
2960
2961        Ok(decoded)
2962    }
2963
2964    /// Return a shared handle to the `.seq` file for `digest`, opening and
2965    /// caching it on a miss. Bounded LRU; the LRU handle is evicted (closed)
2966    /// when the cache is full.
2967    fn get_cached_seq_file(&self, digest: &str) -> Result<Arc<File>> {
2968        let local_path = self
2969            .local_path
2970            .as_ref()
2971            .ok_or_else(|| anyhow!("Partial read requires a local disk-backed store"))?;
2972        let template = self
2973            .seqdata_path_template
2974            .as_ref()
2975            .ok_or_else(|| anyhow!("No sequence data path template configured"))?;
2976        let full_path = local_path.join(Self::expand_template(digest, template));
2977        self.get_cached_file(&full_path)
2978    }
2979
2980    /// Return a shared handle to the file at `full_path`, opening and caching it
2981    /// on a miss. The bounded LRU is keyed by path, so pack files and `.seq`
2982    /// files share one pool of open handles.
2983    pub(crate) fn get_cached_file(&self, full_path: &Path) -> Result<Arc<File>> {
2984        // Fast path: hit. Hold the lock only for the tiny map op.
2985        {
2986            let mut cache = self
2987                .seq_fd_cache
2988                .lock()
2989                .map_err(|_| anyhow!("seq fd cache mutex poisoned"))?;
2990            if let Some(f) = cache.get(full_path) {
2991                return Ok(f);
2992            }
2993        }
2994
2995        // Miss: open OUTSIDE the lock (the open syscall must not serialize
2996        // other readers).
2997        let file = Arc::new(
2998            File::open(full_path)
2999                .with_context(|| format!("Failed to open file {}", full_path.display()))?,
3000        );
3001
3002        // Insert under the lock. A concurrent miss may have inserted the same
3003        // path meanwhile; that is harmless (both handles read the same immutable
3004        // file) -- prefer the already-cached one to avoid duplicating.
3005        let mut cache = self
3006            .seq_fd_cache
3007            .lock()
3008            .map_err(|_| anyhow!("seq fd cache mutex poisoned"))?;
3009        if let Some(existing) = cache.get(full_path) {
3010            return Ok(existing);
3011        }
3012        cache.insert(full_path.to_path_buf(), Arc::clone(&file));
3013        Ok(file)
3014    }
3015
3016    /// Read a substring from a remote `.seq` file via an HTTP byte-range
3017    /// request, fetching only the bytes that cover `[start, end)` and persisting
3018    /// nothing locally.
3019    ///
3020    /// This is the remote fallback for the partial-read path (flow 1): when a
3021    /// sequence is remote-only (no loaded or resident bytes and no cached local
3022    /// `.seq`), [`get_substring`](Self::get_substring) /
3023    /// [`get_substrings`](Self::get_substrings) fall through to here instead of
3024    /// erroring. It mirrors
3025    /// [`get_substring_from_disk`](Self::get_substring_from_disk) but fetches the
3026    /// covering byte window over HTTP `Range:` (reusing [`open_remote_range`], the
3027    /// same machinery as [`stream_sequence`](Self::stream_sequence)) rather than
3028    /// reading from a local file. Decoded with
3029    /// [`decode_substring_from_bytes_at_offset`].
3030    ///
3031    /// Kept `&self` so the `Arc`-shared readonly store stays usable; this path
3032    /// never mutates the store and never writes to disk (use `load_sequence`,
3033    /// flow 3, for caching).
3034    fn get_substring_from_remote(
3035        &self,
3036        metadata: &SeqCore,
3037        start: usize,
3038        end: usize,
3039    ) -> Result<Vec<u8>> {
3040        check_range(start, end, metadata.length)?;
3041
3042        // Zstd records are whole-frame compressed with no base->byte mapping, so
3043        // a covering byte window cannot be computed for a remote range request.
3044        // The novel/unplaced store this mode serves is always local, so this
3045        // path is unreachable in practice; fail loudly rather than fetch garbage.
3046        if self.mode == StorageMode::Zstd {
3047            return Err(anyhow!(
3048                "remote partial read is not supported for Zstd-mode stores; \
3049                 fetch and cache the whole compressed record first"
3050            ));
3051        }
3052
3053        let remote = self
3054            .remote_source
3055            .as_ref()
3056            .ok_or_else(|| anyhow!("Remote partial read requires a remote source"))?;
3057
3058        // Compute the covering byte window. Sequence bytes are headerless raw
3059        // byte arrays, so byte offsets map directly to base positions.
3060        let (byte_start, byte_end) = match self.mode {
3061            StorageMode::Encoded => {
3062                let alphabet = lookup_alphabet(&metadata.alphabet);
3063                byte_range_for_bases(start, end, alphabet.bits_per_symbol)
3064            }
3065            StorageMode::Raw => (start, end),
3066            StorageMode::Zstd => unreachable!("guarded above"),
3067        };
3068
3069        // Resolve where the bytes live on the REMOTE, then range-fetch the
3070        // covering window. Packed reads go through packs/<pack>.pack; standalone
3071        // reads through the templated `.seq` path. The remote packed path issues
3072        // one direct HTTP range per read; its sidecar is fetched whole once and
3073        // kept in memory.
3074        let (relpath, abs_start, abs_end) =
3075            match self.pack_row(&metadata.sha512t24u, StoreSide::Remote)? {
3076                Some(row) => (
3077                    pack_relpath(&row.pack),
3078                    row.offset + byte_start as u64,
3079                    row.offset + byte_end as u64,
3080                ),
3081                None => (
3082                    self.resolve_seq_file_relpath(&metadata.sha512t24u)?,
3083                    byte_start as u64,
3084                    byte_end as u64,
3085                ),
3086            };
3087
3088        let mut reader = open_remote_range(remote, &relpath, abs_start, abs_end)?;
3089        let mut buf = Vec::with_capacity(byte_end - byte_start);
3090        reader
3091            .read_to_end(&mut buf)
3092            .context("Failed to read remote byte range")?;
3093
3094        let decoded: Vec<u8> = match self.mode {
3095            StorageMode::Encoded => {
3096                let alphabet = lookup_alphabet(&metadata.alphabet);
3097                decode_substring_from_bytes_at_offset(&buf, byte_start, start, end, alphabet)
3098            }
3099            StorageMode::Raw => buf,
3100            StorageMode::Zstd => unreachable!("guarded above"),
3101        };
3102
3103        // The Encoded decoder emits only ASCII alphabet bytes and Raw stores
3104        // ASCII sequence bytes, so this validation always passes; we keep it
3105        // checked (rather than skipping straight to bytes) because this is the
3106        // untrusted-remote path — bytes come from an HTTP server we don't
3107        // control — and the validation cost is nil against the network fetch.
3108        // Reuse the validated String buffer when returning bytes.
3109        String::from_utf8(decoded)
3110            .map(String::into_bytes)
3111            .map_err(|e| anyhow!("decoded remote sequence was not valid UTF-8: {}", e))
3112    }
3113
3114    // =========================================================================
3115    // Streaming retrieval
3116    // =========================================================================
3117
3118    /// Resolve the relative on-disk/remote path for a sequence's encoded bytes.
3119    fn resolve_seq_file_relpath(&self, digest: &str) -> Result<PathBuf> {
3120        let template = self
3121            .seqdata_path_template
3122            .as_deref()
3123            .unwrap_or(DEFAULT_SEQDATA_PATH_TEMPLATE);
3124        let relpath = Self::expand_template(digest, template);
3125        let relpath_str = relpath
3126            .to_str()
3127            .ok_or_else(|| anyhow!("Non-UTF8 sequence path"))?;
3128        Self::sanitize_relative_path(relpath_str)?;
3129        Ok(relpath)
3130    }
3131
3132    // =====================================================================
3133    // Packed layout: pack locations
3134    // =====================================================================
3135
3136    /// The pack location of `digest` on `side`: the local side through the
3137    /// per-row pack columns, the remote side by binary search of its fetched
3138    /// sidecar. `Ok(None)` when that side is standalone; an error when it is
3139    /// packed and its sidecar lacks the digest.
3140    pub(crate) fn pack_row(
3141        &self,
3142        digest: &str,
3143        side: StoreSide,
3144    ) -> Result<Option<super::packidx::PackRow>> {
3145        let row = match (side, self.layout, self.remote_layout) {
3146            (StoreSide::Local, Layout::Packed, _) => match self.catalog.find_sha(digest) {
3147                Some(r) => self
3148                    .local_pack_cols()?
3149                    .get(r)
3150                    .map(|(pack, offset, len)| super::packidx::PackRow { pack, offset, len }),
3151                None => None,
3152            },
3153            (StoreSide::Remote, _, Layout::Packed) => {
3154                super::packidx::lookup(&self.remote_pack_index_bytes()?, digest)?
3155            }
3156            _ => return Ok(None),
3157        };
3158        row.map(Some).ok_or_else(|| anyhow!("sequence {} not in pack index", digest))
3159    }
3160
3161    /// The local pack columns, building them from `sequences.pack.idx` on
3162    /// first use.
3163    fn local_pack_cols(&self) -> Result<Arc<super::catalog::PackColumns>> {
3164        if let Some(c) = self.pack_cols.lock().unwrap().as_ref() {
3165            return Ok(Arc::clone(c));
3166        }
3167        let local_path = self
3168            .local_path
3169            .as_ref()
3170            .ok_or_else(|| anyhow!("packed store requires a local path"))?;
3171        let bytes = super::packidx::load_pack_idx_or_empty(local_path)?;
3172        let cols = Arc::new(super::catalog::PackColumns::build(&self.catalog, &bytes)?);
3173        let mut g = self.pack_cols.lock().unwrap();
3174        if let Some(existing) = g.as_ref() {
3175            return Ok(Arc::clone(existing));
3176        }
3177        *g = Some(Arc::clone(&cols));
3178        Ok(cols)
3179    }
3180
3181    /// The REMOTE side's sidecar bytes, fetched whole on first use.
3182    fn remote_pack_index_bytes(&self) -> Result<Arc<Vec<u8>>> {
3183        {
3184            let g = self.remote_pack_index.lock().unwrap();
3185            if let Some(h) = g.as_ref() {
3186                return Ok(Arc::clone(h));
3187            }
3188        }
3189        let handle = Arc::new(Self::fetch_file(
3190            &self.local_path,
3191            &self.remote_source,
3192            "sequences.pack.idx",
3193            false,
3194            false,
3195        )?);
3196        let mut g = self.remote_pack_index.lock().unwrap();
3197        if let Some(existing) = g.as_ref() {
3198            return Ok(Arc::clone(existing));
3199        }
3200        *g = Some(Arc::clone(&handle));
3201        Ok(handle)
3202    }
3203
3204    /// Invalidate the cached local pack index (call after a commit that changed
3205    /// the sidecar). The next resolution reloads from disk.
3206    pub(crate) fn invalidate_pack_index(&self) {
3207        *self.pack_cols.lock().unwrap() = None;
3208        self.pack_lengths.lock().unwrap().clear();
3209    }
3210
3211    /// The byte length of a pack file, cached (the block cache needs it to
3212    /// clamp the final block of a read).
3213    fn pack_file_len(&self, pack: &Arc<str>) -> Result<u64> {
3214        if let Some(len) = self.pack_lengths.lock().unwrap().get(pack).copied() {
3215            return Ok(len);
3216        }
3217        let local_path = self
3218            .local_path
3219            .as_ref()
3220            .ok_or_else(|| anyhow!("packed read requires a local path"))?;
3221        let path = local_path.join("packs").join(format!("{}.pack", pack));
3222        let len = std::fs::metadata(&path)
3223            .with_context(|| format!("stat {}", path.display()))?
3224            .len();
3225        self.pack_lengths.lock().unwrap().insert(Arc::clone(pack), len);
3226        Ok(len)
3227    }
3228
3229    /// Read `[abs_start, abs_end)` from a LOCAL pack file: one positional read
3230    /// on the cached file handle, or through the block cache when it is on.
3231    fn read_pack_bytes_local(&self, pack: &Arc<str>, abs_start: u64, abs_end: u64) -> Result<Vec<u8>> {
3232        let local_path = self
3233            .local_path
3234            .as_ref()
3235            .ok_or_else(|| anyhow!("packed read requires a local path"))?;
3236        let file = self.get_cached_file(&local_path.join(pack_relpath(pack)))?;
3237        let fetch = |off: u64, len: u64| -> Result<Vec<u8>> {
3238            crate::posread::read_exact_window(&file, off as usize, len as usize)
3239        };
3240        match &self.pack_cache {
3241            None => fetch(abs_start, abs_end - abs_start),
3242            Some(cache) => {
3243                let pack_len = self.pack_file_len(pack)?;
3244                cache.read_range(pack, pack_len, abs_start, abs_end, &fetch)
3245            }
3246        }
3247    }
3248
3249    /// Set the per-pack size cap in bytes for new packs.
3250    pub fn set_pack_cap_bytes(&mut self, cap: u64) {
3251        self.pack_cap_bytes = cap.max(1);
3252    }
3253
3254    /// Turn the pack block cache on with room for `mb` megabytes, or off with
3255    /// 0 (the default). Alpha. The cache helps clustered reads on a cold
3256    /// network file system and hurts scattered reads on stores larger than
3257    /// the cache. It fronts local pack reads only.
3258    pub fn set_pack_cache_mb(&mut self, mb: usize) {
3259        use super::packcache::{PackBlockCache, PACK_BLOCK_SIZE};
3260        self.pack_cache = (mb > 0)
3261            .then(|| PackBlockCache::new((mb << 20) / PACK_BLOCK_SIZE as usize, PACK_BLOCK_SIZE));
3262    }
3263
3264    // =====================================================================
3265    // Packed layout: the session pack every packed write goes through
3266    // =====================================================================
3267
3268    /// Append `bytes` (already in store-mode encoding) to the open session pack,
3269    /// sealing the current pack first if it would exceed the cap.
3270    pub(crate) fn session_pack_append(&self, digest: &str, bytes: &[u8]) -> Result<()> {
3271        use sha2::Digest as _;
3272
3273        let local_path = self
3274            .local_path
3275            .as_ref()
3276            .ok_or_else(|| anyhow!("packed write requires a local path"))?;
3277        let packs_dir = local_path.join("packs");
3278
3279        let mut guard = self.open_session_pack.lock().unwrap();
3280        if guard.is_none() {
3281            std::fs::create_dir_all(&packs_dir)?;
3282            let ordinal = 0usize;
3283            let token = super::atomic::unique_temp_token();
3284            let (tmp_path, file) = SessionPack::create_temp(&packs_dir, &token, ordinal)?;
3285            *guard = Some(SessionPack {
3286                packs_dir: packs_dir.clone(),
3287                token,
3288                ordinal,
3289                tmp_path,
3290                file,
3291                len: 0,
3292                hasher: sha2::Sha256::new(),
3293                rows: Vec::new(),
3294                sealed: Vec::new(),
3295                created: Vec::new(),
3296            });
3297        }
3298
3299        let session = guard.as_mut().unwrap();
3300        let len = bytes.len() as u64;
3301        // Seal-before-place at cap (a sequence never straddles two packs).
3302        if session.len > 0 && session.len + len > self.pack_cap_bytes {
3303            session.seal()?;
3304        }
3305        // Write at the tracked offset, not at the file cursor: bytes a failed
3306        // write left behind are overwritten here or cut off at seal, so they
3307        // never shift this row or a later one.
3308        let offset = session.len;
3309        #[cfg(unix)]
3310        {
3311            use std::os::unix::fs::FileExt;
3312            session.file.write_all_at(bytes, offset)?;
3313        }
3314        #[cfg(not(unix))]
3315        {
3316            use std::io::{Seek, SeekFrom, Write};
3317            session.file.seek(SeekFrom::Start(offset))?;
3318            session.file.write_all(bytes)?;
3319        }
3320        session.hasher.update(bytes);
3321        session.len += len;
3322        session.rows.push((digest.to_string(), offset, len));
3323        Ok(())
3324    }
3325
3326    /// Seal any open session pack and return its `(digest, PackRow)` rows for
3327    /// the sidecar merge. Called by the commit path under the lock.
3328    pub(crate) fn seal_open_session_pack(
3329        &self,
3330    ) -> Result<Vec<(String, super::packidx::PackRow)>> {
3331        let mut guard = self.open_session_pack.lock().unwrap();
3332        let Some(mut session) = guard.take() else {
3333            return Ok(Vec::new());
3334        };
3335        if let Err(e) = session.seal() {
3336            // Keep the session, with the rows of sub-packs it already
3337            // sealed, so a later commit can retry instead of losing them.
3338            *guard = Some(session);
3339            return Err(e);
3340        }
3341        // The rows go to the commit path now, so dropping the session must
3342        // not delete their packs.
3343        session.created.clear();
3344        Ok(std::mem::take(&mut session.sealed))
3345    }
3346
3347    // =====================================================================
3348    // Packed deletion accounting + compaction
3349    // =====================================================================
3350
3351    /// Dead (unreferenced) bytes inside pack files:
3352    /// `sum(pack sizes) - sum(live sidecar lengths)`. `Ok(0)` for a store with
3353    /// no packs. Computed, not tracked.
3354    pub fn packed_dead_bytes(&self) -> Result<u64> {
3355        let local_path = self
3356            .local_path
3357            .as_ref()
3358            .ok_or_else(|| anyhow!("packed_dead_bytes requires a local path"))?;
3359        let total_pack_bytes: u64 = Self::pack_file_sizes(&local_path.join("packs")).iter().sum();
3360        let mut live: u64 = 0;
3361        super::packidx::for_each_row(
3362            &super::packidx::load_pack_idx_or_empty(local_path)?,
3363            |_, _, _, len| {
3364                live += len;
3365                Ok(())
3366            },
3367        )?;
3368        Ok(total_pack_bytes.saturating_sub(live))
3369    }
3370
3371    /// Rewrite the live spans of a packed store into fresh sealed packs,
3372    /// reclaiming dead bytes. Deterministic and locality-preserving (packs
3373    /// visited by name, rows by offset). Retrieval is byte-identical before and
3374    /// after. Same as [`Self::compact_with`] with default options.
3375    pub fn compact(&mut self) -> Result<CompactReport> {
3376        self.compact_with(CompactOptions::default())
3377    }
3378
3379    /// [`Self::compact`] with options; see [`CompactOptions`].
3380    pub fn compact_with(&mut self, opts: CompactOptions) -> Result<CompactReport> {
3381        if self.layout != Layout::Packed {
3382            return Err(anyhow!("compact() only applies to a packed store"));
3383        }
3384        let local_path = self
3385            .local_path
3386            .clone()
3387            .ok_or_else(|| anyhow!("compact requires a local disk-backed store"))?;
3388        // A batch lock the caller already holds stays held.
3389        let held = self.holds_batch_lock();
3390        self.lock_for_batch("compact")?;
3391        let result = self.compact_inner(&local_path, opts);
3392        if !held {
3393            self.release_batch_lock();
3394        }
3395        result
3396    }
3397
3398    fn compact_inner(&self, local_path: &Path, opts: CompactOptions) -> Result<CompactReport> {
3399        use super::packidx::{read_pack_idx_rows, write_pack_idx, PackRow};
3400        use std::collections::BTreeMap;
3401
3402        let packs_dir = local_path.join("packs");
3403        let idx_path = local_path.join("sequences.pack.idx");
3404
3405        let old_rows: BTreeMap<String, PackRow> =
3406            read_pack_idx_rows(&super::packidx::load_pack_idx_or_empty(local_path)?)?;
3407
3408        let packs_before = Self::pack_file_sizes(&packs_dir).len();
3409        let dead_before = self.packed_dead_bytes()?;
3410
3411        // Deterministic, locality-preserving order: packs by name, rows by offset.
3412        let mut by_pack: BTreeMap<Arc<str>, Vec<(String, u64, u64)>> = BTreeMap::new();
3413        for (digest, row) in &old_rows {
3414            by_pack
3415                .entry(Arc::clone(&row.pack))
3416                .or_default()
3417                .push((digest.clone(), row.offset, row.len));
3418        }
3419        for v in by_pack.values_mut() {
3420            v.sort_by_key(|(_, off, _)| *off);
3421        }
3422
3423        // Stream every live span through the session-pack builder into fresh
3424        // sealed packs (reusing the incremental writer machinery).
3425        for (pack_name, rows) in &by_pack {
3426            let src_path = packs_dir.join(format!("{}.pack", pack_name));
3427            let src = File::open(&src_path)
3428                .with_context(|| format!("opening source pack {}", src_path.display()))?;
3429            for (digest, offset, len) in rows {
3430                let bytes =
3431                    crate::posread::read_exact_window(&src, *offset as usize, *len as usize)?;
3432                self.session_pack_append(digest, &bytes)?;
3433            }
3434        }
3435        let new_rows: BTreeMap<String, PackRow> =
3436            self.seal_open_session_pack()?.into_iter().collect();
3437
3438        // Publish the replacement sidecar, then drop the old packs it no longer
3439        // uses. Only packs the old sidecar listed are dropped; see
3440        // `remove_fully_dead_packs`.
3441        write_pack_idx(&idx_path, &new_rows)?;
3442        self.invalidate_pack_index();
3443        let old_pack_names: HashSet<String> =
3444            old_rows.values().map(|r| r.pack.to_string()).collect();
3445        self.remove_fully_dead_packs(local_path, &old_pack_names)?;
3446
3447        let new_pack_names: HashSet<String> =
3448            new_rows.values().map(|r| r.pack.to_string()).collect();
3449        let packs_pruned = if opts.prune_unreferenced {
3450            Self::remove_unreferenced_packs(&packs_dir, &new_pack_names)?
3451        } else {
3452            0
3453        };
3454
3455        let dead_after = self.packed_dead_bytes()?;
3456        Ok(CompactReport {
3457            packs_before,
3458            packs_after: new_pack_names.len(),
3459            bytes_reclaimed: dead_before.saturating_sub(dead_after),
3460            packs_pruned,
3461        })
3462    }
3463
3464    /// Unlink every sealed `*.pack` in `packs_dir` whose name is not in
3465    /// `referenced`, and return how many were unlinked. Temp files
3466    /// (`.rgstore.tmp.*`) are never touched. Called under the store lock
3467    /// right after the index that `referenced` describes was published.
3468    fn remove_unreferenced_packs(packs_dir: &Path, referenced: &HashSet<String>) -> Result<usize> {
3469        use std::io::ErrorKind::NotFound;
3470        let entries = match fs::read_dir(packs_dir) {
3471            Ok(entries) => entries,
3472            Err(e) if e.kind() == NotFound => return Ok(0),
3473            Err(e) => return Err(e).with_context(|| format!("listing {}", packs_dir.display())),
3474        };
3475        let mut removed = 0;
3476        for entry in entries {
3477            let entry = entry?;
3478            let file_name = entry.file_name();
3479            let Some(name) = file_name.to_str() else { continue };
3480            if name.starts_with(".rgstore.tmp.") {
3481                continue;
3482            }
3483            let Some(pack) = name.strip_suffix(".pack") else { continue };
3484            if referenced.contains(pack) || !entry.file_type()?.is_file() {
3485                continue;
3486            }
3487            match fs::remove_file(entry.path()) {
3488                Ok(()) => removed += 1,
3489                Err(e) if e.kind() == NotFound => {}
3490                Err(e) => {
3491                    return Err(e).with_context(|| {
3492                        format!("removing unreferenced pack {}", entry.path().display())
3493                    })
3494                }
3495            }
3496        }
3497        Ok(removed)
3498    }
3499
3500    /// Names of the packs the on-disk sidecar references.
3501    fn sidecar_pack_names(local_path: &Path) -> Result<HashSet<String>> {
3502        let mut names = HashSet::new();
3503        super::packidx::for_each_row(
3504            &super::packidx::load_pack_idx_or_empty(local_path)?,
3505            |_, pack, _, _| {
3506                names.insert(pack.to_string());
3507                Ok(())
3508            },
3509        )?;
3510        Ok(names)
3511    }
3512
3513    /// Unlink each pack in `candidates` that the current sidecar no longer
3514    /// references. Called under the store lock after the sidecar dropped rows.
3515    ///
3516    /// Only packs the caller saw listed in the sidecar, read earlier under the
3517    /// same lock, are candidates. A pack the sidecar has never listed may have
3518    /// been sealed by another writer that has not committed yet, so it is never
3519    /// deleted here, even though nothing references it.
3520    fn remove_fully_dead_packs(&self, local_path: &Path, candidates: &HashSet<String>) -> Result<()> {
3521        let live = Self::sidecar_pack_names(local_path)?;
3522        let packs_dir = local_path.join("packs");
3523        for name in candidates.difference(&live) {
3524            let _ = fs::remove_file(packs_dir.join(format!("{}.pack", name)));
3525        }
3526        Ok(())
3527    }
3528
3529    /// Byte sizes of the sealed `*.pack` files (temp files excluded) in a
3530    /// `packs/` directory.
3531    fn pack_file_sizes(packs_dir: &Path) -> Vec<u64> {
3532        let Ok(entries) = fs::read_dir(packs_dir) else { return Vec::new() };
3533        entries
3534            .filter_map(|e| e.ok())
3535            .filter(|e| e.file_name().to_str().is_some_and(|n| n.ends_with(".pack")))
3536            .map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))
3537            .collect()
3538    }
3539
3540    /// Stream a (sub)sequence as decoded ASCII bases without loading the full
3541    /// sequence into memory.
3542    ///
3543    /// Opens a bounded byte window on the backing store (local file via
3544    /// `seek`+`take`, or remote via HTTP `Range: bytes=`), and wraps it in a
3545    /// [`StreamingDecoder`] when the store is in `Encoded` mode. In `Raw`
3546    /// mode the bounded byte source is returned directly, since bytes and
3547    /// bases are 1:1.
3548    ///
3549    /// Memory use is O(1) in the sequence length.
3550    pub fn stream_sequence<K: AsRef<[u8]>>(
3551        &self,
3552        sha512_digest: K,
3553        start: Option<u64>,
3554        end: Option<u64>,
3555    ) -> Result<Box<dyn Read + Send>> {
3556        // 1. Resolve digest (MD5 -> SHA512t24u fallback).
3557        let actual_key = self.seq_row(sha512_digest.as_ref()).ok_or_else(|| {
3558            anyhow!(
3559                "Sequence not found: {}",
3560                String::from_utf8_lossy(sha512_digest.as_ref())
3561            )
3562        })?;
3563
3564        // 2. Fetch metadata only (do not load bytes).
3565        let metadata = &self.catalog.seq(actual_key).core();
3566        let owned = self.loaded_arc(actual_key);
3567
3568        // 3. Resolve bounds.
3569        let length = metadata.length as u64;
3570        let start = start.unwrap_or(0);
3571        let end = end.unwrap_or(length);
3572        if start > end || end > length {
3573            return Err(anyhow!(
3574                "Invalid stream range: start={}, end={}, length={}",
3575                start,
3576                end,
3577                length
3578            ));
3579        }
3580
3581        // 3b. Zstd: no base->byte mapping into a compressed frame, so the byte-
3582        // window streaming machinery below does not apply. Decompress the whole
3583        // record (small CDC chunk) once and stream the requested ASCII slice.
3584        if self.mode == StorageMode::Zstd {
3585            let (s, e) = (start as usize, end as usize);
3586            let stored = self.read_stored_bytes(actual_key, false)?;
3587            let ascii = zstd::decode_all(&stored[..])
3588                .context("zstd decompression of sequence record failed")?;
3589            return Ok(Box::new(std::io::Cursor::new(ascii[s..e].to_vec())));
3590        }
3591
3592        // 4. Look up alphabet and compute bits-per-base.
3593        let alphabet = crate::digest::lookup_alphabet(&metadata.alphabet);
3594        let bps = match self.mode {
3595            StorageMode::Encoded => alphabet.bits_per_symbol as u64,
3596            StorageMode::Raw => 8,
3597            StorageMode::Zstd => unreachable!("handled above"),
3598        };
3599
3600        // 5. Compute byte range + leading-skip bits.
3601        let start_bit = start * bps;
3602        let end_bit = end * bps;
3603        let byte_start = start_bit / 8;
3604        let byte_end = end_bit.div_ceil(8);
3605        let leading_skip_bits = (start_bit - byte_start * 8) as u8;
3606        let bases_to_emit = end - start;
3607        let byte_len = byte_end - byte_start;
3608
3609        // Fast path for empty range.
3610        if bases_to_emit == 0 {
3611            return Ok(Box::new(std::io::empty()));
3612        }
3613
3614        let sha = metadata.sha512t24u.to_string();
3615
3616        // 6. Build the source reader. Loaded bytes are streamed
3617        // directly from their encoded byte buffer. Otherwise try the
3618        // on-disk path (local_path / remote_source).
3619        if let Some(sequence) = owned {
3620            // Share ownership of the already-resident buffer instead of
3621            // cloning the byte range. This keeps peak allocation O(1) in
3622            // the sequence size.
3623            let source: Box<dyn Read + Send> = Box::new(ArcSliceReader::new(
3624                sequence,
3625                byte_start as usize,
3626                byte_end as usize,
3627            ));
3628            return match self.mode {
3629                StorageMode::Encoded => Ok(Box::new(StreamingDecoder::new(
3630                    source,
3631                    alphabet,
3632                    leading_skip_bits,
3633                    bases_to_emit,
3634                ))),
3635                StorageMode::Raw => {
3636                    debug_assert_eq!(leading_skip_bits, 0);
3637                    Ok(source)
3638                }
3639                StorageMode::Zstd => unreachable!("handled above"),
3640            };
3641        }
3642
3643        // Open a bounded window on a local file (seek + take), verifying it is
3644        // long enough. Shared by the standalone `.seq` and packed-pack paths.
3645        let open_local_window =
3646            |full: &Path, at: u64| -> Result<Box<dyn Read + Send>> {
3647                let mut file = File::open(full)
3648                    .with_context(|| format!("Failed to open local file: {}", full.display()))?;
3649                file.seek(SeekFrom::Start(at))
3650                    .context("Failed to seek in local file")?;
3651                let file_len = file
3652                    .metadata()
3653                    .with_context(|| format!("Failed to stat local file: {}", full.display()))?
3654                    .len();
3655                if file_len < at + byte_len {
3656                    return Err(anyhow!(
3657                        "Local file is too short to satisfy the requested byte range \
3658                         [{}..{}) (file has {} bytes): {}",
3659                        at,
3660                        at + byte_len,
3661                        file_len,
3662                        full.display()
3663                    ));
3664                }
3665                Ok(Box::new(BufReader::new(file).take(byte_len)))
3666            };
3667
3668        // Prefer a locally-present file; the local side of a remote packed store
3669        // is standalone, so its cached `.seq` is used when present.
3670        let local_source: Option<Box<dyn Read + Send>> = if let Some(local) = self.local_path.as_ref() {
3671            match self.pack_row(&sha, StoreSide::Local)? {
3672                Some(row) => Some(open_local_window(
3673                    &local.join(pack_relpath(&row.pack)),
3674                    row.offset + byte_start,
3675                )?),
3676                None => {
3677                    let full = local.join(self.resolve_seq_file_relpath(&sha)?);
3678                    if full.exists() {
3679                        Some(open_local_window(&full, byte_start)?)
3680                    } else {
3681                        None
3682                    }
3683                }
3684            }
3685        } else {
3686            None
3687        };
3688
3689        let source: Box<dyn Read + Send> = if let Some(s) = local_source {
3690            s
3691        } else if let Some(remote) = self.remote_source.as_ref() {
3692            match self.pack_row(&sha, StoreSide::Remote)? {
3693                Some(row) => open_remote_range(
3694                    remote,
3695                    &pack_relpath(&row.pack),
3696                    row.offset + byte_start,
3697                    row.offset + byte_end,
3698                )?,
3699                None => open_remote_range(
3700                    remote,
3701                    &self.resolve_seq_file_relpath(&sha)?,
3702                    byte_start,
3703                    byte_end,
3704                )?,
3705            }
3706        } else {
3707            return Err(anyhow!("No backing source configured for sequence {}", sha));
3708        };
3709
3710        // 7. Dispatch on mode.
3711        match self.mode {
3712            StorageMode::Encoded => Ok(Box::new(StreamingDecoder::new(
3713                source,
3714                alphabet,
3715                leading_skip_bits,
3716                bases_to_emit,
3717            ))),
3718            StorageMode::Raw => {
3719                debug_assert_eq!(leading_skip_bits, 0);
3720                Ok(source)
3721            }
3722            StorageMode::Zstd => unreachable!("handled above"),
3723        }
3724    }
3725
3726    // =========================================================================
3727    // Internal helpers
3728    // =========================================================================
3729
3730    /// Expand a path template by substituting digest-based placeholders.
3731    pub(crate) fn expand_template(digest_str: &str, template: &str) -> PathBuf {
3732        debug_assert!(
3733            digest_str.len() >= 4,
3734            "Digest string must be at least 4 characters for template expansion, got {} chars",
3735            digest_str.len()
3736        );
3737        let path_str = template
3738            .replace("%s2", digest_str.get(0..2).unwrap_or(digest_str))
3739            .replace("%s4", digest_str.get(0..4).unwrap_or(digest_str))
3740            .replace("%s", digest_str);
3741        PathBuf::from(path_str)
3742    }
3743
3744    /// Return the full filesystem path to a sequence `.seq` file for the given digest.
3745    ///
3746    /// Returns `None` if the store has no local path or no seqdata path template.
3747    pub fn sequence_file_path(&self, seq_digest: &str) -> Option<PathBuf> {
3748        let local_path = self.local_path.as_ref()?;
3749        let template = self.seqdata_path_template.as_ref()?;
3750        Some(local_path.join(Self::expand_template(seq_digest, template)))
3751    }
3752
3753    /// Return the full filesystem path to a collection RGSI file for the given digest.
3754    ///
3755    /// Returns `None` if the store has no local path.
3756    pub fn collection_file_path(&self, coll_digest: &str) -> Option<PathBuf> {
3757        let local_path = self.local_path.as_ref()?;
3758        Some(local_path.join(format!("collections/{}.rgsi", coll_digest)))
3759    }
3760
3761    /// Validate a relative path to prevent directory traversal attacks.
3762    pub(crate) fn sanitize_relative_path(path: &str) -> Result<()> {
3763        if path.starts_with('/') || path.starts_with('\\') {
3764            return Err(anyhow!("Absolute paths not allowed: {}", path));
3765        }
3766        if path.contains("..") {
3767            return Err(anyhow!("Directory traversal not allowed: {}", path));
3768        }
3769        if path.contains('\0') {
3770            return Err(anyhow!("Null bytes not allowed in path"));
3771        }
3772        Ok(())
3773    }
3774
3775    /// Helper function to fetch a file from local path or remote source
3776    pub(crate) fn fetch_file(
3777        local_path: &Option<PathBuf>,
3778        remote_source: &Option<String>,
3779        relative_path: &str,
3780        persist_to_disk: bool,
3781        force_refresh: bool,
3782    ) -> Result<Vec<u8>> {
3783        Self::sanitize_relative_path(relative_path)?;
3784
3785        if persist_to_disk && !force_refresh {
3786            if let Some(local_path) = local_path {
3787                let full_local_path = local_path.join(relative_path);
3788                if full_local_path.exists() {
3789                    return fs::read(&full_local_path).context(format!(
3790                        "Failed to read local file: {}",
3791                        full_local_path.display()
3792                    ));
3793                }
3794            }
3795        }
3796
3797        #[cfg(feature = "http")]
3798        if let Some(remote_url) = remote_source {
3799            let data = Self::fetch_remote(remote_url, relative_path)?;
3800
3801            if persist_to_disk {
3802                if let Some(local_path) = local_path {
3803                    let full_local_path = local_path.join(relative_path);
3804
3805                    if let Some(parent) = full_local_path.parent() {
3806                        create_dir_all(parent)?;
3807                    }
3808
3809                    fs::write(&full_local_path, &data).context(format!(
3810                        "Failed to cache file to: {}",
3811                        full_local_path.display()
3812                    ))?;
3813                }
3814            }
3815
3816            return Ok(data);
3817        }
3818
3819        let _ = remote_source;
3820        Err(anyhow!(
3821            "File not found locally and no remote source configured: {}",
3822            relative_path
3823        ))
3824    }
3825
3826    /// GET one file from a remote store into memory. Writes nothing to disk.
3827    #[cfg(feature = "http")]
3828    pub(crate) fn fetch_remote(remote_url: &str, relative_path: &str) -> Result<Vec<u8>> {
3829        Self::sanitize_relative_path(relative_path)?;
3830        let full_remote_url = if remote_url.ends_with('/') {
3831            format!("{}{}", remote_url, relative_path)
3832        } else {
3833            format!("{}/{}", remote_url, relative_path)
3834        };
3835
3836        let response = ureq::get(&full_remote_url)
3837            .call()
3838            .map_err(|e| anyhow!("Failed to fetch from remote: {}", e))?;
3839
3840        let mut data = Vec::new();
3841        response
3842            .into_body()
3843            .into_reader()
3844            .read_to_end(&mut data)
3845            .context("Failed to read response body")?;
3846        Ok(data)
3847    }
3848
3849    /// The stored bytes (packed, raw or zstd, as on disk) of one sequence: its
3850    /// loaded or resident bytes if present, else the local pack, the local
3851    /// `.seq` file, the remote pack, or the remote `.seq` file, in that order.
3852    /// With `cache`, bytes fetched from the remote are also written to the
3853    /// local cache as a standalone `.seq`. Never adds the sequence to the
3854    /// loaded set.
3855    pub(crate) fn read_stored_bytes(&self, row: SeqRow, cache: bool) -> Result<Arc<Vec<u8>>> {
3856        if let Some(bytes) = self.loaded_arc(row).or_else(|| self.resident_lookup(row)) {
3857            return Ok(bytes);
3858        }
3859        let sha = self.catalog.seq(row).sha512t24u();
3860        let sha = sha.as_str();
3861        if let Some(p) = self.pack_row(sha, StoreSide::Local)? {
3862            return Ok(Arc::new(self.read_pack_bytes_local(&p.pack, p.offset, p.offset + p.len)?));
3863        }
3864
3865        let relpath = self.resolve_seq_file_relpath(sha)?;
3866        if let Some(local_path) = &self.local_path {
3867            let full = local_path.join(&relpath);
3868            match fs::read(&full) {
3869                Ok(data) => return Ok(Arc::new(data)),
3870                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
3871                Err(e) => return Err(anyhow!("Failed to read seq file {}: {}", full.display(), e)),
3872            }
3873        }
3874
3875        let Some(remote) = &self.remote_source else {
3876            return Err(anyhow!(
3877                "Sequence data for {} not found locally and no remote source configured",
3878                sha
3879            ));
3880        };
3881        if let Some(p) = self.pack_row(sha, StoreSide::Remote)? {
3882            let mut buf = Vec::with_capacity(p.len as usize);
3883            open_remote_range(remote, &pack_relpath(&p.pack), p.offset, p.offset + p.len)?
3884                .read_to_end(&mut buf)
3885                .context("Failed to read remote pack byte range")?;
3886            if cache && self.local_path.is_some() {
3887                self.write_sequence_to_disk_single(&self.catalog.seq(row).to_metadata(), &buf)?;
3888            }
3889            return Ok(Arc::new(buf));
3890        }
3891        let relpath = relpath.to_str().ok_or_else(|| anyhow!("Non-UTF8 sequence path"))?;
3892        Ok(Arc::new(Self::fetch_file(&self.local_path, &self.remote_source, relpath, cache, false)?))
3893    }
3894
3895    /// Ensure a collection's member list is loaded into the catalog.
3896    pub(crate) fn ensure_collection_loaded(&mut self, collection_digest: &str) -> Result<()> {
3897        let existing = self.catalog.find_coll(collection_digest);
3898        if existing.is_some_and(|c| self.catalog.is_loaded(c)) {
3899            return Ok(());
3900        }
3901        let digest_str = match existing {
3902            Some(c) => self.catalog.coll_meta(c).digest.clone(),
3903            None => collection_digest.to_string(),
3904        };
3905
3906        let relative_path = format!("collections/{}.rgsi", digest_str);
3907
3908        if !self.quiet {
3909            let cached = self
3910                .local_path
3911                .as_ref()
3912                .map(|p| p.join(&relative_path).exists())
3913                .unwrap_or(false);
3914            let verb = if cached { "Loading" } else { "Downloading" };
3915            eprintln!("{} collection metadata {}...", verb, digest_str);
3916        }
3917        let _collection_data =
3918            Self::fetch_file(&self.local_path, &self.remote_source, &relative_path, true, false)?;
3919
3920        let local_path = self
3921            .local_path
3922            .as_ref()
3923            .ok_or_else(|| anyhow!("No local path configured"))?;
3924
3925        let collection_file_path = local_path.join(&relative_path);
3926        self.load_collection_rgsi(&collection_file_path, Some(collection_digest))?;
3927        Ok(())
3928    }
3929
3930    /// Ensure a sequence is loaded into memory. A remote store writes the
3931    /// fetched bytes through to its local cache as a standalone `.seq`.
3932    pub(crate) fn ensure_sequence_loaded(&mut self, row: SeqRow) -> Result<()> {
3933        if self.loaded.contains_key(&row) {
3934            return Ok(());
3935        }
3936        if !self.quiet && self.layout == Layout::Standalone && self.remote_layout == Layout::Standalone {
3937            let sha = self.catalog.seq(row).sha512t24u();
3938            let cached = self.sequence_file_path(&sha).is_some_and(|p| p.exists());
3939            let verb = if cached { "Loading" } else { "Downloading" };
3940            eprintln!("{} sequence {}...", verb, sha);
3941        }
3942        let data = self.read_stored_bytes(row, self.persist_to_disk)?;
3943        self.loaded.insert(row, data);
3944        Ok(())
3945    }
3946
3947    // =========================================================================
3948    // Write methods
3949    // =========================================================================
3950
3951    /// Write the store using its configured paths.
3952    pub fn write(&self) -> Result<()> {
3953        if !self.persist_to_disk {
3954            return Err(anyhow!(
3955                "write() only works with disk-backed stores - use write_store_to_dir() instead"
3956            ));
3957        }
3958        self.write_index_files()
3959    }
3960
3961    /// Write a RefgetStore object to a directory
3962    pub fn write_store_to_dir<P: AsRef<Path>>(
3963        &self,
3964        root_path: P,
3965        seqdata_path_template: Option<&str>,
3966    ) -> Result<()> {
3967        let root_path = root_path.as_ref();
3968
3969        let template = seqdata_path_template
3970            .or(self.seqdata_path_template.as_deref())
3971            .unwrap_or(DEFAULT_SEQDATA_PATH_TEMPLATE);
3972
3973        if !self.quiet {
3974            eprintln!(
3975                "Writing store to directory: {}; Using seqdata path template: {}",
3976                root_path.display(),
3977                template
3978            );
3979        }
3980
3981        fs::create_dir_all(root_path)?;
3982
3983        let sequences_dir = root_path.join("sequences");
3984        fs::create_dir_all(&sequences_dir)?;
3985
3986        let collections_dir = root_path.join("collections");
3987        fs::create_dir_all(&collections_dir)?;
3988
3989        for row in self.catalog.seq_rows() {
3990            let record = self.seq_record(row);
3991            match &record {
3992                SequenceRecord::Full { metadata, .. } => {
3993                    let rel_path = Self::expand_template(&metadata.sha512t24u, template);
3994                    let full_path = root_path.join(&rel_path);
3995                    record.to_file(full_path)?;
3996                }
3997                SequenceRecord::Stub(metadata) => {
3998                    // A PACKED source has no resident bytes; export each sequence
3999                    // as a STANDALONE `.seq` by reading its whole span from the
4000                    // pack. This is also the practical "convert a packed store"
4001                    // escape hatch.
4002                    if self.layout == Layout::Packed && self.local_path.is_some() {
4003                        let bytes = self.read_stored_bytes(row, false)?;
4004                        let rel_path = Self::expand_template(&metadata.sha512t24u, template);
4005                        let full_path = root_path.join(&rel_path);
4006                        if let Some(parent) = full_path.parent() {
4007                            fs::create_dir_all(parent)?;
4008                        }
4009                        super::atomic::publish_bytes_nosync(&full_path, &bytes)?;
4010                    }
4011                }
4012            }
4013        }
4014
4015        for c in self.catalog.coll_rows() {
4016            let meta = self.catalog.coll_meta(c);
4017            let collection_file_path = root_path.join(format!("collections/{}.rgsi", meta.digest));
4018            crate::collection::write_collection_rgsi_rows(
4019                &collection_file_path,
4020                meta,
4021                self.catalog.members(c).map(|m| m.to_metadata()),
4022            )?;
4023        }
4024
4025        let sequence_index_path = root_path.join("sequences.rgsi");
4026        self.write_sequences_rgsi(&sequence_index_path)?;
4027
4028        let collection_index_path = root_path.join("collections.rgci");
4029        self.write_collections_rgci(&collection_index_path)?;
4030
4031        let aliases_dir = root_path.join("aliases");
4032        self.aliases.write_to_dir(&aliases_dir)?;
4033
4034        super::fhr_metadata::write_sidecars(&root_path.join("fhr"), &self.fhr_metadata)?;
4035
4036        self.write_rgstore_json(root_path, template)?;
4037
4038        Ok(())
4039    }
4040
4041    /// Returns statistics about the store.
4042    ///
4043    /// The `*_in_memory` fields are a RAM-residency snapshot, not a record of
4044    /// what any import run did; see [`StoreStats`].
4045    pub fn stats(&self) -> StoreStats {
4046        let n_sequences = self.catalog.n_sequences();
4047        let n_sequences_in_memory = self.loaded.len();
4048        let n_collections = self.catalog.n_collections();
4049        let n_collections_in_memory = self
4050            .catalog
4051            .coll_rows()
4052            .filter(|&c| self.catalog.is_loaded(c))
4053            .count();
4054        let mode_str = match self.mode {
4055            StorageMode::Raw => "Raw",
4056            StorageMode::Encoded => "Encoded",
4057            StorageMode::Zstd => "Zstd",
4058        };
4059        let packed_dead_bytes = if self.layout == Layout::Packed {
4060            self.packed_dead_bytes().ok()
4061        } else {
4062            None
4063        };
4064        StoreStats {
4065            n_sequences,
4066            n_sequences_in_memory,
4067            n_collections,
4068            n_collections_in_memory,
4069            storage_mode: mode_str.to_string(),
4070            logical_sequence_bytes: self.logical_sequence_bytes() as u64,
4071            packed_dead_bytes,
4072        }
4073    }
4074
4075    /// List alias namespaces available on this store (from manifest).
4076    pub fn available_alias_namespaces(&self) -> AvailableAliases<'_> {
4077        AvailableAliases {
4078            sequences: &self.available_sequence_alias_namespaces,
4079            collections: &self.available_collection_alias_namespaces,
4080        }
4081    }
4082}
4083
4084impl Display for ReadonlyRefgetStore {
4085    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
4086        let total_size = self.logical_sequence_bytes();
4087        let size_str = format_bytes(total_size);
4088        writeln!(f, "ReadonlyRefgetStore object:")?;
4089        writeln!(f, "  Mode: {:?}", self.mode)?;
4090        writeln!(f, "  Disk size: {} ({} bytes)", size_str, total_size)?;
4091        writeln!(f, ">Sequences (n={}):", self.catalog.n_sequences())?;
4092        for (i, view) in self.sequence_views().take(10).enumerate() {
4093            let first_8_chars = match self.loaded_arc(view.row()) {
4094                None => "<stub>".to_string(),
4095                Some(seq) => match self.mode {
4096                    StorageMode::Encoded => {
4097                        let alphabet = lookup_alphabet(&view.alphabet());
4098                        let decoded =
4099                            decode_substring_from_bytes(&seq, 0, 8.min(view.length()), alphabet);
4100                        String::from_utf8(decoded).unwrap_or_else(|_| "???".to_string())
4101                    }
4102                    StorageMode::Raw => String::from_utf8(seq[0..8.min(seq.len())].to_vec())
4103                        .unwrap_or_else(|_| "???".to_string()),
4104                    StorageMode::Zstd => zstd::decode_all(&seq[..])
4105                        .ok()
4106                        .and_then(|ascii| {
4107                            String::from_utf8(ascii[0..8.min(ascii.len())].to_vec()).ok()
4108                        })
4109                        .unwrap_or_else(|| "???".to_string()),
4110                },
4111            };
4112
4113            writeln!(
4114                f,
4115                "   - {}. {:02x?}, MD5: {:02x?}, Length: {}, Alphabet: {:?}, Start: {}",
4116                i + 1,
4117                view.sha512t24u().as_str(),
4118                view.md5().as_str(),
4119                view.length(),
4120                view.alphabet(),
4121                first_8_chars
4122            )?;
4123        }
4124        let loaded: Vec<CollRow> =
4125            self.catalog.coll_rows().filter(|&c| self.catalog.is_loaded(c)).collect();
4126        writeln!(f, ">Collections (n={:?}):", loaded.len())?;
4127        for (i, &c) in loaded.iter().enumerate() {
4128            let n = self.catalog.n_members(c);
4129            writeln!(
4130                f,
4131                "  {}. Collection Digest: {:02x?} ({} sequences)",
4132                i + 1,
4133                self.catalog.coll_meta(c).digest,
4134                n
4135            )?;
4136            for m in self.catalog.members(c).take(5) {
4137                writeln!(f, "   - Name: {}, SHA512: {:02x?}", m.name(), m.seq().sha512t24u().as_str())?;
4138            }
4139            if n > 5 {
4140                writeln!(f, "   - ... and {} more", n - 5)?;
4141            }
4142        }
4143
4144        Ok(())
4145    }
4146}
4147
4148
4149#[cfg(all(test, feature = "http"))]
4150mod open_remote_range_tests {
4151    use super::*;
4152    use std::net::TcpListener;
4153    use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
4154
4155    /// Spin up an HTTP server that DELIBERATELY IGNORES the Range header,
4156    /// responding 200 OK with the full body. Models a misbehaving CDN/origin.
4157    /// Returns (base_url, shutdown_fn).
4158    fn start_range_ignoring_server(body: Vec<u8>) -> (String, impl FnOnce()) {
4159        use std::io::{Read as _, Write as _};
4160
4161        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
4162        let port = listener.local_addr().unwrap().port();
4163        let base_url = format!("http://127.0.0.1:{}", port);
4164        let stop = Arc::new(AtomicBool::new(false));
4165        let stop_clone = Arc::clone(&stop);
4166
4167        std::thread::spawn(move || {
4168            listener.set_nonblocking(false).ok();
4169            while !stop_clone.load(Ordering::Relaxed) {
4170                match listener.accept() {
4171                    Ok((mut stream, _)) => {
4172                        let mut buf = [0u8; 4096];
4173                        let _ = stream.read(&mut buf).unwrap_or(0);
4174                        // Respond 200 OK with the full body, ignoring the Range header.
4175                        let header = format!(
4176                            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
4177                            body.len()
4178                        );
4179                        let _ = stream.write_all(header.as_bytes());
4180                        let _ = stream.write_all(&body);
4181                    }
4182                    Err(_) => break,
4183                }
4184            }
4185        });
4186
4187        let shutdown = move || {
4188            stop.store(true, Ordering::Relaxed);
4189            let _ = std::net::TcpStream::connect(format!("127.0.0.1:{}", port));
4190        };
4191
4192        (base_url, shutdown)
4193    }
4194
4195    /// When a remote server ignores the Range header and returns 200 + full body,
4196    /// `open_remote_range` MUST return an error rather than silently wrapping the
4197    /// wrong bytes in a StreamingDecoder. Otherwise callers get silent corruption.
4198    #[test]
4199    fn test_open_remote_range_rejects_non_206_response() {
4200        let full_body: Vec<u8> = (0u8..=255).collect();
4201        let (base_url, shutdown) = start_range_ignoring_server(full_body.clone());
4202
4203        // Request only a middle slice: bytes 10..20.
4204        let result = open_remote_range(
4205            &base_url,
4206            std::path::Path::new("seq.dat"),
4207            10,
4208            20,
4209        );
4210
4211        shutdown();
4212
4213        match result {
4214            Err(e) => {
4215                let msg = format!("{}", e);
4216                assert!(
4217                    msg.contains("Range") || msg.contains("206") || msg.contains("status"),
4218                    "expected a Range/206/status error, got: {}",
4219                    msg
4220                );
4221            }
4222            Ok(mut reader) => {
4223                use std::io::Read as _;
4224                let mut got = Vec::new();
4225                reader.read_to_end(&mut got).unwrap();
4226                // If we got here, the bug is live: the reader yielded bytes
4227                // that are NOT the requested 10..20 slice. The `.take(byte_len)`
4228                // in the buggy code returns the FIRST `byte_len` bytes of the
4229                // full body, i.e. 0..10, instead of the requested 10..20.
4230                assert_eq!(
4231                    got,
4232                    full_body[10..20],
4233                    "BUG: open_remote_range silently returned wrong bytes \
4234                     when server ignored the Range header. Got {:?}, expected {:?}. \
4235                     The function should have returned an error instead.",
4236                    got,
4237                    &full_body[10..20]
4238                );
4239            }
4240        }
4241    }
4242}
4243
4244/// Tests for the flow-1 remote byte-range fallback: a cold `get_substring` /
4245/// `get_substrings` against a remote-only `Stub` must fetch just the covering
4246/// bytes over HTTP `Range:`, decode correctly, and persist nothing.
4247#[cfg(all(test, feature = "http"))]
4248mod remote_partial_read_tests {
4249    use super::*;
4250    use crate::digest::digest_sequence;
4251    use std::io::{Read as _, Write as _};
4252    use std::net::TcpListener;
4253    use std::sync::{
4254        atomic::{AtomicBool, Ordering},
4255        Arc,
4256    };
4257
4258    /// Spin up an HTTP server that HONORS the `Range` header, replying 206 with
4259    /// the requested byte slice (and 200 + full body if no Range is sent). The
4260    /// same `body` is served for every path. Returns (base_url, shutdown_fn).
4261    fn start_range_honoring_server(body: Vec<u8>) -> (String, impl FnOnce()) {
4262        start_range_server(move |_| Some(body.clone()))
4263    }
4264
4265    /// The same server, serving each file under `root` at its relative path
4266    /// (404 for a path with no file), so a whole store directory is remote.
4267    #[cfg(feature = "filesystem")]
4268    fn start_store_dir_server(root: PathBuf) -> (String, impl FnOnce()) {
4269        start_range_server(move |rel| std::fs::read(root.join(rel)).ok())
4270    }
4271
4272    /// Range-honoring server whose body for a request path (without the
4273    /// leading `/`) comes from `lookup`; `None` is a 404.
4274    fn start_range_server(
4275        lookup: impl Fn(&str) -> Option<Vec<u8>> + Send + 'static,
4276    ) -> (String, impl FnOnce()) {
4277        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
4278        let port = listener.local_addr().unwrap().port();
4279        let base_url = format!("http://127.0.0.1:{}", port);
4280        let stop = Arc::new(AtomicBool::new(false));
4281        let stop_clone = Arc::clone(&stop);
4282
4283        std::thread::spawn(move || {
4284            while !stop_clone.load(Ordering::Relaxed) {
4285                match listener.accept() {
4286                    Ok((mut stream, _)) => {
4287                        let mut buf = [0u8; 4096];
4288                        let n = stream.read(&mut buf).unwrap_or(0);
4289                        let req = String::from_utf8_lossy(&buf[..n]);
4290                        let path = req
4291                            .lines()
4292                            .next()
4293                            .and_then(|l| l.split_whitespace().nth(1))
4294                            .unwrap_or("/")
4295                            .trim_start_matches('/');
4296                        let Some(body) = lookup(path) else {
4297                            let _ = stream.write_all(
4298                                b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
4299                            );
4300                            continue;
4301                        };
4302                        // Parse "Range: bytes=START-END" (inclusive END).
4303                        let range = req.lines().find_map(|l| {
4304                            let l = l.trim();
4305                            if !l.to_ascii_lowercase().starts_with("range:") {
4306                                return None;
4307                            }
4308                            let v = l.split('=').nth(1)?.trim();
4309                            let mut parts = v.split('-');
4310                            let s: usize = parts.next()?.trim().parse().ok()?;
4311                            let e: usize = parts.next()?.trim().parse().ok()?;
4312                            Some((s, e))
4313                        });
4314                        if let Some((s, e)) = range {
4315                            let s = s.min(body.len());
4316                            let end_excl = (e + 1).min(body.len());
4317                            let slice = &body[s..end_excl];
4318                            let header = format!(
4319                                "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {}-{}/{}\r\n\
4320                                 Content-Length: {}\r\nConnection: close\r\n\r\n",
4321                                s,
4322                                end_excl.saturating_sub(1),
4323                                body.len(),
4324                                slice.len()
4325                            );
4326                            let _ = stream.write_all(header.as_bytes());
4327                            let _ = stream.write_all(slice);
4328                        } else {
4329                            let header = format!(
4330                                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
4331                                body.len()
4332                            );
4333                            let _ = stream.write_all(header.as_bytes());
4334                            let _ = stream.write_all(&body);
4335                        }
4336                    }
4337                    Err(_) => break,
4338                }
4339            }
4340        });
4341
4342        let shutdown = move || {
4343            stop.store(true, Ordering::Relaxed);
4344            let _ = std::net::TcpStream::connect(format!("127.0.0.1:{}", port));
4345        };
4346
4347        (base_url, shutdown)
4348    }
4349
4350    /// A remote-only store: a `Stub` whose encoded bytes live solely on the
4351    /// remote server. No `local_path`, so nothing can be (or is) persisted.
4352    fn remote_only_store(remote: &str, record: &SequenceRecord) -> ReadonlyRefgetStore {
4353        let mut store = ReadonlyRefgetStore::new(StorageMode::Encoded);
4354        store.remote_source = Some(remote.to_string());
4355        store.seqdata_path_template = Some(DEFAULT_SEQDATA_PATH_TEMPLATE.to_string());
4356        let meta = record.metadata().clone();
4357        store.catalog.add_sequence(&meta).unwrap();
4358        store
4359    }
4360
4361    #[test]
4362    fn test_get_substring_cold_remote_byte_range_and_no_persist() {
4363        // Mixed ACGT + IUPAC (N) bases exercise the variable-bit decode path.
4364        let bases = b"ACGTACGTACGTTTGGCCAANNNNACGTACGTACGTACGTACGT";
4365        let record = digest_sequence("chrTest", bases);
4366        let meta = record.metadata().clone();
4367        let alphabet = lookup_alphabet(&meta.alphabet);
4368        let encoded = encode_sequence(&bases[..], alphabet).unwrap();
4369
4370        let (base_url, shutdown) = start_range_honoring_server(encoded.clone());
4371        let store = remote_only_store(&base_url, &record);
4372
4373        // Cold read of an interior sub-range: must fetch via byte-range + decode.
4374        let got = store
4375            .get_substring(meta.sha512t24u.as_bytes(), 4, 12)
4376            .expect("cold remote get_substring should succeed");
4377        let expected = String::from_utf8(bases[4..12].to_vec()).unwrap();
4378        assert_eq!(got, expected, "remote byte-range decode mismatch");
4379
4380        // Zero-length range on the REMOTE path returns "" (no HTTP request),
4381        // matching the resident/disk paths and the wasm/JS contract; an
4382        // inverted range (start > end) still errors.
4383        assert_eq!(
4384            store.get_substring(meta.sha512t24u.as_bytes(), 5, 5).unwrap(),
4385            "",
4386            "remote: zero-length range should return empty string"
4387        );
4388        assert!(
4389            store.get_substring(meta.sha512t24u.as_bytes(), 8, 4).is_err(),
4390            "remote: inverted range (start > end) must error"
4391        );
4392        let mixed = store
4393            .get_substrings(meta.sha512t24u.as_bytes(), &[(2, 2), (4, 8)])
4394            .expect("remote get_substrings with empty range should succeed");
4395        assert_eq!(mixed[0], "", "remote batch: empty range -> empty string");
4396        assert_eq!(mixed[1], String::from_utf8(bases[4..8].to_vec()).unwrap());
4397
4398        // Batch read of several disjoint ranges via the same remote fallback.
4399        let batch = store
4400            .get_substrings(meta.sha512t24u.as_bytes(), &[(0, 4), (20, 24), (40, 44)])
4401            .expect("cold remote get_substrings should succeed");
4402        shutdown();
4403        assert_eq!(batch[0], String::from_utf8(bases[0..4].to_vec()).unwrap());
4404        assert_eq!(batch[1], String::from_utf8(bases[20..24].to_vec()).unwrap());
4405        assert_eq!(batch[2], String::from_utf8(bases[40..44].to_vec()).unwrap());
4406
4407        // Persists nothing: no local path, and the record stays a Stub (never
4408        // promoted to a resident Full by the partial-read path).
4409        assert!(store.local_path.is_none());
4410        assert!(
4411            matches!(
4412                store.t_seq(&meta.sha512t24u.to_key()).unwrap(),
4413                SequenceRecord::Stub(_)
4414            ),
4415            "remote partial read must not promote the record to Full (no caching)"
4416        );
4417    }
4418
4419    #[test]
4420    fn test_get_substrings_bulk_remote_promotes_to_whole_download() {
4421        // 64-base sequence so we can request many disjoint ranges.
4422        let bases: &[u8] =
4423            b"ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT";
4424        let record = digest_sequence("chrBulk", bases);
4425        let meta = record.metadata().clone();
4426        let alphabet = lookup_alphabet(&meta.alphabet);
4427        let encoded = encode_sequence(bases, alphabet).unwrap();
4428
4429        let (base_url, shutdown) = start_range_honoring_server(encoded.clone());
4430
4431        // Remote store WITH a local cache dir, so the bulk path can promote into it.
4432        let cache_dir =
4433            std::env::temp_dir().join(format!("gtars_bulk_fetch_test_{}", meta.sha512t24u));
4434        let _ = std::fs::remove_dir_all(&cache_dir);
4435        std::fs::create_dir_all(&cache_dir).expect("create cache dir");
4436
4437        let mut store = ReadonlyRefgetStore::new(StorageMode::Encoded);
4438        store.remote_source = Some(base_url);
4439        store.seqdata_path_template = Some(DEFAULT_SEQDATA_PATH_TEMPLATE.to_string());
4440        store.local_path = Some(cache_dir.clone());
4441        store.catalog.add_sequence(&meta.clone()).unwrap();
4442
4443        let cached_path = cache_dir.join(ReadonlyRefgetStore::expand_template(
4444            &meta.sha512t24u,
4445            DEFAULT_SEQDATA_PATH_TEMPLATE,
4446        ));
4447
4448        // Sub-threshold batch: served per-range by byte-range; nothing cached.
4449        let small: Vec<(usize, usize)> = vec![(0, 3), (8, 11), (60, 63)];
4450        let small_out = store
4451            .get_substrings(meta.sha512t24u.as_bytes(), &small)
4452            .expect("small remote get_substrings should succeed");
4453        for (i, &(s, e)) in small.iter().enumerate() {
4454            assert_eq!(small_out[i], String::from_utf8(bases[s..e].to_vec()).unwrap());
4455        }
4456        assert!(
4457            !cached_path.exists(),
4458            "a sub-threshold batch must not download/cache the whole .seq"
4459        );
4460
4461        // Bulk batch (>= REMOTE_BULK_FETCH_THRESHOLD): promote to one whole
4462        // download, cache it, and serve every range from the local file.
4463        let bulk: Vec<(usize, usize)> = (0..REMOTE_BULK_FETCH_THRESHOLD)
4464            .map(|i| (i * 4, i * 4 + 3))
4465            .collect();
4466        assert_eq!(bulk.len(), REMOTE_BULK_FETCH_THRESHOLD);
4467        let bulk_out = store
4468            .get_substrings(meta.sha512t24u.as_bytes(), &bulk)
4469            .expect("bulk remote get_substrings should succeed");
4470        shutdown();
4471        for (i, &(s, e)) in bulk.iter().enumerate() {
4472            assert_eq!(
4473                bulk_out[i],
4474                String::from_utf8(bases[s..e].to_vec()).unwrap(),
4475                "bulk range {} decode mismatch",
4476                i
4477            );
4478        }
4479
4480        // The promotion cached the WHOLE encoded `.seq` (not a partial window).
4481        assert!(
4482            cached_path.exists(),
4483            "bulk batch must cache the whole .seq locally"
4484        );
4485        let on_disk = std::fs::read(&cached_path).expect("read cached .seq");
4486        assert_eq!(on_disk, encoded, "cached file must be the full encoded sequence");
4487
4488        let _ = std::fs::remove_dir_all(&cache_dir);
4489    }
4490
4491    /// A packed store served over HTTP reads back through every remote read
4492    /// path: one range and a small batch (byte ranges into the remote pack), a
4493    /// bulk batch (whole record fetched once and cached as a local `.seq`), the
4494    /// bulk batch again from that cache, `load_sequence`, and FASTA export.
4495    #[cfg(feature = "filesystem")]
4496    #[test]
4497    fn remote_packed_store_reads() {
4498        use crate::store::{ExportOptions, ExportSelection, LabelTemplate, RefgetStore};
4499
4500        let short = "GGGGCCCCAAAATTTT";
4501        let long: String = (0..200usize).map(|i| b"ACGT"[(i * 7 + i / 5) % 4] as char).collect();
4502        let with_n = "NNNNACGTACGTTTGGCCAANNNNACGT";
4503        // chrLong is second, so its record starts at a non-zero pack offset.
4504        let fasta = format!(">chrA\n{short}\n>chrLong\n{long}\n>chrN\n{with_n}\n");
4505        let sha = |name: &str, bases: &str| {
4506            digest_sequence(name, bases.as_bytes()).metadata().sha512t24u.clone()
4507        };
4508        let (long_sha, n_sha) = (sha("chrLong", &long), sha("chrN", with_n));
4509        let wanted = |ranges: &[(usize, usize)]| -> Vec<String> {
4510            ranges.iter().map(|&(s, e)| long[s..e].to_string()).collect()
4511        };
4512        let few: Vec<(usize, usize)> = vec![(0, 9), (10, 11), (37, 80), (150, 199), (5, 5)];
4513        let bulk: Vec<(usize, usize)> = (0..20).map(|i| (i * 9 + 1, i * 9 + 8)).collect();
4514        assert!(bulk.len() >= REMOTE_BULK_FETCH_THRESHOLD);
4515
4516        for mode in [StorageMode::Encoded, StorageMode::Raw, StorageMode::Zstd] {
4517            let work = tempfile::tempdir().unwrap();
4518            let fa = work.path().join("in.fa");
4519            std::fs::write(&fa, &fasta).unwrap();
4520            let served = work.path().join("served");
4521            let coll_digest = {
4522                let mut s = RefgetStore::on_disk_packed(&served).unwrap();
4523                s.set_quiet(true);
4524                s.set_encoding_mode(mode).unwrap();
4525                let (meta, _) = s
4526                    .add_sequence_collection_from_fasta(&fa, FastaImportOptions::new().jobs(1))
4527                    .unwrap();
4528                meta.digest
4529            };
4530            let pack_rows = super::super::packidx::read_pack_idx_rows(
4531                &std::fs::read(served.join("sequences.pack.idx")).unwrap(),
4532            )
4533            .unwrap();
4534            let long_row = &pack_rows[&long_sha];
4535            assert!(long_row.offset > 0, "{mode:?}: chrLong should not start its pack");
4536            let long_stored = std::fs::read(served.join(pack_relpath(&long_row.pack))).unwrap()
4537                [long_row.offset as usize..(long_row.offset + long_row.len) as usize]
4538                .to_vec();
4539
4540            let (url, shutdown) = start_store_dir_server(served.clone());
4541            let mut store = RefgetStore::open_remote(work.path().join("cache"), &url).unwrap();
4542            store.set_quiet(true);
4543            store.load_sequence_index().unwrap();
4544            assert_eq!(store.remote_layout, Layout::Packed);
4545
4546            // Zstd stores refuse remote partial reads by design.
4547            if mode != StorageMode::Zstd {
4548                let got = store.get_substring(&long_sha, 3, 50).unwrap();
4549                assert_eq!(got, long[3..50], "{mode:?}: one range");
4550                let got = store.get_substrings(&long_sha, &few).unwrap();
4551                assert_eq!(got, wanted(&few), "{mode:?}: small batch");
4552            }
4553
4554            let cached = store.sequence_file_path(&long_sha).unwrap();
4555            assert!(!cached.exists(), "{mode:?}: nothing cached before the bulk batch");
4556            let got = store
4557                .get_substrings(&long_sha, &bulk)
4558                .unwrap_or_else(|e| panic!("{mode:?}: bulk batch failed: {e:#}"));
4559            assert_eq!(got, wanted(&bulk), "{mode:?}: bulk batch");
4560            assert_eq!(
4561                std::fs::read(&cached).unwrap(),
4562                long_stored,
4563                "{mode:?}: the cached .seq must be the record's bytes from the pack"
4564            );
4565            let got = store.get_substrings(&long_sha, &bulk).unwrap();
4566            assert_eq!(got, wanted(&bulk), "{mode:?}: bulk batch from the cache");
4567
4568            store.load_sequence(&n_sha).unwrap();
4569            assert!(store.get_sequence(&n_sha).unwrap().is_loaded());
4570            let got = store.get_substring(&n_sha, 0, with_n.len()).unwrap();
4571            assert_eq!(got, with_n, "{mode:?}: loaded sequence");
4572
4573            let out = work.path().join("out.fa");
4574            let opts = ExportOptions {
4575                label: LabelTemplate::parse("{name}").unwrap(),
4576                molecule: None,
4577                line_width: 0,
4578            };
4579            let sel = ExportSelection::Collections { digests: vec![coll_digest], names: None };
4580            store.export_fasta(&sel, &out, &opts).unwrap();
4581            shutdown();
4582            assert_eq!(std::fs::read_to_string(&out).unwrap(), fasta, "{mode:?}: export");
4583        }
4584    }
4585}