gtars_refget/store/import.rs
1//! FASTA import pipeline for RefgetStore.
2//!
3//! Contains the streaming FASTA import pipeline and cached metadata fast path.
4//!
5//! ## Single-knob parallelism model
6//!
7//! There is ONE concurrency knob: `jobs` = the number of input FASTA files
8//! imported concurrently. With multiple files, up to `jobs` files are
9//! decoded/built concurrently, each with its OWN decoder (so K gzip streams
10//! decompress in parallel). With a single file `jobs` has no effect.
11//!
12//! ## Streaming, bounded-memory design
13//!
14//! Each builder emits sequences ONE AT A TIME over a bounded cross-file channel
15//! rather than accumulating a whole collection in RAM. The single inserter
16//! (owner, `&mut self`) writes each `.seq` to disk immediately as it arrives and
17//! retains only lightweight per-sequence METADATA (name + digest), so peak
18//! memory is bounded by `jobs x channel_depth x avg_encoded_seq_size` plus the
19//! on-disk index metadata, INDEPENDENT of how many sequences a collection holds.
20//!
21//! ### Per-file pipeline (basic chain)
22//!
23//! Each file is processed by a simple linear pipeline of ~3 threads with
24//! `bounded(1)` channels providing back-pressure (a couple of contigs in flight):
25//! a decompress/read thread, a digest thread, and an encode step on the build
26//! thread. Records flow through the chain in FASTA order; the build thread
27//! forwards each finished sequence onto the cross-file output channel instead of
28//! pushing into a `Vec`. This keeps each collection's member order (and
29//! therefore the collection digest) deterministic and identical to a
30//! single-threaded build.
31//!
32//! ### File-level parallelism (across files)
33//!
34//! The build half (decode + parse + digest + encode) touches NO shared store
35//! state and runs concurrently across files; the insert half (`&mut self`
36//! registration of sequences, collections and aliases) runs on a single
37//! owner. Because the on-disk indexes are written once at the end, sorted by
38//! content/collection digest, the resulting store is byte-identical to a serial
39//! build regardless of which builder finishes first or how `Seq`/`End` messages
40//! from different files interleave.
41
42use super::*;
43use super::readonly::ReadonlyRefgetStore;
44
45use std::collections::{HashMap, HashSet};
46use std::path::{Path, PathBuf};
47use std::sync::Mutex;
48use std::thread::available_parallelism;
49use std::time::Instant;
50
51use anyhow::{anyhow, Context, Result};
52use crossbeam_channel::{bounded, Receiver, Sender};
53
54use crate::collection::SequenceCollectionExt;
55use crate::digest::{
56 SequenceCollection, SequenceCollectionMetadata,
57 SequenceEncoder, SequenceMetadata, SequenceRecord,
58};
59use crate::hashkeyable::{DigestKey, HashKeyable};
60
61/// Threshold above which the reader processes sequences inline (to bound peak
62/// memory: the few huge contigs are hashed+encoded on the reader instead of
63/// being passed down the pipeline holding extra copies in flight).
64const LARGE_SEQ_THRESHOLD: usize = 500 * 1024 * 1024; // 500 MB
65
66/// Per-builder output channel depth (multiplied by `jobs` for the shared
67/// cross-file channel). Small constant: a couple sequences in flight per builder
68/// is enough to keep builders and the inserter busy without unbounded buffering.
69const CHANNEL_DEPTH: usize = 4;
70
71/// Bounded depth of the inserter -> writer-pool channel, per writer thread. The
72/// channel capacity is `K * WRITER_CHANNEL_DEPTH` so a few `.seq` writes can be
73/// queued ahead of the writers without unbounded buffering. Keeping this a small
74/// constant preserves the bounded-memory property (peak RAM stays O(K x channel
75/// depth x avg encoded seq size), independent of collection size).
76const WRITER_CHANNEL_DEPTH: usize = 8;
77
78/// A unit of work for the writer pool: one standalone `.seq` file, written to
79/// its full path. The inserter has already committed the dedup decision and
80/// the in-memory metadata; only the byte write is offloaded here. Per-digest
81/// files are independent, so the writes are race-free.
82type WriteJob = (PathBuf, Vec<u8>);
83
84/// A fully-built sequence ready for the single inserter, in FASTA order.
85///
86/// Carries the encoded bytes ONLY from emission until the inserter writes them
87/// to disk; the inserter then drops the bytes and keeps only metadata.
88struct ReadySequence {
89 metadata: SequenceMetadata,
90 sequence_data: Vec<u8>,
91 aliases: Vec<(String, String)>,
92}
93
94/// One message in the streaming import protocol, consumed by the single inserter.
95///
96/// A builder emits `Begin`, then one `Seq` per record in FASTA order, then `End`.
97/// Messages from different files may interleave on the shared channel; the
98/// `file_idx` tag disambiguates which in-flight collection each `Seq` belongs to.
99enum InsertMsg {
100 /// A builder started processing this file.
101 Begin { file_idx: usize },
102 /// The collection was found already present in the store (cached `.rgsi`
103 /// short-circuit). No `Begin`/`Seq`/`End` is emitted for this file: the FASTA
104 /// is never opened or decoded. The inserter records `was_new = false`.
105 Skip {
106 file_idx: usize,
107 metadata: SequenceCollectionMetadata,
108 },
109 /// One fully digested+encoded sequence, in FASTA order within its file.
110 Seq {
111 file_idx: usize,
112 ready: ReadySequence,
113 },
114 /// The collection finished: metadata computed from the retained per-sequence
115 /// stubs (NOT from bytes), plus the RGSI cache path (raw builds only).
116 End {
117 file_idx: usize,
118 metadata: SequenceCollectionMetadata,
119 stub_records: Vec<SequenceRecord>,
120 rgsi_cache_path: Option<PathBuf>,
121 source_path: PathBuf,
122 seq_count: usize,
123 },
124}
125
126// ============================================================================
127// Build half (no &mut self): decode + parse + digest + encode -> stream of msgs
128//
129// These free functions run concurrently across files. They touch NO shared
130// store state; they emit `InsertMsg`s onto a bounded channel. The inserter on a
131// single owner thread persists them.
132// ============================================================================
133
134/// Configuration needed by the build half, extracted from the store so the
135/// build can run without borrowing `&self` across threads.
136#[derive(Clone, Copy)]
137struct BuildConfig<'a> {
138 mode: StorageMode,
139 quiet: bool,
140 ancillary_digests: bool,
141 /// Whether the store is disk-backed (controls RGSI cache read/write).
142 use_cache: bool,
143 namespaces: &'a [&'a str],
144 /// Re-process collections even if already present (disables the cached
145 /// `.rgsi` pre-decode short-circuit).
146 force: bool,
147 /// Read-only snapshot of collection digest keys already present in the store,
148 /// taken once before builders spawn. Lets the build half (which has no
149 /// `&self`) short-circuit an already-present collection BEFORE opening the
150 /// FASTA, avoiding a wasteful decode+encode on resume.
151 present_collections: &'a HashSet<DigestKey>,
152}
153
154/// Build half for a single FASTA file: digest + encode, streaming each sequence
155/// onto `out` as `InsertMsg::Seq`, framed by `Begin`/`End`.
156///
157/// Checks for an RGSI metadata cache first and dispatches to the cached fast
158/// path if present and valid; otherwise runs the full digest+encode pipeline.
159/// Does NOT touch `&mut self`.
160fn build_collection_from_fasta(
161 file_idx: usize,
162 file_path: &Path,
163 cfg: BuildConfig<'_>,
164 out: &Sender<InsertMsg>,
165) -> Result<()> {
166 use crate::utils::PathExtension;
167
168 let rgsi_path = file_path.replace_exts_with("rgsi");
169 let have_rgsi = cfg.use_cache && rgsi_path.exists();
170
171 if have_rgsi {
172 match build_collection_from_cached_metadata(file_idx, file_path, &rgsi_path, cfg, out) {
173 Ok(()) => return Ok(()),
174 Err(BuildError::Channel(e)) => return Err(BuildError::Channel(e).into()),
175 Err(BuildError::Encode(e)) => return Err(BuildError::Encode(e).into()),
176 // Cache was stale/empty; fall through to the full pipeline. Note: a
177 // partial cached run cannot have emitted `Seq`s (the cache validity
178 // is checked before any `Begin`/`Seq` is sent), so re-running the
179 // full pipeline is safe.
180 Err(BuildError::Other(_)) => {}
181 }
182 }
183
184 build_collection_full(file_idx, file_path, cfg, out)
185}
186
187/// Errors from the build half. `Channel` means the inserter hung up (fatal);
188/// `Encode` means a sequence could not be encoded with its alphabet after
189/// `Begin` was sent (fatal); `Other` means a recoverable build error (e.g.
190/// stale cache) the caller may choose to handle by falling through to another
191/// path.
192enum BuildError {
193 Channel(anyhow::Error),
194 Encode(anyhow::Error),
195 Other(anyhow::Error),
196}
197
198impl From<BuildError> for anyhow::Error {
199 fn from(e: BuildError) -> Self {
200 match e {
201 BuildError::Channel(e) | BuildError::Encode(e) | BuildError::Other(e) => e,
202 }
203 }
204}
205
206/// Full build half: digest + encode every sequence and stream it to the inserter.
207///
208/// Uses the basic 3-thread chain: a reader/decompress thread, a digest thread,
209/// and the encode step on this (build) thread. `bounded(1)` channels keep at
210/// most a couple of contigs in flight, capping per-builder RAM. Records flow in
211/// FASTA order, and each finished sequence is forwarded onto `out` (the shared
212/// cross-file channel) instead of being collected into a Vec. The builder
213/// retains ONLY the lightweight stub metadata to compute the collection digest
214/// at `End` -- never the encoded bytes.
215fn build_collection_full(
216 file_idx: usize,
217 file_path: &Path,
218 cfg: BuildConfig<'_>,
219 out: &Sender<InsertMsg>,
220) -> Result<()> {
221 use crate::utils::PathExtension;
222 use md5::Md5;
223 use sha2::{Digest, Sha512};
224
225 // --- Channel message types ---
226 struct DecompressedSequence {
227 name: String,
228 description: Option<String>,
229 raw_header: String,
230 raw_bytes: Vec<u8>,
231 }
232 struct DigestedSequence {
233 metadata: SequenceMetadata,
234 raw_bytes: Vec<u8>,
235 aliases: Vec<(String, String)>,
236 }
237 enum ToDigest {
238 NeedsWork(DecompressedSequence),
239 AlreadyDone(ReadySequence),
240 }
241 enum ToEncode {
242 NeedsWork(DigestedSequence),
243 AlreadyDone(ReadySequence),
244 }
245
246 let (decompress_tx, decompress_rx) = bounded::<ToDigest>(1);
247 let (digest_tx, digest_rx) = bounded::<ToEncode>(1);
248
249 let file_path_buf = file_path.to_path_buf();
250 let namespaces: Vec<String> = cfg.namespaces.iter().map(|s| s.to_string()).collect();
251 let ns_for_digest = namespaces.clone();
252
253 let quiet = cfg.quiet;
254 let mode = cfg.mode;
255
256 // --- Thread 1: read FASTA (decompress) ---
257 let decompress_handle = std::thread::spawn(move || -> Result<()> {
258 let mut fasta_reader = crate::fasta::FastaReader::from_path(&file_path_buf)?;
259
260 while let Some(record) = fasta_reader.next_record()? {
261 if record.raw_bytes.len() > LARGE_SEQ_THRESHOLD {
262 if !quiet {
263 println!(
264 " Large sequence '{}' ({} MB) -- processing inline to reduce memory",
265 record.name,
266 record.raw_bytes.len() / (1024 * 1024),
267 );
268 }
269 let crate::fasta::FastaRecord { name, description, raw_header, raw_bytes } = record;
270
271 let mut sha512_hasher = Sha512::new();
272 sha512_hasher.update(&raw_bytes);
273 let sha512 = base64_url::encode(&sha512_hasher.finalize()[0..24]);
274
275 let mut md5_hasher = Md5::new();
276 md5_hasher.update(&raw_bytes);
277 let md5 = format!("{:x}", md5_hasher.finalize());
278
279 let mut guesser = crate::digest::AlphabetGuesser::new();
280 guesser.update(&raw_bytes);
281 let alphabet = guesser.guess();
282
283 let length = raw_bytes.len();
284 let aliases = if !namespaces.is_empty() {
285 let ns_refs: Vec<&str> = namespaces.iter().map(|s| s.as_str()).collect();
286 crate::digest::fasta::extract_aliases_from_header(&raw_header, &ns_refs)
287 } else {
288 vec![]
289 };
290 let sequence_data = match mode {
291 StorageMode::Encoded => {
292 let mut encoder = SequenceEncoder::new(alphabet, length);
293 encoder.update(&raw_bytes);
294 drop(raw_bytes);
295 encoder
296 .finalize()
297 .with_context(|| format!("encoding {name}"))?
298 }
299 StorageMode::Raw => raw_bytes,
300 // Zstd stores compress the whole ASCII body at the store's
301 // write seam (add_sequence_record[_deferred_write]); pass
302 // ASCII through here unpacked.
303 StorageMode::Zstd => raw_bytes,
304 };
305
306 let metadata = SequenceMetadata {
307 name,
308 description,
309 length,
310 sha512t24u: sha512,
311 md5,
312 alphabet,
313 fai: None,
314 };
315
316 decompress_tx
317 .send(ToDigest::AlreadyDone(ReadySequence {
318 metadata,
319 sequence_data,
320 aliases,
321 }))
322 .map_err(|_| anyhow!("Digest thread stopped receiving"))?;
323 } else {
324 decompress_tx
325 .send(ToDigest::NeedsWork(DecompressedSequence {
326 name: record.name,
327 description: record.description,
328 raw_header: record.raw_header,
329 raw_bytes: record.raw_bytes,
330 }))
331 .map_err(|_| anyhow!("Digest thread stopped receiving"))?;
332 }
333 }
334 Ok(())
335 });
336
337 // --- Thread 2: digest ---
338 let digest_handle = std::thread::spawn(move || -> Result<()> {
339 let ns_refs: Vec<&str> = ns_for_digest.iter().map(|s| s.as_str()).collect();
340
341 for msg in decompress_rx {
342 match msg {
343 ToDigest::NeedsWork(seq) => {
344 let mut sha512_hasher = Sha512::new();
345 sha512_hasher.update(&seq.raw_bytes);
346 let sha512 = base64_url::encode(&sha512_hasher.finalize()[0..24]);
347
348 let mut md5_hasher = Md5::new();
349 md5_hasher.update(&seq.raw_bytes);
350 let md5 = format!("{:x}", md5_hasher.finalize());
351
352 let mut guesser = crate::digest::AlphabetGuesser::new();
353 guesser.update(&seq.raw_bytes);
354 let alphabet = guesser.guess();
355
356 let metadata = SequenceMetadata {
357 name: seq.name,
358 description: seq.description,
359 length: seq.raw_bytes.len(),
360 sha512t24u: sha512,
361 md5,
362 alphabet,
363 fai: None,
364 };
365
366 let aliases = if !ns_refs.is_empty() {
367 crate::digest::fasta::extract_aliases_from_header(&seq.raw_header, &ns_refs)
368 } else {
369 vec![]
370 };
371
372 digest_tx
373 .send(ToEncode::NeedsWork(DigestedSequence {
374 metadata,
375 raw_bytes: seq.raw_bytes,
376 aliases,
377 }))
378 .map_err(|_| anyhow!("Encode thread stopped receiving"))?;
379 }
380 ToDigest::AlreadyDone(ready) => {
381 digest_tx
382 .send(ToEncode::AlreadyDone(ready))
383 .map_err(|_| anyhow!("Encode thread stopped receiving"))?;
384 }
385 }
386 }
387 drop(digest_tx);
388 Ok(())
389 });
390
391 // --- Thread 3 (this thread): encode + stream in FASTA order ---
392 // Emit Begin, then a Seq per record. Retain ONLY stub metadata + alias
393 // triples (no bytes) to compute the collection digest at End.
394 out.send(InsertMsg::Begin { file_idx })
395 .map_err(|_| anyhow!("Inserter stopped receiving"))?;
396
397 let mut stub_records: Vec<SequenceRecord> = Vec::new();
398
399 for msg in digest_rx {
400 let ready = match msg {
401 ToEncode::NeedsWork(digested) => {
402 let sequence_data = match mode {
403 StorageMode::Encoded => {
404 let mut encoder =
405 SequenceEncoder::new(digested.metadata.alphabet, digested.metadata.length);
406 encoder.update(&digested.raw_bytes);
407 drop(digested.raw_bytes);
408 encoder
409 .finalize()
410 .with_context(|| format!("encoding {}", digested.metadata.name))?
411 }
412 StorageMode::Raw => digested.raw_bytes,
413 // See the Zstd note above: pass ASCII through; the store
414 // write seam owns compression.
415 StorageMode::Zstd => digested.raw_bytes,
416 };
417 ReadySequence {
418 metadata: digested.metadata,
419 sequence_data,
420 aliases: digested.aliases,
421 }
422 }
423 ToEncode::AlreadyDone(ready) => ready,
424 };
425
426 stub_records.push(SequenceRecord::Stub(ready.metadata.clone()));
427 out.send(InsertMsg::Seq { file_idx, ready })
428 .map_err(|_| anyhow!("Inserter stopped receiving"))?;
429 }
430
431 // Join threads and propagate errors.
432 decompress_handle
433 .join()
434 .map_err(|e| anyhow!("Decompress thread panicked: {:?}", e))??;
435 digest_handle
436 .join()
437 .map_err(|e| anyhow!("Digest thread panicked: {:?}", e))??;
438
439 // Compute collection metadata from the retained sequence stubs (FASTA order).
440 let mut seqcol_metadata = SequenceCollectionMetadata::from_sequences(
441 &stub_records,
442 Some(file_path.to_path_buf()),
443 );
444 if cfg.ancillary_digests {
445 seqcol_metadata.compute_ancillary_digests(&stub_records);
446 }
447
448 let seq_count = stub_records.len();
449 let rgsi_cache_path = if cfg.use_cache {
450 Some(file_path.replace_exts_with("rgsi"))
451 } else {
452 None
453 };
454
455 out.send(InsertMsg::End {
456 file_idx,
457 metadata: seqcol_metadata,
458 stub_records,
459 rgsi_cache_path,
460 source_path: file_path.to_path_buf(),
461 seq_count,
462 })
463 .map_err(|_| anyhow!("Inserter stopped receiving"))?;
464
465 Ok(())
466}
467
468/// Build half for the RGSI cached-metadata fast path: skip digesting, only
469/// decompress + encode, streaming each sequence to the inserter.
470///
471/// Uses a basic 2-thread split: a reader/decompress thread feeds raw records
472/// (with their already-known cached metadata) to this thread, which encodes them
473/// in FASTA order and forwards them. Returns `BuildError::Other` if the cache is
474/// invalid (caller falls through to the full pipeline) -- this is checked BEFORE
475/// any `Begin`/`Seq` is emitted.
476fn build_collection_from_cached_metadata(
477 file_idx: usize,
478 file_path: &Path,
479 rgsi_path: &Path,
480 cfg: BuildConfig<'_>,
481 out: &Sender<InsertMsg>,
482) -> Result<(), BuildError> {
483 let mut seqcol = crate::collection::read_rgsi_file(rgsi_path)
484 .map_err(BuildError::Other)?;
485
486 if seqcol.sequences.is_empty() {
487 let _ = std::fs::remove_file(rgsi_path);
488 return Err(BuildError::Other(anyhow!("Empty RGSI cache")));
489 }
490
491 // Pre-decode short-circuit: if this collection is already present in the
492 // store (and we're not forcing), skip it WITHOUT opening/decoding the FASTA.
493 // The `.rgsi` sidecar gave us the collection digest for free; re-decoding +
494 // re-encoding every record only to discover the duplicate at `End` wastes
495 // enormous CPU on resume. Emit a `Skip` so the inserter records
496 // `was_new = false`, then return before spawning the reader thread.
497 if !cfg.force && cfg.present_collections.contains(&seqcol.metadata.digest.to_key()) {
498 if !cfg.quiet {
499 println!(
500 "Skipped {} (already exists) [cached metadata]",
501 seqcol.metadata.digest
502 );
503 }
504 out.send(InsertMsg::Skip {
505 file_idx,
506 metadata: seqcol.metadata.clone(),
507 })
508 .map_err(|_| BuildError::Channel(anyhow!("Inserter stopped receiving")))?;
509 return Ok(());
510 }
511
512 if cfg.ancillary_digests {
513 seqcol.metadata.compute_ancillary_digests(&seqcol.sequences);
514 }
515
516 let mut seqmeta_hashmap: HashMap<String, SequenceMetadata> =
517 HashMap::with_capacity(seqcol.sequences.len());
518 for r in &seqcol.sequences {
519 let meta = r.metadata().clone();
520 if seqmeta_hashmap.insert(meta.name.clone(), meta).is_some() {
521 return Err(BuildError::Other(anyhow!(
522 "RGSI cache has duplicate sequence names; rebuilding from FASTA"
523 )));
524 }
525 }
526
527 let mode = cfg.mode;
528 let namespaces: Vec<String> = cfg.namespaces.iter().map(|s| s.to_string()).collect();
529 let file_path_buf = file_path.to_path_buf();
530
531 // Reader item: a raw record plus its already-known cached metadata.
532 struct CachedRaw {
533 metadata: SequenceMetadata,
534 raw_bytes: Vec<u8>,
535 aliases: Vec<(String, String)>,
536 }
537
538 let (read_tx, read_rx) = bounded::<CachedRaw>(1);
539
540 // --- Thread 1: read FASTA + look up cached metadata ---
541 let read_handle = std::thread::spawn(move || -> Result<()> {
542 let ns_refs: Vec<&str> = namespaces.iter().map(|s| s.as_str()).collect();
543 let mut fasta_reader = crate::fasta::FastaReader::from_path(&file_path_buf)?;
544
545 while let Some(record) = fasta_reader.next_record()? {
546 let (name, _) = crate::fasta::parse_fasta_header(&record.raw_header);
547
548 let aliases = if !ns_refs.is_empty() {
549 crate::digest::fasta::extract_aliases_from_header(&record.raw_header, &ns_refs)
550 } else {
551 vec![]
552 };
553
554 let dr = seqmeta_hashmap
555 .get(&name)
556 .ok_or_else(|| anyhow!("Sequence '{}' not found in cached metadata", name))?
557 .clone();
558
559 read_tx
560 .send(CachedRaw {
561 metadata: dr,
562 raw_bytes: record.raw_bytes,
563 aliases,
564 })
565 .map_err(|_| anyhow!("Encode thread stopped receiving"))?;
566 }
567 Ok(())
568 });
569
570 // The cache is valid; from here on we emit Begin/Seq/End. A channel error is
571 // fatal (inserter hung up), not a recoverable cache miss.
572 out.send(InsertMsg::Begin { file_idx })
573 .map_err(|_| BuildError::Channel(anyhow!("Inserter stopped receiving")))?;
574
575 // --- Thread 2 (this thread): encode + stream in FASTA order ---
576 for unit in read_rx {
577 let sequence_data = match mode {
578 StorageMode::Encoded => {
579 let mut encoder =
580 SequenceEncoder::new(unit.metadata.alphabet, unit.metadata.length);
581 encoder.update(&unit.raw_bytes);
582 drop(unit.raw_bytes);
583 encoder.finalize().map_err(|e| {
584 BuildError::Encode(anyhow::Error::new(e).context(format!(
585 "encoding {} with the alphabet from cached metadata {}; \
586 delete the stale .rgsi cache and re-import",
587 unit.metadata.name,
588 rgsi_path.display()
589 )))
590 })?
591 }
592 StorageMode::Raw => unit.raw_bytes,
593 // See the Zstd note above: pass ASCII through; the store write seam
594 // owns compression.
595 StorageMode::Zstd => unit.raw_bytes,
596 };
597 let ready = ReadySequence {
598 metadata: unit.metadata,
599 sequence_data,
600 aliases: unit.aliases,
601 };
602 out.send(InsertMsg::Seq { file_idx, ready })
603 .map_err(|_| BuildError::Channel(anyhow!("Inserter stopped receiving")))?;
604 }
605
606 read_handle
607 .join()
608 .map_err(|e| BuildError::Other(anyhow!("Decompress thread panicked: {:?}", e)))?
609 .map_err(BuildError::Other)?;
610
611 let stub_records = seqcol.sequences.clone();
612 let metadata = seqcol.metadata.clone();
613 let seq_count = stub_records.len();
614
615 out.send(InsertMsg::End {
616 file_idx,
617 metadata,
618 stub_records,
619 // Cache already exists and is valid; no need to rewrite it.
620 rgsi_cache_path: None,
621 source_path: file_path.to_path_buf(),
622 seq_count,
623 })
624 .map_err(|_| BuildError::Channel(anyhow!("Inserter stopped receiving")))?;
625
626 Ok(())
627}
628
629/// Count FASTA records (`>` header lines) in a possibly-gzipped file, without
630/// digesting or encoding. Used by the standalone pre-flight count gate.
631fn count_fasta_records(path: &Path) -> Result<usize> {
632 use std::io::BufRead;
633 let mut reader = gtars_core::utils::get_dynamic_reader(path)
634 .with_context(|| format!("opening {} for a pre-flight count", path.display()))?;
635 let mut n = 0usize;
636 let mut buf = Vec::new();
637 loop {
638 buf.clear();
639 let read = reader.read_until(b'\n', &mut buf)?;
640 if read == 0 {
641 break;
642 }
643 if buf.first() == Some(&b'>') {
644 n += 1;
645 }
646 }
647 Ok(n)
648}
649
650/// Count the `.rgsi` sidecar rows whose sequence is NOT already in the store.
651/// Used by the pre-flight count gate, so re-importing a FASTA the store
652/// already holds adds nothing to the count.
653fn count_new_rgsi_rows(path: &Path, is_present: impl Fn(&str) -> bool) -> Result<usize> {
654 use std::io::BufRead;
655 let file = std::fs::File::open(path)?;
656 let mut n = 0usize;
657 for line in std::io::BufReader::new(file).lines() {
658 let line = line?;
659 if line.starts_with('#') {
660 continue;
661 }
662 if let Some(f) = crate::digest::types::parse_rgsi_fields(&line) {
663 if !is_present(f.sha512t24u) {
664 n += 1;
665 }
666 }
667 }
668 Ok(n)
669}
670
671// ============================================================================
672// Per-in-flight collection scratch held by the inserter
673// ============================================================================
674
675/// Lightweight per-in-flight-collection state held by the single inserter
676/// between `Begin` and `End`. Metadata-sized only -- never holds encoded bytes
677/// (those are written to disk as each `Seq` arrives, then dropped). At most
678/// `jobs` of these are live at once.
679struct InFlight {
680 /// (namespace, alias_value, sha512t24u) alias triples in FASTA order.
681 aliases: Vec<(String, String, String)>,
682}
683
684impl InFlight {
685 fn new() -> Self {
686 InFlight {
687 aliases: Vec::new(),
688 }
689 }
690}
691
692// ============================================================================
693// ReadonlyRefgetStore import methods
694// ============================================================================
695
696impl ReadonlyRefgetStore {
697 /// Import multiple FASTA files into the store with file-level parallelism.
698 ///
699 /// Up to `jobs` files are decoded/built concurrently (each with its own
700 /// decoder, so gzip decompression is parallelized across files). Each builder
701 /// STREAMS its sequences one at a time over a bounded cross-file channel; the
702 /// single inserter (`&mut self`) on this owner thread persists each `.seq`
703 /// immediately and retains only metadata, so peak memory is bounded by
704 /// `jobs x channel_depth x avg_encoded_seq_size`, independent of collection
705 /// size. The on-disk indexes are written once at the very end (sorted by
706 /// content/collection digest), guaranteeing a byte-identical store to a serial
707 /// build regardless of build/arrival order.
708 ///
709 /// Returns an [`ImportReport`]: per-file `(collection_metadata, was_new)`
710 /// results in input order, plus genuine per-run ingest counters
711 /// (`n_sequences_written`, `n_sequences_deduped`, `n_collections_new`).
712 /// Note these are per-RUN counts, unlike [`StoreStats`], which is a
713 /// RAM-residency snapshot.
714 ///
715 /// ## Error handling / non-transactional semantics
716 ///
717 /// This function is NOT fully transactional. On a build or writer error, any
718 /// sequences already emitted (as `InsertMsg::Seq`) before the failure may have
719 /// been written to disk (as `.seq` files or into a pack) and inserted into
720 /// the in-memory catalog, but the corresponding collection will NOT be
721 /// registered (it never received an `End`). These are orphan sequences:
722 /// referenced by no surviving collection.
723 ///
724 /// On error this function calls [`Self::remove_orphan_seq_files`] which
725 /// performs a best-effort cleanup: it removes every sequence this import
726 /// staged (and its `.seq` file) that no surviving collection references.
727 /// The in-memory store is left consistent (no dangling references), but if
728 /// you require a fully clean store on error, discard the store and rebuild.
729 pub fn add_sequence_collections_from_fastas(
730 &mut self,
731 files: &[PathBuf],
732 opts: FastaImportOptions<'_>,
733 ) -> Result<ImportReport> {
734 if files.is_empty() {
735 return Ok(ImportReport {
736 collections: Vec::new(),
737 n_sequences_written: 0,
738 n_sequences_deduped: 0,
739 n_collections_new: 0,
740 });
741 }
742
743 // One collection alias cannot name N collections. Reject BEFORE any
744 // thread spawns or any file is opened, so a rejected call leaves the
745 // store completely untouched. Applying the alias to every collection
746 // would let an arbitrary one win (finalize order across builder threads
747 // is non-deterministic), which is a worse version of the silent
748 // misnaming this option exists to eliminate.
749 if opts.collection_alias.is_some() && files.len() > 1 {
750 return Err(anyhow!(
751 "collection_alias names a single collection but {} FASTA files were given; \
752 import them without collection_alias and call add_collection_alias() per \
753 returned collection metadata (results are in input order)",
754 files.len(),
755 ));
756 }
757
758 // Resolve concurrency: 0 = auto (available_parallelism). Has no effect
759 // with a single file (clamped to 1).
760 let jobs = match opts.jobs {
761 0 => available_parallelism().map(|n| n.get()).unwrap_or(1),
762 n => n,
763 };
764 let jobs = jobs.min(files.len()).max(1);
765
766 // Pre-flight count gate (STANDALONE disk imports only). Packed stores
767 // bypass it; `standalone_file_limit` sets the ceiling. Checked BEFORE
768 // any bytes are written, via a cheap counting pass (no digesting, no
769 // encoding).
770 if self.persist_to_disk && self.layout == Layout::Standalone {
771 use crate::utils::PathExtension;
772 let existing = self.catalog.n_sequences();
773 let limit = opts.standalone_file_limit;
774 let mut counted = 0usize;
775 for file in files {
776 let rgsi = file.replace_exts_with("rgsi");
777 // The sidecar lists digests, so count only sequences the store
778 // lacks. Without it we cannot tell, so count every record.
779 let n = if self.local_path.is_some() && rgsi.exists() {
780 count_new_rgsi_rows(&rgsi, |d| self.seq_row(d).is_some()).unwrap_or(0)
781 } else {
782 count_fasta_records(file)?
783 };
784 counted += n;
785 if existing + counted > limit {
786 return Err(anyhow!(
787 "importing {} sequences would put the store at {} standalone .seq \
788 files, over the limit of {}. Re-create the store with the packed \
789 layout (CLI `--packed`, Python `RefgetStore.on_disk(path, \
790 packed=True)`, R `refget_store_on_disk(path, packed = TRUE)`), \
791 or raise standalone_file_limit.",
792 counted,
793 existing + counted,
794 limit
795 ));
796 }
797 }
798 }
799
800 // Snapshot the digest keys of collections already present in the store,
801 // taken ONCE here (before any builder spawns). The build half has no
802 // `&self`, so this read-only set is how it learns which collections can
803 // be skipped before opening their FASTAs. New collections added during
804 // this run are NOT in the snapshot, so they are never wrongly skipped;
805 // duplicates within the same batch are still deduped by the inserter.
806 let present_collections: HashSet<DigestKey> = self
807 .catalog
808 .coll_rows()
809 .map(|c| self.catalog.coll_meta(c).digest.to_key())
810 .collect();
811
812 let cfg = BuildConfig {
813 mode: self.mode,
814 quiet: self.quiet,
815 ancillary_digests: self.ancillary_digests,
816 use_cache: self.local_path.is_some(),
817 namespaces: opts.namespaces,
818 force: opts.force,
819 present_collections: &present_collections,
820 };
821
822 let overall_start = Instant::now();
823
824 // Per-file results, filled in by the inserter as each `End` arrives, then
825 // returned in input order.
826 let mut results: Vec<Option<(SequenceCollectionMetadata, bool)>> =
827 (0..files.len()).map(|_| None).collect();
828
829 // Bounded cross-file output channel: builders block on `send` when it is
830 // full, throttling fast builders to the inserter's pace (back-pressure)
831 // and capping in-flight encoded bytes.
832 let (out_tx, out_rx) = bounded::<InsertMsg>(jobs * CHANNEL_DEPTH);
833
834 // Bounded job queue feeds a fixed pool of `jobs` builder threads.
835 let (job_tx, job_rx) = bounded::<(usize, PathBuf)>(jobs);
836
837 // The first builder error encountered (build threads stash it here).
838 let build_err: std::sync::Mutex<Option<anyhow::Error>> = std::sync::Mutex::new(None);
839 let build_err_ref = &build_err;
840
841 // --- Writer pool (disk-backed standalone stores only) ----------------
842 // The single inserter does the FAST in-memory work (dedup decision,
843 // alias buffering, collection finalization) and DISPATCHES
844 // the actual `.seq` byte write for each NEW sequence to a bounded pool
845 // of `jobs` writer threads. Per-digest `.seq` files are independent, so
846 // these writes are race-free. A BOUNDED channel provides back-pressure
847 // so memory stays O(jobs x channel depth x avg seq size). In-memory mode
848 // never dispatches (the writer pool is effectively unused). The shard-dir
849 // cache lets writers skip a `create_dir_all` syscall per (tiny) sequence.
850 // A packed store appends each new sequence to its session pack on the
851 // inserter thread instead, in arrival order, so the packs and the
852 // sidecar are the same for any job count.
853 let writer_disk_backed = self.persist_to_disk && self.local_path.is_some();
854 let packed = self.layout == Layout::Packed;
855 let (write_tx, write_rx) = bounded::<WriteJob>(jobs * WRITER_CHANNEL_DEPTH);
856 let created_shards: Mutex<HashSet<PathBuf>> = Mutex::new(HashSet::new());
857 let created_shards_ref = &created_shards;
858 let write_err: Mutex<Option<anyhow::Error>> = Mutex::new(None);
859 let write_err_ref = &write_err;
860
861 // --- Per-run ingest counters ----------------------------------------
862 // Plain locals, not atomics: the inserter loop runs on THIS thread
863 // (inside the scope closure), so these are ordinary register/stack
864 // increments with no synchronization in the per-sequence hot path.
865 let mut n_seqs_written: usize = 0;
866 let mut n_seqs_deduped: usize = 0;
867
868 let scope_result = std::thread::scope(|scope| -> Result<()> {
869 // Spawn the writer pool. Each writer drains `WriteJob`s and writes
870 // the `.seq` bytes; the first error is stashed and stops the writer.
871 let mut writer_handles = Vec::with_capacity(jobs);
872 if writer_disk_backed && !packed {
873 for _ in 0..jobs {
874 let write_rx: Receiver<WriteJob> = write_rx.clone();
875 let handle = scope.spawn(move || {
876 for (full_path, bytes) in write_rx.iter() {
877 let result = ReadonlyRefgetStore::write_seq_bytes_to_full_path(
878 &full_path,
879 &bytes,
880 created_shards_ref,
881 );
882 if let Err(e) = result {
883 let mut slot = write_err_ref.lock().unwrap();
884 if slot.is_none() {
885 *slot = Some(e);
886 }
887 break;
888 }
889 }
890 });
891 writer_handles.push(handle);
892 }
893 }
894 // The inserter keeps its own clone of `write_tx`; drop this extra one
895 // so the writers' channel closes once the inserter drops its clone.
896 drop(write_rx);
897
898 // Spawn the builder pool.
899 for _ in 0..jobs {
900 let job_rx = job_rx.clone();
901 let out_tx = out_tx.clone();
902 scope.spawn(move || {
903 for (idx, path) in job_rx.iter() {
904 if let Err(e) = build_collection_from_fasta(idx, &path, cfg, &out_tx) {
905 let mut slot = build_err_ref.lock().unwrap();
906 if slot.is_none() {
907 *slot = Some(e);
908 }
909 // Stop pulling more jobs; let the inserter drain and
910 // the scope tear down.
911 break;
912 }
913 }
914 });
915 }
916 // Drop our extra senders so the inserter's loop terminates once all
917 // builders finish.
918 drop(out_tx);
919 drop(job_rx);
920
921 // Feeder thread: push all jobs, then drop the sender. Runs in the
922 // scope so it can proceed while the inserter (this thread) drains the
923 // output channel -- otherwise a bounded job queue + bounded output
924 // channel could deadlock.
925 let feeder = {
926 let job_tx = job_tx.clone();
927 let files = files.to_vec();
928 let quiet = self.quiet;
929 scope.spawn(move || {
930 for (idx, file) in files.into_iter().enumerate() {
931 if !quiet {
932 println!("Processing {}...", file.display());
933 }
934 if job_tx.send((idx, file)).is_err() {
935 break;
936 }
937 }
938 })
939 };
940 drop(job_tx);
941
942 // --- Single inserter: drain the streaming channel. ---
943 // Per-in-flight-collection scratch keyed by file_idx (metadata-sized,
944 // at most `jobs` live).
945 let mut in_flight: HashMap<usize, InFlight> = HashMap::new();
946
947 // For each unique sequence digest, the input file_idx whose name
948 // currently "owns" the store-wide sequence label. The global RGSI
949 // row for a shared digest carries one (arbitrary but DETERMINISTIC)
950 // name; we make the highest-file-index name win, matching the
951 // serial build's fixed-file-order, last-writer-wins behavior so
952 // parallel == serial byte-identical. (Per-collection names are
953 // always correct in each collection's members.)
954 let mut seq_name_owner: HashMap<DigestKey, usize> = HashMap::new();
955
956 // Move ownership of out_rx into the inserter block so we can
957 // explicitly drop it after the loop (before joining the feeder).
958 let out_rx = out_rx;
959 for msg in out_rx.iter() {
960 match msg {
961 InsertMsg::Begin { file_idx } => {
962 in_flight.insert(file_idx, InFlight::new());
963 }
964 InsertMsg::Skip { file_idx, metadata } => {
965 // Already-present collection skipped before any decode.
966 // No scratch was created (no Begin), nothing to persist.
967 // This path never reaches finalize_collection, so the
968 // requested collection alias must be registered HERE --
969 // otherwise re-importing an already-imported FASTA would
970 // silently drop the name the caller asked for.
971 if let Err(e) = self.register_import_collection_alias(
972 opts.collection_alias,
973 &metadata.digest,
974 opts.force,
975 ) {
976 let mut slot = build_err_ref.lock().unwrap();
977 if slot.is_none() { *slot = Some(e); }
978 break;
979 }
980 results[file_idx] = Some((metadata, false));
981 }
982 InsertMsg::Seq { file_idx, ready } => {
983 let ReadySequence { metadata, sequence_data, aliases } = ready;
984 let seq_key = metadata.sha512t24u.to_key();
985
986 // Stash alias triples (members come from the End
987 // message's stub records, already in FASTA order).
988 let scratch = in_flight
989 .get_mut(&file_idx)
990 .expect("Seq before Begin");
991 for (ns, alias_value) in &aliases {
992 scratch.aliases.push((
993 ns.clone(),
994 alias_value.clone(),
995 metadata.sha512t24u.clone(),
996 ));
997 }
998
999 // Commit the dedup decision + in-memory metadata on this
1000 // (single) inserter thread, then DISPATCH the `.seq` byte
1001 // write to the bounded writer pool. Dedup is keyed on the
1002 // content digest. The first occurrence of a digest always
1003 // dispatches a write. For a sequence shared across
1004 // collections we re-do the in-memory metadata ONLY when
1005 // this file's index is higher than the current name owner,
1006 // so the highest-file-index name wins deterministically
1007 // (matching the serial fixed-file-order build). The bytes
1008 // are identical (same digest) on such an overwrite, so we
1009 // do NOT re-dispatch the disk write -- the on-disk `.seq`
1010 // is already correct (byte-identical). A disk-backed
1011 // store does not keep the bytes in memory; an in-memory
1012 // store keeps them and dispatches no write.
1013 let force = match seq_name_owner.get(&seq_key) {
1014 None => {
1015 seq_name_owner.insert(seq_key, file_idx);
1016 false // first occurrence: insert unconditionally
1017 }
1018 Some(&owner) if file_idx > owner => {
1019 seq_name_owner.insert(seq_key, file_idx);
1020 true // higher file index: overwrite stored name
1021 }
1022 Some(_) => {
1023 // Lower-or-equal file index already owns the name;
1024 // skip (still deduped, no re-write).
1025 n_seqs_deduped += 1;
1026 continue;
1027 }
1028 };
1029 // A forced overwrite only changes in-memory name metadata
1030 // (identical bytes); skip dispatching a redundant write.
1031 let already_written = force;
1032 // Per-run counter classification costs NOTHING on the
1033 // disk-backed (throughput-critical) path: it is derived
1034 // from `force` plus whether a write was dispatched, both
1035 // of which we already have. Only an in-memory store is
1036 // ambiguous -- there a `None` return means either a dedup
1037 // hit or a fresh insert -- so it alone pays for a lookup,
1038 // and the `!writer_disk_backed` short-circuit keeps that
1039 // lookup out of the disk path entirely.
1040 let mem_is_new =
1041 !writer_disk_backed && self.catalog.find_sha(&metadata.sha512t24u).is_none();
1042 let digest = packed.then(|| metadata.sha512t24u.clone());
1043 match self.add_sequence_record_deferred_write(
1044 SequenceRecord::Full {
1045 metadata,
1046 sequence: std::sync::Arc::new(sequence_data),
1047 },
1048 force,
1049 )? {
1050 Some((full_path, bytes)) => {
1051 if !already_written {
1052 n_seqs_written += 1;
1053 if let Some(digest) = &digest {
1054 if let Err(e) = self.session_pack_append(digest, &bytes) {
1055 write_err_ref.lock().unwrap().get_or_insert(e);
1056 break;
1057 }
1058 } else if write_tx.send((full_path, bytes)).is_err() {
1059 // BOUNDED send: blocks (back-pressure) when
1060 // the writer pool is saturated. An error
1061 // means the writers all hung up (an earlier
1062 // write error); stop feeding and let the
1063 // error propagate.
1064 break;
1065 }
1066 } else {
1067 // `force` name-overwrite: identical bytes are
1068 // already on disk, so nothing was written.
1069 n_seqs_deduped += 1;
1070 }
1071 }
1072 // Disk-backed: `None` is always a dedup hit. In-memory:
1073 // the pre-check above decided it.
1074 None => {
1075 if !writer_disk_backed && mem_is_new {
1076 n_seqs_written += 1;
1077 } else {
1078 n_seqs_deduped += 1;
1079 }
1080 }
1081 }
1082 }
1083 InsertMsg::End {
1084 file_idx,
1085 metadata,
1086 stub_records,
1087 rgsi_cache_path,
1088 source_path,
1089 seq_count,
1090 } => {
1091 let scratch = in_flight
1092 .remove(&file_idx)
1093 .expect("End before Begin");
1094 match self.finalize_collection(
1095 metadata,
1096 stub_records,
1097 scratch,
1098 rgsi_cache_path,
1099 &source_path,
1100 seq_count,
1101 opts.force,
1102 opts.collection_alias,
1103 ) {
1104 Ok((meta, was_new)) => results[file_idx] = Some((meta, was_new)),
1105 Err(e) => {
1106 let mut slot = build_err_ref.lock().unwrap();
1107 if slot.is_none() { *slot = Some(e); }
1108 break;
1109 }
1110 }
1111 }
1112 }
1113 }
1114 // Disconnect the cross-file channel BEFORE joining: if we exited the
1115 // loop early (writer hang-up `break`, or finalize error `break`),
1116 // builders may be blocked in `out_tx.send()`. Dropping the receiver
1117 // makes those sends return Err so builders break and the scope can join.
1118 drop(out_rx);
1119
1120 feeder.join().map_err(|e| anyhow!("Feeder thread panicked: {:?}", e))?;
1121
1122 // END-OF-RUN BARRIER: close the writer channel and JOIN every writer
1123 // so all dispatched `.seq` files are on disk BEFORE the global index
1124 // files are written. Writer-completion order does not affect any
1125 // persisted bytes (per-digest files are independent) nor index
1126 // ordering (indexes are sorted and written after this barrier), so
1127 // determinism is preserved.
1128 drop(write_tx);
1129 for handle in writer_handles {
1130 handle
1131 .join()
1132 .map_err(|e| anyhow!("Writer thread panicked: {:?}", e))?;
1133 }
1134
1135 Ok(())
1136 });
1137
1138 // Seal the session pack and stage a sidecar row for every new sequence
1139 // in a sealed pack. This runs before the error returns below: a
1140 // collection that finalized stays staged after a later file fails, and
1141 // a later commit on this handle must publish its pack rows with it.
1142 // After a write error the open pack is dropped, temp file and all,
1143 // instead of sealed: the failed sequence's bytes are not in it, and a
1144 // failed import does not seal a partial pack. The rows of a pack that
1145 // was not sealed point at bytes that are not on disk; their keys are
1146 // kept so the error path can drop the sequence and every collection
1147 // using it.
1148 let mut unwritten: HashSet<DigestKey> = HashSet::new();
1149 let mut seal_err: Option<anyhow::Error> = None;
1150 // Packs the session created. Taken out of the session so dropping it
1151 // does not delete them: on success their staged rows go to the next
1152 // commit, and the error path deletes those no staged row uses.
1153 let mut created: Vec<String> = Vec::new();
1154 let session = self.open_session_pack.get_mut().unwrap().take();
1155 if let Some(mut session) = session {
1156 let not_sealed = if write_err.lock().unwrap().is_some() {
1157 true
1158 } else if let Err(e) = session.seal() {
1159 seal_err = Some(e);
1160 true
1161 } else {
1162 false
1163 };
1164 if not_sealed {
1165 unwritten.extend(session.rows.iter().map(|(digest, _, _)| digest.to_key()));
1166 }
1167 let mut pending = self.pending.lock().unwrap();
1168 for (digest, row) in session.sealed.drain(..) {
1169 pending.pack_rows.insert(digest.to_key(), row);
1170 }
1171 created = std::mem::take(&mut session.created);
1172 }
1173 if !packed
1174 && writer_disk_backed
1175 && (scope_result.is_err() || write_err.lock().unwrap().is_some())
1176 {
1177 // Standalone: a write that failed, or was still queued when the
1178 // writers stopped, left no `.seq` file (writes are temp + rename),
1179 // yet a collection naming that sequence may have finalized. A file
1180 // present under the digest's path holds the right bytes, so only
1181 // missing files count.
1182 let staged: Vec<DigestKey> =
1183 self.pending.lock().unwrap().sequences.iter().copied().collect();
1184 for key in staged {
1185 let digest = crate::hashkeyable::key_to_digest_string(&key);
1186 if self.sequence_file_path(&digest).is_some_and(|p| !p.exists()) {
1187 unwritten.insert(key);
1188 }
1189 }
1190 }
1191
1192 // Helper: clean up orphan sequences on any failure path. Sequences of a
1193 // file that never finalized, and sequences whose bytes never reached
1194 // disk (with the collections that use them), are dropped along with
1195 // their staged pack rows and aliases. Then each pack this import
1196 // created that no staged row uses any more is deleted. Such a pack
1197 // cannot be in the on-disk index yet (nothing was committed), so the
1198 // staged rows are this handle's only references to it; see
1199 // `remove_uncommitted_packs` for the risk from other writers.
1200 let packs_dir = self.local_path.as_ref().map(|p| p.join("packs"));
1201 let cleanup_on_err = |store: &mut ReadonlyRefgetStore| {
1202 if !unwritten.is_empty() {
1203 store.forget_collections_using(&unwritten);
1204 }
1205 store.remove_orphan_seq_files();
1206 if let Some(packs_dir) = &packs_dir {
1207 let still_staged: HashSet<String> = store
1208 .pending
1209 .lock()
1210 .unwrap()
1211 .pack_rows
1212 .values()
1213 .map(|r| r.pack.to_string())
1214 .collect();
1215 super::readonly::remove_uncommitted_packs(packs_dir, &created, &still_staged);
1216 }
1217 };
1218
1219 // Surface scope errors (e.g. feeder/writer panics), then builder/writer errors.
1220 if let Err(e) = scope_result {
1221 cleanup_on_err(self);
1222 return Err(e);
1223 }
1224
1225 // Propagate the first builder error, if any.
1226 if let Some(e) = build_err.into_inner().unwrap() {
1227 cleanup_on_err(self);
1228 return Err(e);
1229 }
1230
1231 // Propagate the first writer error, if any (every `.seq` must be on disk
1232 // before the index files reference it).
1233 if let Some(e) = write_err.into_inner().unwrap() {
1234 cleanup_on_err(self);
1235 return Err(e);
1236 }
1237
1238 // Propagate a failed seal of the session pack.
1239 if let Some(e) = seal_err {
1240 cleanup_on_err(self);
1241 return Err(e);
1242 }
1243
1244 // Finalize ALL indexes ONCE, after every collection is persisted -- and
1245 // therefore take the store write lock ONCE, for the length of a delta
1246 // commit rather than the length of the import.
1247 //
1248 // WITHIN ONE PROCESS this is byte-identical to a serial import:
1249 // sequences.rgsi sorts by sha512t24u and collections.rgci sorts by
1250 // collection digest, so arrival/build order is irrelevant.
1251 //
1252 // ACROSS PROCESSES that guarantee does not hold, and the reason is worth
1253 // knowing. The commit starts from whatever is on disk and does not
1254 // overwrite an already-published row for a sequence digest, so the `name`
1255 // column is first-committer-wins: if another process publishes the same
1256 // sequence as `1` before we publish it as `chr1`, `1` is what stays in
1257 // the index. Every content-derived column (length, alphabet, md5, and all
1258 // the collection digests) is unaffected -- only `name`/`description`,
1259 // which are advisory in this file. The authoritative per-collection names
1260 // live in each collections/<digest>.rgsi.
1261 if self.persist_to_disk && self.local_path.is_some() {
1262 self.write_index_files()?;
1263 }
1264
1265 if !self.quiet {
1266 println!(
1267 "Imported {} file(s) in {:.1}s (jobs={})",
1268 files.len(),
1269 overall_start.elapsed().as_secs_f64(),
1270 jobs,
1271 );
1272 }
1273
1274 let collections: Vec<(SequenceCollectionMetadata, bool)> = results
1275 .into_iter()
1276 .map(|slot| {
1277 slot.ok_or_else(|| anyhow!("internal error: a file index was not finalized"))
1278 })
1279 .collect::<Result<_>>()?;
1280
1281 let n_collections_new = collections.iter().filter(|(_, was_new)| *was_new).count();
1282
1283 Ok(ImportReport {
1284 collections,
1285 n_sequences_written: n_seqs_written,
1286 n_sequences_deduped: n_seqs_deduped,
1287 n_collections_new,
1288 })
1289 }
1290
1291 /// Import a single FASTA file. Thin wrapper over the multi-file path.
1292 pub fn add_sequence_collection_from_fasta<P: AsRef<Path>>(
1293 &mut self,
1294 file_path: P,
1295 opts: FastaImportOptions<'_>,
1296 ) -> Result<(SequenceCollectionMetadata, bool)> {
1297 let files = [file_path.as_ref().to_path_buf()];
1298 let mut report = self.add_sequence_collections_from_fastas(&files, opts)?;
1299 report
1300 .collections
1301 .pop()
1302 .ok_or_else(|| anyhow!("internal error: importing one file yielded no result"))
1303 }
1304
1305 /// Finalize one collection at `End`: register the collection record, install
1306 /// its members (FASTA order) and aliases. Sequence bytes were
1307 /// already written to disk as each `Seq` arrived. Does NOT write the global
1308 /// index files (the import owner does that ONCE at the end).
1309 #[allow(clippy::too_many_arguments)]
1310 fn finalize_collection(
1311 &mut self,
1312 metadata: SequenceCollectionMetadata,
1313 stub_records: Vec<SequenceRecord>,
1314 scratch: InFlight,
1315 rgsi_cache_path: Option<PathBuf>,
1316 source_path: &Path,
1317 seq_count: usize,
1318 force: bool,
1319 collection_alias: Option<(&str, &str)>,
1320 ) -> Result<(SequenceCollectionMetadata, bool)> {
1321 let coll_key = metadata.digest.to_key();
1322 let coll_digest_display = metadata.digest.clone();
1323
1324 // Validate the requested collection alias BEFORE touching any state.
1325 // A conflicting alias is a hard error, and it must be raised while the
1326 // store is still untouched: everything below this point (the collection
1327 // record, its on-disk `.rgsi`, its members, sequence aliases) is
1328 // committed immediately, but the top-level index is only written once
1329 // at the very end of the import. Erroring after those mutations would
1330 // report a failed import while leaving the collection in the store --
1331 // and, on disk, an orphaned `collections/<digest>.rgsi` that no index
1332 // ever references. The actual alias registration still happens below,
1333 // once the collection is registered, and is published with it.
1334 self.check_import_collection_alias(collection_alias, &metadata.digest, force)?;
1335 // Same for the header-tag sequence aliases: a clash within this file,
1336 // or with an existing binding, must fail before anything is touched.
1337 self.check_import_sequence_aliases(&scratch.aliases, source_path)?;
1338
1339 if !force && self.catalog.find_coll(&metadata.digest).is_some() {
1340 // Register the name even on the in-run duplicate path: the
1341 // collection IS in the store and the caller DID ask for it to be
1342 // named. Skipping here would mean a re-import silently drops the
1343 // alias. The helper is idempotent, so a second registration of the
1344 // same digest is a no-op.
1345 self.register_import_collection_alias(collection_alias, &metadata.digest, force)?;
1346 if !self.quiet {
1347 println!("Skipped {} (already exists)", coll_digest_display);
1348 }
1349 return Ok((metadata, false));
1350 }
1351
1352 let insert_start = Instant::now();
1353
1354 // Write the RGSI cache for next time (only for raw-FASTA builds).
1355 // Empty collections are never cached (a delete at the read site is
1356 // defensive only — empty caches are never written here).
1357 if let Some(rgsi_path) = &rgsi_cache_path {
1358 if !stub_records.is_empty() {
1359 let seqcol_for_cache = SequenceCollection {
1360 metadata: metadata.clone(),
1361 sequences: stub_records.clone(),
1362 };
1363 let _ = seqcol_for_cache.write_collection_rgsi(rgsi_path);
1364 }
1365 }
1366
1367 // Register the collection (members in FASTA order) in one call.
1368 let members: Vec<SequenceMetadata> = stub_records
1369 .into_iter()
1370 .map(|s| match s {
1371 SequenceRecord::Stub(m) => m,
1372 SequenceRecord::Full { metadata, .. } => metadata,
1373 })
1374 .collect();
1375 if self.persist_to_disk && self.local_path.is_some() {
1376 self.write_collection_to_disk_single(&metadata, &members)?;
1377 }
1378 self.insert_collection(metadata.clone(), &members)?;
1379 self.record(|p| p.add_collection(coll_key));
1380
1381 // Register aliases in FASTA order. Pending only: they are published
1382 // with the indexes in the final commit, not one TSV rewrite per header.
1383 for (ns, alias_value, sha512t24u) in &scratch.aliases {
1384 self.add_sequence_alias_pending(ns, alias_value, sha512t24u)?;
1385 }
1386
1387 // Register the collection alias (if requested). Conflicts were already
1388 // rejected up front, while nothing had been mutated; this records the
1389 // alias as pending so it lands on disk in the same commit as the
1390 // collection index that makes its target resolvable.
1391 self.register_import_collection_alias(collection_alias, &metadata.digest, force)?;
1392
1393 if !self.quiet {
1394 println!(
1395 "Added {} ({} seqs) from {} in {:.1}s",
1396 coll_digest_display,
1397 seq_count,
1398 source_path.display(),
1399 insert_start.elapsed().as_secs_f64(),
1400 );
1401 }
1402
1403 Ok((metadata, true))
1404 }
1405}