Tests, release builds, and parallelism

Day 5

Rust for bioinformaticians

What this lecture is

  • 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].

fn gc_content(seq: &[u8]) -> f64 { /* ... */ }

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn gc_of_acgt() {
        assert_eq!(gc_content(b"ACGT"), 0.5);
    }
}
  • #[test] — discoverable by the test harness
  • assert_eq! — fails (with both values) if the sides differ
Horizontal flow diagram: a known input value box on the left labelled `b"ACGT"`, an arrow into a function box labelled `gc_content(...)`, an arrow into a comparison box labelled `assert_eq!(result, 0.5)`, with two outcomes branching out: green PASS arrow and red FAIL arrow. Above the diagram a title: 'A test = known input + the function + an expected answer.'

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

Two-panel diagram. Left panel labelled src/lib.rs shows the gc_content function followed by a yellow-highlighted #[cfg(test)] band and a mod tests block containing a #[test] fn gc_of_acgt. An arrow labelled 'runs' points to the right panel, a dark terminal labelled $ cargo test showing two tests in green ok and one in red FAILED, with the failure expanded into an assertion `left == right` failed message naming left: 0.75 and right: 1.0 at src/lib.rs:14:9, and a final summary line in red showing 2 passed, 1 failed.

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 true

assert_eq!(gc_content(b"GC"), 1.0);     // left == right

assert_ne!(reverse_complement(b"A"),    // left != right
           b"A".to_vec());
  • assert! — generic boolean check
  • assert_eq! — prints both values on failure (most useful)
  • assert_ne! — opposite; you want them to differ

#[should_panic] — testing the failure path

#[test]
#[should_panic]
fn complement_of_unknown_base_panics() {
    complement_base(b'X');
}

#[test]
#[should_panic(expected = "unsupported base")]
fn panic_message_is_useful() {
    complement_base(b'Z');
}

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 crate
cargo 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 terminal
cargo 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>)| {
    let mut 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-bug
cargo test

You are given a reverse_complement that compiles, runs, and looks right.

Your job:

  1. Write six tests (empty input, palindrome, single base, known answer, N pass-through, round trip)
  2. Watch one fail
  3. Fix the function

Tests are the diagnostic tool — see Exercise 1 page.

Part 2 — Release builds

The default build is slow on purpose

cargo build           # target/debug/<crate>  — fast to compile, slow to run
cargo run             # same: debug profile
cargo 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 run
cargo run --release

Same source, two pipelines

A flow diagram. A central src/main.rs box branches into two pipelines. The top branch is the cargo build default: target/debug/, then a box saying the compiler keeps the safety net (array bounds checks, overflow panics, no inlining, full debug info), then a slow binary box labelled ~40s on the 7-mer workload. The bottom branch is cargo build --release: target/release/, then a box saying LLVM -O3 unleashed (inlining, loop unrolling, SIMD vectorisation, overflow wraps silently), then a fast binary box labelled ~0.8s on the same workload.

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.

A three-layer stack from top to bottom: a Rust source snippet `let x = a + b;`, an assembly line `add rax, rbx`, and the machine-code bytes `48 01 D8`. Each layer labelled with what it is and who reads it.

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.

Two panels. Left panel: caller box with an arrow labelled 'call' going to a separate function box, and an arrow labelled 'return' coming back. Right panel: caller box with the function's contents copied inside it, no separate function box, no arrows. Annotation: release mode inlines small/hot functions automatically; sometimes 10x speedup.

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.

Two side-by-side code panels. Left panel labelled 'debug': ~25 lines of x86-64 assembly with many movs and a call to a separate function. Right panel labelled 'release': ~6 lines of tight assembly using SIMD registers (xmm) and no function call. A small Rust snippet at the top shows the original 4-line source.

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

Bar chart with two bars on a logarithmic time axis: a tall red 'debug' bar at 40 seconds and a short green 'release' bar at 0.8 seconds, with an arrow between them labeled '50x faster'.

50x speedup is typical.

Measuring a block — std::time::Instant

A diagram with a code panel on the left and an output panel on the right. The code panel shows: use std::time::Instant; let t = Instant::now(); a yellow comment-block containing a sequence iter-map-sum fold over 1,000,000 sequences; let dt = t.elapsed(); println!("elapsed: {:.3?}", dt). The output panel is a dark terminal labelled $ cargo run --release showing 'counting GC over 1M reads...', then 'elapsed: 142.317ms' in green, then 'total GC: 53_812_419'. Below the output, a small timeline diagram shows two blue tick marks labelled t and t.elapsed() bracketing a yellow strip labelled 'the work'.

Three std-library lines and you have a real measurement.

Exercise 2 — measure the release speedup

cd day5/ex-release-mode

time cargo run -- 1000              # debug
time cargo run --release -- 1000    # release

# scale up until release takes around 1s:
time cargo run --release -- 5000

No code to write. Read the elapsed times.

Expect at least 20x; 50x is normal. See Exercise 2 page.

Part 3 — Parallelism with rayon

Why parallelism

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 CPU die schematic showing 8 cores arranged in a 2x4 grid, each labelled Core 0 through Core 7, with a shared L3 cache band below. Annotation: typical laptop has 4-12 cores; server CPUs have 32-128.

A modern CPU has many physical cores; rayon spreads independent work across all of them.

Sequential vs parallel — a timeline

A two-panel animated timeline diagram. The top panel labelled Sequential (.iter()) shows a single thread T0 with eight green boxes appearing one after the other, seq 0 through seq 7, total time 8 units. The bottom panel labelled Parallel (.par_iter()) shows four thread rows T0 through T3 each with two green boxes appearing simultaneously; T0 holds seq 0 then seq 4, T1 holds seq 1 then seq 5, T2 holds seq 2 then seq 6, T3 holds seq 3 then seq 7; the total time is 2 units.

The boxes appear one at a time on top, then in parallel on the bottom — same total work, different wall-clock time.

Rayon in one line

use rayon::prelude::*;

// sequential
let gcs: Vec<f64> = sequences.iter()
    .map(|seq| gc_content(seq))
    .collect();

// parallel
let gcs: Vec<f64> = sequences.par_iter()
    .map(|seq| gc_content(seq))
    .collect();

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]:

Three animated worker columns. T0 in blue shows a deque with one remaining item seq 7 and a caption 'busy: 6 items done'. T1 in green shows an empty deque captioned 'idle: looks for work'. T2 in orange shows a deque of five items seq 11 through seq 15 with the bottom item seq 15 (the tail) highlighted in a darker shade and labelled 'tail'; caption 'backlog of 5 items'. A curved orange arrow animates from T1's column down and back up to seq 15 in T2's deque, with the label 'T1 steals seq 15 from T2's tail'. A footer reads: No manual scheduling. Rayon's runtime balances the load while your code says only .par_iter().

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:

Thread A — deposit $50:                Thread B — deposit $30:
    read  balance       → 100              read  balance       → 100
    add   50            → 150              add   30            → 130
    write balance       ← 150              write balance       ← 130

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

Three timeline panels showing three interleavings of two threads each running counter += 1. Panel 1: serial — both increments take effect, final = 2 (green). Panel 2: thread 2 reads before thread 1 writes — only one increment takes effect, final = 1 (red). Panel 3: same shape, final = 1 again (red).

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

Diagram with two large panels side by side. Left panel in blue is titled Send: T can be moved to another thread, with a small diagram showing a value moving from a Thread A box to a Thread B box along a green 'move' arrow; an examples list shows Vec<u8>, String, HashMap as OK (green) and Rc<u8>, *mut T as NO (red), with side notes 'DNA sequences travel freely', 'non-atomic refcount would race', 'raw pointer, no safety analysis'. Right panel in green is titled Sync: &T can be shared between threads, with a value box and two arrows out to Thread A and Thread B both carrying '&value'; examples show &[u8], &Vec<u8>, Mutex<T> as OK and Cell<u8>, RefCell<T> as NO with side notes 'read-only is safe', 'guards its own state', 'mutation w/o sync', 'single-thread only'. Footer: 'Fearless concurrency': the compiler refuses code that would race, before it ever runs.

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

let mut total = 0usize;                    // shared mutable counter

sequences.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.

Horizontal bar chart with three rows. Row 1 (red): 'per-task overhead (~microseconds)' at ~1-10 µs. Row 2 (orange): 'gc_content on a 1000-bp read' at ~1 µs. Row 3 (green): 'gc_content on a 10000-bp read' at ~10 µs. Annotation: if each item is faster than the overhead, parallelism makes things slower.

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.

A non-clonable iterator (e.g. a noodles FASTQ Reader's record iterator) on the left feeding into par_bridge() which dispatches items to multiple worker threads on the right.

rayon::join — run two closures in parallel; useful for divide-and-conquer (a recursive split-and-merge pattern).

A function call split into two halves running concurrently; both finish, results are combined.

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.

A slice &mut [T] with N elements; multiple threads each get a chunk and update elements in place; no shared writes.

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.

A chart with cores on the x-axis (1, 2, 4, 8, 16, 32, 64) and speedup factor on the y-axis (1, 2, 4, 8, 16, 32, 64). A dashed grey line shows the ideal y = x. A solid green curve shows observed speedup: 1.0x, 1.9x, 3.7x, 6.8x, 11x, 14x, 15x — close to ideal at low core counts, flattening as cores grow. Annotation: 'Amdahl's law sets the ceiling — the serial fraction of your program limits the maximum achievable speedup.'

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-gc

cargo test                              # all three tests must pass
cargo 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.

See Exercise 3 page.

Recap

  • Tests — #[cfg(test)] mod tests { #[test] fn ... }, assert_eq!, cargo test
  • Property tests — assert invariants over many inputs, not specific outputs
  • Integration tests — files in tests/, use only the public API
  • --release — 10x to 100x faster; always benchmark with it
  • Instant::now() ... .elapsed() — three lines, the right tool for order-of-magnitude
  • rayon — .par_iter() plus a work-stealing pool; the compiler keeps you race-free
  • Send / Sync — auto-derived for almost everything; the few exceptions are the trip wires

To the exercises

cd day5/ex-find-the-bug
cargo test