whittle 1.0.0

Coordinate-consistent trimming of long-read uBAM and tagged FASTQ
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! FASTQ workflows: sequential and parallel trim, filter and write drivers.

use std::io::Write;
use std::sync::Arc;
use std::sync::atomic::Ordering;

use super::reject::{self, Reason, RejectItem};
use super::{
    BatchSink, Counters, FASTQ_BATCH, Rejection, Stats, process_read_segments, run_bytes_parallel,
};
use crate::config::Config;
use crate::io::fastq::write_segment;
use crate::record::ReadRecord;
use crate::trim;

/// Runs the single-threaded FASTQ workflow: trims, filters each produced segment
/// and writes the survivors straight to `writer`.
fn run_fastq_seq<W: Write>(
    records: impl Iterator<Item = anyhow::Result<ReadRecord>>,
    writer: &mut W,
    cfg: &Config,
    counters: &Arc<Counters>,
) -> anyhow::Result<Stats> {
    let mut buf = Vec::new();
    for rec in records {
        let rec = rec?;
        counters.input_reads.fetch_add(1, Ordering::Relaxed);
        counters
            .input_bases
            .fetch_add(rec.seq.len() as u64, Ordering::Relaxed);
        buf.clear();
        render_record(rec, cfg, counters, &mut buf)?;
        writer.write_all(&buf)?;
    }
    Ok(counters.snapshot())
}

/// Trims one record, filters each produced segment through
/// `process_read_segments`, and appends survivors to the reusable output buffer.
pub(super) fn render_record(
    rec: ReadRecord,
    cfg: &Config,
    counters: &Counters,
    w: &mut Vec<u8>,
) -> anyhow::Result<()> {
    if crate::io::tagged::has_aux_tags(&rec.name) {
        if !counters.tagged_fastq.swap(true, Ordering::Relaxed) {
            tracing::info!("FASTQ headers carry SAM aux tags; tags are rewritten per segment");
        }
        return super::bam::render_tagged_fastq_read(rec, cfg, counters, w);
    }
    let _read = super::read_span(&rec.name);
    let _read = _read.enter();
    let produced = trim::apply(&rec.seq, &rec.qual, &cfg.trim, cfg.adapters.as_ref(), None);
    process_read_segments(
        &produced,
        &rec.seq,
        &rec.qual,
        &cfg.filter,
        counters,
        |idx, total, s, e| {
            write_segment(w, &rec.name, &rec.seq[s..e], &rec.qual[s..e], total, idx)?;
            Ok(())
        },
        |rejection| {
            if !counters.wants_rejects() {
                return Ok(());
            }
            counters.reject(RejectItem::Fastq(rejected_fastq(&rec, rejection)))
        },
    )
}

/// Renders a rejected plain FASTQ segment, or the whole read, with its reason
/// tag in the header.
pub(super) fn rejected_fastq(rec: &ReadRecord, rejection: Rejection) -> Vec<u8> {
    let mut out = Vec::new();
    match rejection {
        Rejection::Segment {
            idx,
            total,
            start,
            end,
            reason,
        } => {
            crate::io::fastq::write_head(&mut out, &rec.name, total, idx)
                .expect("Writing to a Vec does not fail");
            reject::push_fastq_tag(&mut out, Reason::Dropped(reason));
            crate::io::fastq::write_body(&mut out, &rec.seq[start..end], &rec.qual[start..end])
                .expect("Writing to a Vec does not fail");
        },
        Rejection::Whole => {
            crate::io::fastq::write_head(&mut out, &rec.name, 1, 0)
                .expect("Writing to a Vec does not fail");
            reject::push_fastq_tag(&mut out, Reason::TrimmedToNothing);
            crate::io::fastq::write_body(&mut out, &rec.seq, &rec.qual)
                .expect("Writing to a Vec does not fail");
        },
    }
    out
}

/// Renders a plain FASTQ read rejected by the tag filter.
pub(crate) fn tag_filtered_fastq(rec: &ReadRecord) -> Vec<u8> {
    let mut out = Vec::new();
    crate::io::fastq::write_head(&mut out, &rec.name, 1, 0)
        .expect("Writing to a Vec does not fail");
    reject::push_fastq_tag(&mut out, Reason::TagFilter);
    crate::io::fastq::write_body(&mut out, &rec.seq, &rec.qual)
        .expect("Writing to a Vec does not fail");
    out
}

/// Runs the FASTQ workflow: sequential when `cfg.threads <= 1`; otherwise
/// records render on a rayon pool and drain through `run_parallel`, in input
/// order under `cfg.ordered` and in completion order otherwise. A writer that
/// takes compressed blocks (see `BatchSink::block_level`) has each batch
/// compressed on the pool.
pub(crate) fn run_fastq<W, I>(
    records: I,
    writer: &mut W,
    cfg: &Config,
    counters: &Arc<Counters>,
) -> anyhow::Result<Stats>
where
    W: BatchSink,
    I: Iterator<Item = anyhow::Result<ReadRecord>> + Send,
{
    if cfg.threads <= 1 {
        return run_fastq_seq(records, writer, cfg, counters);
    }
    run_bytes_parallel(
        records,
        FASTQ_BATCH,
        |rec| rec.seq.len(),
        cfg,
        writer,
        |rec, cfg, buf| render_record(rec, cfg, counters, buf),
        counters,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::filter;
    use crate::qual::QualMode;
    use crate::record::ReadRecord;
    use crate::trim::{QualityMethod, QualityOp, TrimPlan};

    fn rec(name: &str, seq: &[u8], phred: Vec<u8>) -> ReadRecord {
        ReadRecord {
            name: name.as_bytes().to_vec(),
            seq: seq.to_vec(),
            qual: phred,
        }
    }

    /// A pass-through config (no trimming, no filtering, no adapters) with the
    /// given thread count; each test overrides the fields it exercises.
    fn test_cfg(threads: usize) -> Config {
        let null = std::path::Path::new("/dev/null");
        crate::cli::config_for_test_threads(null, null, 0, 0, threads)
    }

    #[test]
    fn shared_counters_reflect_totals() {
        use std::sync::Arc;

        use crate::workflow::Counters;
        let mut cfg = test_cfg(1);
        cfg.trim = TrimPlan {
            head: 1,
            tail: 1,
            quality: None,
        };
        let recs = vec![Ok(rec("r1", b"ACGT", vec![40, 40, 40, 40]))];
        let mut out = Vec::new();
        let counters = Arc::new(Counters::default());
        let stats = run_fastq_seq(recs.into_iter(), &mut out, &cfg, &counters).unwrap();
        assert_eq!((stats.input_reads, stats.output_reads), (1, 1));
        assert_eq!(
            counters
                .input_reads
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );
        assert_eq!(
            counters
                .output_reads
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );
    }

    #[test]
    fn fixed_crop_writes_one_segment() {
        let mut cfg = test_cfg(1);
        cfg.trim = TrimPlan {
            head: 1,
            tail: 1,
            quality: None,
        };
        let recs = vec![Ok(rec("r1", b"ACGT", vec![40, 40, 40, 40]))];
        let mut out = Vec::new();
        let stats = run_fastq_seq(
            recs.into_iter(),
            &mut out,
            &cfg,
            &Arc::new(Counters::default()),
        )
        .unwrap();
        assert_eq!(out, b"@r1\nCG\n+\nII\n");
        assert_eq!((stats.input_reads, stats.output_reads), (1, 1));
    }

    #[test]
    fn split_writes_suffixed_segments() {
        let mut cfg = test_cfg(1);
        cfg.trim.quality = Some(QualityOp::runs(10, 1));
        // Three good, one bad, three good (`III#III`) gives two segments, (0,3)
        // and (4,7).
        let phred: Vec<u8> = b"III#III".iter().map(|&b| b - 33).collect();
        let recs = vec![Ok(rec("r1", b"AAATAAA", phred))];
        let mut out = Vec::new();
        let stats = run_fastq_seq(
            recs.into_iter(),
            &mut out,
            &cfg,
            &Arc::new(Counters::default()),
        )
        .unwrap();
        assert_eq!(
            out,
            b"@r1_segment_1\nAAA\n+\nIII\n@r1_segment_2\nAAA\n+\nIII\n"
        );
        assert_eq!((stats.input_reads, stats.output_reads), (1, 2));
    }

    #[test]
    fn filtered_read_produces_no_output() {
        let mut cfg = test_cfg(1);
        cfg.filter.min_length = 10;
        let recs = vec![Ok(rec("short", b"ACGT", vec![40; 4]))];
        let mut out = Vec::new();
        let stats = run_fastq_seq(
            recs.into_iter(),
            &mut out,
            &cfg,
            &Arc::new(Counters::default()),
        )
        .unwrap();
        assert!(out.is_empty());
        assert_eq!((stats.input_reads, stats.output_reads), (1, 0));
    }

    /// One produced segment rejected by length counts as all-filtered, not
    /// trimmed-to-nothing.
    #[test]
    fn too_short_segment_bumps_segments_dropped_short_counter() {
        let mut cfg = test_cfg(1);
        cfg.filter.min_length = 10;
        let recs = vec![Ok(rec("short", b"ACGT", vec![40; 4]))];
        let mut out = Vec::new();
        let counters = Arc::new(Counters::default());
        let stats = run_fastq_seq(recs.into_iter(), &mut out, &cfg, &counters).unwrap();
        assert_eq!(stats.segments_dropped_short, 1);
        assert_eq!(stats.reads_all_filtered, 1);
        assert_eq!(stats.reads_trimmed_to_nothing, 0);
        assert_eq!(
            counters
                .segments_dropped_short
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );
    }

    /// A crop that removes the complete read produces no segments.
    #[test]
    fn trimmed_to_nothing_bumps_reads_trimmed_to_nothing_counter() {
        let mut cfg = test_cfg(1);
        cfg.trim.head = 10;
        let recs = vec![Ok(rec("r1", b"ACGT", vec![40; 4]))];
        let mut out = Vec::new();
        let stats = run_fastq_seq(
            recs.into_iter(),
            &mut out,
            &cfg,
            &Arc::new(Counters::default()),
        )
        .unwrap();
        assert!(out.is_empty());
        assert_eq!(stats.reads_trimmed_to_nothing, 1);
        assert_eq!(stats.reads_all_filtered, 0);
        assert_eq!(stats.segments_dropped_short, 0);
    }

    /// Filtering uses the cropped sequence rather than the original read.
    #[test]
    fn quality_below_raw_mean_but_above_trimmed_insert_survives() {
        let mut cfg = test_cfg(1);
        cfg.filter.qual_mode = QualMode::Arithmetic;
        cfg.filter.min_qual = 30.0;
        cfg.trim.head = 4;
        // Original mean: 24.8. Cropping four Q2 bases leaves six Q40 bases.
        let mut phred = vec![2u8; 4];
        phred.extend(std::iter::repeat_n(40u8, 6));
        assert!(
            filter::check(b"AAAAAAAAAA", &phred, &cfg.filter).is_some(),
            "The complete input read must fail the quality filter"
        );
        let recs = vec![Ok(rec("r1", b"AAAAAAAAAA", phred))];
        let mut out = Vec::new();
        let counters = Arc::new(Counters::default());
        let stats = run_fastq_seq(recs.into_iter(), &mut out, &cfg, &counters).unwrap();
        assert_eq!(out, b"@r1\nAAAAAA\n+\nIIIIII\n");
        assert_eq!(stats.output_reads, 1);
        assert_eq!(
            counters
                .reads_with_output
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );
        assert_eq!(stats.reads_trimmed_to_nothing, 0);
        assert_eq!(stats.reads_all_filtered, 0);
        assert_eq!(stats.segments_dropped_low_qual, 0);
    }

    /// An interior adapter splits a read into a long insert (survives length
    /// filtering) and a short insert (rejected `TooShort`). The survivor keeps
    /// its produced index: it is named `_segment_1`, not renamed to look
    /// unsplit, although its sibling `_segment_2` is not written. A lone suffix
    /// with a gap signals that the read was split.
    #[test]
    fn split_produces_long_survivor_and_short_segment_drop() {
        use crate::adapter::{Adapter, AdapterConfig, Role};

        let adapter = b"GGGGTTTTGGGGTTTT"; // 16 bp, no A/C, so it cannot match the flanks
        let mut seq = vec![b'A'; 24]; // long flank, survives the length filter
        seq.extend_from_slice(adapter);
        // Short flank, TooShort; longer than the flank slack, so the adapter
        // stage emits it instead of folding it into the excision.
        seq.extend_from_slice(&[b'C'; 12]);
        let phred = vec![40u8; seq.len()];

        let mut cfg = test_cfg(1);
        cfg.filter.min_length = 13;
        cfg.adapters = Some(AdapterConfig {
            adapters: vec![Adapter {
                name: "mid".into(),
                seq: adapter.to_vec(),
                role: Role::Adapter,
            }],
            error_rate: 0.1,
            // With `end_size` 1, both flanks (24 and 12 bases from the match)
            // sit outside the end zone, so the adapter is interior and the
            // read splits rather than being terminal-trimmed.
            end_size: 1,
            split: true,
            min_piece: 1,
            candidate_index: std::sync::OnceLock::new(),
            amplicon: false,
        });
        let recs = vec![Ok(rec("r1", &seq, phred))];
        let mut out = Vec::new();
        let counters = Arc::new(Counters::default());
        let stats = run_fastq_seq(recs.into_iter(), &mut out, &cfg, &counters).unwrap();

        assert_eq!(stats.output_reads, 1, "Only the long flank survives");
        assert_eq!(
            stats.segments_dropped_short, 1,
            "The short flank is dropped"
        );
        assert_eq!(
            counters
                .reads_with_output
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );
        assert_eq!(stats.reads_trimmed_to_nothing, 0);
        assert_eq!(stats.reads_all_filtered, 0);
        let s = String::from_utf8(out).unwrap();
        assert!(
            s.starts_with("@r1_segment_1\n"),
            "Survivor keeps its produced index (1 of 2): {s:?}"
        );
        assert!(
            !s.contains("_segment_2"),
            "The dropped short segment must not appear in output: {s:?}"
        );
    }

    /// An empty input read produces no trim intervals, so it bumps the
    /// read-level `reads_trimmed_to_nothing` counter with no segment-level
    /// drop: the per-segment filter loop never runs.
    #[test]
    fn empty_read_bumps_reads_trimmed_to_nothing_with_no_segment_drop() {
        let cfg = test_cfg(1);
        let recs = vec![Ok(rec("empty", b"", vec![]))];
        let mut out = Vec::new();
        let counters = Arc::new(Counters::default());
        let stats = run_fastq_seq(recs.into_iter(), &mut out, &cfg, &counters).unwrap();
        assert!(out.is_empty());
        assert_eq!(stats.input_reads, 1);
        assert_eq!(stats.output_reads, 0);
        assert_eq!(stats.reads_trimmed_to_nothing, 1);
        assert_eq!(stats.reads_all_filtered, 0);
        assert_eq!(stats.segments_dropped_short, 0);
        assert_eq!(stats.segments_dropped_long, 0);
        assert_eq!(stats.segments_dropped_low_qual, 0);
        assert_eq!(stats.segments_dropped_high_qual, 0);
        assert_eq!(stats.segments_dropped_gc, 0);
    }

    #[test]
    fn parallel_matches_sequential_as_multiset() {
        let mk = |threads| {
            let mut cfg = test_cfg(threads);
            cfg.trim.quality = Some(QualityOp::new(QualityMethod::Ends, 20));
            cfg
        };
        // Owned records (`ReadRecord: Clone`), wrapped in `Ok` at iteration time
        // so each run gets a fresh `Send` iterator. `anyhow::Error` is not
        // `Clone`, so a `Vec<Result<..>>` cannot be cloned; the `Vec<ReadRecord>`
        // is cloned and re-wrapped instead.
        let recs: Vec<ReadRecord> = (0..500)
            .map(|i| rec(&format!("r{i}"), b"ACGTACGTAC", vec![40; 10]))
            .collect();

        let mut seq_out = Vec::new();
        run_fastq(
            recs.clone().into_iter().map(anyhow::Ok),
            &mut seq_out,
            &mk(1),
            &Arc::new(Counters::default()),
        )
        .unwrap();

        let mut par_out = Vec::new();
        run_fastq(
            recs.into_iter().map(anyhow::Ok),
            &mut par_out,
            &mk(4),
            &Arc::new(Counters::default()),
        )
        .unwrap();

        let sort_records = |bytes: &[u8]| {
            let mut v: Vec<Vec<u8>> = bytes
                .split(|&b| b == b'@')
                .filter(|s| !s.is_empty())
                .map(|s| s.to_vec())
                .collect();
            v.sort();
            v
        };
        assert_eq!(sort_records(&seq_out), sort_records(&par_out));
    }

    #[test]
    fn parallel_surfaces_write_error_without_deadlock() {
        use std::io::{self, Write};

        struct FailAfter {
            limit: usize,
            written: usize,
        }
        impl Write for FailAfter {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                if self.written >= self.limit {
                    return Err(io::Error::new(io::ErrorKind::BrokenPipe, "boom"));
                }
                self.written += buf.len();
                Ok(buf.len())
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }
        impl BatchSink for FailAfter {}

        let cfg = test_cfg(4);
        // Enough records to exceed the bounded channel capacity before the
        // writer fails.
        let recs: Vec<ReadRecord> = (0..2000)
            .map(|i| rec(&format!("r{i}"), b"ACGTACGTAC", vec![40; 10]))
            .collect();
        let mut w = FailAfter {
            limit: 100,
            written: 0,
        };
        let res = run_fastq(
            recs.into_iter().map(anyhow::Ok),
            &mut w,
            &cfg,
            &Arc::new(Counters::default()),
        );
        assert!(
            res.is_err(),
            "Write error must surface as Err and must not hang"
        );
    }

    #[test]
    fn parallel_surfaces_parse_error_instead_of_dropping_it() {
        let cfg = test_cfg(4);
        let good: Vec<anyhow::Result<ReadRecord>> = (0..5)
            .map(|i| anyhow::Ok(rec(&format!("r{i}"), b"ACGTACGTAC", vec![40; 10])))
            .collect();
        let recs = good
            .into_iter()
            .chain(std::iter::once(Err(anyhow::anyhow!("bad record"))));

        let mut out = Vec::new();
        let res = run_fastq(recs, &mut out, &cfg, &Arc::new(Counters::default()));
        assert!(
            res.is_err(),
            "A malformed record must not be dropped on the parallel path"
        );
    }
}