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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
//! whittle: coordinate-consistent trimming of long-read uBAM and tagged FASTQ.
//!
//! `run` is the library entry point; `cli::parse` builds its `Config`.

pub mod adapter;
pub(crate) mod banner;
pub mod cli;
pub mod config;
pub mod filter;
pub(crate) mod guards;
pub mod io;
pub mod mods;
pub mod obs;
pub mod qual;
pub mod record;
pub mod summary;
pub mod tagfilter;
pub mod trim;
pub mod workflow;

pub use banner::command_line;

use std::borrow::Cow;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use anyhow::Context as _;

pub use config::Config;
use io::Format;

/// Runs one trimming job. A directory input selects folder-merge mode (every
/// read file in it is merged into one output); any other input is a single file
/// or stdin. FASTQ and unaligned BAM are supported.
///
/// `obs` drives progress and end-of-run output; library callers pass
/// `obs::ProgressHandle::disabled()`.
pub fn run(cfg: Config, obs: &mut obs::ProgressHandle) -> anyhow::Result<()> {
    let mut cfg = cfg;
    let dir = cfg
        .io
        .input
        .as_deref()
        .filter(|p| p.is_dir())
        .map(Path::to_path_buf);
    let result = match dir {
        Some(dir) => run_folder(&dir, &mut cfg, obs),
        None => run_single(&mut cfg, obs),
    };
    // `announce` drains the parse-time advisories as it prints them. A setup
    // failure ahead of the banner leaves them pending, and they print here so an
    // early error never hides a skipped FASTA entry or a rejected `WHITTLE_LOG`.
    emit_advisories(&mut cfg.advisories);
    result
}

/// Runs single-file (or stdin) mode: detects the format, announces, and
/// dispatches.
fn run_single(cfg: &mut Config, obs: &mut obs::ProgressHandle) -> anyhow::Result<()> {
    let setup_start = Instant::now();
    guards::guard_output_collisions(cfg, &[])?;

    let in_path = cfg.io.input.clone();
    let in_path = in_path.as_deref();

    // The total input byte count, known for a file, drives a determinate
    // progress bar with percent and ETA; stdin has no size, so `None` selects a
    // spinner (see `obs::ProgressHandle::start`).
    let total: Option<u64> = in_path
        .and_then(|p| std::fs::metadata(p).ok())
        .map(|m| m.len());

    // Created before the reader so one `Arc` is shared by `CountingReader`, the
    // workflow call, and `obs.start`.
    let counters = Arc::new(workflow::Counters::default());

    // The input (file or stdin) is opened before format detection so the sniffed
    // bytes are kept: whatever detection consumes is chained back in front of
    // the stream through a `Cursor` before the reader is built. `CountingReader`
    // sits innermost, so sniffed bytes are counted once.
    let raw: Box<dyn Read + Send> = match in_path {
        Some(p) => Box::new(
            std::fs::File::open(p).with_context(|| format!("opening input {}", p.display()))?,
        ),
        None => Box::new(std::io::stdin()),
    };
    let raw: Box<dyn Read + Send> =
        Box::new(io::counting::CountingReader::new(raw, counters.clone()));
    let mut source: Box<dyn Read + Send> = Box::new(BufReader::new(raw));

    let in_fmt = match cfg.io.in_format {
        // A forced format is checked against the stream: a wrong `--input-format`
        // would otherwise read zero records and exit 0, or fail inside a
        // decoder with a message that names no flag.
        Some(forced) => {
            let (detected, replayed) = detect_format(in_path, source).with_context(|| {
                format!(
                    "--input-format {} but the input does not look like {}",
                    forced.label(),
                    forced.label()
                )
            })?;
            source = replayed;
            match detected {
                None => forced,
                Some(d) if io::forced_format_accepts(forced, d) => d,
                Some(d) => anyhow::bail!(
                    "--input-format {} but the input is {}; drop the flag or pass --input-format {}",
                    forced.label(),
                    d.label(),
                    d.flag_value()
                ),
            }
        },
        None => match in_path.and_then(io::from_extension) {
            // A `.gz` extension covers both plain gzip and BGZF; the first block
            // header decides, and BGZF gets a block-parallel decode share.
            Some(Format::FastqGz) => io::probe_gz(&mut source)?,
            Some(f) => f,
            None => {
                let (fmt, replayed) = detect_format(in_path, source)?;
                source = replayed;
                fmt.ok_or_else(|| {
                    anyhow::anyhow!("cannot determine input format; pass --input-format")
                })?
            },
        },
    };

    // Advisory only: an explicit `--input-format` or `--output-format` decides the
    // format, and a disagreement with the path's extension (`--output-format fastq`
    // on an `out.fastq.gz` path) is reported as a warning. Skipped for stdin,
    // stdout, and paths without an extension. Only the check runs here; both
    // warnings are logged after the banner with the other advisories.
    let mismatch_warn = io::format_mismatch_warning("--input-format", cfg.io.in_format, in_path);
    let out_mismatch_warn = io::format_mismatch_warning(
        "--output-format",
        cfg.io.out_format,
        cfg.io.output.as_deref(),
    );

    let out_fmt = cfg
        .io
        .out_format
        .unwrap_or_else(|| io::resolve_output(cfg.io.output.as_deref(), in_fmt));

    // Hard error before any writer or output file is created: BAM or gzipped
    // bytes are refused on an interactive terminal.
    guards::guard_stdout_binary(cfg, out_fmt)?;
    // Detection has classified the stream, so a piped or extensionless FASTQ
    // reaches the same refusals `cli::parse` applies to a named one.
    guards::guard_bam_only_flags(cfg, in_fmt)?;
    guards::guard_fastq_to_bam(in_fmt, out_fmt)?;

    tracing::debug!(
        stage = "setup",
        format = in_fmt.label(),
        elapsed_ms = setup_start.elapsed().as_millis() as u64,
        "Input format detected"
    );

    let budget = plan_budget(
        cfg,
        match in_fmt {
            Format::FastqBgzf | Format::Bam => config::Decode::Blocks,
            Format::FastqGz => config::Decode::Stream,
            Format::Fastq => config::Decode::Inline,
        },
    );

    let mut warnings: Vec<String> = Vec::new();
    warnings.extend(mismatch_warn);
    warnings.extend(out_mismatch_warn);
    if cfg.io.out_format.is_none() {
        warnings.extend(io::unknown_extension_warning(
            cfg.io.output.as_deref(),
            out_fmt,
        ));
    }
    if is_no_op(cfg, in_fmt == out_fmt) {
        warnings.push(NO_OP_WARNING.to_string());
    }
    announce(
        cfg,
        obs,
        counters.clone(),
        &Startup {
            input_line: match (in_path, total) {
                (Some(p), Some(size)) => {
                    format!("Input: {} ({})", p.display(), obs::human_bytes(size))
                },
                (Some(p), None) => format!("Input: {}", p.display()),
                (None, _) => "Input: <stdin>".to_string(),
            },
            total,
            in_fmt,
            out_fmt,
            budget,
            warnings,
        },
    );

    let session = Session::begin(cfg, budget, counters, in_fmt, out_fmt);
    session.dispatch(cfg, obs, in_fmt, out_fmt, Source::Stream(source))
}

/// Runs folder-merge mode (`-i <dir>`): classifies the directory into one
/// format family, then merges its read files into a single trimmed output
/// through the same dispatch as the single-file path.
fn run_folder(dir: &Path, cfg: &mut Config, obs: &mut obs::ProgressHandle) -> anyhow::Result<()> {
    // `--input-format` is inert for a directory, whose family is decided per file
    // by extension, so a warning is queued below.
    let folder_in_format_ignored = cfg.io.in_format.is_some();

    // `classify` hard-errors when `-o` names a read file inside `-i <dir>`:
    // overwriting real input or stale prior output while merging the rest is
    // silent data loss. The guard then checks every other written file against
    // every member.
    let (family, paths) = io::dir::classify(dir, cfg.io.output.as_deref())?;
    guards::guard_output_collisions(cfg, &paths)?;
    let family_fmt = match family {
        io::dir::Family::Fastq => Format::Fastq,
        io::dir::Family::Bam => Format::Bam,
    };
    let out_fmt = cfg
        .io
        .out_format
        .unwrap_or_else(|| io::resolve_output(cfg.io.output.as_deref(), family_fmt));
    guards::guard_stdout_binary(cfg, out_fmt)?;
    guards::guard_bam_only_flags(cfg, family_fmt)?;
    guards::guard_fastq_to_bam(family_fmt, out_fmt)?;

    // A `.gz` member is BGZF when its first block header says so. Members are
    // read one at a time, so a plain gzip member inflates on one of the
    // decode workers BGZF members take.
    let decode = if family_fmt == Format::Bam {
        config::Decode::Blocks
    } else {
        paths
            .iter()
            .map(|p| match io::from_extension(p) {
                Some(Format::FastqBgzf) => config::Decode::Blocks,
                Some(Format::FastqGz) if io::is_bgzf_file(p) => config::Decode::Blocks,
                Some(Format::FastqGz) => config::Decode::Stream,
                _ => config::Decode::Inline,
            })
            .max()
            .unwrap_or(config::Decode::Inline)
    };
    let budget = plan_budget(cfg, decode);
    let counters = Arc::new(workflow::Counters::default());

    // Summed unconditionally, not only when the banner prints: it also drives
    // the determinate progress bar.
    let total_bytes: u64 = paths
        .iter()
        .filter_map(|p| std::fs::metadata(p).ok())
        .map(|m| m.len())
        .sum();
    tracing::debug!(
        stage = "setup",
        format = family_fmt.label(),
        files = paths.len(),
        "Folder classified"
    );

    let mut warnings: Vec<String> = Vec::new();
    if folder_in_format_ignored {
        warnings.push(
            "--input-format is ignored for a directory input; folder files are classified by \
             extension per file"
                .to_string(),
        );
    }
    warnings.extend(io::format_mismatch_warning(
        "--output-format",
        cfg.io.out_format,
        cfg.io.output.as_deref(),
    ));
    // Every member file's precise format, not the collapsed family: a folder of
    // `.fastq.gz` merged into plain `.fastq` is a conversion.
    let same_format = paths.iter().all(|p| io::from_extension(p) == Some(out_fmt));
    if is_no_op(cfg, same_format) {
        warnings.push(NO_OP_WARNING.to_string());
    }
    announce(
        cfg,
        obs,
        counters.clone(),
        &Startup {
            input_line: format!(
                "Input: {} {} files, {}",
                paths.len(),
                family_fmt.label(),
                obs::human_bytes(total_bytes)
            ),
            total: Some(total_bytes),
            in_fmt: family_fmt,
            out_fmt,
            budget,
            warnings,
        },
    );

    let session = Session::begin(cfg, budget, counters, family_fmt, out_fmt);
    session.dispatch(cfg, obs, family_fmt, out_fmt, Source::Folder(paths))
}

/// Sniffs the input format from the stream's first bytes when neither
/// `--input-format` nor the path extension decides it. Returns the format and the
/// stream with the consumed bytes chained back in front, so the reader built
/// next sees the input from its start.
fn detect_format(
    in_path: Option<&Path>,
    mut source: Box<dyn Read + Send>,
) -> anyhow::Result<(Option<Format>, Box<dyn Read + Send>)> {
    // The probe covers a full BGZF block header (18 bytes), which tells a BAM on
    // stdin or under an unknown extension apart from gzipped FASTQ.
    let mut probe = [0u8; 18];
    let n = io::fill(&mut source, &mut probe)?;
    let mut replay = probe[..n].to_vec();
    // An empty stream has no format; the caller decides whether that is an
    // error or a run over zero records.
    if n == 0 {
        return Ok((None, source));
    }
    let fmt = if io::is_bgzf(&replay) {
        let block_size = usize::from(u16::from_le_bytes([replay[16], replay[17]])) + 1;
        if block_size < replay.len() {
            anyhow::bail!("invalid BGZF block size {block_size}");
        }
        replay.resize(block_size, 0);
        source.read_exact(&mut replay[n..]).with_context(|| {
            format!(
                "truncated BGZF block in {}",
                in_path.map_or_else(|| "<stdin>".to_string(), |p| p.display().to_string())
            )
        })?;
        io::detect_bgzf_block(&replay)?
    } else {
        io::detect_input(&replay)?
    };
    Ok((
        Some(fmt),
        Box::new(std::io::Cursor::new(replay).chain(source)),
    ))
}

/// Returns the thread budget of a run: compressed input takes its decode
/// workers out of the `-t` budget and the render pool takes the rest.
fn plan_budget(cfg: &Config, decode: config::Decode) -> config::ThreadBudget {
    config::thread_budget(cfg.threads, decode)
}

/// Where the records come from: one stream (a file or stdin, with any sniffed
/// bytes chained back in), or the member files of a folder.
enum Source {
    /// A single byte stream.
    Stream(Box<dyn Read + Send>),
    /// The read files of a directory, in merge order.
    Folder(Vec<PathBuf>),
}

/// The per-run state every dispatch arm shares: the thread split, the live
/// counters, the output label, and the processing-phase clock. One `dispatch`
/// serves both entry points, so every arm settles the configuration and writes
/// the summary file.
struct Session {
    /// The per-stage worker split.
    budget: config::ThreadBudget,
    /// Live counters shared with the reader and the progress ticker.
    counters: Arc<workflow::Counters>,
    /// The output path or `<stdout>`, as shown in the banner and the closer.
    out_desc: String,
    /// Start of the processing phase. Stages run concurrently (read, trim, and
    /// write overlap across threads), so this marks a phase boundary, not a
    /// CPU-time split.
    t0: Instant,
}

impl Session {
    /// Opens the processing phase, after the banner has printed.
    fn begin(
        cfg: &Config,
        budget: config::ThreadBudget,
        counters: Arc<workflow::Counters>,
        in_fmt: Format,
        out_fmt: Format,
    ) -> Self {
        tracing::debug!(
            stage = "dispatch",
            input = in_fmt.label(),
            output = out_fmt.label(),
            threads = cfg.threads,
            decode = budget.decode,
            render = budget.render,
            "Processing started"
        );
        Session {
            budget,
            counters,
            out_desc: banner::output_desc(cfg.io.output.as_deref()),
            t0: Instant::now(),
        }
    }

    /// Runs the workflow for one (input, output) format pair.
    ///
    /// Every arm settles the adapter set before creating the output file: an
    /// inference-report exit (`Ok(None)` from `settle`) returns before any output
    /// is touched, since building the writer first would truncate a pre-existing
    /// `-o` file even though report mode writes no records. The FASTQ-to-BAM
    /// rejection sits before its writer for the same reason, so a rejected run
    /// leaves no 0-byte file behind.
    fn dispatch(
        self,
        cfg: &mut Config,
        obs: &mut obs::ProgressHandle,
        in_fmt: Format,
        out_fmt: Format,
        source: Source,
    ) -> anyhow::Result<()> {
        match (in_fmt, out_fmt) {
            (Format::Bam, Format::Bam) => {
                note_tags_ignored(cfg, in_fmt, out_fmt);
                let (header, records) = self.bam_reader(source, true)?;
                let mut out_header = io::bam::provenance_header(
                    header,
                    cfg.threads <= 1 || cfg.ordered,
                    &command_line(std::env::args_os()),
                );
                let rejects = self.start_rejects(cfg, out_fmt, Some(&out_header))?;
                let records = self.tag_filtered_bam(cfg, records, out_fmt);
                let Some(records) = settle(
                    records,
                    cfg,
                    self.budget,
                    adapter::resolve::bam_seq,
                    adapter::resolve::bam_sample_weight,
                )?
                else {
                    return Ok(());
                };
                io::bam::merge_trim_mode(&mut out_header, cfg.trim_classes);
                let mut sink = io::bam::writer(
                    cfg.io.output.as_deref(),
                    &out_header,
                    cfg.threads > 1,
                    cfg.compression_level,
                )?;
                let stats =
                    workflow::run_raw_bam(&out_header, records, &mut sink, cfg, &self.counters)?;
                // Explicit finish (final bgzf block and EOF marker) rather than
                // `Drop`, which discards a `try_finish` error: an I/O failure on
                // the final flush (ENOSPC) would otherwise yield a truncated BAM
                // and a success exit code.
                sink.finish()?;
                finish_rejects(rejects)?;
                self.finish(obs, &stats, cfg)
            },
            (Format::Bam, Format::Fastq | Format::FastqGz | Format::FastqBgzf) => {
                note_update_moves_ignored(cfg, out_fmt);
                let (_header, records) = self.bam_reader(source, false)?;
                let rejects = self.start_rejects(cfg, out_fmt, None)?;
                let records = self.tag_filtered_bam(cfg, records, out_fmt);
                let Some(records) = settle(
                    records,
                    cfg,
                    self.budget,
                    adapter::resolve::bam_seq,
                    adapter::resolve::bam_sample_weight,
                )?
                else {
                    return Ok(());
                };
                let mut writer = io::fastq::writer(cfg, out_fmt, cfg.threads > 1)?;
                let stats = workflow::run_bam_to_fastq(records, &mut writer, cfg, &self.counters)?;
                writer.finish()?;
                finish_rejects(rejects)?;
                self.finish(obs, &stats, cfg)
            },
            (Format::Fastq | Format::FastqGz | Format::FastqBgzf, Format::Bam) => {
                anyhow::bail!("FASTQ-to-BAM conversion is not supported")
            },
            (Format::Fastq | Format::FastqGz | Format::FastqBgzf, _) => {
                let rejects = self.start_rejects(cfg, out_fmt, None)?;
                #[cfg(feature = "paraseq")]
                let mut source = source;
                #[cfg(feature = "paraseq")]
                let sampling = cfg.adapter_infer != config::AdapterInfer::Off
                    || cfg
                        .adapters
                        .as_ref()
                        .is_some_and(|a| !a.adapters.is_empty());
                #[cfg(feature = "paraseq")]
                let paraseq = workflow::paraseq_selected()
                    && !sampling
                    && cfg.tag_filters.is_empty()
                    && in_fmt != Format::FastqBgzf
                    && cfg.threads > 1;
                #[cfg(feature = "paraseq")]
                if let (true, Source::Stream(src)) = (paraseq, &mut source) {
                    let src = std::mem::replace(src, Box::new(std::io::empty()));
                    cfg.render_workers = self.budget.render;
                    let stream = io::fastq::byte_stream(src, in_fmt == Format::FastqGz, true);
                    let mut writer = io::fastq::writer(cfg, out_fmt, true)?;
                    let stats =
                        workflow::run_fastq_paraseq(stream, &mut writer, cfg, &self.counters)?;
                    let tagged = self
                        .counters
                        .tagged_fastq
                        .load(std::sync::atomic::Ordering::Relaxed);
                    writer.finish()?;
                    finish_rejects(rejects)?;
                    guards::guard_tag_flags(cfg, in_fmt, tagged)?;
                    if !tagged {
                        note_tags_ignored(cfg, in_fmt, out_fmt);
                    }
                    return self.finish(obs, &stats, cfg);
                }
                let records = self.fastq_reader(source, in_fmt, cfg.threads > 1)?;
                let records = self.tag_filtered_fastq(cfg, records);
                let Some(records) = settle(
                    records,
                    cfg,
                    self.budget,
                    |r| Cow::Borrowed(r.seq.as_slice()),
                    |r| {
                        (
                            std::mem::size_of::<record::ReadRecord>()
                                + r.name.capacity()
                                + r.seq.capacity()
                                + r.qual.capacity(),
                            r.seq.len(),
                        )
                    },
                )?
                else {
                    return Ok(());
                };
                let mut writer = io::fastq::writer(cfg, out_fmt, cfg.threads > 1)?;
                let stats = workflow::run_fastq(records, &mut writer, cfg, &self.counters)?;
                let tagged = self
                    .counters
                    .tagged_fastq
                    .load(std::sync::atomic::Ordering::Relaxed);
                writer.finish()?;
                finish_rejects(rejects)?;
                guards::guard_tag_flags(cfg, in_fmt, tagged)?;
                if !tagged {
                    note_tags_ignored(cfg, in_fmt, out_fmt);
                }
                self.finish(obs, &stats, cfg)
            },
        }
    }

    /// Opens the BAM record stream. A stdin BAM's sniffed bytes are chained back
    /// into the stream, so it is read as is rather than reopened. Only the
    /// first file of a folder contributes its header, so `check_read_groups`
    /// asks the folder reader to reject incompatible read-group definitions;
    /// BAM output only, since FASTQ output writes no header.
    fn bam_reader(
        &self,
        source: Source,
        check_read_groups: bool,
    ) -> anyhow::Result<(noodles_sam::Header, io::bam::RawRecordIter)> {
        match source {
            Source::Stream(src) => io::bam::reader_from(src, self.budget.decode),
            Source::Folder(paths) => io::dir::bam_reader(
                &paths,
                self.budget.decode,
                self.counters.clone(),
                check_read_groups,
            ),
        }
    }

    /// Applies the run's tag filters to a raw BAM stream, or returns it as is.
    fn tag_filtered_bam(
        &self,
        cfg: &Config,
        records: io::bam::RawRecordIter,
        out_fmt: Format,
    ) -> io::bam::RawRecordIter {
        if cfg.tag_filters.is_empty() {
            return records;
        }
        let filters = cfg.tag_filters.clone();
        let counters = Arc::clone(&self.counters);
        let cfg = cfg.clone();
        workflow::filter_by_tags(
            records,
            Arc::clone(&self.counters),
            move |rec| filters.keeps(rec),
            |rec| rec.sequence().len(),
            |rec| io::bam::display_name(rec.name().map(AsRef::as_ref)),
            move |rec| {
                if !counters.wants_rejects() {
                    return Ok(());
                }
                let item = if out_fmt == Format::Bam {
                    workflow::bam::tag_filtered_bam(rec)?
                } else {
                    workflow::bam::tag_filtered_bam_fastq(rec, &cfg)?
                };
                counters.reject(item)
            },
        )
    }

    /// Opens the rejected output when `--rejected-output` is set, registers its
    /// channel with the counters and returns the writer to finish after the
    /// run. Called before the first record is read, so tag-filtered reads
    /// reach it too.
    fn start_rejects(
        &self,
        cfg: &Config,
        out_fmt: Format,
        header: Option<&noodles_sam::Header>,
    ) -> anyhow::Result<Option<workflow::reject::RejectWriter>> {
        let Some(path) = cfg.rejected_output.as_deref() else {
            return Ok(None);
        };
        let format = workflow::reject::resolve_format(path, out_fmt)?;
        let (rejects, writer) = workflow::reject::RejectWriter::start(
            path,
            format,
            cfg.compression_level,
            header.cloned(),
            cfg.threads.max(1),
        )?;
        self.counters
            .rejects
            .set(rejects)
            .map_err(|_| anyhow::anyhow!("the rejected output was opened twice"))?;
        Ok(Some(writer))
    }

    /// Applies the run's tag filters to a FASTQ stream, or returns it as is.
    /// A header without aux tags offers no tags, so every comparison on it is
    /// false; the input guard reports a plain FASTQ after the run.
    fn tag_filtered_fastq(
        &self,
        cfg: &Config,
        records: Box<dyn Iterator<Item = anyhow::Result<record::ReadRecord>> + Send>,
    ) -> Box<dyn Iterator<Item = anyhow::Result<record::ReadRecord>> + Send> {
        if cfg.tag_filters.is_empty() {
            return records;
        }
        let filters = cfg.tag_filters.clone();
        let counters = Arc::clone(&self.counters);
        workflow::filter_by_tags(
            records,
            Arc::clone(&self.counters),
            move |rec| {
                if !io::tagged::has_aux_tags(&rec.name) {
                    return filters.keeps(&tagfilter::NoTags);
                }
                counters
                    .tagged_fastq
                    .store(true, std::sync::atomic::Ordering::Relaxed);
                let fields = rec
                    .name
                    .iter()
                    .position(|&b| b == b'\t')
                    .map_or(&[][..], |t| &rec.name[t + 1..]);
                let data = io::tagged::parse_aux_fields(fields)?;
                filters.keeps(&data)
            },
            |rec| rec.seq.len(),
            |rec| {
                String::from_utf8_lossy(
                    rec.name
                        .split(|&b| b == b'\t' || b == b' ')
                        .next()
                        .unwrap_or(&[]),
                )
                .into_owned()
            },
            {
                let counters = Arc::clone(&self.counters);
                move |rec| {
                    if !counters.wants_rejects() {
                        return Ok(());
                    }
                    counters.reject(workflow::reject::RejectItem::Fastq(
                        workflow::tag_filtered_fastq(rec),
                    ))
                }
            },
        )
    }

    /// Opens the FASTQ-family record stream for `in_fmt`. Plain gzip inflates
    /// on its own thread when `threaded`, the thread the budget set aside.
    fn fastq_reader(
        &self,
        source: Source,
        in_fmt: Format,
        threaded: bool,
    ) -> anyhow::Result<Box<dyn Iterator<Item = anyhow::Result<record::ReadRecord>> + Send>> {
        match source {
            Source::Stream(src) => match in_fmt {
                Format::Fastq => Ok(io::fastq::reader_from(src, false, false)),
                Format::FastqGz => Ok(io::fastq::reader_from(src, true, threaded)),
                Format::FastqBgzf => io::fastq::reader_from_bgzf(src, self.budget.decode),
                Format::Bam => unreachable!("BAM input is dispatched to bam_reader"),
            },
            Source::Folder(paths) => Ok(io::dir::fastq_records(
                &paths,
                self.budget.decode,
                threaded,
                self.counters.clone(),
            )),
        }
    }

    /// Closes out a finished dispatch: logs the phase duration and the
    /// end-of-run summary, writes `--summary-json`, then logs the closer. The
    /// artifact precedes the `Completed` line so a failed write is never
    /// reported after a success line.
    fn finish(
        &self,
        obs: &mut obs::ProgressHandle,
        stats: &workflow::Stats,
        cfg: &Config,
    ) -> anyhow::Result<()> {
        tracing::debug!(
            stage = "dispatch",
            elapsed_ms = self.t0.elapsed().as_millis() as u64,
            reads_in = stats.input_reads,
            reads_out = stats.output_reads,
            bases_in = stats.input_bases,
            bases_out = stats.output_bases,
            "Processing finished"
        );
        let elapsed = obs.finish(stats);
        if let Some(path) = cfg.summary_json.as_deref() {
            summary::Summary::new(
                cfg,
                stats,
                command_line(std::env::args_os()),
                self.out_desc.clone(),
                elapsed,
            )
            .write(path)?;
        }
        obs.complete(elapsed, &self.out_desc);
        Ok(())
    }
}

/// Settles the configuration for dispatch and returns the record stream.
///
/// Two fields are only knowable here. The adapter set depends on the reads:
/// presence detection samples a prefix and inference discovers from one, so the
/// set is final only after the banner has printed the configured set. The
/// render-pool size comes from the thread budget. Both are assigned in this one
/// place so every dispatch arm sees the same narrowed set and pool size.
///
/// `Ok(None)` means the run is over without writing records: that is
/// `--adapter-report`, which prints the inferred FASTA and stops.
fn settle<R, I, F>(
    records: I,
    cfg: &mut Config,
    budget: config::ThreadBudget,
    seq_of: F,
    weight: impl Fn(&R) -> (usize, usize),
) -> anyhow::Result<Option<Box<dyn Iterator<Item = anyhow::Result<R>> + Send>>>
where
    I: Iterator<Item = anyhow::Result<R>> + Send + 'static,
    R: Send + 'static,
    F: for<'a> Fn(&'a R) -> std::borrow::Cow<'a, [u8]>,
{
    let Some(resolved) = adapter::resolve::resolve(records, cfg, seq_of, weight)? else {
        note_report_only_ignores(cfg);
        return Ok(None);
    };
    // Captured before the overwrite: the banner already printed this figure, and
    // the summary reports it alongside what resolution settled on.
    cfg.adapters_configured = cfg.adapters.as_ref().map(|a| a.adapters.len());
    cfg.adapters = resolved.adapters;
    cfg.trim_classes = trim_classes(cfg);
    cfg.render_workers = budget.render;
    Ok(Some(resolved.records))
}

/// Returns which sequence classes the resolved adapter set trims, as the
/// `adapter`, `primer` and `barcode` flags of `io::bam::merge_trim_mode`.
fn trim_classes(cfg: &Config) -> [bool; 3] {
    let mut classes = [false; 3];
    for adapter in cfg.adapters.iter().flat_map(|a| &a.adapters) {
        let class = match adapter.role {
            adapter::Role::Adapter => 0,
            adapter::Role::Primer => 1,
            adapter::Role::Barcode => 2,
        };
        classes[class] = true;
    }
    classes
}

/// Warns for every artifact flag that report-only inference leaves unwritten;
/// the run exits 0 without creating any of them.
fn note_report_only_ignores(cfg: &Config) {
    for (flag, _) in cfg.write_targets() {
        tracing::warn!("{flag} is ignored under --adapter-report, which writes no records");
    }
}

/// The resolved facts both entry points announce before processing starts.
struct Startup {
    /// The `Input:` line body: a path and size, `<stdin>`, or a folder's file
    /// count and total size.
    input_line: String,
    /// Input bytes, when known. Drives a determinate bar; `None` gives a spinner.
    total: Option<u64>,
    /// The input format, or a folder's format family.
    in_fmt: Format,
    /// The resolved output format.
    out_fmt: Format,
    /// The per-stage worker split shown in the `Threads:` line.
    budget: config::ThreadBudget,
    /// Advisories specific to this entry point, logged after the shared ones.
    warnings: Vec<String>,
}

/// Prints the startup banner and the deferred advisories, then starts progress.
///
/// The order is the output contract: `whittle {version}` and `Command:` (from
/// `main`), then the resolved config, then every advisory, then live progress,
/// so the run's provenance is at the top and nothing interleaves with the bar.
/// Both entry points call this function, so an advisory is emitted on both
/// paths. Starting progress here rather than at the call sites makes the
/// ordering a property of this function.
fn announce(
    cfg: &mut Config,
    obs: &mut obs::ProgressHandle,
    counters: Arc<workflow::Counters>,
    s: &Startup,
) {
    if obs.shows_lines() {
        tracing::info!("{}", banner::operation_line(s.in_fmt, s.out_fmt));
        tracing::info!("{}", s.input_line);
        tracing::info!(
            "{}",
            banner::output_banner_line(cfg.io.output.as_deref(), s.out_fmt, cfg.compression_level)
        );
        tracing::info!("{}", banner::threads_banner_line(cfg.threads, s.budget));
        if let Some(p) = cfg.rejected_output.as_deref() {
            tracing::info!("Rejected: {}", p.display());
        }
        tracing::info!("{}", banner::filters_and_trim_line(&cfg.filter, &cfg.trim));
        for text in cfg.tag_filters.texts() {
            tracing::info!("Tag filter: {text}");
        }
        if let Some(line) = banner::adapter_banner_line(
            cfg.adapters.as_ref(),
            cfg.adapter_sample,
            cfg.adapter_infer,
        ) {
            tracing::info!("{line}");
        }
    } else if obs.is_bar() {
        // Bar mode prints one line so the live bar stays clean.
        tracing::info!(
            "{} ({} threads)",
            banner::operation_line(s.in_fmt, s.out_fmt),
            cfg.threads
        );
    }

    emit_advisories(&mut cfg.advisories);
    if let Some((requested, ncpu)) = cfg.threads_clamped {
        tracing::warn!(
            requested,
            ncpu,
            "Requested -t exceeds the CPU count; using the CPU count"
        );
    }
    for w in &s.warnings {
        tracing::warn!("{w}");
    }

    obs.start(s.total, counters);
}

/// Logs and drains the parse-time diagnostics held by `cli::parse` and
/// `obs::init` until the subscriber exists, so `--quiet` silences them and they
/// carry the standard prefix. Draining makes a second call a no-op, so `run`
/// prints only what the banner did not reach.
fn emit_advisories(advisories: &mut Vec<config::Advisory>) {
    for a in advisories.drain(..) {
        if a.warn {
            tracing::warn!("{}", a.message);
        } else {
            tracing::info!("{}", a.message);
        }
    }
}

/// True when the run neither trims nor filters, so the output mirrors the input
/// apart from format.
///
/// `same_format` is supplied by the caller because the two entry points answer
/// it differently: folder mode's family collapses `.fastq`, `.fastq.gz`, and
/// `.fastq.bgz` into one value, so comparing families there would classify a
/// decompression run as a no-op.
fn is_no_op(cfg: &Config, same_format: bool) -> bool {
    let no_trim = cfg.trim.head == 0 && cfg.trim.tail == 0 && cfg.trim.quality.is_none();
    let pass_through_filter = cfg.filter.min_length <= 1
        && cfg.filter.max_length == usize::MAX
        && cfg.filter.min_qual <= 0.0
        && cfg.filter.max_qual >= 1000.0
        && cfg.filter.max_expected_errors.is_none()
        && cfg.filter.min_gc.is_none()
        && cfg.filter.max_gc.is_none();
    no_trim
        && pass_through_filter
        && cfg.adapters.is_none()
        && cfg.remove_tags.is_empty()
        && cfg.tag_filters.is_empty()
        && same_format
}

/// Finishes the rejected output, if one was opened.
fn finish_rejects(writer: Option<workflow::reject::RejectWriter>) -> anyhow::Result<()> {
    match writer {
        Some(writer) => writer.finish(),
        None => Ok(()),
    }
}

/// Warning for a run that neither trims nor filters.
const NO_OP_WARNING: &str =
    "No trimming or filtering options set; output will mostly mirror the input";

/// Warns when `--fastq-tags` was set to a non-default value (`none` or an
/// explicit list) on a path other than BAM-to-FASTQ, where it has no effect. An
/// explicit `all` equals the default and is silent.
fn note_tags_ignored(cfg: &Config, in_fmt: Format, out_fmt: Format) {
    if !matches!(cfg.fastq_tags, config::FastqTags::All) {
        tracing::warn!(
            input = in_fmt.label(),
            output = out_fmt.label(),
            "--fastq-tags applies only to BAM-to-FASTQ output and is ignored"
        );
    }
}

/// Warns that `--update-moves` has no effect on BAM-to-FASTQ output, which
/// drops the signal tags on every trim.
fn note_update_moves_ignored(cfg: &Config, out_fmt: Format) {
    if cfg.update_moves {
        tracing::warn!(
            output = out_fmt.label(),
            "--update-moves applies only to BAM-to-BAM output and is ignored"
        );
    }
}

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

    fn a_read() -> crate::record::ReadRecord {
        crate::record::ReadRecord {
            name: b"r1".to_vec(),
            seq: b"ACGTACGTACGT".to_vec(),
            qual: vec![40; 12],
        }
    }

    /// `settle` is the one place both dispatch-time fields are written. A
    /// missing `render_workers` assignment would oversubscribe the render pool
    /// or run it single-threaded on the BAM full-window path.
    #[test]
    fn settle_sets_both_dispatch_fields() {
        let mut cfg = base_config();
        cfg.render_workers = 0;
        cfg.adapters = None;
        let budget = config::ThreadBudget {
            decode: 1,
            render: 5,
        };

        let records = vec![Ok(a_read())].into_iter();
        let got = settle(
            records,
            &mut cfg,
            budget,
            |r| Cow::Borrowed(r.seq.as_slice()),
            |r| (r.name.len() + r.seq.len() + r.qual.len(), r.seq.len()),
        )
        .expect("Settle succeeds")
        .expect("Records are returned when not in report mode");

        assert_eq!(
            cfg.render_workers, 5,
            "Render pool size comes from the budget"
        );
        assert!(cfg.adapters.is_none(), "No adapters configured stays none");
        assert_eq!(got.count(), 1, "The record stream is handed back intact");
    }

    /// With no adapter work to do, the stream passes through untouched rather
    /// than being buffered.
    #[test]
    fn settle_passes_records_through_when_adapters_are_off() {
        let mut cfg = base_config();
        let budget = config::ThreadBudget {
            decode: 1,
            render: 1,
        };
        let records = (0..7).map(|_| Ok(a_read()));
        let got = settle(
            records,
            &mut cfg,
            budget,
            |r| Cow::Borrowed(r.seq.as_slice()),
            |r| (r.name.len() + r.seq.len() + r.qual.len(), r.seq.len()),
        )
        .unwrap()
        .unwrap();
        assert_eq!(got.count(), 7);
    }

    fn base_config() -> Config {
        Config {
            threads: 8,
            quiet: true,
            ..Config::default()
        }
    }
}