Skip to content

perf(methylate): speed up methylate and skip CpGs in ambiguous reference sequence - #27

Open
tfenne wants to merge 6 commits into
mainfrom
tf_speedup_methylate
Open

tfenne wants to merge 6 commits into
mainfrom
tf_speedup_methylate

Conversation

@tfenne

@tfenne tfenne commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Makes methylate 2.5–3.7× faster on a single thread, and stops it assigning methylation to CpGs that only exist because Ns were resolved to random bases. This is offered as an alternative to the per-contig threading in #21: on hs38DH without a VCF it takes 24 s single-threaded, with lower memory and no new concurrency.

Behaviour change

A CG now counts as a CpG only when both bases are uppercase. Fasta::load_contig already uppercases real ACGT and stores bases synthesized from N and other ambiguity codes in lowercase, so this excludes CpGs made of invented bases. Random sequence has a CG every 16 bases, so assembly gaps produced 26% of all CpG records on hs38DH (41.8 M records before, 30.9 M after).

  • methylate's VCF and bedGraph, simulate's CpG truth bedGraph, and the golden BAM's XM/YM tags all follow the rule.
  • For a given --seed, methylation values differ from earlier versions on any reference containing ambiguity codes, because removing CpGs shifts the random draws. On a reference without ambiguity codes the output is byte-identical to main.
  • Methylation VCFs written by earlier versions should be regenerated. Most still load, but one with a variant next to an ambiguity code is rejected with an MT/MB length mismatch.
  • VCF alternate alleles are uppercased when haplotypes are built, so lowercase keeps the single meaning "synthesized". methylate still echoes REF/ALT exactly as given.

Output-preserving speed-ups

  • One shared memchr substring search for CG replaces five hand-written scan loops.
  • A haplotype with no variants on a contig borrows the reference instead of copying it. The reference's CpGs and island contexts are found once and shared; only the methylation draw is per haplotype.
  • The bedGraph writer streams records directly when no haplotype has variants, and otherwise merges per-haplotype counts with a sort instead of a BTreeMap.
  • Haplotype::extract_fragment copies the reference run between variants in bulk instead of one base at a time. simulate uses this too.
  • CpG island runs are computed directly instead of via a per-base bit mask (speed-neutral, less code).

Benchmarks

hs38DH, single thread, BGZF VCF plus bedGraph, --seed 1. The VCF case uses 3.5 M mutate-generated variants.

main (ac66f99) This branch
No VCF, wall time 86.9 s 23.8 s
No VCF, peak memory 2.1 GB 0.64 GB
With VCF, wall time 126.2 s 49.5 s
With VCF, peak memory 3.95 GB 3.96 GB

Testing

  • cargo ci-fmt, cargo ci-lint, cargo ci-test (448 passed).
  • Each output-preserving commit was checked byte-identical to the previous step on chr1 (no VCF) and chr22 (42k and 85k variants), for both the VCF and the bedGraph.
  • simulate FASTQs and golden BAM are byte-identical to main on a reference with variants and no ambiguity codes.
  • An independent review compared main against the branch over 60 random seeds × 3 scenarios (ploidy 1–3; SNPs, MNPs, indels, multi-allelic and contig-edge variants): methylate and simulate outputs were byte-identical wherever the behaviour change does not apply.
  • New tests: no CpGs inside a run of N (VCF and bedGraph); lowercase dinucleotides skipped by the scan, the methylation table and the golden-BAM context classifier; island runs merge and separate correctly; Haplotype::sequence borrows without variants, includes inserted bases, and uppercases lowercase alternate alleles.

Not addressed

With a VCF, each haplotype is still copied in full four times per contig along with a per-base position array, which is why memory is unchanged in that case.

Summary by CodeRabbit

  • Bug Fixes
    • methylate and simulate now count CpGs only when both bases are real, preventing calls at ambiguous reference positions.
    • Lowercase VCF alternate bases are counted as real bases by simulate --max-n-frac.
  • Performance
    • methylate runs faster and uses less memory when no VCF is provided. simulate also benefits from faster haplotype fragment extraction.

tfenne added 6 commits October 1, 2026 19:03
A CG now counts as a CpG only when both bases are uppercase, i.e. real
reference or variant bases. Lowercase bases are those load_contig
synthesized from N and other ambiguity codes; random sequence has a CG
every 16 bases, so assembly gaps produced 26% of all CpG records on
hs38DH. The scan is a memchr substring search shared by the methylation
walk, the VCF classifier and the bedGraph writer.

VCF alleles are uppercased when parsed so that lowercase keeps the single
meaning of an ambiguity-resolved reference base.

Whole-genome methylate on hs38DH: 87 s to 52 s.
A haplotype with no variants on a contig borrows the reference instead of
copying it, and the reference's CpGs and their island contexts are found
once and shared by every such haplotype; only the methylation draw is per
haplotype. The bedGraph writer streams records directly in that case, and
otherwise merges per-haplotype counts with a sort instead of a BTreeMap.

methylate on chr1 without a VCF: 3.7 s to 1.7 s, 1.75 GB to 0.6 GB.
Golden-BAM XM/YM context classification now ignores lowercase (synthesized)
reference bases, matching the methylation VCF and the CpG truth bedGraph.

VCF alleles are uppercased when haplotypes are built rather than when the
VCF is parsed, so methylate echoes REF/ALT unchanged (symbolic and breakend
alleles included) and simulate can still match records in methylation VCFs
whose alleles are lowercase.
@coderabbitai

coderabbitai Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (1)
CLAUDE.md — auto-discovered

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: a988dfe8-e7cd-4542-a9d9-bc5d750d72b1

📥 Commits

Reviewing files that changed from the base of the PR and between ac66f99 and 4abf2ae.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • CHANGELOG.md
  • Cargo.toml
  • README.md
  • src/haplotype.rs
  • src/meth.rs
  • src/methylation_tags.rs
  • src/output/methylation_bedgraph.rs
  • src/vcf/methylation.rs
  • tests/test_methylate.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Haplotype extraction now supports borrowed reference sequences and owned variant sequences. CpG scans recognize uppercase CG only, and island contexts use merged intervals. Methylation construction, classification, and bedGraph output apply these rules.

Changes

CpG Recognition and Methylation Output

Layer / File(s) Summary
Haplotype sequences and extraction
src/haplotype.rs, CHANGELOG.md
Haplotypes can borrow the reference sequence when they contain no variants. Reference extraction copies contiguous runs, and alternate alleles are stored in uppercase. The changelog also records the extraction performance changes and lowercase alternate-base handling in simulate.
CpG and context classification
Cargo.toml, src/meth.rs, src/methylation_tags.rs, src/vcf/methylation.rs
Shared CpG detection recognizes uppercase CG. Island contexts use merged intervals. Methylation construction caches reference CpG sites, while methylation tags and VCF classification use the updated CpG and context rules.
Methylation outputs and validation
src/output/methylation_bedgraph.rs, tests/test_methylate.rs, README.md, CHANGELOG.md
BedGraph output counts CpGs that map to adjacent reference CG bases. The end-to-end test checks output around a run of ambiguous bases. The documentation describes the corresponding methylation and simulation outputs.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: nh13

Merge Risk: ⚪ Minimal · up to 4abf2

No identified issue remains that needs correction before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 4abf2

The change has limited design risk and does not show increased privileges or a new service boundary. Older methylation VCFs should be regenerated: newly detected incompatibilities can stop simulation after output files have already been created, leaving incomplete results.

Retained concerns

  • Low · reliability · inferred: Uppercase-only CpG ownership can reject formerly accepted variant MT/MB data on a later contig. Simulation creates output writers before per-contig methylation decoding, so this new compatibility failure can leave an incomplete output set. The non-transactional lifecycle predates the PR; explicit error propagation and documented VCF regeneration reduce, but do not eliminate, the upgrade failure-containment risk.
Security review details

Security Blast Radius

  • inferred — The traced exposure is caller-supplied sequence and variant data influencing per-contig methylation state and simulation files within the invoking process. The added sequence wrapper uses the existing fragment extractor and does not itself grant file, network or credential authority.

Security Findings and Attack Paths

  • observed — Standalone MT/MB records validate format, ploidy and bit values but do not verify uppercase reference CG identity before populating tables. Those bits can influence simulation chemistry. Both the permissive reader and chemistry sink predate this PR; the inspected comparison does not establish a newly introduced or expanded security attack path.

Trust Boundaries and Controls

  • observed — The added reference-sharing path does not share mutable methylation state: reference slices and CpG metadata are read-only, while draws allocate separate tables. Existing VCF identity lookup uses POS, REF, ALT and GT together, and decoding rejects invalid positions, malformed fields and cardinality mismatches.

Resilience and Maintainability Implications

  • inferred — Error handling contains failed VCF decoding within unreturned contig tables, but does not provide an atomic transaction across simulation output files. This lifecycle already existed; the PR's documented legacy-data rejection adds an upgrade-specific route into it. Exact interruption cleanup and rerun overwrite behavior were not fully inspected.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the primary changes: improved methylate performance and exclusion of CpGs in ambiguous reference sequences.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 6 files. (3 skipped: 3…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks each letter’s face,
And finds real CG in its place.
Long runs hop by, neat and fast,
While lowercase shadows pass.
BedGraph keeps the counts in line,
The rabbit nibbles, pleased to dine.

Comment @coderabbitai help to get the list of available commands.

@nh13 nh13 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice speedup, and skipping CpGs in N runs makes sense. I'd fix two things before merge: old VCFs loading silently (and the default-threads abort), and the XM/YM context next to Ns. Docs and test gaps are inline. I checked the extract_fragment run-copy rewrite against main with a randomized differential test (960k cases, including overlapping variants and contig ends) and the output is identical.

Outside the diff:

  • apply_standalone_record (src/vcf/methylation.rs:1077) doesn't check the reference base, so an old methylation VCF with records inside N runs loads silently and sets bits at positions that are no longer CpGs. Warn or fail when a record isn't on an uppercase CG.
  • NM/MD uppercase the reference base (src/methylation_tags.rs:271, :304) but XM/YM now skip lowercase, so a resolved c read as T is a bisulfite match in NM/MD and . in XM/YM. Document it or make them agree.
  • The "(uppercase)" docs at src/vcf/methylation.rs:63, :932 and :1422 are stale, as is the methylate help ("every CpG dinucleotide", src/commands/methylate.rs:18, and the module doc at line 3).

Comment thread src/methylation_tags.rs
}
let next1 = *ref_bytes.get(ref_idx + 1)?;
if next1.eq_ignore_ascii_case(&b'G') {
if next1 == b'G' {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A real C next to a resolved base is now called CHH/CHG (ACgT gives CHH, and the new test pins it). Bismark calls that context unknown (U/u) when the neighbour is an N, since it might have been a G, and treats other IUPAC codes as non-G. Returning None (.) when the deciding neighbour is lowercase is the closer match, and probably what the README's "no CpG calls there" intends.

Comment thread CHANGELOG.md
golden BAM. For a given `--seed`, methylation values differ from earlier
versions on any reference that contains ambiguity codes. Methylation VCFs
written by earlier versions should be regenerated: most still load, but one
with a variant next to an ambiguity code is rejected with an MT/MB length

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Users won't see this message with the default --threads: it aborts with exit 134 from a pooled-writer panic before the mismatch prints. --threads 1 gives the clean error. The abort predates this PR, but please fix the error path or reword this.

Comment thread CHANGELOG.md
contain a `CG` about every 16 bases, and each of these was written as a CpG
record; on hs38DH they were 26% of all records. A `CG` now counts as a CpG
only when both bases are real reference or variant bases. `simulate` applies
the same rule to its CpG truth bedGraph and to the `XM`/`YM` tags in the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CHG/CHH calls at a resolved C also become . in XM/YM, not only CpG calls. The lowercase-ALT entry (lines 28-30) could also say this changes simulate output for a given --seed, since --max-n-frac no longer rejects those reads.

Comment thread tests/test_methylate.rs
}

#[test]
fn methylate_emits_no_cpgs_inside_a_run_of_n() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This passes because seed 42 happens to resolve one CG in the Ns (the comment says "several"). After a rand upgrade it could resolve none and still pass. A second seed or a longer N run would fix that. No test covers the N-run rule on the methylate --vcf path either, which is where the MT/MB mismatch comes from.

Comment thread src/meth.rs
let runs = island_runs(mask);
/// open-sea relative to the island `runs` produced by [`island_runs`]: inside
/// a run is an island, within [`SHORE_WIDTH_BP`] of one is a shore.
fn classify_cpg_contexts(cpg_top_c: &[u32], runs: &[(u32, u32)]) -> Vec<CpgContext> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no test fails if the upstream-shore branch or either SHORE_WIDTH_BP boundary breaks. Only the downstream branch is covered.

Comment thread src/meth.rs
.map(|hap| MethylationTable::from_haplotype(hap, reference, model, rng))
.map(|hap| {
if hap.is_reference() {
let sites = reference_sites.get_or_insert_with(|| CpgSites::find(reference));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no test covers this reference fast path with lowercase bases. Uppercasing the reference here still passes every test.

// Variants present → materialize each haplotype, walk its bases looking
// for CpGs, and map each one back to a reference position via the per-base
// `ref_positions` returned by `extract_fragment`.
let mut per_haplotype: Vec<CpgCounts> = Vec::new();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: per_haplotype holds one entry per (haplotype, CpG), while meth.rs uses the same name for a per-haplotype Vec. Maybe per_hap_cpg?

Comment thread Cargo.toml
# Vec<bool> would cost 8x the memory at whole-chromosome scale. See
# MethylationTable in src/meth.rs.
bitvec = "1"
memchr = "2"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: bstr already pulls in memchr and has find_iter, so this costs nothing. Fine either way.

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.

2 participants