Skip to content

fix(flagstat): match samtools counts, alignment priority and percentages - #175

Closed
NicoDeVeaux wants to merge 5 commits into
mainfrom
ndv/fix-flagstat-qcfail-proper-dup
Closed

NicoDeVeaux wants to merge 5 commits into
mainfrom
ndv/fix-flagstat-qcfail-proper-dup

Conversation

@NicoDeVeaux

@NicoDeVeaux NicoDeVeaux commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

QC-failed records now populate the second flagstat column, unmapped records cannot count as properly paired, and QC-failed duplicates remain duplicates. The flagstat writer and the legacy stats accumulator now both give SECONDARY priority over SUPPLEMENTARY, so dual-flagged records are counted once. samtools stats reports secondary records alone as non-primary alignments, and percentage division follows samtools' C float expression before formatting.

This extends the secondary-priority and stats semantics proposed by Benjamin Demaille in #131 to the separate FlagstatCounts path introduced here. Merging the previous versions of #131 and this PR unchanged would leave the new counter double-counting. #131 remains open for maintainer coordination; adopting the samtools code's precedence for #125 still needs maintainer agreement.

The regression tests no longer modify the oracle to preserve the old overlap behavior. They retain the original samtools-generated all-flags fixture, cover overlap combined with QC-fail/duplicate flags, compare partitioned counter merges, and check large-count rounding. Integration tests use Cargo's actual test binary rather than falling back to an unrelated debug build. The branch also includes the recorded crossbeam-epoch/libz-sys lockfile updates and a separate iterator-only fix for three existing Clippy warnings.

Validation of candidate a9083c:

  • All 244 release tests pass on macOS and Linux: 205 library, 12 binary, 25 integration and two doc tests. Formatting and strict Clippy pass on both.
  • Native samtools 1.22.1 and 1.24 agree with the candidate in 48 targeted F/S CLI cases and 24 aggregate all-flags CLI cases, across 1/2/4/8 threads and two repeats. A compiled production-counter probe agrees in all 12,288 flag/placement rows.
  • Four pinned nf-core module tasks pass on two original paired-end BAMs. MultiQC 1.35 parsing and actual CLI raw exports agree with the corresponding samtools outputs for both pairs. These real fixtures have no QC-failed or supplementary reads; the synthetic cases exercise those triggers.
  • The local cached security audit passed at its recorded advisory snapshot. Fresh upstream CI and a fresh Linux audit remain separate checks.

This is targeted flagstat/stats evidence. It does not establish complete RNA-QC equivalence, Wave/container packaging, a full rnaseq run, genuine single-end coverage or strand-selection equivalence. Other stats fields, including reads properly paired, have separate definitions and are outside these targeted repairs. The wider frozen campaign retains five old-baseline expectation failures, and empty input still exits zero with one thread but nonzero with 2/4/8; no expectations were changed after scoring. The separate living review has two scientific PASS gates and nine pending recipes, so full merge/release acceptance remains UNKNOWN. Its byte/source/build records are trusted evidence, without machine or source-to-binary attestation.

This counting PR stays independent of the #118 noodles migration and its stacked #177/#178 fixes.

This update is written by GPT-6 on Nico DeVeaux's behalf. The original PR was prepared with Claude Code.

NicoDeVeaux and others added 5 commits October 23, 2026 11:13
…plicate counts

Failing tests for three divergences from samtools flagstat 1.22.1:

- QC-failed reads (0x200) are counted in the QC-passed column; the second
  column is always 0.
- "properly paired" counts a PAIRED|PROPER_PAIR record that is itself
  unmapped (samtools requires !UNMAP, bam_stat.c:61).
- A QC-failed duplicate (0x600) is in neither "duplicates" column, while
  "primary duplicates" counts it.

The unit tests check every 12-bit flag against a transcription of samtools'
flagstat_loop; the integration tests compare `rustqc rna` output with
golden output from samtools 1.22.1. The SECONDARY|SUPPLEMENTARY line
(#125) is kept at its current behaviour and pinned as such.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…stat_loop

flagstat now keeps its own `[QC-passed, QC-failed]` counters
(`FlagstatCounts`), counted like samtools' `flagstat_loop` (bam_stat.c):

- QC-failed reads (0x200) go in the second column, with their own
  percentages, instead of being folded into the first.
- "properly paired" requires the read itself to be mapped.
- "duplicates" counts every 0x400 record, not the RSeQC bam_stat cascade
  counter that drops QC-failed duplicates.

The SECONDARY|SUPPLEMENTARY case (#125) is unchanged: such a record still
counts on both lines. The counters that only fed flagstat are removed from
BamStatAccum/BamStatResult; those samtools stats reads are untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port PR #131 secondary priority to both legacy and QC-split counters. Match the pinned samtools C percentage arithmetic, restore unmodified exhaustive oracles, and cover QC-failed duplicate overlaps and partition merges.

Select the Cargo-provided integration binary at compile time so release tests keep their profile and CARGO_TARGET_DIR. Add a raw production-counter example for independent differential validation.

Fixes #125
Replace the three existing needless_range_loop findings with fixed-size iterator zips. Preserve cycle/channel order and u64 addition order; floating percentage calculations are unchanged.

Validated with cargo fmt --check, strict cargo clippy, and the complete 244-test release suite.
@NicoDeVeaux NicoDeVeaux changed the title fix(flagstat): split counts by QC pass/fail and follow samtools' flagstat_loop fix(flagstat): match samtools counts, alignment priority and percentages Nov 1, 2026
rhassaine added a commit to rhassaine/RustQC that referenced this pull request Nov 26, 2026
…nd stats on every flag

samtools gives SECONDARY priority over SUPPLEMENTARY in `flagstat_loop`
(bam_stat.c) and in `stats.c`: a record carrying both flags is secondary
only. The flagstat writer already did this through `FlagstatCounts`, but the
per-field counters behind `samtools stats` still counted such a record as
secondary and as supplementary, so `SN supplementary alignments` was too
high (3072 against samtools' 6144 on the all-flags input below). Use
`else if`, so primary + secondary + supplementary == total.

Add the regression tests that expose it, all checked against samtools
1.22.1 (bioconda build h96c455f_0):

- all 4096 flag values in three mate placements: flagstat and the `SN`
  section of stats against samtools-generated golden files, on the serial
  and the per-contig parallel path (integration test);
- one flagged record between two plain reads for QC-failed, QC-failed
  duplicate, secondary+supplementary, QC-failed 0xf00 and the
  "properly paired needs a mapped read" case (0x4f);
- unit tests against a transcription of samtools' flagstat_loop for every
  flag and placement, merged and partitioned counters, dual flags with
  QC-fail and duplicate, and large-count percentage rounding (expected
  strings produced by compiling samtools' percent() unchanged).

The test cases and the semantics they pin come from seqeralabs#175
(Nico DeVeaux) and seqeralabs#131 (Benjamin Demaille).

Co-authored-by: Nico DeVeaux <105398+NicoDeVeaux@users.noreply.github.com>
Co-authored-by: Benjamin Demaille <41732816+BenjaminDEMAILLE@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ewels pushed a commit that referenced this pull request Nov 26, 2026
* fix(samtools): match samtools stats and flagstat 1.22.1 exactly

Port the remaining details of samtools stats.c and bam_stat.c (1.22.1) so
every data line of the stats output and the whole flagstat output match
samtools, independent of --threads.

samtools stats:
- GCD: normalise bin GC with rint() in double precision (ties to even),
  compute percentiles and depth scaling in single precision as samtools
  does, compare GC groups like fabs(float - float) < 0.1, and give
  supplementary reads a GC of 0. Bins are put back in BAM order before
  output, because samtools leaves the last bin un-normalised; before, the
  "last" bin depended on how contigs were split across threads.
- COV: simulate the samtools round buffer per contig. Its flush to the end
  visits only size - 1 slots, so one slot is carried into the next contig
  and dropped after the last one. The carry is resolved after all contigs
  are merged, so the result does not depend on --threads.
- SN: error rate and the averages are float divisions in samtools; the
  insert-size summary halves each orientation separately and keeps
  insert size 0 for same-contig pairs; filtered sequences is 0; QC-failed,
  unmapped, properly paired, duplicated and different-chromosome counts
  use samtools' own conditions; mismatches and duplicates include
  supplementary reads; non-primary alignments counts secondary records.
- First/last fragments follow samtools' read order (read1 only / read2
  only); read lengths include hard clips; ID only lists indels up to 300
  bases and skips leading deletions like count_indels; GCT skips empty
  cycles; FFQ/LFQ share one maximum quality and keep all 256 quality
  values (missing qualities are 255).

samtools flagstat: count QC-passed and QC-failed records separately
(port of flagstat_loop) and compute percentages in single precision.

Library API: BamStatResult gains the samtools-only counters and a
FlagstatCounts; ffq/lfq rows are [u64; 256]; the public
BamStatAccum::flush_cov_buf_all is gone (coverage is finished per contig).

Verified byte for byte (all non-comment lines of stats, full flagstat and
idxstats) against samtools 1.22.1 (bioconda h96c455f_0) on the eight
RustQC-benchmarks datasets and on synthetic BAMs with QC-fail,
supplementary, secondary, hard-clipped, spliced and unmapped reads, at
--threads 1, 2 and 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(samtools): secondary beats supplementary in stats; pin flagstat and stats on every flag

samtools gives SECONDARY priority over SUPPLEMENTARY in `flagstat_loop`
(bam_stat.c) and in `stats.c`: a record carrying both flags is secondary
only. The flagstat writer already did this through `FlagstatCounts`, but the
per-field counters behind `samtools stats` still counted such a record as
secondary and as supplementary, so `SN supplementary alignments` was too
high (3072 against samtools' 6144 on the all-flags input below). Use
`else if`, so primary + secondary + supplementary == total.

Add the regression tests that expose it, all checked against samtools
1.22.1 (bioconda build h96c455f_0):

- all 4096 flag values in three mate placements: flagstat and the `SN`
  section of stats against samtools-generated golden files, on the serial
  and the per-contig parallel path (integration test);
- one flagged record between two plain reads for QC-failed, QC-failed
  duplicate, secondary+supplementary, QC-failed 0xf00 and the
  "properly paired needs a mapped read" case (0x4f);
- unit tests against a transcription of samtools' flagstat_loop for every
  flag and placement, merged and partitioned counters, dual flags with
  QC-fail and duplicate, and large-count percentage rounding (expected
  strings produced by compiling samtools' percent() unchanged).

The test cases and the semantics they pin come from #175
(Nico DeVeaux) and #131 (Benjamin Demaille).

Co-authored-by: Nico DeVeaux <105398+NicoDeVeaux@users.noreply.github.com>
Co-authored-by: Benjamin Demaille <41732816+BenjaminDEMAILLE@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Nico DeVeaux <105398+NicoDeVeaux@users.noreply.github.com>
Co-authored-by: Benjamin Demaille <41732816+BenjaminDEMAILLE@users.noreply.github.com>
@rhassaine

rhassaine commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for this! It's now covered by #198 (merged), which uses the same semantics (checked against the samtools 1.22.1 source). Your test cases are folded in: all 4,096 flags × 3 placements, the QC-fail and dual-flag cases, and the percentage checks. They caught one SN supplementary alignments count for records flagged both secondary and supplementary, which #198 then fixed. cc @ewels

@ewels ewels closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants