Chapter 33One pop(0) Too Many: Making Biopython's NEXUS Tokenizer 100x Faster, and Proving It
Parsing a NEXUS command with 16,000 entries in Biopython took about 1.9 seconds. After a change touching maybe twenty lines, it takes 0.018. A TRANSLATE block of the same size went from 4.4 seconds to 0.041. Roughly a hundred times faster, and nothing clever happened: the parser stopped doing list.pop(0).
The speedup is the easy part. The question I care about is the one after it: if you rewrite the core of a tokenizer people have used for years, how do you know it still returns exactly the same thing?
Where I found it#
I was reading scientific Python parsers for one shape of bug: a loop doing "a little work" per character that quietly costs O(n). Every line looks innocent, and it only shows up on inputs much bigger than the author tested.
NEXUS is a phylogenetics text format of blocks with commands like CHARSET, TAXSET and TRANSLATE, some very long: thousands of column indices or taxon labels. Bio.Nexus.Nexus has a small class, CharBuffer, that tokenizes one command at a time. It stored its input like this:
def __init__(self, string):
if string:
self.buffer = list(string)
else:
self.buffer = []
def __next__(self):
if self.buffer:
return self.buffer.pop(0)
else:
return NoneWhy that's quadratic#
A Python list is a contiguous array. pop(0) shifts every remaining element left, so it's O(n), and reading n characters costs n + (n-1) + (n-2) + ... = O(n²).
buffer [ A ][ B ][ C ][ D ][ E ] index 0 1 2 3 4
Five unread characters.
There was a second offender. The peek method did:
def peek_nonwhitespace(self):
b = "".join(self.buffer).strip()
if b:
return b[0]
else:
return NoneEvery call joins the whole remaining buffer into a string, strips it, and reads one character. O(n) per call, and the word reader calls it often. skip_whitespace had self.buffer = self.buffer[1:], copying the whole list to drop one character.
Irrelevant on a command of a few dozen characters. Very relevant on a 16,000-entry charset, which real datasets contain.
The fix: keep the string, move a cursor#
def __init__(self, string):
self._text = string or ""
self._pos = 0
def __next__(self):
if self._pos < len(self._text):
c = self._text[self._pos]
self._pos += 1
return c
else:
return None
def peek_nonwhitespace(self):
text = self._text
pos = self._pos
# str.isspace matches what str.strip() removes
while pos < len(text) and text[pos].isspace():
pos += 1
if pos < len(text):
return text[pos]
else:
return Nonebuffer: [ ' ' ][ C ][ D ][ E ] ... 16,000 more characters
+------------- join all of it -------------+
|
v
one new string, strip it, take [0]
cost per call: everything left in the buffertext: A B [ ' ' ][ C ][ D ][ E ] ... 16,000 more characters
^ ^
pos first non-space: return it
cost per call: only the whitespace skippedThe other methods follow: next_until uses str.find(target, pos), peek_word compares a slice, rest returns self._text[self._pos:]. A whole command is now linear. Numbers from the PR (Python 3.13, macOS):
| input | before | after |
|---|---|---|
| charset with 4,000 entries | 0.10 s | 0.004 s |
| charset with 16,000 entries | 1.89 s | 0.018 s |
TRANSLATE with 16,000 entries | 4.42 s | 0.041 s |
To be honest about it: "100x" is for long commands. At 4,000 entries it's 25x, and on the short commands most NEXUS files are made of, the old code was already fast enough. This fixes the tail, which is where people were waiting seconds.
How do I know it's still right?#
A tokenizer bug doesn't crash. It shifts a word boundary and some alignment quietly gets a different taxon name. "Obviously equivalent" is how off-by-one bugs get merged. Three details made me nervous:
- The old
peek_nonwhitespaceused.strip(), which trims both ends; the new one only scans forward. Is the first character of a stripped string always the first non-whitespace one? Yes, because the trailing strip can never eat a non-whitespace character. - The old
skip_whitespaceraisesIndexErroron an empty buffer. The new one must raise it in the same situations. next_untilwent fromlist.indexplus a split tostr.findwith an offset plus a slice. One indexes the remaining list, the other the whole text.
I added unit tests and a randomized comparison running old and new classes side by side on 200,000 short inputs full of quotes, brackets, punctuation and mixed whitespace, calling every method in random order. Zero differences. But random testing only covers inputs I generated. I wanted every input and every call sequence, so I wrote it in Lean.
Lean, and the one-line invariant#
Lean 4 is a programming language that is also a proof checker: if the proof has a gap, it doesn't compile. It has no idea what CPython does, so I wrote both buffers as small Lean functions mirroring the Python:
- Old: a list
lof remaining characters; reading pops the front. - New: the whole text
tplus a positionp; reading advancesp.
old buffer new buffer
────────── ──────────
[ C D E ] = text [ A B C D E ] drop pos=2
└─ "text.drop pos"
invariant: old buffer = text.drop pos
every op returns the same value on both sides and keeps it trueThe theorem#
Each primitive gets a lemma: peek, next, peek_nonwhitespace, skip_whitespace, next_until, peek_word, rest. They're packaged into an Op per method and two interpreters: runOld runs a list of ops on the old buffer, runNew on the text-and-cursor one.
/-- Main result: starting from the same text, any sequence of buffer calls
returns the same values in the old and new implementation. -/
theorem run_exact (t : List α) (ops : List (Op α)) (p : Nat) :
runOld ops (t.drop p) = runNew t ops p := by
induction ops generalizing p with
| nil => rfl
| cons op ops ih =>
simp only [runOld, runNew, step_exact, ih]Any text t, any start p, any list of calls of any length and order: the old buffer holding t.drop p and the new one holding t at p give exactly the same outputs. The proof is induction on the calls; zero calls agree, and if one step agrees (step_exact) and keeps the invariant, the rest follows. run_exact_init specializes to p = 0, how the parser builds a buffer.
Characters are an arbitrary type and "is whitespace" an arbitrary predicate, so it doesn't matter that old code used .strip() and new code .isspace(). The equivalence holds as long as both sides use the same predicate. (That c.strip() == "" and c.isspace() agree for every Unicode code point is a Python fact I checked and left a comment about. The proof doesn't establish it.)
The proof uses Lean core only, no Mathlib, no sorry, and #print axioms shows only Lean's three standard axioms.
The lemmas that cover my worries
strip_head: the first character ofstrip lequals the first character oflafter dropping leading whitespace. This is what makes the forward scan a legal replacement for"".join(buf).strip()[0]. It has to argue the right-hand strip can't remove the first non-whitespace character, the step I'd have hand-waved without Lean.findFrom_specanduntil_exact:str.find(c, pos)plus a slice gives the same found substring and the same remaining buffer aslist.indexplus a split, including "not found".skip_exact:skip_whitespacereturns an error value on both sides, in exactly the same situations, which models theIndexError.
What's proved and what's assumed#
"Formally verified" sounds like more than it is.
| Status | |
|---|---|
| New buffer behaves like old, all inputs, all call sequences | Proved, in the Lean model |
| Python-to-Lean translation | Modelled by hand. Strings as character lists, str.find as a recursive scan, "".join(...) vanishes. Nothing mechanically checks it. If I misread list.index on a miss, the proof would still pass and be wrong about Python. |
next_word, next_nonwhitespace | Not modelled. Unchanged, and they only call the primitives, so their call sequences are covered by run_exact. Sound, but an argument, not a theorem. |
So the proof doesn't replace the tests; it changes what they're for. TestCharBuffer walks a real CharBuffer through quoted words with an escaped quote, a bracketed comment, next_until, peek_word, rest and end of input. Another test checks empty and None input behave the same and skip_whitespace still raises IndexError; a third parses a 20,000-entry charset. With the 200,000-case comparison, they check real Python matches the model on concrete inputs. The proof says the model is right on all of them. Tests sample the space; the proof covers the whole space, but of a model. Together they get close.
Where it stands#
The PR is biopython/biopython#5397, "Make Nexus CharBuffer tokenizing linear instead of quadratic". Review status lives on the PR itself. The proof is in lean-perf-proofs/biopython-nexus-charbuffer, next to proofs for a few other performance fixes I've sent upstream, each with a README spelling out proved versus modelled.
What I keep coming back to is how small the proof was once the invariant was written down: old buffer = text.drop pos is the entire idea. How many "obviously equivalent" rewrites have an invariant that short underneath them, and should writing it down be part of sending the patch? The open question is the middle gap: the Python-to-Lean translation is hand-done and trusted. How far can you shrink that trusted step before the proof costs more than the fix?