Skip to content

fix: count secondary+supplementary records as secondary only (flagstat) - #131

Closed
BenjaminDEMAILLE wants to merge 1 commit into
seqeralabs:mainfrom
BenjaminDEMAILLE:fix/flagstat-supplementary-double-count
Closed

BenjaminDEMAILLE wants to merge 1 commit into
seqeralabs:mainfrom
BenjaminDEMAILLE:fix/flagstat-supplementary-double-count

Conversation

@BenjaminDEMAILLE

Copy link
Copy Markdown
Contributor

Fixes #125.

Problem

Records carrying both SECONDARY (0x100) and SUPPLEMENTARY (0x800) were counted in both the secondary and supplementary flagstat totals, because the two bits were tested independently:

if is_secondary { self.secondary += 1; }
if is_supplementary { self.supplementary += 1; }

samtools gives SECONDARY priority — bam_stat.c (flagstat) and stats.c both classify such a record as secondary and never reach the supplementary counter. The double count inflates the supplementary total and breaks the invariant primary + secondary + supplementary == total.

While checking this against samtools, a second instance of the same conflation showed up in the samtools stats SN section: non-primary alignments is nreads_secondary in samtools, but RustQC emitted secondary + supplementary. That line was wrong for any BAM containing supplementary alignments, dual-flagged or not.

Fix

  • accumulators.rs: if is_secondary { .. } else if is_supplementary { .. }
  • stats.rs: non-primary alignments: now reports secondary alone

Verification

Ground truth from samtools 1.24 on a synthetic BAM (4 primary pairs, 2 secondary-only, 3 supplementary-only, 5 dual-flagged):

samtools flagstat            samtools stats
18 + 0 in total              SN  non-primary alignments:  7
 8 + 0 primary               SN  supplementary alignments: 3
 7 + 0 secondary
 3 + 0 supplementary

A second control file with the dual-flagged records removed (2 secondary-only, 3 supplementary-only) gives non-primary alignments: 2, confirming that line tracks secondary alone rather than the sum.

New unit test test_dual_flagged_reads_count_as_secondary_only builds the same record mix and asserts those numbers plus the sum invariant.

  • cargo test — 201 lib + 18 integration tests pass
  • cargo fmt --check, cargo clippy -- -D warnings clean

🤖 Generated with Claude Code

samtools gives the SECONDARY (0x100) flag priority over SUPPLEMENTARY
(0x800): a record carrying both is counted as secondary and never reaches
the supplementary counter (bam_stat.c flagstat_loop and stats.c both return
early on secondary). RustQC tested the two bits independently, so
dual-flagged records were counted twice — inflating the flagstat
supplementary total and breaking the invariant
`primary + secondary + supplementary == total`.

The same conflation affected the samtools stats SN section: "non-primary
alignments" is `nreads_secondary` in samtools, not secondary+supplementary.

Verified against samtools 1.24 on a synthetic BAM with 4 primary pairs,
2 secondary-only, 3 supplementary-only and 5 dual-flagged records:
18 total / 8 primary / 7 secondary / 3 supplementary, non-primary 7.

Closes seqeralabs#125

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
NicoDeVeaux added a commit that referenced this pull request Nov 1, 2026
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
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

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): records flagged both secondary and supplementary are counted as secondary only, in flagstat and in samtools stats, and stats' non-primary alignments counts secondary records only. cc @ewels

@ewels ewels closed this Nov 27, 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.

samtools flagstat: reads with both SECONDARY and SUPPLEMENTARY flags are double-counted in the supplementary total

3 participants