Skip to content

📝 docs: benchmark parse() against other tree builders - #13

Merged
gaborbernat merged 1 commit into
tox-dev:mainfrom
gaborbernat:feat/parse-benchmarks
Jun 15, 2026
Merged

gaborbernat merged 1 commit into
tox-dev:mainfrom
gaborbernat:feat/parse-benchmarks

Conversation

@gaborbernat

Copy link
Copy Markdown
Member

The parse() feature shipped without a published comparison against the HTML tree builders people actually use. The parse benchmark only raced turbohtml against lexbor, so a reader had no way to weigh it against lxml or html5lib or BeautifulSoup. 📊 This adds those three to the parse suite and publishes the numbers in the README and the docs, next to the existing escape, unescape, and tokenize tables.

The four comparison libraries (lexbor through selectolax, lxml, html5lib, and BeautifulSoup) are declared bench dependencies and imported at module scope, since the bench environment controls them and the old skip-when-absent dance is no longer warranted. turbohtml builds the tree into its arena and returns lazy wrappers, so it parses faster than the C parsers lexbor and lxml and 30 to 70 times faster than the pure-Python html5lib and BeautifulSoup, while building the WHATWG tree that lxml's libxml2 does not. That settles the "beat lxml.html on throughput while staying more spec-correct" bar from #10.

The same change runs a no-slop pass over the README and the documentation: em-dashes go (including from the doctest output, where the example input changed to keep the result accurate), along with promotional phrasing and passive voice, in favor of plain, direct, technical prose.

This does not close #10: its core landed earlier and this validates its throughput bar, but the html5lib and bs4 tree-builder adapters it scopes are still open.

@gaborbernat gaborbernat added the documentation Improvements or additions to documentation label Jun 14, 2026
@gaborbernat
gaborbernat force-pushed the feat/parse-benchmarks branch 2 times, most recently from fc01b74 to bce3379 Compare June 14, 2026 21:31
The parse suite only raced turbohtml against lexbor, so the new parse()
feature had no published comparison with the libraries users actually reach
for. This adds lxml, html5lib, and BeautifulSoup to the parse benchmark and
publishes the results in the README and the docs alongside the escape,
unescape, and tokenize tables.

The four comparison libraries are declared bench dependencies and imported
directly, since the bench environment controls them. turbohtml builds the tree
into its arena and returns lazy wrappers, so it parses faster than the C
parsers lexbor and lxml and 30 to 70 times faster than the pure-Python
html5lib and BeautifulSoup, which validates the throughput bar from tox-dev#10.

The same change runs a no-slop pass over the README and the documentation:
removing em-dashes (including from doctest output), promotional phrasing, and
passive voice in favor of plain, direct, technical prose.
@gaborbernat
gaborbernat force-pushed the feat/parse-benchmarks branch from bce3379 to d40cfab Compare June 15, 2026 01:23
@gaborbernat
gaborbernat merged commit 2cae34f into tox-dev:main Jun 15, 2026
35 checks passed
@gaborbernat
gaborbernat deleted the feat/parse-benchmarks branch June 18, 2026 18:25
gaborbernat added a commit that referenced this pull request Jul 3, 2026
* 🐛 fix(parser): tree-construction whitespace handling

Two WHATWG §13 whitespace bugs in tree construction.

The pre/listing/textarea leading-newline skip fired whenever a newline
later reached the first text token, even when a comment or element came
between the start tag and the newline. HTML ignores the newline only when
it is the token immediately following the start tag, so clear the drop
flag on any intervening token. `<pre>\nX` still drops the newline;
`<pre><!--c-->\nX` now keeps it.

A carriage return decoded from a character reference (&#13; / &#xD;)
reached tree construction as a real U+000D but was not classified as
whitespace, so a leading one leaked a stray text node and flipped
frameset-ok. Input preprocessing folds a literal CR to LF, but a CR from
a reference bypasses it; U+000D is whitespace in every insertion mode, so
add it to the whitespace set. The tokenizer's raw scan never sees a CR,
so its delimiting is unaffected.

closes #402
closes #439

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
gaborbernat added a commit to gaborbernat/turbohtml that referenced this pull request Jul 5, 2026
Route the hand-rolled ASCII classification scattered across the C core
through one Python-free header, core/ascii.h, next to core/vec.h. It holds
lower_ascii, is_ascii_alpha, is_ascii_digit, is_ascii_hexdigit, and is_space
as static inline helpers on a uint32_t, so each site inlines the same
comparison it wrote by hand and the css/js engines compile it in their
JM_STANDALONE builds. The width-tagged buffer helpers (ucs_width, buf_read,
buf_write) move to tokenizer/statemachine.h, next to th_buf, so ascii.h keeps
no CPython dependency.

Reconciling the drift the audit flagged, kept explicit rather than accidental:

- Whitespace, CR omission (BUG). Four scanners in links.c, sanitize.c,
  serialize/internal.h, and readability.c dropped U+000D, reasoning that input
  preprocessing folds every CR to LF. A &tox-dev#13; character reference decodes to a
  real CR past that step, and CR is HTML ASCII whitespace, so links() kept a
  stray CR on a trimmed URL and the text/markdown/main_text exporters left one
  uncollapsed. All four now share is_space. Regression tests cover each.
- dates.c is_space includes vertical tab (INTENTIONAL). It matches the Perl \s
  the ported _dates.py regex used, not HTML whitespace. Renamed is_perl_space
  with a why-comment; kept local; a VT-separated date test locks it.
- dates.c lower_cp folds Latin-1 (INTENTIONAL). The month vocabulary needs
  accented letters (AOUT, MARZ). Renamed lower_month_cp, noting it is wider
  than ASCII lower_ascii on purpose.
- char vs Py_UCS4 case fold (RECONCILED). The encoding sniffer's byte folds now
  call (char)lower_ascii(ch), so classification is shared while char storage
  stays.

Parser and serializer output is unchanged except the CR fix. Verified 100%
line and branch on both toolchains: macOS llvm-cov and gcc-13 in ubuntu:24.04.

Part of tox-dev#478.
gaborbernat added a commit that referenced this pull request Jul 5, 2026
)

* ♻️ refactor(c): shared ascii.h + CR whitespace fix

Route the hand-rolled ASCII classification scattered across the C core
through one Python-free header, core/ascii.h, next to core/vec.h. It holds
lower_ascii, is_ascii_alpha, is_ascii_digit, is_ascii_hexdigit, and is_space
as static inline helpers on a uint32_t, so each site inlines the same
comparison it wrote by hand and the css/js engines compile it in their
JM_STANDALONE builds. The width-tagged buffer helpers (ucs_width, buf_read,
buf_write) move to tokenizer/statemachine.h, next to th_buf, so ascii.h keeps
no CPython dependency.

Reconciling the drift the audit flagged, kept explicit rather than accidental:

- Whitespace, CR omission (BUG). Four scanners in links.c, sanitize.c,
  serialize/internal.h, and readability.c dropped U+000D, reasoning that input
  preprocessing folds every CR to LF. A &#13; character reference decodes to a
  real CR past that step, and CR is HTML ASCII whitespace, so links() kept a
  stray CR on a trimmed URL and the text/markdown/main_text exporters left one
  uncollapsed. All four now share is_space. Regression tests cover each.
- dates.c is_space includes vertical tab (INTENTIONAL). It matches the Perl \s
  the ported _dates.py regex used, not HTML whitespace. Renamed is_perl_space
  with a why-comment; kept local; a VT-separated date test locks it.
- dates.c lower_cp folds Latin-1 (INTENTIONAL). The month vocabulary needs
  accented letters (AOUT, MARZ). Renamed lower_month_cp, noting it is wider
  than ASCII lower_ascii on purpose.
- char vs Py_UCS4 case fold (RECONCILED). The encoding sniffer's byte folds now
  call (char)lower_ascii(ch), so classification is shared while char storage
  stays.

Parser and serializer output is unchanged except the CR fix. Verified 100%
line and branch on both toolchains: macOS llvm-cov and gcc-13 in ubuntu:24.04.

Part of #478.

* test(c): cover date parser wide-storage reads

The 3.10 whole-tree C branch gate slipped to 96.9% (floor 97%) after the
ascii.h refactor folded ~50 covered inline ASCII checks into shared inline
functions, shrinking the branch denominator so 3.10's dead PyUnicode_READ
ternaries crossed the 3% budget. dates.c sat at 55% branch: every CP() read
is PyUnicode_READ, whose 2- and 4-byte ternary sides never run when the whole
date-test corpus feeds 1-byte ASCII strings (branchless on 3.11+, hence green
there). Re-run the scan/scan_all/url cases with a BMP star and astral emoji
appended so the argument is 2- and 4-byte stored; the same dates must fall out.
This lifts dates.c to 99.5% and the tree to 99.0% branch on gcc-13/3.10, keeps
macOS llvm-cov at 100% line+branch.
gaborbernat added a commit to gaborbernat/turbohtml that referenced this pull request Oct 8, 2026
A line break in a title came out raw, and the next line could open a block,
such as a quote, ending the paragraph mid-link. A title decodes character
references (CommonMark 6.3), so the converter writes line breaks as &tox-dev#10; or
&tox-dev#13; and escapes a reference-shaped "&".
gaborbernat added a commit to gaborbernat/turbohtml that referenced this pull request Oct 9, 2026
A line break in a title came out raw, and the next line could open a block,
such as a quote, ending the paragraph mid-link. A title decodes character
references (CommonMark 6.3), so the converter writes line breaks as &tox-dev#10; or
&tox-dev#13; and escapes a reference-shaped "&".
gaborbernat added a commit to gaborbernat/turbohtml that referenced this pull request Oct 9, 2026
A line break in a title came out raw, and the next line could open a block,
such as a quote, ending the paragraph mid-link. A title decodes character
references (CommonMark 6.3), so the converter writes line breaks as &tox-dev#10; or
&tox-dev#13; and escapes a reference-shaped "&".
gaborbernat added a commit that referenced this pull request Oct 9, 2026
`to_markdown` copied a line break in a link or image title as written.
`<a href="t" title="&#10;&gt;">x</a>` became `[x](t "\n>")`, and its
second line opens a block quote ([CommonMark
5.1](https://spec.commonmark.org/0.31.2/#block-quotes)) that ends the
paragraph in the middle of the link. A `&` that starts a reference
stayed bare too, so `title="a&amp;amp;"` read back as `a&`.

A title decodes character references
([6.3](https://spec.commonmark.org/0.31.2/#links)), so the converter now
writes a line break as `&#10;` or `&#13;` and escapes a reference-shaped
`&`. The first example becomes `[x](t "&#10;>")`.

markdownify 1.2.3 writes `[x](t "\n>")`, and html2text 2025.4.15 writes
`[x](t "\n\n>")\n\n`, a blank line that ends the paragraph inside the
title.
gaborbernat added a commit to gaborbernat/turbohtml that referenced this pull request Nov 14, 2026
Writing CR as &tox-dev#13; added one 16-bit compare to the SSE2 clean-run scan, and
that compare slowed the serializer benchmarks by about 5%. The scan stopped at
the first eight-code-point block that held a special, then walked the block
again with the SWAR pair loop to name the code point. The SSE2 path now takes
the position from the movemask bits, so the second walk is gone. A tail of
fewer than eight code points uses one overlapping block, or a bitmap for one
to three code points, instead of the pair loop.

The special mask now stops on CR, so minify no longer probes CR separately.
NEON and the scalar build keep the skip-and-rescan structure, moved into
sbuf_find_special.
gaborbernat added a commit to gaborbernat/turbohtml that referenced this pull request Nov 14, 2026
The serializer now escapes CR in text and attribute values as &tox-dev#13;, so
a raw HTML run never receives a raw CR. The CR branch of md_put_html_run
could not be reached and left a C branch uncovered on the coverage gate.
gaborbernat added a commit that referenced this pull request Nov 14, 2026
The serializer escapes `&`, `<`, `>`, `"` and U+00A0 in
[`sbuf_special_mask`](https://github.com/tox-dev/turbohtml/blob/69953e1bca7a4baea7da16177b182377566dca70/src/turbohtml/_c/serialize/internal.h#L52-L61)
and
[`sbuf_put_special`](https://github.com/tox-dev/turbohtml/blob/69953e1bca7a4baea7da16177b182377566dca70/src/turbohtml/_c/serialize/internal.h#L121-L136),
but not U+000D. A carriage return in text or an attribute value is
therefore written as a raw byte. The parser folds a raw CR to LF, so the
serialized output does not read back as the tree that was written.
`sanitize(sanitize(x)) != sanitize(x)` for `<div>&#xd;</div>`, and
`minify` drops a leading CR inside `<pre>` and `<textarea>` on reparse.
After this change the serializer writes U+000D as `&#13;` under every
formatter, so the output reparses to the same text. Fixes #1864.

### The serializer wrote U+000D as a raw byte

The HTML parser normalizes input before tokenizing: a CR or CRLF becomes
LF ([input stream
preprocessing](https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream)).
A character reference such as `&#13;` skips that step and yields a CR in
the tree. The serializer then copied the CR through unchanged, so the
second parse produced an LF. The WHATWG fragment serialization algorithm
does not escape CR either. The XML serializer already writes it as
`&#13;`, and this change applies the same reference to the HTML
serializer.

The new special set is in
[`sbuf_special_mask`](https://github.com/tox-dev/turbohtml/blob/45289bae826beef975265f859830ee00234327fa/src/turbohtml/_c/serialize/internal.h#L53-L62),
with the quote check split into
[`sbuf_value_mask`](https://github.com/tox-dev/turbohtml/blob/45289bae826beef975265f859830ee00234327fa/src/turbohtml/_c/serialize/internal.h#L64-L68)
for the ARM and scalar scans. On x86 the SSE2 scan
[`sbuf_block_special_bits`](https://github.com/tox-dev/turbohtml/blob/45289bae826beef975265f859830ee00234327fa/src/turbohtml/_c/serialize/internal.h#L120-L140)
builds a bit mask of specials and
[`sbuf_find_special`](https://github.com/tox-dev/turbohtml/blob/45289bae826beef975265f859830ee00234327fa/src/turbohtml/_c/serialize/internal.h#L142-L175)
reads the first one's position from it. The replacement is in
[`sbuf_put_special`](https://github.com/tox-dev/turbohtml/blob/45289bae826beef975265f859830ee00234327fa/src/turbohtml/_c/serialize/internal.h#L221-L237).
The named-entity classifier
[`sbuf_named_special`](https://github.com/tox-dev/turbohtml/blob/45289bae826beef975265f859830ee00234327fa/src/turbohtml/_c/serialize/internal.h#L41-L46)
also reports CR, since the NAMED formatter takes the same path.

### Attribute values and minify use the same writer

Attribute values pass through `sbuf_put_text` with the quote escape
enabled, so a CR in an attribute now becomes `&#13;` too. `minify`
writes `pre`, `textarea` and attribute values through the same helper,
so the `pre` and `textarea` reparse change and the attribute change are
fixed by the same edit. Collapsed text outside those elements already
folds CR to a space, so its output does not change.

### Behavior changes

- Output changes only for input that contains U+000D. Source CR is
normalized to LF when read, so a CR reaches the serializer only from a
character reference (`&#13;`, `&#xd;`) or from a DOM text node.
- `serialize`, `encode`, `to_source`, `sanitize` and `minify` write
`&#13;` wherever a CR appears in text or an attribute value, under the
WHATWG, MINIMAL and NAMED_ENTITIES formatters.
- An inline `style` attribute whose CSS contains a line continuation now
serializes its CR as `&#13;`. The sanitized declaration is the same
after parsing.
- Raw-text elements (`script`, `style` and the other raw-text elements)
still write their text verbatim, because character references are not
decoded there. The parser cannot put a CR in that text, so only a DOM
mutation can produce one. This change does not cover that case.

### Performance

CR is one more compare in the existing vector scan. To pay for it, the
SSE2 scan now reports where the first special is directly from the
vector compare mask. Before, it stopped at the first block that held a
special and walked that block again pair by pair. Runs shorter than one
vector step now use one overlapping block, or for one to three code
points a bitmap, in place of the pair loop. NEON and the scalar build
keep the skip-and-rescan scan.

Callgrind instruction counts inside the extension module on release LTO
builds, `PYTHONHASHSEED=0`, `setarch -R`. Each case runs at 20 and 220
repetitions, and the table shows the difference in millions of
instructions per 200 repetitions. Two separate builds of upstream/main
produce identical counts, so the noise floor on this measure is 0.

| benchmark               | upstream/main | this PR | change |
| ----------------------- | ------------: | ------: | -----: |
| serialize               |        562.02 |  500.63 | -10.9% |
| serialize-inner         |        603.08 |  541.80 | -10.2% |
| serialize-inner-indent  |        649.97 |  585.93 |  -9.9% |
| serialize-inner-minify  |       1866.77 | 1853.21 |  -0.7% |
| encode-inner            |        603.09 |  541.81 | -10.2% |
| iterate-inner           |        609.06 |  547.81 | -10.1% |
| whitespace-roundtrip    |       3432.71 | 3379.47 |  -1.6% |
| lossless-serialize      |       2634.80 | 2625.94 |  -0.3% |
| minify                  |       4112.15 | 4099.85 |  -0.3% |
| serialize-attributes    |        107.64 |  103.34 |  -4.0% |
| serialize-named         |       2046.67 | 2046.67 |   0.0% |
| sanitize-spec           |       3215.42 | 3097.27 |  -3.7% |
| serialize-xml (control) |        727.08 |  727.87 |  +0.1% |
| parse (control)         |       2121.09 | 2121.14 |   0.0% |

The serialize-xml change is an LTO inlining difference in the XML
namespace path. That path does not use the scan.
gaborbernat added a commit that referenced this pull request Nov 16, 2026
The scheduled `🧪 fuzz` workflow runs the mutation oracle in
`tools/fuzz/sanitize_oracles.py`, and it reports divergences that come
from two intended output changes rather than from a sanitizer bug. #1866
makes the serializer write U+000D as `&#13;`. #1862 unwraps an implied
`tbody`, `tr` or `colgroup` that a policy omits, so the output is no
longer a re-parse fixpoint. The oracle did not account for either
change, so it failed on correct output. This PR changes the oracle only.
The library is unchanged.

### The expected dump folded CR to LF

`_normalized_dump` replaced CR with LF on the turbohtml side. That
matched the old serializer, which wrote a raw CR, because input
preprocessing turns a raw CR into LF on re-parse. A CR in the tree now
comes only from a character reference, and the serializer writes it as
`&#13;`. html5lib-python and parse5 both read that reference back as CR,
as the WHATWG tokenizer specifies, so the fold was the only difference.
The fix removes the fold and leaves the reference parser alone.
Downgrading the finding to non-failing would have kept the fold, so the
fold itself is what changes.

The fold also hid a real defect. A serializer that wrote a raw CR was
not reported before this change, and it is reported now.

### Implied wrappers the policy omits

The sanitizer judges the children of an omitted wrapper in place and
removes the wrapper from the output (`unwrap_omitted_implied` in
`src/turbohtml/_c/clean/sanitize.c`). A browser re-creates the wrapper
when the output is parsed again. Rather than requiring the re-parse to
be a fixpoint, the comparison drops the same wrappers from the re-parse,
the way #1862 drops them from the output. The sanitized tree already
lacks omitted wrappers, so the expected dump needs no change.

The rule applies only to an attribute-less `tbody`, `tr` or `colgroup`
under its implied parent, and only when the policy omits it. A wrapper
the policy allows, or one that carries attributes, still counts in the
comparison. Nested wrappers are judged under the parent they sit in
before any unwrapping, so an omitted row under an omitted row group is
dropped too. The rule runs on both reference paths: the html5lib
re-parse, and the turbohtml re-parse used when the tree contains a
`select`. The parse5 confirmation, which runs on the findings that
remain, drops the same wrappers in
`tools/bench/node/parse5_tree_runner.js`. A finding whose only
difference is a wrapper therefore reads as `html5lib-only`, not
`confirmed`.

### Tests

`tests/test_fuzz_sanitize_oracles.py` is new. Its first group checks
that the sanitized output compares equal to its tree for the reported
shapes and for a template. Seven of the eight equal-output cases fail on
`main`; the template case passes on both and guards the template branch
of the dump, which changed signature. Its second group checks that real
divergences still fire: altered text, an attributed wrapper and a raw
CR. The raw-CR case fails on `main`.

The parse5 confirmation has unit tests that run on canned dumps without
node: the request names the wrappers the policy omits, a wrapper-only
dump is `html5lib-only`, and a divergence beside an omitted wrapper
stays `confirmed`. The runner itself runs in
`tests/conformance/test_sanitize_oracles_parse5_conformance.py`, which
the conformance job runs with node and the parse5 install present.

### Docs

`docs/development/index.rst` states the wrapper exception in the
description of the sanitizer oracle.

### Behavior changes

The oracle no longer reports the two false findings. It now reports a
serializer that writes a raw CR. The library behaves the same.

### Checks

`tox r -e fix` and `tox r -e type` pass, and the touched test file
passes. The coverage gate covers `src` and `tests` only, and this PR
changes no C file, so no C coverage or benchmark run applies.
`tools/fuzz` is outside the coverage sources.

A local `python tools/fuzz/fuzz.py --mode oracle --minutes 4` run
compared 577,296 cases and wrote no findings. That run predates the
parse5 change; the change only affects the verdict on findings, and the
run had none. That run had no ASan runtime preloaded, because the local
clang does not ship one. The CI lane runs with the sanitizer preload.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

✨ feat: WHATWG tree construction — parse() with html5lib/BeautifulSoup adapters

1 participant