Chapter 32Hours to Seconds: A Heartbeat Detector Fix, and a Proof It Changes Nothing
An issue on wfdb-python (MIT PhysioNet's toolkit for physiological signals) has been open since March 2022. The reporter ran the XQRS heartbeat detector over single-channel ECG traces, under an hour to 24 hours long. About 95% finished in minutes. About 5% took hours. Two clusters, and trace length didn't predict which one you'd land in.
They'd already found the hot spot, backsearch, and asked the right question: "How far back does it rescan? Clearly if it rescans a large percentage of the earlier marked signal, then it will cause a quadratic slowdown."
It sat for four and a half years. This post answers it, then covers the part I enjoyed most: a machine-checked proof that the fast version gives exactly the same answers.
What backsearch does#
XQRS walks the signal peak by peak. A peak that looks like a QRS complex (the spike marking a heartbeat) updates the beat estimate (_update_qrs). Otherwise it updates the noise estimate (_update_noise).
If too long passes without a beat, the detector suspects it was too strict. It runs a backsearch: re-check every peak since the last beat with a looser threshold, and promote any that pass.
if self.last_qrs_peak_num is not None:
for peak_num in range(self.last_qrs_peak_num + 1, self.peak_num + 1):
if self._is_qrs(peak_num=peak_num, backsearch=True):
self._update_qrs(peak_num=peak_num, backsearch=True)"Every peak since the last beat, up to the current one." The bug is right there.
Why it goes quadratic#
Say the lead falls off for 40 minutes. The signal becomes low-amplitude noise, every small peak is rejected, and the detector is soon overdue. Backsearch fires and finds nothing. So last_qrs_peak_num doesn't move. On the next peak it fires again, over the same range plus one more.
last beat | v B . . . . . . . . ^ scanned: 1 peak
Overdue, so backsearch fires. Nothing found.
That's the bimodal behavior. A clean trace never hits a long gap. One loose lead overnight pays the quadratic cost. What matters is the longest stretch without a beat.
The maintainer ran my regression test against the old code: in a 2-minute noise gap in a sample record, backsearch checked 856 peaks a total of 366,768 times.
The fix is one remembered number#
Re-checking a peak backsearch already rejected is pointless, as long as nothing the check depends on has changed. So remember the last peak looked at and start after it:
if self.last_qrs_peak_num is not None:
start = max(self.last_qrs_peak_num, self._backsearch_peak_num) + 1
for peak_num in range(start, self.peak_num + 1):
if self._is_qrs(peak_num=peak_num, backsearch=True):
self._update_qrs(peak_num=peak_num, backsearch=True)
self._backsearch_peak_num = self.peak_numpeak: 0 1 2 3 4 5 6 7 last beat: B fires at 5: . x x x x x fires at 6: . x x x x x x fires at 7: . x x x x x x x same peaks, again and again
peak: 0 1 2 3 4 5 6 7 last beat: B fires at 5: . x x x x x fires at 6: . . . . . . x start after the last peak looked at fires at 7: . . . . . . . x
Plus initializing _backsearch_peak_num = -1. That's the whole change. Benchmark on record 100 from the sample data, with a gap of low-amplitude noise inserted:
| gap | before | after |
|---|---|---|
| 10 min | 1.7 s | 0.4 s |
| 40 min | 23.4 s | 1.3 s |
The maintainer reproduced similar numbers: 2.3 s to 0.7 s for 10 minutes, 28.2 s to 1.6 s for 40. The 10-minute speedup is modest (about 4x) because there's little quadratic work to remove yet. The win grows with gap length.
But is it still right?#
A speedup in a medical signal library is only welcome if the output is unchanged.
The argument: whether a peak passes backsearch depends only on qrs_thr, last_qrs_ind, the configuration and the signal. Those change only inside _update_qrs, which always moves last_qrs_peak_num past everything the earlier backsearch rejected. So either nothing changed and a skipped peak would be rejected again, or a beat was found and the next scan starts beyond the skipped peaks anyway.
Convincing, and exactly the kind of paragraph that's wrong at some edge case. I tested it: a regression test, plus 300 random old-vs-new comparisons with noise gaps, flat sections, amplitude changes and random detector settings, with and without learning. qrs_inds, backsearch_qrs_inds and every running parameter matched. But random tests only cover the cases you tried. I wanted the argument itself checked for every input, so I wrote it in Lean.
Modeling without modeling#
Lean is a language where you state theorems about your functions and the compiler checks the proofs. It proves things about Lean code, not the Python that ships.
The trick was to not model the math at all. The detector state is an abstract type S, and every piece is an arbitrary function the proof knows nothing about.
| Name | Stands for |
|---|---|
isQ | main-loop "is this a QRS?" check |
bs | backsearch version of that check |
req | does this peak require a backsearch? |
upd | _update_qrs |
noise | _update_noise |
lastPeak | reads last_qrs_peak_num; none is Python's None |
I transcribed both loops. The new step carries one extra number, the next peak to start from, and scans from max(last + 1, next). oldRun and newRun apply the steps to peaks 0 through n - 1. Because everything is a parameter, the proof can only use what I explicitly hand it.
The theorem#
theorem run_exact
(upd_last : ∀ s j p, lastPeak (upd s j p) = some p)
(noise_last : ∀ s j, lastPeak (noise s j) = lastPeak s)
(noise_bs : ∀ s j, bs (noise s j) = bs s)
(s : S) (n : Nat) :
(newRun lastPeak bs upd noise isQ req s n).1 =
oldRun lastPeak bs upd noise isQ req s n := byThe three hypotheses are the only facts the proof may assume:
upd_last: after_update_qrs, the last QRS peak number is the current peakp.noise_last:_update_noisenever changes the last QRS peak number.noise_bs:_update_noisenever changes the backsearch check's answer.
For any start state and any n, the new loop's state (.1 drops the extra counter) equals the old loop's. Not "same detections": the whole state, every threshold and running average included. Nothing assumed about isQ, req or what bs computes, so no floating point reasoning.
The invariant behind the proof
The proof is an induction over peaks with one invariant:
def BsInv (s : S) (nxt : Nat) : Prop :=
∀ l, lastPeak s = some l → ∀ j, l < j → j < nxt → bs s j = false"Every peak strictly between the last beat and the skip point would be rejected by backsearch right now." If so, skipping them is harmless, since scanning peaks that all fail leaves the state untouched (lemma scan_false). The work is showing the invariant survives each step: the main loop's update either moves the last beat to the current peak (empty range) or is a noise update (check unchanged by assumption), and a backsearch scan either finds nothing (its whole range joins the rejected set) or finds a beat (last peak resets to the current one, lemma scan_cases).
The edge cases I worried about are explicit cases in the proof: lastPeak being none before the first beat, a beat found mid-scan, a beat found by the main loop. The file compiles with Lean core only, no Mathlib, no sorry, and #print axioms run_exact shows only Lean's three standard axioms.
What the proof does not tell you#
"Formally verified" sounds stronger than this is. The Lean model is hand-written from reading qrs.py; nothing connects it mechanically to the Python. If I mistranscribed the loop, the proof is about a loop that doesn't exist. And I checked the three hypotheses by reading the code, not Lean.
What ties model to code is the PR's testing: a regression test that spies on _is_qrs, asserts backsearch never checks a peak twice and that beats on both sides of a 2-minute gap are still found (it fails on the old code), plus the 300 random runs. The proof says the argument is airtight; the tests say the code matches it.
The maintainer found the soft spot#
The PR was MIT-LCP/wfdb-python#596, since merged. Tom Pollard reproduced the failing test and timings, ran his own randomized comparison, then pointed at where this kind of proof is weakest. The skip depends on two things that "look like they could be changed later": _update_noise not recalculating qrs_thr, and _update_qrs setting last_qrs_peak_num to the current peak rather than the peak it was called with.
Almost word for word, the hypotheses of run_exact. Writing the proof forced me to list every assumption, and a careful reviewer who never read the Lean landed on the same list and asked what stops someone breaking them later.
The proof can't answer that. So he opened an issue suggesting a comment naming the dependencies, and I followed up with #598: the comment, plus a test that checks both properties during detection and fails if either changes. Also merged. #598 turns the proof's hypotheses into executable checks next to the code, the closest thing to a mechanical link this setup has.
Where this leaves me#
The Lean file is in lean-perf-proofs/wfdb-xqrs-backsearch, alongside a few other performance fixes I've sent upstream, each with a proof that the new code returns exactly what the old did.
What works for me: make the model as abstract as possible, then put the few structural facts in front of a reviewer in plain words. The proof is less about catching a bug than making assumptions impossible to hide.
The gap I still can't close: the model is hand-transcribed, the hypotheses now have runtime checks, but the loop structure doesn't. Is there a lightweight way to keep a hand-written model honest as the code evolves, short of verifying Python? I suspect "test the hypotheses, diff the loop shape", but I haven't found a version I'd want to maintain. If you have, I'd love to hear it.