Repository navigation
Switch rust-htslib to noodles - #118
Conversation
* Migrate BAM I/O from rust-htslib to noodles (#113) Replace rust-htslib with a pure-Rust noodles backend behind a compatibility shim at src/rna/bam/. The shim preserves the existing Reader/IndexedReader/Record API used across dupRadar, RSeQC, preseq, Qualimap, and samtools-compatible outputs. Key changes: - Add noodles-backed BAM/SAM/CRAM readers with indexed fetch support - Preserve samtools-identical CHK checksums via packed sequence bytes - Update build docs: no cmake/htslib system deps required - All integration and unit tests pass in release mode Co-authored-by: Phil Ewels <phil.ewels@seqera.io> * Update docs, Dockerfile, and CI for noodles migration Replace rust-htslib build prerequisites with noodles (pure Rust) across the website docs, Dockerfile, GitHub Actions workflows, and CHANGELOG. Co-authored-by: Phil Ewels <phil.ewels@seqera.io> * Fix CI: rustfmt and bump MSRV to 1.89 for noodles - Remove extra blank line in main.rs (cargo fmt --check) - Bump rust-version to 1.89 (required by noodles 0.111) - Update MSRV CI job to match Co-authored-by: Phil Ewels <phil.ewels@seqera.io> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Follow-up to the rust-htslib → noodles migration (#115). Three fixes surfaced during code review: - align_record: propagate CIGAR decode errors in `Record::from_bam` instead of silently falling back to an empty CIGAR via `unwrap_or_default()`. A swallowed decode error would have produced wrong coverage/indel statistics with no signal. - align_record: complete the ASCII→4-bit sequence packing table to the full htslib `seq_nt16_table` (all 16 IUPAC codes), so SAM/CRAM records containing ambiguity codes round-trip faithfully and produce samtools-identical CHK checksums. Previously every non-ACGT base was collapsed to N. - io: build the fetch `Region` directly from the reference name and a full interval instead of formatting and re-parsing `name:start-end`. The old approach mangled reference names containing `:` or `-` (e.g. HLA contigs) and lossily decoded non-UTF-8 names. Adds unit tests covering IUPAC packing round-trips, lowercase handling, and odd-length trailing-nibble layout. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The indexed BAM reader buffered every record of a fetched reference (and all unmapped reads) into a `Vec` before yielding any. dupRadar fetches one chromosome per worker thread concurrently, so peak memory scaled as reference size × thread count — gigabytes for a deep chromosome. Replace the buffering with a lazy `BamCursor` that mirrors noodles' `csi::io::Query` chunk state machine: `fetch(tid)` resolves the reference's index chunks up front (small) and `read()` seeks/decodes one record at a time straight from the BGZF stream, filtering out the occasional neighbouring-reference record that shares a chunk boundary block. `fetch(Unmapped)` seeks to the index's unmapped offset (falling back to a reopen + first-record scan when the index lacks the metadata pseudo-bin) and streams to EOF. Peak memory is now O(1) per reader. CRAM (sequential and indexed) still buffers — noodles' slice-based CRAM iterators don't expose an equivalent low-level chunk API — and is left as a documented follow-up. Output is unchanged: the dupRadar integration tests assert exact counts and matrices over a 2-reference fixture and drive both the per-tid and unmapped streaming paths. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
CRAM was the remaining buffered path after the indexed-BAM streaming fix: the sequential reader collected every record in the file into a `Vec`, and indexed `fetch` collected the whole queried reference (or all unmapped reads) before yielding any. noodles' `Records`/`Query` iterators already stream container-by-container (~one container of records at a time), but they borrow the reader they read from, so they can't be stored next to it in a plain struct — which is why the original code collected eagerly. Unlike BAM, noodles keeps CRAM's per-container decode internals (`Container`/`Slice` helpers, the reference repository accessor) `pub(crate)`, so the hand-rolled state machine used for BAM isn't possible here. Wrap the reader + its borrowing iterator in `ouroboros` self-referential structs (`CramReaderCursor`, `CramIndexedCursor`) so the streaming iterator can live alongside the reader. Sequential reads stream directly; indexed `fetch(tid)` / `fetch(Unmapped)` rebuild the cursor with a fresh query via `into_heads`. Peak CRAM memory drops from whole-file to ~one container. Adds a runtime test that writes a reference-backed CRAM and streams it back through the sequential reader, since CRAM previously had no fixture. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
Test / benchmark PRs:
Not checked at all yet, so still needs a lot of validation work. |
|
There's an issue here, identified thanks to When RustQC runs with more than one thread, which is how rnaseq runs it, the PR counts a placed unmapped mate twice if it sits near the end of the last contig.
|
On the indexed (parallel) path, `fetch(Unmapped)` seeks to the last linear-index window of the last reference and keeps every UNMAP-flagged record, so a placed unmapped mate in that window is read by both its reference's fetch and the sweep. htslib's HTS_IDX_NOCOOR returns only records with no reference (tid -1). - Unit tests: BAM (noodles-written) and two samtools-written CRAMs (per-reference slices, one multi-reference slice); the sweep must return exactly the two unplaced records. - Integration test: flagstat at --threads 1 and 4 must match samtools 1.22.1; at 4 the placed mate is counted twice (in total 7, not 6). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`fetch(Unmapped)` now keeps a record only when it has no reference sequence ID, matching htslib's HTS_IDX_NOCOOR: - BAM: the sweep seeks to the last reference's final linear-index window, so it re-read placed records there and kept every UNMAP-flagged one; a placed unmapped mate in that window was counted twice on the parallel path (flagstat "in total" 7 instead of 6 in the new test). - CRAM: `query_unmapped` starts at the slice holding the unplaced reads, which in a multi-reference slice also holds placed records; the same filter applies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… records In a multi-reference CRAM slice, `fetch(tid)` returns every record in the slice whose position overlaps the (whole-reference) interval, whatever its reference: noodles' query filters on the interval only. On the parallel path each such record is counted once per reference fetch (flagstat "in total" 10 instead of 6 for the samtools-written fixture at --threads 4). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
noodles' CRAM `query` filters records on the interval only, so in a multi-reference slice `fetch(tid)` also returned other references' records whose positions fall inside the whole-reference interval. Keep only records whose reference sequence ID is `tid`, as htslib does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
I also found a second issue, I think I'll add both failing tests and a fix as a PR into this. |
|
In general, this is great: it removes RustQC's only raw-pointer |
|
Port the verified iterator-only delta from a9083c5. Preserve integer addition and channel order. Clears the three existing needless_range_loop warnings on the pinned native toolchain.
Retain the public PR178 ancestry and updated PR177 fixes. Resolve append-only test and fixture documentation conflicts by keeping both complete regressions.
Use the equivalent Option propagation required by current Clippy. Preserve cursor exhaustion and seek-error behavior.
Pin crossbeam-epoch 0.9.20 using the exact version and checksum already validated in the combined candidate. Leave all other lock entries unchanged.
|
I test-merged this with current main: rhassaine/RustQC:test/noodles-118-on-main has #118 + main + #177/#178, with split_bam, tin, stats and the newer tests ported to the shim (plus a |
|
Thanks for doing the merge - makes sense it was a lot: everything that landed on main after this (split_bam, the TIN and samtools parity fixes, the dupRadar counting changes) was written against the rust-htslib API and had to be ported to the shim. Checked eec96c3 against main (bfeb03d) on the full HCC1395 RNA BAM from the oncoanalyser full-size test (STAR, 60M pairs, 10.7 GB), both as release builds (LTO, codegen-units=1, x86-64-v3), 3 paired runs per machine on two machine types:
|
|
Ran the edge cases again on eec96c3 vs main: the placed-unmapped and multi-ref/multi-slice CRAM cases all match samtools flagstat now at 1/4/6 threads, and the 8 nf-core BAM datasets give identical output. One thing I noticed with CRAM input though: I think noodles doesn't regenerate NM/MD when decoding CRAM the way htslib does, so on the chr6 test data converted to CRAM, samtools stats reports 0 mismatches (main and samtools itself give 39,821) and the split_bam BAMs lose their MD/NM tags. BAM input isn't affected. Not sure if that's something to handle in the shim or worth a note for now? |
|
Nice, 5% slow is better than 15% 🎉 Maybe worth posting an issue upstream to Noodles about the flags if you're sure, that sounds like it's behaviour that should be captured. |
|
Had a look before opening one - it's already come up upstream: zaeleus/noodles#379, where the maintainer says it's by design (noodles doesn't add NM/MD when decoding CRAM and leaves it to the caller, whereas htslib computes them by default). So I think it'd need to go in the shim - computing NM/MD from the reference for CRAM records that don't have them (htslib already does that work on CRAM, so it shouldn't cost anything over main, and BAM input isn't touched). Happy to have a go at that if useful, or we could just note it as a known difference for CRAM input for now |
The noodles shim rebuilt a fresh Record (RecordBuf plus packed sequence, quality and CIGAR caches) for every read and dropped the previous one, which cost roughly 28 extra malloc calls per record versus the htslib path. Fill the caller's Record in place instead: RecordBuf::try_clone_from_alignment_record already reuses the name, CIGAR, sequence, quality and data vectors, and the packed-sequence, quality and decoded-CIGAR caches are now cleared and refilled rather than reallocated. Output is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Record::qual() now borrows the quality scores held by the underlying RecordBuf instead of a second cached copy, and Record::cigar() returns a CigarStringView that borrows the decoded CIGAR rather than cloning the vector on every call (it is called several times per read by the accumulators). The packed 4-bit sequence is copied straight from the BAM record into a reused buffer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
set_threads() was a no-op for indexed BAM readers, so every counting worker inflated BGZF blocks inline on its own thread, while the htslib build gave each worker a dedicated decompression pool. BAM readers now wrap their BGZF stream in an enum that is either the inline reader or noodles' MultithreadedReader (one helper thread reads raw blocks, N threads inflate). set_threads(N) switches at the current virtual position, so an already-read header is kept; set_threads(0) goes back to inline. The BAM index is loaded separately, because noodles' IndexedReader is tied to the inline BGZF reader. The per-worker thread count chosen in the counting loop is unchanged (at least one decompression thread per worker), and CRAM and SAM inputs are unaffected. Output is identical to the inline path at 1, 4 and 8 threads on the bundled test data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Had a go at the 4-thread gap: profiling showed the shim rebuilding a RecordBuf per record (~2x the allocations of htslib) and decompressing BGZF inline on each worker, since set_threads is a no-op in the shim (htslib gives each reader its own decompression thread). Three small commits on top of eec96c3 - reuse the record buffer, drop the per-record qual/cigar copies, and honour set_threads with noodles' MultithreadedReader: rhassaine/RustQC:perf/118-shim-alloc On the full HCC1395 BAM (release builds, 3 runs each) that takes #118 from +3.4% to -2.2% vs main at 4 threads, and from -7.1% to -9.2% at 12, with identical outputs and memory still ~30% lower. Happy to open it as a PR into this branch if useful |
perf(bam): reuse record buffers and decompress on helper threads in the noodles shim
htslib rebuilds the NM and MD tags while decoding CRAM (CRAM_OPT_DECODE_MD is set to auto on every CRAM it opens), noodles leaves that to the caller. Without them samtools stats reports 0 mismatches for CRAM input and the split_bam BAMs lose NM/MD. The CRAM readers now add the missing tags from the reference, following cram_decode_seq (mismatch rules, MD zero padding, deletions, splices, NM width, tag order with RG last). Tags a record already has are kept. It runs once per run only for what a tool needs (--cram-decode-md auto, the default): NM for samtools stats, NM and MD for the split_bam BAMs. always fills both on every mapped record, never turns it off. Also settable as cram.decode_md in the config file. BAM/SAM input is untouched. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
feat: regenerate NM/MD on CRAM input, like htslib
|
On "pure Rust": the BAM/CRAM side is now fully Rust. rust-htslib and hts-sys are gone, and compression goes through 1. The C++ RNG shim (
2. Fonts for the plots. So it's htslib-free rather than strictly pure Rust. |
Brings seqeralabs#134 up to date with main, including the noodles migration (seqeralabs#118), split_bam and CRAM decode_md. Only the merge conflicts are resolved here: both sides' additions are kept (config sections, accumulators, CLI wiring, tests and docs), and the RSeQC tool count becomes 11. The new modules still import rust_htslib, so this merge does not build on its own; the next commit ports them to the noodles shim. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings the bigWig branch up to date with the noodles migration (#118) and everything else on main. The bigWig accumulator and its integration-test helper now use the rust-htslib-shaped shim at crate::rna::bam instead of rust_htslib. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
rust-htslib is gone since the noodles migration (#118). The writer in rna::bam keeps the same API, so only the imports and one header value change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
rust-htslib is gone since the noodles migration (#118). BAM fixtures use the writer in rna::bam. The CRAM fixture is written with noodles, which puts both contigs in one multi-reference slice; noodles' own indexer can't decode that without a reference, so the test builds the .crai with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Re-submits the BAM I/O migration from rust-htslib to a pure-Rust noodles backend, together with the follow-up review and performance fixes.
Background
The original migration was merged prematurely as #115 and has now been removed from `main` (`main` is back on rust-htslib). This PR brings the work back as a single, complete unit so it can be reviewed and merged properly. It supersedes #117.
Contents
Supersedes #117.