Most of the cost tests in a Rust side project of mine, which rewrites HTML with scraper (and so html5ever underneath), follow one recipe, and a review of a planned test showed me an input where that recipe can’t fail, so let’s go through why, and what we changed in the inputs to fix it. It’s a small thing about html5ever, but it applies to any test that measures your code against a library’s time on the same input.
The recipe
A lot of that code walks an HTML tree and moves nodes around, and each walk has to stay linear in the size of the document, because a pass that is quadratic in it is fine on a small test file and very slow on a large one. So for each such pass there is a test that builds a large input, times the pass, and fails if it took too long.
“Too long” is not a fixed number of seconds. A fixed bound ends up measuring the machine more than the code (a debug build, cargo test running the binary’s other tests on parallel threads, another build running next to it), so instead the test times html5ever parsing the same input, right beside the pass, and bounds the pass by a multiple of that plus a small constant. When the machine is slow, the parse is slow too, and the bound moves with it. If the first run is over the bound, the test times both again and fails only if the second run is over too, since a burst of load from somewhere else has to hit both runs to cause a false failure, while a real blow-up is over both times anyway. The shape is roughly this:
use scraper::Html;
use std::time::{Duration, Instant};
#[test]
fn chained_disclosures_cost_no_more_than_their_parse() {
const N: usize = 10_000;
let html = "<details><summary><object>Q".repeat(N);
let timed = || {
let started = Instant::now();
let mut document = Html::parse_fragment(&html);
let parse = started.elapsed();
let started = Instant::now();
let changed = end_unclosed_disclosures(&mut document);
let pass = started.elapsed();
// Pin what the pass did, so we know which path was timed.
assert!(!changed);
(pass, parse)
};
let within = |(pass, parse): (Duration, Duration)| {
pass < parse * 4 + Duration::from_millis(100)
};
let first = timed();
if within(first) {
return;
}
let second = timed();
assert!(within(second), "(pass, parse): {first:?} then {second:?}");
}
The <object> in that input is the fix this post is about, so let’s look at what was there before it.
The pass and the first input
The pass in question ends unclosed <details> elements. In HTML no start tag closes an open <details>, so if one is never closed, everything after it in the document ends up folded inside it. The pass finds where each unclosed disclosure should end, and part of that is a search forward from each <details> that passes over any <summary> without looking inside it.
The plan for it had a cost test over "<details><summary>Q</summary>A".repeat(10_000), bounded by four times the parse plus 100 ms, and a scratch implementation of the pass fit inside that bound comfortably, which I took as a sign that it was linear. That conclusion had two holes in it. The bound was relative to html5ever’s parse of that input, which is itself quadratic, and the input never put a disclosure inside a summary, which is the one shape where the search was slow. Between them they hid a quadratic walk, which the reviewers found by measuring a scratch copy.
html5ever parses nested blocks in quadratic time
Here is html5ever 0.40 parsing a few repeated inputs with Html::parse_fragment, best of three runs, release build on my Mac:
| Input, repeated n times | n = 2,000 | 4,000 | 8,000 | 16,000 |
|---|---|---|---|---|
<details><summary>Q</summary>A | 14.4 ms | 42.8 ms | 169.6 ms | 675.0 ms |
<div>A | 4.8 ms | 17.4 ms | 74.7 ms | 296.6 ms |
<details><summary>Q</summary><object>A | 1.6 ms | 3.1 ms | 6.4 ms | 12.8 ms |
<details><summary><object>Q | 1.1 ms | 2.3 ms | 4.3 ms | 8.8 ms |
Doubling n roughly quadruples the time for the first two rows, and only doubles it for the last two. The reason is in the HTML spec, and html5ever follows it closely. When the parser sees the start tag of a block like <details>, <summary>, <div>, <ul>, <p> or a heading, it first checks whether a <p> is open “in button scope”, and closes it if so (that’s how <p>a<div>b ends the paragraph before the div). The check walks the stack of open elements from the top down, and stops when it finds a <p> or an element that starts a new scope:
// html5ever/src/tree_builder/mod.rs, in_scope
for node in self.open_elems.borrow().iter().rev() {
if pred(node.clone()) {
return true;
}
if scope(self.sink.elem_name(node).expanded()) {
return false;
}
}
The stack is usually a handful of elements deep, so this is cheap. In a test input where every unit opens a block inside the previous one and nothing closes, the stack is as deep as the number of units so far, and every block start tag walks all of it, so the total grows with n². Nested <div>s do the same thing, so it’s not specific to <details>.
The elements that stop the walk are the scope markers, which in html5ever 0.40 are applet, caption, html, table, td, th, marquee, object, select and template (plus a few MathML and SVG integration points, and button for button scope). With an <object> in each repeated unit the walk always stops one or two elements down, and the parse becomes linear, which is what the last two rows show.
Not every marker on that list does this, tho. Putting each of them after the <summary> of <details><summary><X>Q and parsing 2,000 units, <object>, <applet>, <marquee> and <template> kept all 2,000 disclosures nested and parsed in linear time, <table> and <button> parsed fast only because the chain came out flat (no disclosure more than one level deep, so the slow path is never reached), <select> was still quadratic, and <caption>, <td>, <th> and <html> are ignored at that point in the body, so they changed nothing, which leaves <object> or one of the three that behaved like it.
A cost test bounded by “k times the parse” only proves the pass is no worse than the parse. If the parse of the test input is quadratic, a quadratic pass fits under the bound.
The walk that still walked what it skipped
The tree walks in that code went through a small iterator over ego_tree’s traverse(), which yields an Open and a Close edge for every node in document order, with a skip method that sets a flag so the edges inside a node aren’t yielded. That reads like a jump, but the iterator underneath still produces every one of those edges, the wrapper just drops them, and traverse() has no way to seek past a subtree. Boiled down, the search looked like this (is_summary and is_details just compare the element’s name):
use ego_tree::{iter::Edge, NodeRef};
use scraper::Node;
// Is there a <details> in `d` outside any <summary>?
fn search_skipping(d: NodeRef<Node>) -> bool {
let mut skipping = None;
for edge in d.traverse() {
match edge {
Edge::Close(n) if skipping == Some(n.id()) => skipping = None,
_ if skipping.is_some() => {} // still pulled, just not looked at
Edge::Open(n) if n.id() != d.id() && is_summary(n) => skipping = Some(n.id()),
Edge::Open(n) if n.id() != d.id() && is_details(n) => return true,
_ => {}
}
}
false
}
When disclosures are nested inside summaries (<details><summary><details><summary>…), each summary holds every disclosure after it, so passing over the summary of the i-th one costs n − i, and the whole pass is quadratic. The fix is a cursor that moves with next_sibling and parent, so stepping over a node costs one step whatever is inside it:
fn search_by_cursor(d: NodeRef<Node>) -> bool {
let mut cursor = d.first_child().map(|child| (child, true));
while let Some((node, opens)) = cursor {
if opens && is_details(node) {
return true;
}
let enter = opens && !is_summary(node) && node.first_child().is_some();
cursor = if enter {
node.first_child().map(|child| (child, true))
} else {
match node.next_sibling() {
Some(sibling) => Some((sibling, true)),
None => node.parent().filter(|p| p.id() != d.id()).map(|p| (p, false)),
}
};
}
false
}
Putting the two together
Here are the two searches, run once per <details> in the document, next to the parse of the same input (same machine, release build, one run each, so the parse times are a little off from the table above):
| Input, n = 16,000 | Parse | Skipping walk | Cursor |
|---|---|---|---|
<details><summary>Q</summary>A | 730 ms | 0.15 ms | 0.09 ms |
<details><summary>Q | 1.8 s | 3.0 s | 0.3 ms |
<details><summary><object>Q | 9.3 ms | 2.9 s | 0.2 ms |
The first row is the input from the plan, and it doesn’t nest anything in a summary, so neither walk has anything to be slow on. The second row does reach the quadratic path, and the skipping walk takes 3.0 s there, but the parse takes 1.8 s, so four times the parse plus 100 ms is over 7 s and the search fits under it with room to spare. Only the third row, where the <object> keeps the parse at 9 ms, puts the bound at about 140 ms, and the skipping walk misses it by a factor of twenty. The test from the top of the post, with each search standing in for the pass, behaves the same way at n = 10,000 in both the debug build cargo test uses by default and a release build, failing the skipping walk and passing the cursor on the <object> input, and passing both on the input without it. Debug slows html5ever down more than it slows the walk, so the debug run is the one where a quadratic parse hides the most, which makes it the one to try the quadratic version in.
Summary
A bound of “k times the library’s time” is only as good as the library’s cost on that input, so the first thing to check is that the library alone is linear there, and timing it over a few doublings of n (not just one, since a small n can land anywhere between 2x and 4x) is a quick way to see that. For html5ever and deeply nested blocks it isn’t linear, because of the <p>-in-button-scope check, and an <object> in each repeated unit fixes that while keeping the units nested, which <table> or <button> don’t. A linear parse still doesn’t prove the input reaches the slow path, so the test also pins what the pass did (the assert!(!changed) above), and a deliberately quadratic version of the pass has to fail it in the build profile the tests run in, since a cost test that has never been seen failing doesn’t tell us much (more on that habit in Writing checks that can fail on the bug they guard against). The walk itself had the same kind of problem one level down, since a skip method over traverse() only stops yielding the subtree’s nodes and still costs as much as the subtree is big, and moving past it with next_sibling and parent is what makes the walk linear.