When a piece of code that is slow but obviously right has to become fast, one thing that is easy to skip is keeping the slow version around, in the tests, and checking the fast one against it over a lot of generated inputs. I did that recently in the Rust importer of the reading app I’m building on the side, where it threw out two fast versions that looked fine on paper before a third one agreed with it, and then a wider generator found a case where even the third one doesn’t agree, so these are my notes on how the comparison was set up and on what “they agree” ended up meaning.
The transform
The pass in question is the same one I wrote about in Bounding a Rust cost test by the parser’s own time, which ends <details> elements the source never closes, so here we only need the short version. No start tag closes an open <details>, so html5ever (through the scraper crate) keeps an unclosed one open until whatever holds it ends, and in an FAQ-style book a run of them nests, each inside the one before it, with the rest of the book inside the last one. Since the app never cuts a chapter inside a disclosure, all of that ends up as one chapter hidden behind the first summary. The pass ends each unclosed disclosure at the first thing an author wouldn’t put inside one (a chapter heading, the next <details>, or a page break marker), and moves everything from that point on out after it, so this:
<details><summary>Can I return it?</summary>Yes, within 30 days.
<details><summary>Do you ship abroad?</summary>Only within the EU.
<h2>Chapter 2</h2>
<p>The rest of the book...</p>
comes out as this:
<details><summary>Can I return it?</summary>Yes, within 30 days.</details>
<details><summary>Do you ship abroad?</summary>Only within the EU.</details>
<h2>Chapter 2</h2>
<p>The rest of the book...</p>
The first version ended them innermost first, so every outer disclosure looks for its boundary in a tree where everything inside it is already fixed. It was picked after generated inputs showed plain document order leaving a chapter heading hidden in 457 of 100,000 cases, in a shape we’ll get to below. The trouble with innermost first is the cost on a flat run, because ending the innermost one moves its tail out into the one around it, then ending that one moves the inner disclosure plus everything already moved out after it, and so on outwards, so each outer disclosure carries every one already moved out after it and a run costs the square of its length. A run of 8,000 FAQ entries took 697 ms against a 152 ms parse of the same input, and the parse is itself quadratic for nested disclosures (the cost-test post goes into why), so that was a lot to add on top of a step that is already slow on this kind of input.
Moving the slow version into the tests
In document order each disclosure of a run moves out as a single node (the next <details> with everything still inside it), so on a run the cost is linear, and the fast version was going to be some variation of document order. The question was which variation gives the same tree as innermost first. Instead of being deleted, the innermost-first loop went into the test module as ended_innermost_first, next to one test that parses the same input twice, runs the new pass on one copy and the old loop on the other, and compares. Trimmed down (the real test also runs a handful of fixed inputs first, more on those below), it looks like this:
fn next(state: &mut u64) -> u64 {
// xorshift, so a failure reproduces from the seed alone
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
*state
}
#[test]
fn disclosures_end_where_the_innermost_first_rule_ends_them() {
const PIECES: &[&str] = &[
"<details>", "<details>", "<details hidden>", "<details open>",
"<summary>", "</summary>", "</details>",
"<h1>", "<h2>", "<h2 hidden>", "<h3>",
"</h1>", "</h2>", "</h3>", "</h3>",
"<ul><li>", "</ul>", "<div hidden>", "<div>", "</div>",
r#"<div class="pagebreak"></div>"#, "<b>", "x", "y",
];
let mut state: u64 = 0xD1B5_4A32_D192_ED03;
let mut ended = 0;
for _ in 0..30_000 {
let length = (next(&mut state) % 20) as usize + 1;
let html: String = (0..length)
.map(|_| PIECES[(next(&mut state) % PIECES.len() as u64) as usize])
.collect();
let mut fast = SourceDocument::parse_fragment(&html);
let mut slow = SourceDocument::parse_fragment(&html);
ended += usize::from(end_disclosures_in(&mut fast));
ended_innermost_first(&mut slow);
assert_eq!(skeleton(&fast), skeleton(&slow), "{html}");
assert_eq!(fast.closed_by_source, slow.closed_by_source, "{html}");
}
assert!(ended > 3_000, "{ended}");
}
The generator is nothing fancy, just random strings glued together from tag pieces, unbalanced on purpose, because broken markup is the whole point of the pass and the parser turns any string into some tree anyway. You’ll notice that <details> and </h3> appear twice, which makes them twice as likely to be drawn, so the inputs hold more unclosed disclosures and more headings that the source closes, which is the shape the rest of this post turns on. It’s easy to leave the ended counter out, and you shouldn’t, because if the generator stopped building unclosed disclosures both passes would do nothing on every input, agree every time and the test would stay green while checking nothing (one of the shapes in Writing checks that can fail on the bug they guard against), so the last line fails unless the new pass ended something in more than a tenth of the inputs. The committed test runs 30,000 inputs so it stays fast in the normal suite, while the searches for a fast order ran the same loop with other seeds and millions of iterations.
The oracle also isn’t quite the code it replaced. The old loop recorded each disclosure as closed the moment it ended it, while the new pass records every disclosure it ended only once all of them are ended, and the oracle was changed to do the same so the two would agree. That changes what an unclosed <details hidden> inside another one does, which was a decision made in the design, so on that point the closed_by_source comparison above only shows that the two orders agree, and whether the behaviour is right had to be settled outside the test.
Compare what the rule decides, not the serialized HTML.
When a move splits an element that sits between a disclosure and its boundary, it closes it and re-opens a copy after, and the two orders group those copies differently, so one writes a single <b> around two runs of text where the other writes one <b> around each, which a reader sees exactly the same. So the test compares a skeleton of the tree, which keeps only the elements the rule cares about (disclosures, summaries, headings, lists and their items, anything marked hidden, page break markers, with their hidden and open attributes) and the text, plus the set of elements recorded as closed. Anything the skeleton drops is something the test no longer checks, so it’s worth listing what it keeps in the test’s doc comment, which is where you’ll look when a case slips through.
Finding an order that agrees
Let’s start with the shape plain document order gets wrong, which needs a heading the source does close, say an <h3>, with an unclosed disclosure inside it. A disclosure’s search for its boundary skips over a closed heading without looking inside, since cutting there would show half the heading twice. But when the inner disclosure is ended later, its chapter heading is moved out of the <h3> too (a heading left directly inside another heading doesn’t survive the written markup being parsed again, so the pass carries it out), and it lands at a spot the outer disclosure’s search had already passed, so the outer one keeps hiding a chapter.
The first fix for that kept document order and ended a disclosure again whenever a later move put a boundary inside the part it had already searched. The oracle refuted it within 300,000 inputs, because the second ending left behind the splits of the ending it replaced (the first one had already moved a disclosure out of an unclosed <h3>, and ending it again somewhere else didn’t undo that). The second idea was to work out up front which disclosures would be reached that way and end those first, and that was refuted next, because a move can put other disclosures inside a closed heading, and a list of particular disclosures made before the pass doesn’t know about them.
What finally agreed came from looking at why plain document order failed in the first place. A moved boundary only reaches a search that has already passed it by coming out of a heading the source closes, so if every disclosure inside such a heading is ended before any disclosure outside it, no boundary should arrive late. That is still document order, just stably sorted by how many source-closed headings stand above each disclosure, most first, so instead of picking out particular disclosures it orders all of them by one rule, and the counts come out of one walk over the tree. Trimmed from the real function (which uses .get() with a default instead of indexing):
use std::{cmp::Reverse, collections::HashMap};
// descendants() visits a parent before its children, so the parent's count is always there
let mut closed_headings_above = HashMap::new();
for node in source.document.tree.root().descendants() {
let above = node.parent().map_or(0, |parent| {
closed_headings_above[&parent.id()]
+ usize::from(
parent.value().as_element().is_some_and(is_heading)
&& source.closes(parent.id()),
)
});
closed_headings_above.insert(node.id(), above);
}
disclosures.sort_by_key(|details| Reverse(closed_headings_above[details]));
That one agreed with the oracle over 2,000,000 generated inputs, with two seeds and inputs of up to 32 pieces, and it became the fix, and on a long run the transform now takes a few hundredths of the time the parse does. It’s linear on a run like that, while a stack of nested headings that the source closes, each holding a disclosure, still costs the square of its depth, as it did with innermost first and as the parse does. The argument above only says when a boundary is found and says nothing about whether every move ends up producing the same tree, so what showed this order to be safe was the oracle. Both refuted ideas had a perfectly reasonable argument behind them too, and the re-end was the option I had picked, so without the old loop sitting in the tests it would most likely have shipped.
Before the generated loop, the test also runs eight fixed inputs through the same comparison. That matters more when the committed run is small, because a shape that a long search finds once in a few hundred thousand inputs won’t reliably come up again in 30,000 draws, so it’s worth pinning such a shape as a fixed case as soon as a search finds it.
What “they agree” proved
After that, a separate review went over the change with a wider generator of its own, around five million inputs, which could produce pieces the test’s generator never did, a bare <ol> and other heading end tags among them. It found a shape where the new order and the oracle still differ:
<details><ol><details><h1></h4><li>
Here an unclosed disclosure sits directly in an <ol>, which is invalid markup to begin with, inside another unclosed one (and the </h4> closes the <h1>, since any heading end tag closes an open heading). The new order moves the inner disclosure out of the list whole, with the outer disclosure around it, so the <li> after its boundary is written outside any list, where innermost first keeps it inside the <ol>. The reader sees a bullet where there should be a number, and no text goes missing. Fixing it would need yet another order and another round against the oracle, with a real chance of bringing the quadratic run back, so the code stayed as it is, and the test’s doc comment now says that a disclosure held directly in a list is not generated, because there the two differ.
So the two million agreeing inputs only showed that no disagreement turned up among the inputs that were drawn, and the test’s generator could never draw a disclosure directly in a list at all, because there was no <ol> piece and <ul> only ever came with an <li> right after it. That gap came from how the pieces were written, and as far as I can tell nobody chose it.
When a correct but slow implementation has to be replaced, it’s worth moving it into the tests instead of deleting it, since a fast version that looks right is easy to write and comparing the two over generated inputs is very good at finding where it isn’t. The comparison needs a skeleton of what the rule decides, with what it leaves out written down, and a counter that fails when the generator stops exercising the pass, and any shape a long search finds is worth pinning as a fixed case. Agreement also only covers what the generator builds, so write down next to the test what it can and can’t build, and let a wider generator have a go at it if you can, since that is how the list case turned up here.