Three things that turn a working prototype into a deployable tool
Tests — catch regressions before users do
Release builds — the single most important performance flag
Parallelism with rayon — fill all your CPU cores with three letters of change
Part 1 — Tests
Why bother writing tests — a concrete regression
You wrote trim_low_quality(qual, min) six months ago: it walks in from both ends of a quality string and returns the slice in between.
Six months later you “improve” it: you change the boundary check from >= to > because the in-line comment said “skip bases below threshold”. Subtle, looks right, every alignment still runs, every BAM file still gets produced.
But every dataset you process now drops one extra base per read. Quality scores at threshold (the most common case at the read edges) are now treated as “low” instead of “kept”. Six months of downstream coverage stats are off by 1-2 bp per read. Nobody notices until a reviewer asks why your coverage looks lower than the public dataset.
A one-line test asserting trim_low_quality(b"III!", min=8) == b"III" (where I is Q40 and ! is Q0) would have failed the moment you saved the file.
Why bother writing tests — code outlives its author
Real bioinformatics code lives for years. The PhD student who wrote it has graduated and moved on by the time it breaks.
Tests are the institutional memory of “what this function is supposed to do”
Without them, you find out from a user a year later that your published pipeline gives different numbers on the same input
Refactoring without tests is terrifying — every change might silently break a corner case you can’t even articulate. With tests, you change the implementation freely and the tests tell you the moment behaviour shifts.
The anatomy of a Rust test
A unit test [a small test that exercises one function in isolation] is a function with a #[test] attribute and an assertion [a runtime check that aborts the test on false].
assert_eq! — fails (with both values) if the sides differ
A test in three parts: known input → the function under test → an assert_eq! checking the output against the expected value. Pass / fail comes from whether the comparison holds.
Tests live next to the code
Tests ship in the same file but never in the release binary.
Three macros that do most of the work
assert!(seq.len() >0);// the bool must be trueassert_eq!(gc_content(b"GC"),1.0);// left == rightassert_ne!(reverse_complement(b"A"),// left != rightb"A".to_vec());
assert! — generic boolean check
assert_eq! — prints both values on failure (most useful)
The test passes if (and only if) the function panics. The optional expected = ... matches a substring of the panic message.
Running tests — cargo test
cargo test # compile + run every #[test] in the cratecargo test gc # only tests whose name contains "gc"cargo test --release# tests compiled with --release (slower build)cargo test ----nocapture# let println! output through to the terminalcargo test ----test-threads=1 # run tests serially (default: parallel)
The bare -- separates cargo’s flags from the test binary’s flags.
A property-style test in three lines
A property-based test [a test that asserts an invariant that should hold for any input, not one specific input/output pair] using proptest [a Rust crate that generates hundreds of random inputs and, on failure, shrinks them to a minimal example]:
proptest!(|(seq:Vec<u8>)|{letmut v = seq.clone(); v.reverse(); v.reverse();assert_eq!(v, seq);});
The property here is f(f(x)) == x for ANY x — proptest generates hundreds of random x for you.
For random inputs with automatic shrinking, use proptest (teaser, not today).
Unit tests vs integration tests
my-crate/
├── Cargo.toml
├── src/
│ ├── lib.rs <-- unit tests live here, in #[cfg(test)] mod tests { }
│ └── kmer.rs
└── tests/ <-- integration tests
├── end_to_end.rs each file is a separate crate that uses my-crate
└── fasta_round_trip.rs
Unit tests — alongside the code, see private items
Integration tests [tests that exercise your crate from the outside, the way a downstream user would] — in tests/, only the public API, like a real user
Exercise 1 — find the bug
cd day5/ex-find-the-bugcargo test
You are given a reverse_complement that compiles, runs, and looks right.
Your job:
Write six tests (empty input, palindrome, single base, known answer, N pass-through, round trip)
cargo build # target/debug/<crate> — fast to compile, slow to runcargo run # same: debug profilecargo test # same: debug profile
A debug build [the default cargo profile, optimised for fast compilation and helpful panics] prioritises fast compile time and good error messages, not runtime speed.
The single most important Rust performance flag flips this to a release build [the optimised profile cargo uses with --release, intended for shipping]:
cargo build --release# target/release/<crate> — slow to compile, fast to runcargo run --release
Same source, two pipelines
Same source, two compilers; ~50x speedup is typical.
What is assembly?
The CPU doesn’t execute Rust directly. The compiler turns your source into assembly instructions — one CPU operation per line — then those become the machine-code bytes the CPU actually reads.
Rust source → assembly instructions → machine-code bytes that the CPU runs.
Function inlining — what release mode actually does
A function call has overhead: pushing arguments, jumping to the function, returning. For tiny functions that run inside a hot loop [a loop that the program spends most of its time in], that overhead matters.
Inlining [copying a called function’s body directly into the caller so there’s no jump] removes the call entirely.
Before: caller jumps to function and back. After: function body sits inside the caller, no jump at all.
Debug mode keeps the call. Release mode inlines aggressively.
Same code, two assembly outputs
Same Rust source. Same machine. Different --release flag, different assembly.
Release shrinks debug to about a third of the lines and rearranges everything.
Click for the release version.
Left: debug-mode assembly is long, has every variable on the stack, no inlining. Right: release-mode assembly is tight, vectorised, with the loop inlined and the result computed in registers.
Try it yourself: paste any function into godbolt.org, select rustc, toggle -O or -C opt-level=3, watch the right pane shrink.
What --release actually changes
Switch
Debug
Release
Optimisation passes
off
full
Array bounds checks
always
always
Integer overflow checks
panic
wrap silently
Debug info embedded
yes
no
Function inlining
minimal
aggressive
SIMD (wide-math instructions)
rarely
yes
Typical k-mer workload
40 s
0.8 s
Bounds checks stay on in both — Rust does not give up memory safety for speed.
Illustrative numbers
50x speedup is typical.
Measuring a block — std::time::Instant
Three std-library lines and you have a real measurement.
Exercise 2 — measure the release speedup
cd day5/ex-release-modetime cargo run -- 1000 # debugtime cargo run --release-- 1000 # release# scale up until release takes around 1s:time cargo run --release-- 5000
A modern laptop has 8 or more CPU cores. A single-threaded [a thread is one independent stream of execution; one core can run one thread at a time] program uses one.
Many bioinformatics workloads are embarrassingly parallel:
Compute GC content for each of 1 000 000 reads — every read is independent
Score every k-mer in a sequence against a model
Run an alignment for each query against a database
If items are independent, running them on N cores takes ~1/N the time.
A modern CPU has many physical cores; rayon spreads independent work across all of them.
Sequential vs parallel — a timeline
The boxes appear one at a time on top, then in parallel on the bottom — same total work, different wall-clock time.
The change is literally three letters: iter to par_iter.
Where the threads come from
Rayon creates one thread pool [a set of worker threads created once at startup and reused for every parallel call] sized to your CPU count. Override with the RAYON_NUM_THREADS env var if you need to.
RAYON_NUM_THREADS=4 ./my-tool
You never call spawn or join yourself.
Work-stealing keeps every core busy
Work-stealing [idle worker threads grab pending tasks from busy workers’ queues, so the load balances itself without any central scheduler]:
Watch the leftmost worker finish first, then steal a task from a busy neighbour.
Without locking — what a race condition looks like
Your bank account has $100. Two automatic deposits land at the same instant — one for $50, one for $30. You expect to end up with $180.
Each deposit is implemented as read balance → add → write balance:
If the two threads interleave like this — both reading 100 before either writes — thread B’s write overwrites thread A’s, and the account ends at $130 instead of $180. Your $50 deposit silently vanished.
The bank fixes this with a lock (only one transaction touches the row at a time). Rust catches the same class of bug at compile time: it refuses to let two threads share mutable access to the same value unless you wrap it in a synchronising type (Mutex, RwLock, atomics, …).
Race conditions — pictured
Two threads interleaving the read-modify-write of a shared counter; different interleavings give different final values.
In C/C++ this compiles, runs, gives wrong answers, and is famously hard to debug. In Rust the compiler refuses. The next slide shows the mechanism: Send and Sync.
What makes this safe — Send and Sync
Two marker traits make data races a compile error.
Rust refuses to compile code that would race (two threads writing the same data without coordination). The compiler tracks this with two marker traits called Send [the type T can be safely moved between threads] and Sync [&T can be safely shared between threads]. You almost never type these — just know that the borrow checker uses them to reject racy code at compile time.
The compiler refuses the dangerous version
letmut total =0usize;// shared mutable countersequences.par_iter().for_each(|seq|{ total += gc_count(seq);// compile error});// error[E0594]: cannot assign to `total`, as it is a captured variable// note: `total` is captured by an `FnMut` closure, but rayon requires `Fn`
The fix: each closure produces a value, then collect or reduce.
let total:usize= sequences.par_iter().map(|seq| gc_count(seq)).sum();// rayon merges per-thread sums
When parallelism helps — and when it doesn’t
Handing an item to a worker isn’t free. If the per-item work is smaller than that overhead, you slow down.
Per-task overhead is roughly the same size as one GC computation on a short read, but tiny compared to one GC on a long read.
Rule of thumb: <1 µs/item hurts; ~10 µs marginal; >100 µs is a clear win.
Three other rayon tools worth knowing
par_bridge — wraps any iterator (not just &[T]) so you can par_iter over noodles Records, file lines, etc.
rayon::join — run two closures in parallel; useful for divide-and-conquer (a recursive split-and-merge pattern).
par_iter_mut — parallel iteration over &mut [T]. Useful when each element is updated in place — e.g., recompute quality scores across a Vec of records.
What you actually get — speedup saturates
Realistic parallel speedup looks like a SATURATING curve, not a linear line. The first few cores give close to linear gains; each additional core adds less than the one before; eventually you flatten out.
Speedup as a function of core count for a real workload: starts close to the ideal y = x line, then flattens above 8 cores. The serial fraction of the program (Amdahl’s law — the unavoidably sequential part) sets the ceiling.
Past 16-32 cores you’re usually not buying much more speed — the bottleneck shifts to coordination overhead and the part of the program that can’t be parallelised.
Exercise 3 — parallelise GC content
cd day5/ex-parallel-gccargo test # all three tests must passcargo run --release-- 10000 # times both versions
Take a sequential per_seq_gc_sequential(&[Vec<u8>]) -> Vec<f64> and write the rayon-parallel version. The change really is three letters.