refactor: migrate pipeline to NucPage-based stream processing

Replace the existing chunk and Rope-based processing pipeline with a fixed-size NucPage architecture. Introduce a new nucstream module featuring buffer-pooled, in-place parsing that auto-detects and decompresses FASTA/FASTQ/GenBank inputs into normalized ACGT streams with k-mer overlap preservation. Update obikmer scatter and superkmer stages to consume NucPage iterators and cursor-based navigation, eliminating std::io::Read dependencies and optimizing memory management. Add a configurable max_open_files CLI argument and update implementation documentation to reflect the new record vs. stream reading paths.
This commit is contained in:
Eric Coissac committed 2026-05-29 09:10:25 +02:00
1 parent a4b57a96de
commit cfadf63bbc
12 files changed
+876 -609

No files matched your search

+13 -24
View File
@@ -1,9 +1,8 @@
use std::io;
use std::path::PathBuf;
use std::sync::{Arc, Condvar, Mutex};
use clap::Args;
use obikrope::Rope;
use obiread::NucPage;
use obikseq::RoutableSuperKmer;
// ── Shared arguments ──────────────────────────────────────────────────────────
@@ -45,9 +44,11 @@ pub struct CommonArgs {
)]
pub threads: usize,
/// Maximum number of input files open simultaneously
#[arg(long, default_value_t = 20)]
pub max_open_files: usize,
/// Maximum number of input files open simultaneously.
/// Defaults to threads/4 (minimum 1). Keep below the number of workers
/// to ensure CPU workers are always available for the transform stage.
#[arg(long)]
pub max_open_files: Option<usize>,
}
/// Smallest `b` such that `2^b >= n` (i.e. `n.next_power_of_two().ilog2()`).
@@ -86,6 +87,12 @@ impl CommonArgs {
}
}
pub fn effective_max_open(&self) -> usize {
self.max_open_files
.unwrap_or_else(|| (self.threads / 4).max(1))
.max(1)
}
pub fn seqfile_paths(&self) -> obiread::PathIter {
let paths: Vec<PathBuf> = if self.inputs.is_empty() {
vec![PathBuf::from("-")]
@@ -144,13 +151,10 @@ pub struct PathWithSlot {
pub enum PipelineData {
Path(PathWithSlot),
RawChunk(Rope),
NormChunk(Rope),
NucPage(NucPage),
Batch(Vec<RoutableSuperKmer>),
}
// SAFETY: Rope contains Cell<u8> which is !Sync, but pipeline ownership transfers
// exclusively through channels — no item is ever shared across threads.
unsafe impl Send for PipelineData {}
unsafe impl Sync for PipelineData {}
@@ -171,18 +175,3 @@ pub fn throttle_paths(
})
}
// ── I/O plumbing ──────────────────────────────────────────────────────────────
pub fn open_chunks(path: PathBuf) -> io::Result<impl Iterator<Item = Rope>> {
let path_str = path
.to_str()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "non-UTF-8 path"))?;
let iter = obiread::read_sequence_chunks(path_str)?;
Ok(iter.filter_map(|r| match r {
Ok(rope) => Some(rope),
Err(e) => {
eprintln!("chunk read error: {e}");
None
}
}))
}
+1 -1
View File
@@ -231,7 +231,7 @@ pub fn run(args: IndexArgs) {
let theta = args.common.theta;
let n_workers = args.common.threads.max(1);
let max_open = args.common.max_open_files.max(1);
let max_open = args.common.effective_max_open();
scatter(idx.partition_mut(), args.common.seqfile_paths(), k, level_max, theta, n_workers, max_open, &mut rep);
idx.mark_scattered().unwrap_or_else(|e| {
+10 -5
View File
@@ -4,7 +4,7 @@ use clap::Args;
use obifastwrite::write_scatter;
use obikseq::{RoutableSuperKmer, set_k, set_m};
use crate::cli::{CommonArgs, PipelineData, PathWithSlot, open_chunks, partitions_to_bits, throttle_paths};
use crate::cli::{CommonArgs, PipelineData, PathWithSlot, partitions_to_bits, throttle_paths};
#[derive(Args)]
pub struct SuperkmerArgs {
@@ -41,7 +41,7 @@ pub fn run(args: SuperkmerArgs) {
let level_max = args.common.level_max;
let partition_bits = partitions_to_bits(args.common.partitions);
let n_workers = args.common.threads.max(1);
let max_open = args.common.max_open_files.max(1);
let max_open = args.common.effective_max_open();
set_k(k);
set_m(m);
@@ -50,9 +50,14 @@ pub fn run(args: SuperkmerArgs) {
let pipe = obipipeline::make_pipe! {
PipelineData : PathWithSlot => Vec<RoutableSuperKmer>,
||? { |pw: PathWithSlot| open_chunks(pw.path) } : Path => RawChunk,
|? { move |rope| obiread::normalize_sequence_chunk(rope, k) } : RawChunk => NormChunk,
| { move |rope| obiskbuilder::build_superkmers(rope, k, level_max, theta) } : NormChunk => Batch,
||? {
let k = k;
move |pw: PathWithSlot| {
let path_str = pw.path.to_str().unwrap_or("").to_owned();
obiread::open_nuc_stream(&path_str, k)
}
} : Path => NucPage,
| { move |page| obiskbuilder::build_superkmers_page(page, k, level_max, theta) } : NucPage => Batch,
};
let mut out = BufWriter::new(io::stdout());
+39 -17
View File
@@ -1,30 +1,37 @@
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use indicatif::{ProgressBar, ProgressStyle};
use obiread::NucPage;
use obikpartitionner::KmerPartition;
use obikrope::Rope;
use obisys::{Reporter, Stage};
use tracing::info;
use crate::cli::{PipelineData, PathWithSlot, open_chunks, throttle_paths};
use crate::cli::{PipelineData, PathWithSlot, throttle_paths};
// ── Iterator that keeps the slot guard alive until the file is exhausted ──────
struct GuardedIter<I> {
inner: I,
_guard: Box<dyn Send + 'static>,
struct GuardedIter {
inner: Box<dyn Iterator<Item = NucPage> + Send>,
_guard: Box<dyn Send + 'static>,
flat_active: Arc<AtomicU32>,
}
impl<I: Iterator<Item = Rope>> Iterator for GuardedIter<I> {
type Item = Rope;
fn next(&mut self) -> Option<Rope> {
impl Iterator for GuardedIter {
type Item = NucPage;
fn next(&mut self) -> Option<NucPage> {
self.inner.next()
}
}
impl Drop for GuardedIter {
fn drop(&mut self) {
self.flat_active.fetch_sub(1, Ordering::Relaxed);
}
}
// ── scatter ───────────────────────────────────────────────────────────────────
/// Run scatter: normalise → build superkmers → route to partition → close.
@@ -44,23 +51,36 @@ pub fn scatter(
// Throttle in the source thread — never in a worker — to prevent deadlock.
let throttled = throttle_paths(path_source, max_open);
let file_count = Arc::new(AtomicU64::new(0));
let file_count = Arc::new(AtomicU64::new(0));
let flat_active = Arc::new(AtomicU32::new(0));
let transform_active = Arc::new(AtomicU32::new(0));
let t = Stage::start("scatter");
let pipe = obipipeline::make_pipe! {
PipelineData : PathWithSlot => Vec<RoutableSuperKmer>,
||? {
let file_count = Arc::clone(&file_count);
let file_count = Arc::clone(&file_count);
let flat_active = Arc::clone(&flat_active);
let k = k;
move |pw: PathWithSlot| {
let PathWithSlot { path, _guard } = pw;
let n = file_count.fetch_add(1, Ordering::Relaxed) + 1;
info!("indexing [{}]: {}", n, path.display());
// _guard travels into GuardedIter; released when all chunks are read
open_chunks(path).map(|iter| GuardedIter { inner: iter, _guard })
let path_str = path.to_str().unwrap_or("").to_owned();
flat_active.fetch_add(1, Ordering::Relaxed);
obiread::open_nuc_stream(&path_str, k)
.map(|iter| GuardedIter { inner: iter, _guard, flat_active: Arc::clone(&flat_active) })
}
} : Path => RawChunk,
|? { move |rope| obiread::normalize_sequence_chunk(rope, k) } : RawChunk => NormChunk,
| { move |rope| obiskbuilder::build_superkmers(rope, k, level_max, theta) } : NormChunk => Batch,
} : Path => NucPage,
| {
let transform_active = Arc::clone(&transform_active);
move |page| {
transform_active.fetch_add(1, Ordering::Relaxed);
let result = obiskbuilder::build_superkmers_page(page, k, level_max, theta);
transform_active.fetch_sub(1, Ordering::Relaxed);
result
}
} : NucPage => Batch,
};
let pb = ProgressBar::new_spinner();
@@ -93,7 +113,9 @@ pub fn scatter(
(format!("{:.0} Mbp", bp / 1e6), format!("{:.0} Mbp/s", ema_rate / 1e6))
};
let n_files = file_count.load(Ordering::Relaxed);
pb.set_message(format!("{count_str} {rate_str} {n_files} files"));
let r = flat_active.load(Ordering::Relaxed);
let c = transform_active.load(Ordering::Relaxed);
pb.set_message(format!("{count_str} {rate_str} {n_files} files [R:{r} C:{c}]"));
}
kp.write_batch(batch).unwrap_or_else(|e| {
eprintln!("error: {e}");