Skip to content

Switch rust-htslib to noodles - #118

Merged
ewels merged 25 commits into
mainfrom
noodles-migration-redo
Dec 2, 2026
Merged

ewels merged 25 commits into
mainfrom
noodles-migration-redo

Conversation

@ewels

@ewels ewels commented Jun 17, 2026

Copy link
Copy Markdown
Member

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

  • Migrate BAM I/O from rust-htslib to noodles (originally Migrate BAM I/O from rust-htslib to noodles #115) — noodles-backed BAM/SAM/CRAM readers behind a compatibility shim at `src/rna/bam/`, preserving the existing Reader/IndexedReader/Record API and samtools-identical CHK checksums. No cmake/htslib system deps required.
  • fix(bam): harden noodles compatibility shim from Migrate BAM I/O from rust-htslib to noodles #115 review — propagate CIGAR decode errors, complete the IUPAC 4-bit sequence packing table, and build fetch regions directly from reference name + interval.
  • perf(bam): stream indexed reads instead of buffering whole references — lazy `BamCursor` so peak memory is O(1) per reader instead of reference-size × thread-count.
  • perf(bam): stream CRAM reads via self-referential cursors — CRAM now streams ~one container at a time rather than buffering the whole file/reference.

Supersedes #117.

ewels and others added 4 commits June 17, 2026 10:39
* 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>
@ewels ewels changed the title Migrate BAM I/O from rust-htslib to noodles (+ follow-up fixes) Switch rust-htslib to noodles Jun 17, 2026
@ewels ewels mentioned this pull request Jun 17, 2026
@ewels
ewels marked this pull request as draft June 17, 2026 13:10
@ewels

ewels commented Jun 17, 2026

Copy link
Copy Markdown
Member Author

Test / benchmark PRs:

Not checked at all yet, so still needs a lot of validation work.

@NicoDeVeaux

NicoDeVeaux commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

There's an issue here, identified thanks to formal-reviews:

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.

  • Measured: one such mate gives flagstat in total 5 in the PR, against 4 in main, in v0.2.1 and in the PR on one thread. The same mate anywhere else is counted once.
  • Why CI misses it: RustQC's own test BAMs contain no placed unmapped reads.
  • Reach in rnaseq: BAMs from star_rsem and HISAT2 contain such reads; the default star_salmon doesn't.

NicoDeVeaux and others added 4 commits October 23, 2026 11:34
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>
@NicoDeVeaux

Copy link
Copy Markdown
Contributor

I also found a second issue, I think I'll add both failing tests and a fix as a PR into this.

@NicoDeVeaux

Copy link
Copy Markdown
Contributor

In general, this is great: it removes RustQC's only raw-pointer unsafe block (the CHK checksum slice built from htslib's record buffer, rseqc/accumulators.rs:493 on main) by using encoded_bytes(), so the remaining unsafe is just the C++ RNG bridge in cpp_rng.rs. Which makes formal verification easier too.

@NicoDeVeaux

Copy link
Copy Markdown
Contributor

I also found a second issue, I think I'll add both failing tests and a fix as a PR into this.

#178

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.
@rhassaine

Copy link
Copy Markdown
Contributor

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 raw_cigar() on the shim's Record) - feel free to pull it in.
With #177/#178, output is byte-identical to main on the 8 nf-core test datasets at 1 and 6 threads, plus a CRAM conversion and split_bam with written BAMs. Without them, main's test_samtools_flagstat_and_stats_match_on_every_flag fails at --threads 2 (placed unmapped reads counted twice) and multi-threaded CRAM either miscounts or errors.
It does appear a bit slower than htslib though, roughly 15% on a 1M-read BAM, with the same memory.
cc @ewels

@rhassaine

Copy link
Copy Markdown
Contributor

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:

  • outputs identical at 4 and 12 threads
  • 4 threads: ~5% slower (522 → 549 s), 12 threads: ~6% faster (285 → 267 s)
  • peak memory 24-31% lower (18.8 → 13.0 GB at 4 threads, 21.3 → 16.1 GB at 12)

@rhassaine

Copy link
Copy Markdown
Contributor

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?

@ewels

ewels commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

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.

@rhassaine

Copy link
Copy Markdown
Contributor

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

rhassaine and others added 4 commits December 1, 2026 16:56
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>
@rhassaine

rhassaine commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor
5-fixes-wall-time

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

ewels and others added 3 commits December 2, 2026 14:01
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
@ewels
ewels marked this pull request as ready for review December 2, 2026 14:23
@rhassaine

Copy link
Copy Markdown
Contributor

On "pure Rust": the BAM/CRAM side is now fully Rust. rust-htslib and hts-sys are gone, and compression goes through zlib-rs, libbz2-rs-sys and lzma-rust2. Two native pieces remain, though:

1. The C++ RNG shim (cpp/rng_shim.cpp, 56 lines, built by build.rs with cc). It wraps std::mt19937 + std::binomial_distribution, and preseq's bootstrap uses it through src/rna/cpp_rng.rs. Nothing else does. It exists so our random draws are the same as upstream preseq's, which makes the preseq output byte-identical on Linux. On macOS it already differs, because libc++ implements the binomial draw differently.
There are two ways to remove it:

  • Port it to Rust: mt19937 is easy. The binomial part means re-implementing libstdc++'s algorithm (Devroye's rejection method) exactly, roughly 100–150 lines whose only job is to reproduce libstdc++'s draws. Linux output stays byte-identical, but we would own that code instead of linking the C++.
  • Use a standard Rust RNG (e.g. rand_distr::Binomial): less code and nothing to keep in sync, but preseq's bootstrap numbers would no longer match upstream exactly, so the benchmarks would compare them at a tolerance.

2. Fonts for the plots. plotters → font-kit pulls in fontconfig, which we load at runtime through the fontconfig-dlopen feature, and freetype on Linux. To remove them, switch plotters to its ab_glyph backend with a bundled font. Text rendering in the plots would change slightly. I haven't tried this.

So it's htslib-free rather than strictly pure Rust.

@ewels
ewels merged commit 0b38f63 into main Dec 2, 2026
7 checks passed
@ewels
ewels deleted the noodles-migration-redo branch December 2, 2026 17:00
ewels added a commit to BenjaminDEMAILLE/RustQC that referenced this pull request Dec 3, 2026
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>
ewels added a commit that referenced this pull request Dec 3, 2026
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>
ewels pushed a commit that referenced this pull request Dec 4, 2026
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>
ewels pushed a commit that referenced this pull request Dec 4, 2026
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants