Skip to content
Tech Interview Prep
Technical interview guide

Variant Calling & Genomic File Formats

The FASTQ-to-VCF pipeline: how raw reads become a filtered list of called variants, and the file formats each stage produces.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: VCF 4.5 / BCF 2.2, SAM/BAM and CRAM 3.1 specifications; current GATK, bcftools, samtools, GIAB, vcfeval and GA4GH VRS guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-4

Parse alignments without coordinate errors.

Answer

Core answer. Assume SAM/BAM (spec SAMv1, hts-specs 1.6), POS is 1-based and CIGAR offsets are 0-based within the alignment. Walk two pointers, a query pointer over SEQ and a reference pointer starting at POS-1, and advance each per operation. M, I, S, =, X consume query; M, D, N, =, X consume reference; H and P consume neither. Get that table right and coordinates fall out; get it wrong and every downstream interval is shifted.

Mechanism. The reference pointer only moves on ops that occupy reference bases. I inserts query bases with no reference advance; D and N skip reference bases with no query advance (N is the spliced gap, D a deletion). S is present in SEQ but not aligned; H is not in SEQ at all, so len(SEQ) equals query-consuming length only when there is no H. The 1-based reference end is POS + ref_span - 1.

Python
import re
Q = set("MIS=X")   # consume query
R = set("MDN=X")   # consume reference

def spans(cigar):
    q = r = 0
    for n, op in re.findall(r"(\d+)([MIDNSHP=X])", cigar):
        n = int(n)
        if op in Q: q += n
        if op in R: r += n
    return q, r

spans("3S8M2I4M")   # (17, 12)  -- Python 3.11

Worked trace. POS=1000, CIGAR=3S8M2I4M:

opquery ptrref ptr (0-based)
start0999
3S3999
8M111007
2I131007
4M171011

Query length 17, reference span 12, 1-based end 1000+12-1 = 1011. Converting to BED (0-based, half-open): start = POS-1 = 999, end = 999+12 = 1011.

Trade-offs. M means alignment match: it may hide mismatches. If you need identity or variant calls, require =/X (minimap2 --eqx; BWA-MEM does not emit them by default) or read the MD tag. Cost: =/X roughly doubles CIGAR length and inflates BAM. Criterion: coordinates and coverage only → M is fine; per-base identity → =/X or MD. For malformed CIGAR, choose reject-versus-repair deliberately: a validation gate should reject and fail the batch; a long-running pipeline should quarantine the record and continue, because silently clamping a bad CIGAR corrupts every downstream interval. Never repair without logging.

Failure modes. Off-by-one: mixing 1-based POS with 0-based CIGAR offsets shifts intervals by one base. Detect by asserting ref_end == POS + ref_span - 1 on every record. Treating M as exact match inflates identity: detect by comparing against NM/MD. Ignoring 0x10 (reverse strand): SEQ is reverse-complemented relative to the reference, but POS still names the leftmost reference base, so do not flip coordinates. Detect by checking SEQ against the reference. Double-counting 0x100 secondary alignments inflates coverage; 0x800 supplementary records are split parts of one read and should be combined (see the SA tag). Dropping supplementary records loses split alignments entirely. H present but query length computed from len(SEQ) mismatches: assert query_span == len(SEQ) only when no H.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Convert VCF records to intervals safely.

Answer

Clarify and assume. "Convert to intervals" is ambiguous: keep VCF's own 1-based closed coordinates, or emit BED-style 0-based half-open for intersection with BED tracks. I'll assume the latter, and that the VCF declares a build (##reference) and contig naming that matches the target.

Core rule. A record's reference footprint is POS .. POS+len(REF)-1 in 1-based closed coordinates, unless INFO/END is present, in which case it is POS .. END. To emit half-open, subtract 1 from the start and use the 1-based end unchanged as the exclusive end. That one rule covers SNV, insertion, deletion and symbolic records; the cases differ only in how the end is computed.

Worked records on chr1:

record1-based spanBED half-open
SNV POS=100 REF=A ALT=G100–100[99,100)
ins POS=200 REF=A ALT=AT200–200[199,200)
del POS=300 REF=AT ALT=A300–301[299,301)
symbolic POS=400 REF=N ALT=<DEL> END=500400–500[399,500)
BND POS=600 REF=N ALT=N[chr2:700[nonenone

Why insertion has zero reference length. VCF forces a shared anchor base so POS is unambiguous, so an insertion's REF is the base before the inserted sequence. The inserted bases have no reference coordinates; the record's footprint is the anchor alone: one base, not zero. The trap is computing len(ALT)-len(REF) = +1 and emitting [POS, POS+1), a one-base shift on every insertion.

Why END is inclusive. END follows the same 1-based inclusive convention as POS: it is the last affected base, not the first unaffected one. So you use END directly as the half-open end; adding 1 shifts every symbolic interval by one base.

Trade-offs. If you only intersect VCF with VCF, stay in VCF space: conversion buys nothing and loses symbolic/BND semantics. Convert when the other side is BED/GFF. Don't hand-roll: pysam's VariantRecord.start is already 0-based and .stop is 0-based exclusive (POS-1 and POS-1+len(REF), or END for symbolic), and htsjdk exposes the same. bcftools query's %END falls back to POS+len(REF)-1 when INFO/END is absent: the same rule, already implemented. Hand-rolled arithmetic is where the off-by-one lives.

Failure modes and detection.

  • Off-by-one: round-trip VCF→BED→VCF and diff POS; any nonzero diff is the bug.
  • Insertion zero-length: assert no record has start==end; a zero-length interval is the symptom of the len(ALT)-len(REF) mistake.
  • END inclusivity: an END+1 conversion shifts all symbolic intervals; check a known DEL against its expected span.
  • BND loss: BND records carry the mate in the ALT string (N[chr2:700[), not in END, so a POS..POS interval drops it. Count ALTs containing [ or ] and route them separately.
  • Contig mismatch: chr1 vs 1 yields empty intersections. Assert the contig sets match before intersecting.
  • Build mismatch: the same POS is a different locus on GRCh37 vs GRCh38. Read ##reference and refuse to convert if it disagrees with the target.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Parse VCF sample fields robustly.

Answer

Core answer

Assume VCFv4.2 or later (4.2, 4.3 and 4.4 agree on FORMAT semantics), a text stream, and that you cannot assume every record carries the same FORMAT keys. The robust rule: for each record, read the FORMAT column, split it into keys, and index each sample's colon-separated values by that record's key order. Never by a fixed position. Then interpret GT against the record's own ALT list, where 0 is REF and 1..N are ALT alleles in record order.

Mechanism

FORMAT is per-record, not per-file. One record can be GT:AD:DP, the next GT:GQ. The header declares each key's Number and Type; use it. Number=1 is one value per sample (GT, DP, GQ). Number=R is one per allele including REF (AD). Number=G is one per genotype: 3 values for a diploid biallelic site, 6 for two ALT alleles. Number=A is one per ALT allele. GT is Number=1 but its value is a string of allele indexes joined by / (unphased) or | (phased); ploidy is whatever the string contains, and . is a missing allele. Per spec, GT must be the first FORMAT sub-field when present.

Snippet (Python 3.11, no external deps):

Python
def parse_gt(gt_str, n_alt):
    alleles, phased, token = [], None, ""
    for ch in gt_str:
        if ch in "/|":
            alleles.append(_allele(token, n_alt))
            phased, token = ch, ""
        else:
            token += ch
    alleles.append(_allele(token, n_alt))
    return alleles, phased

def _allele(tok, n_alt):
    if tok == ".":
        return None
    i = int(tok)
    if i < 0 or i > n_alt:
        raise ValueError(f"allele index {i} out of range for {n_alt} ALT")
    return i

Trace: parse_gt("1|2", 2) → [1, 2], phased "|". parse_gt("./.", 2) → [None, None], phased "/". parse_gt("2", 1) → ValueError.

Trade-offs

Hand-rolled vs cyvcf2/pysam (both wrap htslib). cyvcf2 is Cython over htslib: fast, spec-correct, handles BGZF and indexing, but adds a native dependency and its own API quirks. Hand-rolled is dependency-free and lets you stream partial or non-BGZF text, but you re-implement the spec and own the bugs. Decide on throughput (millions of records → htslib), whether you need random access via .tbi/.csi, and whether you must round-trip exact text.

Strict vs lenient: strict raises on out-of-range allele index or wrong cardinality. Right for QC pipelines where a bad record should stop the run. Lenient logs and skips: right for messy clinical data where dropping a record is worse than a warning. Decide by whether downstream can tolerate a silently dropped sample.

Failure modes

  • Fixed diploid assumption: gt.split("/")[0:2] truncates haploid chrY/chrM and polyploid calls. Detect by counting alleles per GT against a ploidy histogram; cost is silently wrong genotypes on sex chromosomes.
  • Hard-coded FORMAT order: assuming GT:AD:DP everywhere. Detect by asserting the FORMAT key set per record; cost is AD read as DP.
  • Multiallelic index error: GT=2 with one ALT. Detect by validating max index ≤ len(ALT); cost is an IndexError or a wrong allele.
  • Missing as reference: int(".") → 0. Detect by checking . before conversion; cost is missing genotypes counted as hom-ref, inflating allele frequencies.
  • Phase loss: always joining with /. Detect with a round-trip test; cost is phasing lost for imputation and haplotype work.
  • Sample-column swap: reordering samples without the #CHROM header. Detect by asserting sample names match header order; cost is genotypes attributed to the wrong person.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Interpret PL and GQ fields.

Answer

Core answer (say this first)

PL and GQ are both Phred-scaled, but they answer different questions. PL is a likelihood: PL = -10 * log10 P(observed read data | genotype), normalized so the most likely genotype is 0. GQ is the phred-scaled probability that the called genotype is wrong, conditional on the site being variant.

To interpret PL you need three things from the header and record: the allele ordering, the ploidy, and the Number=G declaration. For a diploid sample the genotype order is fixed by the spec: 0/0, 0/1, 1/1, 0/2, 1/2, 2/2. Ordered by the second allele index ascending, then the first. So a biallelic site carries 3 PL values; a site with two alt alleles carries 6.

Worked example. Biallelic site, alleles A and T, PL=0,60,99. Mapping:

  • 0/0 -> PL 0 -> relative likelihood 10^0 = 1
  • 0/1 -> PL 60 -> 10^-6 = 1e-6
  • 1/1 -> PL 99 -> 10^-9.9 ~ 1.3e-10

The call is 0/0, and it is ~10^6 times more likely than 0/1. GQ = smallest PL among the non-called genotypes = min(60, 99) = 60, i.e. P(call wrong) = 10^-6.

Multiallelic: alleles A, T, G, PL=0,30,90,60,99,120. Six values map to 0/0, 0/1, 1/1, 0/2, 1/2, 2/2. The call is 0/0, GQ = min(30, 90, 60, 99, 120) = 30. Get the ordering wrong and you read 0/2's likelihood as 1/1's.

What PL/GQ are not

PL is not a posterior. It carries no prior on allele frequency or disease prevalence: that is what GP (genotype posterior) adds. If you need "how likely is this genotype given the population," use GP or recompute with a prior; PL alone cannot give it. GQ is not QUAL: QUAL is a site-level confidence that any variant exists, GQ is per-sample confidence in this genotype. A site can have QUAL 200 and a sample GQ of 3.

When PL/GQ suffice, and when they don't

PL/GQ are enough for filtering one caller's output and comparing genotypes within one model. They are not enough to (a) combine evidence across callers with different error models, (b) apply a population prior, or (c) reason about depth. For those, pull AD/DP (allele depths) and GP, or re-genotype. The deciding criterion: if the decision depends on a prior or on cross-caller agreement, PL/GQ are the wrong input.

Failure modes and how to catch them

  • Wrong multiallelic ordering: you assume 3 PL values on a 2-alt site. Detect: assert len(PL) == n_genotypes computed from Number=G and the allele count.
  • Missing value treated as zero: . means "no likelihood," not PL 0 (which means "most likely"). Detect: parse . as missing before any arithmetic.
  • Capped scores: the spec caps PL at 255 and GQ at 99, so 255 means "at least 255" and 99 means "at least 99"; a 255-vs-255 comparison is uninformative. Detect: treat cap values as censored, not exact.
  • GQ confused with QUAL: different scope (sample vs site). Detect: read the FORMAT key, not the column position.
  • Comparing PL/GQ across callers: GATK, DeepVariant and others use different read/error models, so the numbers are not on the same scale. Detect: only compare within one caller, or re-genotype into a common model.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How do you make a variant file randomly queryable, and what breaks when the compression, sort order or contig header is wrong?

Answer

Random access into a variant file rests on three preconditions, all of them properties of the file rather than the query: BGZF compression, records sorted by the header's contig order and then by POS, and every CHROM value declared as a ##contig line. Satisfy those and tabix or bcftools index writes a sidecar that turns a region query into a few seeks instead of a scan.

Why BGZF, not gzip. BGZF is gzip cut into independent blocks of at most 64 KiB, each carrying a BSIZE field in its extra subfield. That gives every byte a virtual offset: 48 bits, the high 32 the offset of the compressed block, the low 16 the offset inside the decompressed block. A plain gzip stream has no block boundaries, so there is nothing to seek to: tabix and bcftools index both refuse a gzip-compressed VCF with a not-BGZF error. BCF is BGZF by construction, so only VCF.gz needs the conversion step.

How a query resolves. TBI and CSI both bin the genome: TBI at a fixed 16 kb (min_shift 14) with a linear index, CSI with configurable min_shift and depth. For a query [beg, end) the index computes the overlapping bins, reads the chunks, virtual-offset ranges, recorded for them, uses the linear index to jump to the first record at or after beg, then scans forward until POS exceeds end. Cost is proportional to records in the region, not file size. A 500 GB cohort VCF.gz answers a 1 kb query by touching a few blocks.

The sort order is the header's, not lexicographic. The index assigns each contig a tid in ##contig order. A CHROM absent from the header has no tid and index build aborts; records ordered chr1, chr10, chr2, what sort -k1,1 -k2,2n produces, mismatch a karyotypic header and the build fails on unsorted positions. Use bcftools sort, which sorts by header order.

failurehow it shows updetectrepair
gzip instead of bgzipindex build refuseshtsfile x.vcf.gz reports gzip, not BGZFbcftools view -Oz -o out.vcf.gz in.vcf.gz
contig missing from headerindex aborts; dictionary-checking tools reject the filediff bcftools view -h | grep ^##contig against the .fai/.dictbcftools annotate --rename-chrs then reheader
unsorted or wrong contig orderindex build fails, or builds and returns empty regionsindex error; query a known variantbcftools sort, then reindex
stale indexqueries silently return the wrong records.csi mtime older than the .vcf.gzreindex after every write
contig longer than 2^29 bpTBI cannot represent itindex build errorCSI with a larger depth

Two things worth saying out loud. TBI caps at 2^29 bp, and CSI's default (min_shift 14, depth 5) caps at the same 2^29, so a 300 Mb chromosome is fine but a 1 Gb plant contig needs a raised depth. And the index stores no checksum of the data file: a stale .csi is the one failure here that fails silently, which is why reindexing belongs inside the pipeline step that writes the VCF, not in a runbook. bcftools index -s listing contigs and counts is a cheap post-write check.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Validate reference compatibility before merging calls.

Answer

Before merging two callsets I want to know what each was called against, and the answer I trust is the sequence, not the label. Assume GRCh38 primary assembly, VCF 4.2, both from short-read pipelines. The rule I work from: coordinates are comparable only when the underlying contig sequence is identical. A build name is a claim; a checksum is evidence. So the merge gate is sequence identity plus a REF-allele check, not a build string comparison.

Why checksums catch what names miss: two references can agree on contig name and length and still differ in bases. A patched or N-masked reference can keep chr1 at 248,956,422 bases while changing what is at a given position. The M5 field in the .dict (or samtools dict ref.fa) is the MD5 of the sequence itself; if M5 matches, coordinates are comparable. If it doesn't, nothing downstream is safe.

The operational test is the REF allele. For every record, fetch the reference base(s) at POS and compare to REF:

Shell
bcftools norm -f GRCh38.fa -c e in.vcf   # -c e: error on REF mismatch

A nonzero mismatch rate means wrong build or wrong contig. This is the check that catches a silent liftover: chain-file liftover maps coordinates, and where the chain is ambiguous or missing the record either drops (Picard LiftoverVcf writes it to the reject VCF) or lands at a nearby position where REF no longer matches. The record survives with a plausible coordinate and a wrong locus. Detection is the post-liftover REF check plus the reject count: a drop rate you didn't expect is the signal.

Trade-offs: strict rejection versus controlled liftover. Rejecting any build difference is right when you have no audited chain and no REF check. It is wrong when you have a validated liftover pipeline (chain file versioned, REF check enforced, reject list reviewed) or when the only difference is contig naming (chr1 vs 1), where you normalize names instead of rejecting. Deciding criteria: is the sequence identical (M5), is the transform audited (chain plus REF check), is the drop rate acceptable.

failurehow it shows updetection
build mismatchhigh REF mismatch ratebcftools norm -c e
chr-prefix maskingcontigs don't join; variants vanish or duplicatediff contig name sets
alt-locus confusionvariants on chr1_KI270706v1_random vs chr1contig whitelist
silent liftoverlow REF mismatch, records at wrong locuspost-liftover REF check + reject count
reversed alleleREF matches ALTflag records where ALT matches reference
decoy differencecontig set differs (hs37d5 vs GRCh37).dict comparison
stale reference cachepipeline used an old .fachecksum the file actually used

What would change the decision: if M5 matches and the REF check passes, merge directly. If M5 differs, either liftover with the audit above or re-call against the target reference: never merge on the assumption that the build label is enough.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Archive alignment data in CRAM safely.

Answer

What "safely" has to mean. Assume the archive must be decodable in five years by someone with no access to your cluster, your reference directory, or your notes. That is stricter than "the file is on disk", and CRAM is the format where the gap bites: CRAM stores each read as a difference from a reference sequence that is not in the file by default. So preservation is four things kept together: the CRAM, its index, the exact reference used to encode it, and the linkage between them.

Where the linkage lives. Every @SQ line in the CRAM header carries M5, the MD5 of the reference sequence uppercased with whitespace removed, and normally UR, a URI for that sequence. A decoder resolves M5 through REF_PATH, a colon-separated list of templates whose default is https://www.ebi.ac.uk/ena/cram/md5/%s (the ENA CRAM reference registry), and caches downloads under REF_CACHE, default $HOME/.cache/hts-ref/%2s/%2s/%s. If M5 is present and the sequence is public, a future consumer can decode without your reference at all. If M5 is missing, for example a file encoded with no_ref=1, the file is decodable only with a reference you supply, and you must archive that reference yourself.

The recipe.

Shell
# encode, keeping M5/UR in the header
samtools view -C -T GRCh38.fa -o sample.cram sample.bam
samtools index sample.cram            # sample.crai

# prove a future consumer can decode with no local reference and an empty cache
REF_CACHE=/tmp/empty-cache \
REF_PATH='https://www.ebi.ac.uk/ena/cram/md5/%s' \
  samtools view sample.cram chr1:1-1000 > /dev/null

Run that decode test in CI on every archived file. samtools quickcheck is not a substitute: it verifies the EOF marker and header, not that the reference can be fetched or that the body decodes.

Trade-offs. Two ways to guarantee the reference survives:

  • Embed it: samtools view -C --output-fmt-option embed_ref=1. The file is self-contained; the cost is the reference itself, roughly 3 GB uncompressed for GRCh38, less after CRAM's compression. Choose this when the reference is private, locally modified, or you cannot depend on a registry.
  • Pin it externally: keep M5/UR, archive the FASTA next to the CRAM, and snapshot a REF_CACHE. Cheaper, but now two artefacts must stay in sync and a mismatch is silent until decode.

When not to use CRAM: if the reference is unknown or unstable (de novo assemblies, some metagenomic pipelines) or downstream tools cannot resolve references, keep BAM. It stores bases directly. For 30x WGS, CRAM typically saves 30-60% over BAM.

Failure modes and how each is caught.

failuredetection
reference missingdecode a slice with an empty REF_CACHE; the decoder aborts with a reference-fetch error
M5 mismatchthe decoder compares the supplied FASTA against M5 and reports the mismatch; also compare header M5 to the MD5 of the uppercased, whitespace-stripped sequence
dead URdecode with the network off; M5 plus ENA should still resolve it
truncated containersamtools quickcheck can pass; compare samtools view -c to the expected record count
stale indexsamtools idxstats totals disagree with samtools view -c; reindex
contig aliasheader chr1 vs FASTA 1: name lookup fails while M5 lookup succeeds
presence mistaken for decodabilityls and quickcheck both pass; only the decode test catches it

The one-line rule: archive the CRAM, the index, and either the embedded reference or a pinned reference plus its M5, and prove decodability with a decode that has no local reference.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Normalize multiallelic calls without corrupting evidence.

Answer

What a strong answer sounds like in the first 90 seconds. "Normalize" is two jobs, and they carry different risk: making a record canonical (left-aligned, parsimonious), and cutting the allele set to one ALT per record. Only the second destroys evidence, and only when a tool treats allele-indexed arrays as opaque lists. Assumptions: diploid germline VCF 4.2/4.3, the consumer can't read multiallelic records so splitting is mandatory, and the pre-split VCF is retained. Answer: split with a header-aware tool, let it remap indices, then prove the split records merge back to the original genotype.

bcftools norm -f ref.fa -m -any -Oz -o split.vcf.gz in.vcf

vt decompose is the older equivalent for the split; GATK's LeftAlignAndTrimVariants covers the left-align/trim half. All of them read the Number= declarations from the header and subset the arrays accordingly. The corruption comes from splitters that rebuild fields by position.

Why indices are the whole problem. ALT is an ordered list, and every array is indexed into it: GT holds ALT indices; Number=A is one value per ALT (INFO/AC, AF); Number=R is one per allele including REF (FORMAT/AD, ADF, ADR); Number=G is one per genotype in the spec's order F(j/k) = k(k+1)/2 + j (FORMAT/PL, GL, GP). Diploid, that is n(n+1)/2 values for n alleles. Splitting shrinks the index space to REF plus one ALT, so each array is re-indexed, not sliced. The saving grace is that PLs are per-genotype: the likelihood of A/C doesn't change because G was in the ALT list, so subsetting PL is exact. Recomputing PL out of depth arithmetic is not, because the caller's model is gone.

Original 1 100 A C,G, FORMAT GT:AD:DP:PL, sample 1/2:30,18,12:60:0,60,200,90,240,255 (hypothetical values). Genotype order for three alleles:

PL indexgenotypevalue
00/0 (A/A)0
10/1 (A/C)60
21/1 (C/C)200
30/2 (A/G)90
41/2 (C/G)240
52/2 (G/G)255

Split:

recordGTADPLsource PL indices
ALT=C1/.30,180,60,2000,1,2
ALT=G./130,120,90,2550,3,5

The A/G heterozygote in the G record scores 90, which is old index 3, not index 1. A position-based slicer writes [0,60,200] there and calls A/A over A/G with 12 supporting reads. The same slicer turns GT 1/2 into two confident hets.

Verification, and the misses it catches. Merge back: bcftools norm -m +any split.vcf must restore GT 1/2 and the original per-allele AD. Per record, assert that len(Number=A) equals the number of ALTs, len(Number=R) equals ALTs+1, len(PL) equals n(n+1)/2, max GT is at most the number of ALTs, min(PL) is 0 (subtract the subset minimum if the original's most likely genotype didn't survive the split), AC equals the allele's count in GT, and AN equals 2 times called samples. bcftools's +fill-tags plugin recomputes AC/AN if the splitter left them stale, and vcf-validator catches malformed arrays outright. Named misses: phasing, since 1|2 becomes 1|. and .|1 and the cis/trans link is gone; AD repeats the reference count, so in the G record 30+12 falls short of DP 60 and any "DP == sum(AD)" filter silently drops the record; CSQ/ANN entries name their own allele, so entries for the dropped ALT must be removed or they annotate the wrong one; left-aligning after splitting can collapse two ALTs into the same allele, so dedupe with bcftools norm -d and watch the record count.

When not to split. If downstream work needs phase, cis/trans, compound het or allelic imbalance, keep the multiallelic record and only left-align (bcftools norm -f ref.fa, no -m). Splitting a 1/2 site also doubles the variant count, so run burden tests and count-based QC after the split. And whatever you drop is unrecoverable from the split file, which is the argument for keeping the pre-split VCF as the evidence of record.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Normalize a VCF for comparison.

Answer

What I'd say first

The point of normalizing is that two records can describe the same haplotype with different strings, so a naive set intersection reports false differences. I pin two assumptions before starting: both VCFs are on the same reference build, and I know whether I'm comparing alleles or genotypes. If the builds differ, I stop: normalizing across builds silently rewrites REF and corrupts the call.

Then the pipeline: verify REF against the pinned reference, split multiallelics under an explicit policy, normalize each record (trim shared bases, left-align), and compare haplotypes rather than strings for anything complex.

Why left-alignment is the whole game

An indel inside a repeat has no unique textual position. Take a run of five T's at chr1:1001-1005. Caller A writes the single-T deletion as POS=1001 REF=TT ALT=T; caller B writes the identical deletion as POS=1003 REF=TT ALT=T. Same haplotype, different strings: a string diff calls them different variants.

Normalization fixes this by parsimony plus left-alignment: repeatedly trim bases shared by REF and ALT, then trim shared leading bases while shifting POS left, until neither end can be trimmed. The result is a canonical, leftmost, minimal representation, so equal haplotypes collapse to equal strings.

callerPOSREFALThaplotype
A1001TTTdelete one T from the run
B1003TTTdelete one T from the run
after norm1001TTTsame

Trimming has to happen with the shift: if you left-align a record still carrying redundant context bases, the shift target isn't well defined, and two callers that padded differently won't converge.

The commands

bcftools 1.19, GRCh38:

bcftools norm -f GRCh38.fa -c e -m -any -d exact -Oz -o a.norm.vcf.gz a.vcf.gz

-f pins the reference; -c e errors on any REF mismatch instead of silently fixing it (-c s would rewrite REF and hide a wrong-build input); -m -any splits multiallelics into biallelic records; -d exact drops exact duplicate records. Run the same command on both files against the same reference.

Trade-offs and when not to

Normalizing both sides is cheap and usually right. The alternative: haplotype-aware comparison, e.g. bcftools norm --atomize or a graph-based comparison: is needed when a record is a complex cluster: an MNP or a multi-base indel that -m -any would shred into primitives. Splitting those loses phase, so two records that are one haplotype become several that look independent. For those, compare haplotypes, not the split records. Don't normalize at all if you must preserve the caller's original representation for clinical reporting or phasing.

Failure modes

  • Wrong reference build: REF mismatches; with -c e you get an error, with -c s you get silent corruption. Detect by checking contig naming (chr1 vs 1) and REF concordance rate.
  • Over-splitting a complex haplotype: primitives lose phase; detect by comparing haplotype-level equality, not record counts.
  • INFO corruption on split: Number=A/R/G fields get split, custom fields may not; check AC/AF after splitting.
  • Duplicate merge: -d exact only removes exact matches; near-duplicates survive.
  • Chromosome boundary: a variant spanning a contig edge can't be left-aligned past it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Audit sequencing quality before calling.

Answer

Core answer (say this first)

Assume short-read Illumina data, human WGS or WES, and "before calling" means before GATK HaplotypeCaller/Mutect2 or DeepVariant runs. The audit is three passes, each with a stop threshold.

Pass 1: per-cycle and per-base quality. Run FastQC per FASTQ, aggregate with MultiQC, and read the per-base sequence quality module. Illumina specs call for ≥80% of bases at Q30 (NovaSeq 6000 ≥85%). If the last 10–15 cycles drop below Q20, that is cycle decay: signal and phasing drift as the cluster ages. Trim those cycles (fastp --cut_tail, or Trimmomatic SLIDINGWINDOW:4:20) instead of handing them to the caller.

Pass 2: per-lane and per-read-group. Confirm the @RG tags: SM (sample), LB (library), PU (platform unit). Duplicate marking is per LB, so a wrong LB silently changes duplicate rates; a wrong SM makes GATK treat one sample as two. Check per-lane depth with mosdepth or samtools stats: a lane at half the median depth is a loading failure, not biology.

Pass 3: empirical mismatch patterns. This is what separates error from variant. Real variants show Ti/Tv ≈ 2.0–2.1 genome-wide and cluster at known dbSNP sites; sequencing error is enriched at read ends, shows strand bias, and lands at positions absent from dbSNP. Compute with Picard CollectSequencingArtifactMetrics, or by intersecting calls with dbSNP.

Why it matters. Phred quality is a claim: Q30 = 10⁻³ error probability, Q20 = 10⁻². A base reported at Q30 but actually wrong 1 in 50 times is miscalibrated, and the caller weights it 1000× more than it deserves. That is why GATK BaseRecalibrator exists: it re-estimates quality from observed mismatches at known sites and rewrites the scores. Skip it on a run with quality-offset error and you inflate false positives exactly where error concentrates: read ends and low-complexity regions.

Trade-offs. Trimming: aggressive quality trimming removes real variant evidence and skews allele balance at read ends, and shortens reads enough to hurt mapping in repeats. Trim only where quality actually decays, then re-check depth. BQSR: it needs a known-sites VCF and enough data; on a small targeted panel it can overfit and is often skipped. Deciding criterion: is the error systematic and reproducible across the run (recalibrate) or random (don't)?

checkthresholdtool
% bases ≥ Q30≥80% (NovaSeq 6000 ≥85%)FastQC / MultiQC
adapter content<0.1% at 3′ endFastQC adapter module
contaminationFREEMIX <0.02VerifyBamID2
Ti/Tv≈2.0–2.1bcftools stats

Failure modes and detection.

  • Quality-offset error: reported Q30, empirical error 1 in 50. Detect: CollectSequencingArtifactMetrics, or compare reported vs observed error rate.
  • Adapter read-through: insert shorter than read length. Detect: FastQC adapter content rising past ~0.1% at the 3′ end; trim with fastp.
  • Cycle decay: quality falls in the final cycles. Detect: the per-base quality curve in FastQC.
  • Recalibration drift: a chemistry change shifts the error profile. Detect: BQSR before/after quality delta.
  • Wrong read group: SM/LB mismatch. Detect: samtools view -H, inspect @RG; a duplicate-rate anomaly is the symptom.
  • Contamination: Detect: VerifyBamID2 FREEMIX >0.02; FastQ Screen for cross-species.
  • Treating reported quality as perfect: skipping BQSR. Detect: Ti/Tv below ~2.0 with excess dbSNP-absent calls.

Stop rule: if ≥80% Q30 fails, adapter content exceeds 0.1%, or FREEMIX exceeds 0.02, stop and re-run or re-sequence before calling.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Set mapping evidence policy for calling.

Answer

Assumptions: Illumina short reads, human GRCh38, germline SNV/indel calling, one aligner per pipeline, BAMs sorted and duplicate-marked. Somatic and long-read pipelines shift the numbers, not the shape of the policy.

Core recommendation. Don't set one MAPQ threshold. Set three things: exclude MAPQ 0 from calling, default to MAPQ ≥ 20 in unique sequence, and in low-mappability regions stop trusting MAPQ and require orthogonal evidence instead. Normalize MAPQ to a common scale before you compare anything across aligners.

Why. MAPQ is a Phred-scaled estimate that the reported position is wrong, computed by the aligner's own heuristic. It is not a probability you can carry between tools. BWA-MEM caps at 60, Bowtie2 at 42, and STAR emits 255 for unique and 3 for multi-mapping. So "MAPQ ≥ 20" means three different things depending on which BAM you're holding.

Aligner (version)UniqueMultiCap
BWA-MEM 0.7.17up to 60060
Bowtie2 2.4.5up to 420–142
STAR 2.7.10b2553255 (sentinel, not a probability)
minimap2 2.24up to 60060

Caller defaults already encode part of this policy, and they disagree:

CallerMin MAPQ defaultSecondary (0x100)
GATK4 HaplotypeCaller 4.420 (--minimum-mapping-quality), plus a default filter dropping MAPQ 0filtered
FreeBayes 1.3.61 (-m)filtered
bcftools mpileup 1.170 (-q)filtered

The policy, in order. First, drop MAPQ 0 from SNV/indel calling: those are multi-mappers and all three callers above already do it. Second, floor at MAPQ ≥ 20 where a k-mer mappability track (GEM, k=100) says the locus is unique. Third, in low-mappability regions do not raise the threshold; raising it just deletes evidence. Require both strands, paired-end concordance, and agreement from a second caller or a haplotype-aware assembly before you emit a call. Fourth, keep supplementary alignments (0x800), they carry split reads for SV breakpoints, while dropping secondary (0x100) from SNV calling but counting them to quantify ambiguity. Fifth, never read MAPQ 60 as a measurement; it's a ceiling.

Trade-offs. A single threshold is defensible when the reference is complete, the sample is a clean diploid, and you're calling in unique sequence: it's faster, reproducible, and trivial to explain. Stratification costs a mappability track and adds a dependency you now have to version alongside the aligner.

Failure modes and how you catch them. Convention mismatch: histogram MAPQ; a spike at 255 means STAR and your ≥ 20 filter is a no-op. Repeat mismapping: high MAPQ, wrong locus. Watch het/hom ratio and excess het calls inside segmental duplications. Alternate-locus bias: count reads with an XA tag or landing on alt contigs. Aligner version drift: re-align the same reads and diff the MAPQ distribution. Reference incompleteness: non-reference sequence reads get MAPQ 0. Watch the unmapped rate. Split-read loss: count 0x800 reads; a drop means SV sensitivity fell. Overconfident caps: the MAPQ 60 spike again.

One line: exclude MAPQ 0, floor at 20 in unique sequence, and in repeats replace the threshold with orthogonal evidence.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Choose duplicate handling for an assay.

Answer

Clarify, then answer

The policy turns on one question: can I define a molecule independently of its coordinates? If yes, collapse. If no, and coordinates are meaningful, mark and let the caller ignore. If coordinates are meaningless, don't mark at all. I'd assume a paired-end Illumina run and a caller that honors the duplicate flag unless told otherwise.

WGS/WES: mark, don't remove. Run Picard/GATK MarkDuplicates. It groups read pairs sharing the same 5' start and 3' end (unpaired reads: same 5' start), keeps the pair with the highest sum of base qualities as the representative, and flags the rest with 0x400. Leave the reads in the BAM. GATK HaplotypeCaller skips 0x400 by default, so the flag does the work and you keep the option to inspect. Set OPTICAL_DUPLICATE_PIXEL_DISTANCE to 2500 on patterned flowcells (NovaSeq, HiSeq 4000/X); the default 100 is for non-patterned. Optical duplicates are clusters landing within that pixel radius of each other: they signal index hopping or a loading problem, not a PCR bottleneck.

Amplicon panels: don't mark. Every read from an amplicon shares the same start and end by construction, so coordinate-based marking deletes real molecules and crushes depth. If the panel carries UMIs, use them; if not, skip marking and let the caller see every read.

UMI assays: collapse. Extract the UMI (8 bp gives 65,536 combinations, 12 bp gives 16.7M), group reads by UMI with fgbio GroupReadsByUmi, then CallMolecularConsensusReads to build one consensus per molecule. This removes PCR error, not just PCR duplicates.

Trade-offs. Marking costs nothing in accuracy when the caller honors 0x400, but it hides the duplicate rate from downstream tools. Removing reads is irreversible and destroys the evidence that duplication was high. UMI consensus raises per-base accuracy but needs enough reads per family: below roughly 3 reads/family you are guessing, and the consensus is no better than the input.

Failure modes and detection

failuresymptomdetection
over-markingdepth drops in low-input or high-GC regionscompare depth pre/post marking; WGS should lose under ~20%
UMI collisiontwo molecules share a UMIfamily-size distribution; excess singletons against Poisson
wrong optical distanceduplicate rate off for the flowcell typeduplicate rate vs expected for the platform
caller ignores flagsomatic caller double-counts duplicatescheck caller docs; compare calls with and without duplicates

If the caller does not honor 0x400, the flag is decorative: either filter duplicates before calling or pick a caller that respects it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Apply BQSR to a non-model organism.

Answer

What I'd say first (60–120s)

Assume: no curated dbSNP for the species, Illumina short reads, a usable reference assembly, and a caller that reads base qualities (GATK HaplotypeCaller, bcftools). You cannot point BaseRecalibrator at human dbSNP: the coordinates and variants are wrong for this genome. Two paths: bootstrap a species-specific known-sites set, or skip BQSR. The deciding factor is the caller, not the organism.

Why known sites matter (mechanism)

BaseRecalibrator walks the BAM and, at every position not in --known-sites, treats a mismatch to the reference as a sequencing error. It tallies those errors by covariate (ReadGroup, ReportedQualityScore, Context (the k-mer around the base), Cycle (position in the read)) and fits an empirical quality per bin. ApplyBQSR rewrites the QUAL field from that table. The model is only valid if non-known-sites mismatches really are errors. With no known sites, every true variant is counted as an error, biasing the fit: worst where divergence is high.

Bootstrap path

Shell
# 1. first-pass call
bcftools mpileup -f ref.fa -Ou aln.bam | bcftools call -mv -Oz -o pass1.vcf.gz
# 2. hard-filter to high-confidence SNPs (GATK-style thresholds)
bcftools filter -e 'QUAL<30 || INFO/MQ<40' pass1.vcf.gz | \
  bcftools view -f PASS -v snps -Oz -o known_sites.vcf.gz
# 3. recalibrate
gatk BaseRecalibrator -R ref.fa -I aln.bam --known-sites known_sites.vcf.gz -O recal.table
gatk ApplyBQSR -R ref.fa -I aln.bam --bqsr-recal-file recal.table -O recal.bam

GATK's classic SNP hard filters are QD<2.0, FS>60.0, MQ<40.0; use them if you call with HaplotypeCaller instead of bcftools. Iterate once if the first-pass set looks noisy.

Skip path

DeepVariant and GATK HaplotypeCaller reassemble locally or use a learned model and are largely insensitive to miscalibrated base qualities; GATK's own documentation notes BQSR gives little benefit for HaplotypeCaller. If you call with bcftools mpileup or an older caller that trusts QUAL directly, recalibration still earns its keep.

pathcostwins whenhurts when
Bootstrap BQSR2 extra BAM passes + a variant call (hours on a 30× mammalian genome)caller reads QUAL; platform has known quality biasbootstrap set contaminated; high divergence
Skip BQSRnoneHaplotypeCaller / DeepVariantbcftools mpileup on biased platform

Failure modes and detection

  • Contaminated bootstrap set: errors in known-sites mask real errors, so the model overcorrects. Detect with gatk AnalyzeCovariates, plotting empirical vs reported quality; a large gap after recalibration is the signal.
  • Wrong reference build: known-sites coordinates don't match; recalibration silently does nothing useful. Check contig names and lengths.
  • Missing @RG: BaseRecalibrator needs read groups; without them it errors or lumps every read into one bin.
  • Sparse covariates: low coverage makes bins noisy; GATK emits an insufficient-data warning.
  • Platform mismatch: a table built on another platform or library prep does not transfer; rebuild per dataset.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Diagnose a missed indel in a haplotype caller.

Answer

Core answer (first 90 seconds)

Assume germline short-read WGS, GATK HaplotypeCaller 4.x, GRCh38, one sample, and "missed" means the truth set has a het or hom-alt indel where the caller emitted 0/0 or no record at all. Those are two different bugs, so separate them first.

Pull the site from the GVCF: bcftools view -r chr7:117199400-117199600 sample.g.vcf.gz. No record means the caller never assembled the region: an active-region miss. A record with a 0/0 genotype means the region was assembled but the alt haplotype was lost. That one check halves the search.

Active-region miss. HaplotypeCaller only assembles inside active regions, which it picks from the activity profile using --active-probability-threshold (default 0.002) and propagates with --max-prob-propagation-distance (default 100 bp). A weak pileup signal (low depth, low base quality, few reads) can fall under the threshold. Confirm with samtools mpileup -r chr7:117199400-117199600 sample.bam: if the deletion shows in the pileup at 14 of 30 reads (AF 0.47) but is absent from the GVCF, the reads are fine and region detection is the fault. Lower the threshold to 0.001 and re-run; if the call appears, that was it.

Assembled but lost. Now the graph is the suspect. Re-run with --graph-output region.dot and read the dot file. Three things drop a real haplotype:

  • Read clipping. Hard-clipped bases (CIGAR H) are gone before assembly; soft clips (S) are kept. If the indel sits inside a hard clip from a supplementary alignment, the alt allele never enters the graph. Check the CIGAR at the site.
  • Repeat collapse. In a homopolymer or STR, k-mers from the repeat and the indel collapse into one path, so the deletion has no distinct haplotype. The dot file shows fewer nodes than the read evidence implies.
  • Reference bias. Reads carrying the alt allele map a touch worse, so the alt fraction is depressed below the 0.5 a het should show. At low depth that pushes the genotype to 0/0. Detection: compare pileup AF to the emitted PL. Flat PLs mean the caller had no confidence.

Failure modes and their signals

failuredetection signalcost
active-region misssite absent from GVCF, present in mpileupfalse negative
pruned true haplotypealt path missing from --graph-output dotfalse negative
repeat collapsegraph node count below read evidencefalse negative in STRs
reference biaspileup AF < 0.4 for a true het0/0 at low depth
wrong ploidy--sample-ploidy ≠ true ploidymiscalibrated PLs
graph explosionlong runtime, region splitdropped or merged calls

Trade-offs. Local assembly beats pileup callers (bcftools mpileup, FreeBayes) on clustered indels and MNPs because it evaluates whole haplotypes, not columns. But it adds two failure surfaces pileup callers don't have: active-region detection and graph construction. If the miss is in a clean, high-depth region, the lever is the active-probability threshold. If it's in a repeat or a clipped region, assembly may never recover it and you need a different caller or long reads. Don't lower global filters to fix a local assembly miss: that trades a false negative for false positives genome-wide.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Call variants across sex chromosomes.

Answer

Core answer (first 90 seconds)

Sex chromosomes break the one assumption every default caller makes: that the sample is diploid at every locus. Outside the pseudoautosomal regions the X is hemizygous in males and diploid in females, and the Y is hemizygous in males and absent in females. So before I call anything I infer sex from the data, then call each region with a ploidy that matches it.

Why ploidy changes the call

A genotype likelihood is a sum over the genotypes the model allows. Diploid: AA, AB, BB. Three terms. Haploid: A, B. Two. Force a haploid sample through the diploid model and a true hemizygous alt, where essentially every read carries the alt, gets called 1/1 instead of 1; the site is found but the genotype field is wrong. Worse, the diploid model carries a het term that has no business existing here, so any mismapped read or low-level contamination produces a false 0/1 on male X non-PAR.

Depth tells the same story. At 30x autosomal coverage, male X non-PAR sits near 15x, because there is one copy, not two. A caller expecting 30x will under-call.

PAR coordinates (GRCh38): PAR1 X:10,001–2,781,479; PAR2 X:155,701,383–156,030,895. Inside PARs, X and Y recombine, both sexes are diploid, and you call normally. Get the boundary wrong by a base and you flip ploidy mid-gene.

Options and when to pick

  1. Call everything diploid, filter sex chromosomes after. Simplest, one pipeline, but you keep the false hets and the wrong GQ/AD, and filtering cannot recover a missed hemizygous call.
  2. Sex-aware ploidy. bcftools call takes --ploidy with presets (GRCh38, X, Y, 1, 2) or --ploidy-file with columns CHROM FROM TO SEX PLOIDY; GATK HaplotypeCaller takes --ploidy (default 2) and a ploidy file. Correct genotypes, but you now depend on reliable sex metadata, and joint genotyping gets harder: GVCFs called at different ploidy do not merge cleanly, so you split the joint call by region or by sex group.
  3. Dedicated sex-aware callers or re-genotyping. More machinery, worth it when X/Y accuracy is the point.

Pick 2 when you have trustworthy sex and a defined reference build; pick 1 only for a quick autosomal-focused pass.

Failure modes and how I catch them

  • False het on male X non-PAR. Detect: het rate on X non-PAR should be near zero; above ~1% points to contamination, a paralog, or mismapping.
  • Missed or mis-genotyped hemizygous variant. Detect: compare GT to expected copy number; a 1/1 on male X non-PAR is a tell.
  • PAR boundary error. Detect: inspect calls at the PAR edges against the build's coordinates.
  • Sample swap. Detect: inferred sex (X het rate plus Y coverage) contradicts recorded sex.
  • Mosaicism or aneuploidy (45,X; 47,XXY). Detect: X het rate intermediate, Y coverage inconsistent with the phenotype.
  • Contamination. Detect: low-level het on X non-PAR in a male.

Sex inference is itself sensitive metadata: handle it under whatever consent and access rules apply, and keep it out of shared reports.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design cohort joint genotyping.

Answer

Assume short-read WGS or exome, one reference build (identical FASTA and .dict for every sample), GATK 4.4/4.5, and a cohort from a few hundred to a few thousand samples. Tens of thousands changes the bottleneck, not the design.

The design is two phases. Phase one calls each sample on its own with HaplotypeCaller in GVCF mode against the identical reference and interval list. Phase two consolidates those gVCFs into a GenomicsDB workspace and runs GenotypeGVCFs once over the whole workspace.

Shell
# phase 1 — per sample
gatk HaplotypeCaller -R ref.fa -I sample.bam -L intervals.bed \
     -ERC GVCF -O sample.g.vcf.gz

# phase 2 — once per cohort, scattered by interval
gatk GenomicsDBImport -V s1.g.vcf.gz -V s2.g.vcf.gz ... \
     --genomicsdb-workspace-path gdb --batch-size 50 -L intervals.bed
gatk GenotypeGVCFs -R ref.fa -V gendb://gdb -O cohort.vcf.gz

--batch-size defaults to 50 samples per import batch. The gVCF is the intermediate that makes phase two possible; the final VCF is not.

Why gVCFs, mechanically. HaplotypeCaller in GVCF mode writes a record at every position where the sample has evidence, but compresses runs of hom-ref positions into blocks: one record with ALT <NON_REF>, an END field marking the block's last position, GT 0/0, and per-sample DP, GQ, MIN_DP, PL. A 30x WGS gVCF lands in the low hundreds of MB against 80-100 GB for the same sample's BAM, and it still carries genotype likelihoods at hom-ref positions.

<NON_REF> is the whole point. At a site where any sample shows a real alt allele, GenotypeGVCFs reads every sample's stored likelihoods for that position and re-runs the genotyping model across the cohort. A sample whose own record said <NON_REF> with a het-ish PL can now be called against the actual alt allele:

samplegVCF record at chr1:200single-sample calljoint call
AALT=G, GT 0/1, PL 0,60,9000/10/1
BALT=<NON_REF>, GT 0/0, PL 0,3,9000/00/1

(PLs illustrative.) Merging per-sample VCFs cannot do this: a merge unions sites that were already called and silently drops the samples that needed the cohort to be called at all.

Trade-offs. Incremental import versus full re-genotyping: GenomicsDBImport can add samples to an existing workspace (--genomicsdb-update-workspace-path), which saves the import cost, but you still re-run GenotypeGVCFs over the full workspace, because new samples can reveal sites the old cohort never saw. Backend: GenomicsDB is the default past a few hundred samples because it indexes by interval and sample; for tens of samples, pass the gVCFs directly to GenotypeGVCFs with repeated -V and skip the workspace. Parallelism: scatter both steps by interval and merge, which is what makes thousand-sample cohorts tractable. Import is the long pole: it reads every gVCF once and writes the workspace, so its cost scales with total gVCF bytes, not sample count alone.

Failure modes, with detection.

  • Mixed reference: gVCF headers carry the sequence dictionary (contig names and lengths, md5 where the .dict has it). GATK errors on contig mismatch, so diff headers before importing.
  • Lost no-call semantics: a plain VCF has no <NON_REF> blocks. Check the ALT column; if <NON_REF> is absent, it is not a gVCF and cannot be joint-genotyped.
  • Incompatible caller versions: annotations and PL conventions shift between HaplotypeCaller versions. Check ##GATKCommandLine in each header and re-call outliers.
  • Cohort drift: adding samples shifts allele frequencies and the genotyping prior, so previously called genotypes can flip. Measure genotype concordance between cohort versions, not just site concordance.
  • Duplicate sample: GenomicsDBImport fails on duplicate sample names; enforce uniqueness before import.
  • GenomicsDB corruption: a failed import leaves a half-written workspace. Re-import into a fresh path rather than reusing it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you distinguish between missing data, reference homozygous, and uncalled regions across multi-sample cohorts using gVCF representation and the non-variant block mechanism?

Answer

In standard single-sample VCFs, genomic positions lacking an alternative allele are simply omitted. In a multi-sample cohort, omitting a site creates ambiguity: does the omitted sample lack read coverage (missing data), match the reference with high confidence (homozygous reference), or possess reads that failed caller-level filters (uncalled/unfiltered)? Genomic VCF (gVCF) resolves this by carrying explicit records across callable space using the <NON_REF> symbolic allele and non-variant block compression via the END tag.

1. Representation & State Differentiation

Cohort StategVCF / Joint VCF RepresentationUnderlying Mechanism & Format Fields
Homozygous Reference (0/0)Explicit gVCF block record: POS=100, INFO/END=150, ALT=<NON_REF>, GT=0/0Caller has sufficient read depth (DP) and quality score (GQ ≥ threshold) supporting reference bases over any alternate allele (PL for alternate alleles is high).
Missing Data (./.)Coordinate absent from gVCF, or record with GT=./., DP=0, and GQ=0Zero coverage or unmapped region. In joint calling (e.g., GATK GenomicsDBImport or GenotypeGVCFs), if an aggregated sample has no gVCF record spanning the locus, it is assigned ./..
Uncalled / Low ConfidencegVCF block record: POS=200, INFO/END=210, ALT=<NON_REF>, GT=./. or low-GQ 0/0 (GQ < 10, PL=[0,3,3])Caller evaluated reads, but depth, base quality, or mapping quality fell below emission thresholds. Genotype cannot be asserted with statistical certainty.

2. The Non-Variant Block Mechanism (<NON_REF> and END)

Emitting every single reference base individually produces file sizes exceeding raw BAMs. To solve this, callers group contiguous non-variant bases into homogeneous confidence intervals.

# Chromosome coordinate space:
chr1: 100 --------------------- 150 151 152 ------------------- 200
      [   Hom-Ref Block (GQ 40)   ] [SNP] [   Hom-Ref Block (GQ 30)   ]
  • Interval Definition: The record POS marks the 1-based start coordinate; INFO/END indicates the inclusive end coordinate.
  • Confidence Binning: GATK HaplotypeCaller groups contiguous positions by GQ bands (e.g., GQ bins: 0, 10, 20, 30, 40, 60). A block terminates whenever the minimum GQ drops into a different band, or when an alternate variant is encountered.
  • The <NON_REF> Symbolic Allele: Represents any potential alternate allele not explicitly modeled in the single-sample call. It enables Likelihood calculations (PL) for an arbitrary alternate allele: PL(Ref/Ref), PL(Ref/NonRef), PL(NonRef/NonRef). When aggregating cohorts, tools project these likelihoods across new candidate alleles identified in other cohort samples.

3. Concrete Example: Joint Resolution Walkthrough

Sample A has a heterozygous SNP at position 105; Sample B is homozygous reference across 100–120; Sample C has an exome capture failure with zero coverage.

# Sample A gVCF:
chr1  105  .  A  G,<NON_REF>  .  .  .  GT:AD:GQ:PL  0/1:15,18,0:99:450,0,420,495,474,969

# Sample B gVCF (Non-variant block):
chr1  100  .  A  <NON_REF>    .  .  END=120  GT:DP:GQ:MIN_DP:PL  0/0:34:60:30:0,60,900

# Sample C gVCF:
# (Position 105 is not spanned by any record because coverage = 0, or explicitly DP=0)

Joint Evaluation at chr1:105:

  • Sample A: Evaluates candidate allele G. Genotype called 0/1.
  • Sample B: Spanned by [100, 120]. The joint caller reads Sample B's PL mapped to <NON_REF>: reference support is high (GQ=60), alternate support is rejected. Genotype called 0/0.
  • Sample C: Outside any confident interval. Imputed as missing data: GT=./., DP=0.

4. Production Failure Modes & Operational Pitfalls

  1. MIN_DP vs. DP Masking: A non-variant block spans 500 bp with mean DP=35, but a 5 bp drop has DP=2. If downstream tools rely on record-level DP instead of MIN_DP, low-coverage regions inside the block are misclassified as high-confidence homozygous reference rather than uncalled.
  2. Block Boundary Off-by-One Errors: INFO/END is 1-based closed [POS, END]. Translating gVCF blocks into half-open BED intervals ([POS-1, END)) during database indexing often leads to 1 bp missing coverage gaps or boundary overlaps, corrupting joint genotypes at interval transitions.
  3. Premature Truncation of <NON_REF>: Stripping <NON_REF> or dropping PL fields to save disk space before joint genotyping destroys the mathematical ability of GenotypeGVCFs to distinguish homozygous reference from uncalled space across cohorts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Build a VCF ingestion quality gate.

Answer

Assume VCF 4.2/4.3, htslib-based tools, and a pipeline that feeds annotation or clinical review. The gate's contract: every FILTER ID in the record must be defined in the header; PASS, '.', and a failure list are three distinct states; genotype-level FT is checked separately; raw FILTER and FT strings plus header definitions are retained for provenance. Default policy: quarantine unknown filters and '.' records for manual review; reject only when the downstream consumer requires a binary PASS and the caller's filter semantics are known and stable.

FILTER is site-level. FT is per-genotype. A site can be PASS while a sample's genotype is LowDP. If the gate only reads FILTER, it passes a record where the only sample has FT=LowDP: a real failure mode in trio and clinical pipelines. The spec says an undefined FILTER ID should be treated as a failure; the gate should also flag it because it usually means a header mismatch or a new caller version. Caller-specific semantics: GATK VQSR emits tranche filters like VQSRTrancheSNP99.00to99.90; DeepVariant and FreeBayes use different IDs. Hardcoding filter IDs breaks when the caller changes. Merging: bcftools merge can drop or combine FILTER; provenance (caller, version, merge command) is required to interpret the result.

PolicyBehaviorUse whenCost
Strict rejectUnknown filter or '.' -> rejectDownstream requires binary PASS; caller semantics fixedHigh false negative; loses valid variants
Quarantine + reviewUnknown/'.' -> flag, keep, route to reviewHeterogeneous callers; header may be incompleteReview capacity; delay
Coerce '.' to PASSTreat '.' as PASSNeverHides unfiltered data; clinical risk
Python
import pysam

def gate(record, header_filters):
    # header_filters = set(record.header.filters.keys())
    site = record.filter  # tuple, e.g. ('PASS',), ('.',), ('q10','lowqual')
    if site == ('.',):
        site_status = 'UNFILTERED'
    elif site == ('PASS',):
        site_status = 'PASS'
    else:
        unknown = [f for f in site if f not in header_filters]
        site_status = 'FAIL:' + ','.join(site)
        if unknown:
            site_status += ' UNKNOWN:' + ','.join(unknown)
    gt_status = {}
    for sample in record.samples:
        ft = record.samples[sample].get('FT')
        if ft is None:
            gt_status[sample] = 'PASS'  # spec: absent FT means passed
        elif ft == '.':
            gt_status[sample] = 'UNFILTERED'
        else:
            gt_status[sample] = 'FAIL:' + ft
    return site_status, gt_status

Trace: record chr1 100 . A T 50 PASS DP=10;AF=0.5 GT:FT:DP:GQ 0/1:LowDP:5:20. Header defines ##FILTER=<ID=LowDP,...> and ##FORMAT=<ID=FT,...>. Gate output: site_status='PASS', gt_status={'sample1': 'FAIL:LowDP'}. A gate that only checks FILTER would pass this record. Another record with FILTER='.' yields site_status='UNFILTERED'; coercing to PASS would treat never-filtered data as validated.

Failure modes: unknown filter (header mismatch or new caller version). Detect by comparing FILTER IDs to header. Lost reasons, if the gate drops the raw FILTER string, you cannot reconstruct why a variant was filtered. Caller-specific semantics: VQSR tranches vs DeepVariant's filters; detect by reading header. Genotype failure hidden by site PASS: check FT. Clinical overinterpretation: PASS is not a clinical assertion; the gate must not label a variant as clinically actionable. Filter removed during merge: bcftools merge may set FILTER to '.' or PASS; detect by comparing pre- and post-merge FILTER.

The gate's output should be a structured record: raw FILTER, raw FT, header definitions, and a decision (PASS/UNFILTERED/FAIL/UNKNOWN). That makes the decision auditable and reproducible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Choose a variant-filtering approach.

Answer

Assumptions: human germline, GATK HaplotypeCaller 4.x, joint-genotyped cohort on GRCh38 at ~30x, truth resources available (GIAB v4.2, 1000G Omni, HapMap).

Core answer. Pick by cohort size and truth availability. VQSR needs enough variants to fit a model: GATK's guidance puts the floor near 30,000 variants, which a 50-sample exome or genome cohort clears. Below that, for non-human organisms, or with no truth set, use hard filters. The CNN scorer (CNNScoreVariants + FilterVariantTranches, GATK 4.x) is the middle option: it needs a labelled training set but far fewer variants than VQSR. Hard filters are fixed per-site cutoffs; VQSR is a fitted model. They are not interchangeable.

Mechanism. VQSR fits a Gaussian mixture over per-variant annotations (QD, MQ, FS, SOR, ReadPosRankSum, MQRankSum), treating high-confidence truth variants as the positive class and everything else as negative. It emits VQSLOD and a tranches file whose levels are the fraction of training truth variants retained: GATK's defaults are 100.0, 99.9, 99.0, 90.0. You pick a level; ApplyVQSR writes FILTER for variants scoring below its VQSLOD cutoff.

gatk VariantRecalibrator -R ref.fa -V cohort.vcf.gz \
  --resource:hapmap,known=false,training=true,truth=true,prior=15.0 hapmap.vcf.gz \
  --resource:omni,known=false,training=true,truth=true,prior=12.0 omni.vcf.gz \
  --resource:1000G,known=false,training=true,truth=false,prior=10.0 1000G.vcf.gz \
  --resource:dbsnp,known=true,training=false,truth=false,prior=2.0 dbsnp.vcf.gz \
  -an QD -an MQ -an MQRankSum -an ReadPosRankSum -an FS -an SOR \
  -mode SNP -O snps.recal --tranches-file snps.tranches

gatk ApplyVQSR -R ref.fa -V cohort.vcf.gz \
  --recal-file snps.recal --tranches-file snps.tranches \
  --truth-sensitivity-filter-level 99.7 -mode SNP -O snps.vqsr.vcf.gz

Hard filters apply the same idea with no model. GATK's recommended cutoffs:

ClassFilters
SNPQD<2.0, FS>60.0, MQ<40.0, MQRankSum<-12.5, ReadPosRankSum<-8.0, SOR>3.0
IndelQD<2.0, FS>200.0, SOR>10.0, ReadPosRankSum<-20.0, InbreedingCoeff<-0.8
gatk VariantFiltration -R ref.fa -V cohort.vcf.gz \
  --filter-expression "QD < 2.0" --filter-name "QD2" \
  --filter-expression "FS > 60.0" --filter-name "FS60" \
  --filter-expression "MQ < 40.0" --filter-name "MQ40" \
  --filter-expression "SOR > 3.0" --filter-name "SOR3" \
  -O snps.filtered.vcf.gz

Worked trace. Two SNPs from the same cohort:

VariantQDFSMQSORMQRankSumReadPosRankSumHard-filter FILTER
chr1:1000 A>G1.875.035.04.2-1.00.5QD2;FS60;MQ40;SOR3
chr1:2000 C>T12.02.158.01.10.3-0.4PASS

Variant 1 trips four SNP cutoffs (1.8<2.0, 75>60, 35<40, 4.2>3.0); variant 2 clears all six. Under VQSR the same annotations are model inputs, not verdicts. Say the tranches file puts the 99.0 cutoff at VQSLOD = -1.2 and 99.9 at 2.5 (hypothetical values). Variant 1 scores VQSLOD = -3.4, below the 99.0 cutoff, so it is filtered; variant 2 scores 4.1 and passes 99.9. The 99.0 label means 99% of training truth variants scored at or above -1.2: sensitivity against the training truth, not precision.

Trade-offs. Hard filters are transparent, need no truth set, and reproduce exactly. They over-filter real rare variants: a singleton has weak annotation support by construction, so QD and MQ are low for reasons unrelated to error. VQSR adapts to the batch and recovers more true positives, but it needs the truth resource, is sensitive to cohort composition, and is opaque: you cannot read off why a variant failed. CNN scoring sits between: fewer variants than VQSR, still a labelled training set.

Failure modes and detection.

  • Overfit training resources: the model memorizes the truth set. Detect with a held-out truth set (GIAB v4.2 excluded from training) and report precision/recall on it.
  • Ancestry or platform shift: truth sets skew European/Illumina. Detect per-ancestry Ti/Tv and array concordance.
  • Circular truth: the same set trains and evaluates. Detect with an independent truth source or orthogonal genotyping.
  • One threshold across classes: SNP cutoffs on indels over-filter. Detect per-class Ti/Tv and Mendelian violation rate.
  • Tranche misinterpretation: 99.0 is sensitivity, not precision. Detect by measuring precision on holdout.
  • Filtering real rare variants: singletons fail hard filters. Detect against a truth singleton set or Mendelian consistency in trios.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Benchmark a germline caller against GIAB.

Answer

Core answer (first 90 seconds)

Benchmarking a germline caller against GIAB means measuring precision and recall against a truth set, and the defensible way to do it is haplotype-aware comparison restricted to the benchmark's high-confidence regions. State three assumptions before any number: the caller ran on the same reference build as the truth set (GRCh38 for GIAB v4.2.1), the sample is the one the benchmark covers (HG002 for the v4.2.1 small-variant set), and both call sets are normalized to the same representation. Then run hap.py or rtg vcfeval with the GIAB high-confidence BED plus the GIAB stratification BEDs, and report stratified metrics rather than one genome-wide figure.

Why representation, not position, decides the match

A caller and the truth set can describe the same haplotype with different records. A 10 bp deletion may be one record in one set and two adjacent 5 bp deletions in the other; an indel in a repeat may be left-aligned differently. Position-and-allele matching scores each of those as one false positive and one false negative, so precision and recall both fall even though the sample is called correctly. Haplotype-aware tools: vcfeval, and hap.py when it runs its xcmp engine: build a sequence graph from each call set, enumerate the haplotype sequences, and compare those. Equivalent representations collapse to a match; only real sequence differences survive as FP/FN.

Worked arithmetic (hypothetical, labelled as such)

stepTPFPFNprecisionrecall
naive position match3,700,000100,000100,00097.4%97.4%
after haplotype-aware normalization3,740,00060,00060,00098.4%98.4%
restricted to high-confidence BED3,740,00010,00060,00099.7%98.4%

The first row is what a position-based intersection such as bcftools isec reports; the second is what normalization recovers; the third is what the BED removes: false positives in regions the truth set never labeled. Recall does not move in the last row because the BED should not contain true positives.

Alternatives and deciding criteria

  • hap.py vs vcfeval: both are GA4GH-compliant and haplotype-aware. hap.py adds stratification and a single report; vcfeval is the engine underneath and is easier to script for one-off comparisons. Use hap.py when you need the stratified report, vcfeval when you need to embed the comparison in a pipeline.
  • Genome-wide vs stratified: a genome-wide F1 hides that recall in tandem repeats is far lower than in unique sequence. Report both, and never quote only the genome-wide number.
  • v4.2.1 vs v3.3.2: v4.2.1 is the current HG002 small-variant benchmark; older releases have smaller high-confidence regions and different variant counts, so numbers are not comparable across releases.

Failure modes to check before you trust a number

  • Truth-build mismatch: caller on GRCh37, truth on GRCh38. Detect by checking the VCF contig header and bcftools norm -f against the reference; a mismatch shows as mass FP/FN at contig boundaries.
  • BED coordinate error: GIAB BEDs are 0-based half-open; a 1-based conversion silently shifts the region. Detect by comparing the BED's total bp against the published figure.
  • Training-test leakage: if the caller or its model was tuned on GIAB, the benchmark is not held out. Detect by checking the caller's training and tuning sets for HG002.
  • Excluding hard regions from the narrative: dropping repeats from the report while claiming genome-wide performance. Detect by comparing the reported region bp to the BED bp.
  • Cherry-picked strata: quoting the stratum where the caller wins. Detect by requiring the full stratification table, not one row.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Use phased calls in compound-heterozygous analysis.

Answer

Core answer

A compound heterozygous call says a gene has one damaging variant on each copy: two hits in trans. The only thing that makes that true is phase, so the answer is: call compound het only when the two variants are demonstrably on opposite haplotypes, and otherwise report the pair as phase-unknown rather than assuming trans.

Accept trans when one of these holds:

  1. Both variants carry phased GT (0|1, 1|0) and the same PS (phase set) value, so the caller placed them on one haplotype block.
  2. Read-backed phasing links them: a single read or read pair spans both positions.
  3. Pedigree: the two variants were inherited from different parents. This is the strongest evidence.

If none holds, the pair is unphased. Do not infer trans across a phase break.

Why phase breaks happen

VCF encodes phase two ways: the | in GT, and the PS field grouping variants phased relative to each other. A pipe alone is not chromosome-scale phase: it means "phased within this block." When PS changes or is absent, the two records sit in different blocks and their relative phase is unknown.

Read-backed phasing (WhatsHap; GATK3's ReadBackedPhasing, removed in GATK4) can only link variants covered by the same fragment. With 150 bp reads and ~300–500 bp fragments, variants more than a few hundred bp apart are rarely spanned, so a long gene fragments into many small phase sets.

Statistical phasing (SHAPEIT2/4, Eagle) infers haplotypes from population LD and a reference panel. Switch error rates are low but nonzero: on the order of 0.1–0.5% of heterozygous sites for common variants, and one switch flips every downstream variant in that block, turning a cis pair into an apparent trans pair.

Failure modes

failurewhat it looks likedetection
switch errorcis pair reported transpair spans a recombination hotspot or PS boundary
missing PSGT phased, no PSPS absent → treat as unphased
overconfident statistical phasehigh-confidence trans from imputationno read or pedigree support
sample mix-upphase inconsistent with pedigreesex check, relatedness
recombinationphase valid only within a blockPS changes across the gene

Trade-offs

Strict read-backed-only phasing is safest but costs real calls: in a 2 kb gene with short reads you may phase only the closest variant pairs and miss true compound hets. Accepting statistical phase recovers those but imports switch-error risk. A defensible middle: require read or pedigree support for the final clinical call, use statistical phase to prioritize which pairs to inspect, and run a sensitivity analysis, if the compound-het list changes materially when you drop statistical-only pairs, the pipeline is over-calling.

What changes the decision: long-read data spanning the whole gene, a trio pedigree, or a validated PS block covering both variants all upgrade an unknown pair to a confident trans call.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Parse structural-variant records.

Answer

What I'd say first

Two questions before parsing: what consumes the output (exact breakpoint adjacency, or just overlap with a gene) and which callers wrote the file, because Manta, Delly and Lumpy encode the same deletion differently. Assuming VCF 4.3/4.4 with a mix of symbolic and breakend records, I parse in two layers. Symbolic: <DEL>, <DUP>, <INV>, <CNV> plus END become a normalized interval. Breakend: BND ALT strings plus MATEID become an adjacency graph. The symbolic layer covers most records cheaply; the breakend layer is what translocations and complex rearrangements need, and it is where naive interval parsing fails.

Mechanism

For a symbolic allele, POS is the anchor base immediately before the variant and END is the last base of the variant, inclusive. So:

chr1  1000  del1  N  <DEL>  .  PASS  SVTYPE=DEL;END=2000;SVLEN=-1000;CIPOS=-10,10;CIEND=-10,10

deletes 1001..2000, i.e. END - POS = 1000 bases, matching |SVLEN|. A parser that treats POS as the first deleted base is off by one on every record, and the check |SVLEN| == END - POS is how you catch it.

Breakend ALT is four characters of grammar: t[p[, t]p], ]p]t, [p[t, where t is the replacement base and p is chr:pos. The bracket type and side encode the join direction. Take a reciprocal pair:

chr1  1000  bnd1  N  N[chr2:2000[  .  PASS  SVTYPE=BND;MATEID=bnd2
chr2  2000  bnd2  N  ]chr1:1000]N  .  PASS  SVTYPE=BND;MATEID=bnd1

N[chr2:2000[ means the sequence to the right of chr2:2000 is joined after chr1:1000; the mate must be ]chr1:1000]N. Strip the brackets and you get "chr1:1000 near chr2:2000", which is also what a duplication and an inversion look like. Orientation is the whole payload.

Trade-offs

Option A: symbolic-only, normalize to (chrom, start, end, SVTYPE). Cheap, one pass, no index. Loses breakend orientation, translocations and complex events. Option B: full adjacency graph, index every ID, resolve MATEID. Needs memory proportional to the BND count and a second pass or buffering, because mates can be megabases apart or on different chromosomes. Decide on the consumer: gene-overlap annotation → A. Fusion calling, assembly, or anything that needs the exact join → B. Most pipelines want A for the bulk of records and B for the BND records.

Failure modes and detection

  • Orphan mate: MATEID resolves to nothing. Detect by building ID→record and counting unresolved MATEIDs; nonzero means a bug or a truncated file.
  • Bracket orientation error: mate's ALT is not the reciprocal form. Detect by checking t[p[ ↔ ]p]t and t]p] ↔ [p[t; flag mismatches.
  • END misuse: END used on BND records, or treated as exclusive. Detect with the |SVLEN| == END - POS check.
  • Double counting: a BND pair or EVENT group counted as two SVs. Detect by grouping on EVENT or canonical mate pair; the count should halve.
  • Imprecision discarded: CIPOS/CIEND dropped, so a ±500 bp interval becomes a point. Detect by diffing interval widths in vs out.
  • Translocation lost: CHROM != mate CHROM records dropped by same-chromosome assumptions. Detect by counting cross-chromosome pairs; a WGS set should have them.
  • Caller convention mismatch: the same event as <DEL> from one caller and a BND pair from another. Detect by comparing SVTYPE distributions per caller before merging.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Validate a copy-number pipeline.

Answer

Core answer

"Validate" here means: does the pipeline recover the events that are actually there, at the sizes and copy states you care about, with a false-positive rate you can defend? Before answering I'd pin three things: assay (WGS vs exome vs panel), germline vs somatic, and whether a matched normal exists. Everything below assumes 30x WGS, somatic calling with a matched normal, and tumor purity above ~20%.

The validation has three layers, and they fail independently.

  1. Technical normalization. Depth is not copies. GC content, mappability, library batch and capture efficiency all move observed read depth. Check that after correction the genome-wide median log2 ratio is ~0 and that per-bin variance matches Poisson expectation. A median off zero means an aneuploid baseline or a purity/ploidy fit that hasn't converged.

  2. Allele and segmentation model. Depth alone cannot separate 2-copy LOH from a neutral region; B-allele fraction at heterozygous SNPs does. Check that VAF clusters sit where the fitted purity and ploidy predict.

  3. Benchmark against truth, stratified. Report precision and recall separately by event size and copy state: a pipeline can be 95% recall on >1 Mb deletions and 20% on 10 kb gains.

checkpassfail (detection)
GC / mappabilitymedian log2 ≈ 0, variance ≈ Poissonper-batch median shift > 0.05 → batch effect; PCA of bins clusters by batch
ploidy / puritygenome-wide median log2 = 0 after fitmedian ≠ 0 → aneuploid baseline or wrong purity
allele modelVAF clusters match fitted purityall VAF at 0.5 → purity too low to call
segmentationsegment count in expected range, BIC-penalizedhundreds of 1-bin segments → overfit
referencesex check, SNP fingerprint concordanceX/Y depth wrong → build or sample mismatch
copy statebootstrap CI on integer copyCI spans two integers → do not report an integer

Arithmetic for the purity floor: a single-copy loss in a tumor at purity p gives observed log2 ratio log2(1 − p/2). At p = 0.3 that is −0.23; at p = 0.1 it is −0.07. At 30x with 1 kb bins, per-bin Poisson noise is 1/√30 ≈ 0.18, and segmenting over N bins cuts that by √N. So a 10% purity focal event is callable only if it spans enough bins: purity and event size are not independent knobs.

Trade-offs: a matched normal removes germline CNVs and most batch structure but costs a second library and fails when the normal is contaminated or from a different tissue. A modeled baseline (a panel of normals, as in GATK4 gCNV or CNVkit's reference) works without a normal but absorbs any CNV shared across the panel and drifts with batch. Use a matched normal when purity is low; use a modeled baseline for germline cohorts where the normal is the same person.

Failure modes and how you catch them: batch effect. Per-batch median log2 shift, PCA of bin counts. Aneuploid baseline: genome-wide median log2 ≠ 0. Low purity: VAF clusters collapse to 0.5. Repeat mapping: bins in segmental duplications with mappability < 0.9 show inflated variance; drop them. Segmentation overfit: segment count and length distribution against BIC. Reference mismatch: sex check and SNP fingerprint. Integer overconfidence: bootstrap CI on copy number.

Benchmark against a truth set: the GIAB HG002 CNV calls for germline and the SEQC2 somatic CNV benchmark for tumor, reporting recall per size bin rather than one aggregate number.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Choose a tumor-normal calling strategy.

Answer

Core answer. Default to matched tumor-normal. If a normal exists, call with Mutect2 or Strelka2, because the normal is the only sample that directly observes the patient's germline: it is what lets you call variants below the population-frequency floor and what catches rare germline variants that gnomAD has never seen. Layer a panel of normals (PoN) and a germline resource on top to kill recurrent sequencing artifacts and common germline. If no normal exists, fall back to tumor-only with PoN + gnomAD, and accept that you cannot separate rare germline from somatic: restrict reporting to hotspots. The deciding question is not "which caller" but "do I have a normal, and how low a VAF must I trust."

Why the normal matters. A somatic caller models allele fractions under a mixture of tumor and normal DNA, not fixed inherited genotypes. Without a matched normal, a heterozygous germline SNP at 50% VAF in a 60%-purity tumor looks exactly like a somatic variant at 30% VAF. The normal breaks that tie by showing the same allele at ~50% in the germline sample.

StrategyWhen it winsWhat it costs
Matched normal (Mutect2, Strelka2)Any tumor fraction; the defaultNeeds a normal; adds CHIP and tumor-in-normal as new failure modes
Tumor-only + PoN + gnomADNo normal: archival tissue, ctDNA-onlyRare germline looks somatic; restrict to hotspots
PoN aloneNever as the only filterRemoves recurrent artifacts, not patient-specific germline

Concrete settings. Mutect2 takes --germline-resource (gnomAD) and --panel-of-normals; its default --af-of-alleles-not-in-resource is 2.5e-6, so anything rarer than that in gnomAD is treated as potentially somatic. GATK recommends at least 40 normal samples in a PoN, drawn from the same assay and batch. Strelka2 is built for tumor-normal pairs and needs no PoN. Estimate purity and ploidy with FACETS or ASCAT on WGS/WES, or PureCN on panels, and feed the result into filtering.

Depth arithmetic. Detection is Poisson. At 100x tumor depth, a 5% VAF variant has 5 expected supporting reads, so P(miss) = e^-5 ≈ 0.7%: reliable. At 1% VAF and 100x, expected reads = 1, P(miss) = e^-1 ≈ 37%: you lose a third. To detect 1% VAF at 95% confidence you need ~300x (3 expected reads, e^-3 ≈ 5%). Below ~0.5% VAF, only UMI/duplex consensus at 5000x+ is defensible.

Failure modes and how you catch them.

  • Germline leakage: rare germline variant absent from gnomAD. Detect: VAF near 50% in tumor and present in the normal at the same VAF.
  • Clonal hematopoiesis (CHIP): DNMT3A, TET2, ASXL1, JAK2, TP53 variants in the blood normal. Detect: variant in the normal at 2–20% VAF in a gene unexpected for the tumor type; confirm with buccal or skin.
  • Tumor-in-normal: normal contaminated by tumor. Detect: estimate with DeTiN or SNP fingerprinting; somatic VAF in the normal above zero.
  • Contamination: estimate with VerifyBamID2 or CalculateContamination; FilterMutectCalls consumes that estimate.
  • FFPE artifacts: C>T / G>A deamination. Detect and remove with a read-orientation model (LearnReadOrientationModel) and the OxoG filter.
  • Low purity: at 20% purity a heterozygous somatic variant drops to ~10% VAF; model it with FACETS/ASCAT/PureCN rather than a fixed threshold.
  • Copy-number allele balance: LOH drives somatic VAF toward 100% or 0; a deletion lowers it. Use allele-specific copy number before trusting any VAF cutoff.

Validate the chosen pipeline on a truth set (e.g. HCC1395/HD753 or a GIAB-style mixture) at the VAFs you intend to report, and state the limit of detection you actually achieved.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design a re-annotatable variant store.

Answer

Core answer

Split the store in two. Layer one holds variant identity and raw call evidence and is append-only: a row is never updated. Layer two holds derived annotations, also append-only, keyed by the full provenance tuple (variant, source, source release, transcript, ruleset version). Reannotation inserts new annotation rows; it never updates old ones. A "current" view picks the newest release per key. That is the whole design: immutable evidence plus provenance-keyed derived rows makes reannotation a pure function you can rerun and diff.

Assumptions. Germline short variants (SNV/indel), GRCh38 primary with GRCh37 retained for legacy, VCF input, and a clinical reporting path that needs an audit trail.

Mechanism

Identity normalization. Split multiallelic records, left-align and trim indels against the reference (bcftools norm -f GRCh38.fa -m -any), then compute a content-addressed ID over the normalized allele. GA4GH VRS gives you this: a VRS allele ID is a 24-character truncated SHA-512 digest (sha512t24u) of the normalized sequence, so two callers that wrote the same allele differently collapse to one ID. Store the original VCF line, sample, GQ/DP/VAF, caller and version, and reference build next to it: that is the evidence, and it never changes.

Annotation rows. Each row is (variant_id, source, source_release, transcript, ruleset_version, payload, computed_at), append-only. Determinism comes from pinning all four inputs: same normalized allele + same source release + same transcript set + same ruleset version → byte-identical payload. Reannotation runs the pipeline with a new source_release or ruleset_version and inserts.

Trade-offs

approachreannotationauditquery costwhen to use
versioned rows (UPDATE + valid_from/valid_to)in place, easy to lose historyweak unless disciplinedcheapsmall, non-clinical
append-only annotation ledgerinsert new rows, old preservedstrongneeds a "latest" view or materializationclinical, regulated
recompute-on-readnothing storedstrong (evidence only)high per query, needs a cacheexploratory, low QPS

Deciding criteria: audit requirement, query latency budget, and how fast sources move. ClinVar ships monthly and gnomAD moved v2.1.1 → v4.0; if sources move faster than you can re-run, recompute-on-read wins; if you must show what you reported last year, the ledger wins.

Failure modes and detection

  • Transcript mismatch: annotation computed against a non-MANE transcript. Detect: store transcript accession + version; alert when a stored transcript is absent from the current MANE release.
  • Stale frequency: gnomAD v2.1.1 AF served as current. Detect: source_release column; the "latest" view must filter on it, and a test asserts no row older than N releases is served.
  • Allele-normalization mismatch: same variant stored twice. Detect: unique constraint on VRS ID; count distinct IDs per raw call.
  • Overwritten interpretation: an UPDATE slipped in. Detect: revoke UPDATE on the annotation table or add a trigger that rejects it; alert on any row whose computed_at is rewritten.
  • Build mismatch: GRCh37 coordinates joined to GRCh38 annotations. Detect: build column on both sides; reject cross-build joins.
  • License restriction: a source that cannot be redistributed. Detect: license tag per source; block export paths.
  • Clinical claim without review: pathogenic call reported unsigned. Detect: review_state column; the reporting query requires signed state.

Worked trace (coordinates illustrative)

Input VCF, GRCh38:

chr1  1000  .  G  A  50  PASS  DP=30;GQ=99

Normalize: already left-aligned, no trim. VRS allele ID = ga4gh:VA.<sha512t24u digest>.

Insert annotation:

variant_id      ga4gh:VA.<digest>
source          ClinVar
source_release  2024-03
transcript      NM_000492.4 (MANE Select)
ruleset_version vep-110
payload         clinsig=Pathogenic, review=criteria provided, multiple submitters
computed_at     2024-03-15T10:00Z

ClinVar 2024-06 reclassifies to Likely pathogenic. Reannotation inserts a second row with source_release=2024-06. The 2024-03 row is untouched. The current view returns the 2024-06 row; a diff query returns both, which is exactly the audit trail.

What would change the decision: if query latency dominated and sources were stable, recompute-on-read with a cache would be simpler; if storage were the binding constraint, keep only the latest row plus a change log.

Curated: · Written: · Reviewed:

Difficulty: Hard