Skip to content

🐛 fix(tokenizer): tokenize svg and math content as browsers do - #1988

Merged
gaborbernat merged 16 commits into
tox-dev:mainfrom
gaborbernat:sec-fix/a331gv1l
Nov 15, 2026
Merged

gaborbernat merged 16 commits into
tox-dev:mainfrom
gaborbernat:sec-fix/a331gv1l

Conversation

@gaborbernat

@gaborbernat gaborbernat commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Fixes #1714

tokenize(), Tokenizer and the html.parser shim switched into raw text, RCDATA, script data or PLAINTEXT after any start tag with one of those names, wherever the tag sat. Inside <svg> and <math> the same names are ordinary elements, and a browser keeps reading markup there. Code that reads the token stream, such as a port of an html.parser subclass, got text where a browser builds elements, and a CDATA section arrived as a comment. 🧭 Now the token stream follows the namespace of the open elements, as tree construction does.

The Tokenizer keeps a stack of the open elements, each with the namespace a browser gives it. It applies the tree-construction rules for foreign content: which start tags break out of <svg> or <math>, which elements are integration points, and which end tags close a foreign element. The stack is capped at the tree builder's nesting limit, and past it the outer half is forgotten, because the innermost elements decide the namespace. The tokenizer now interns each tag name once, and the tree builder and the rewriter read that result.

The tokenizer pairs tags as written. Implied end tags, insertion modes and the list of active formatting elements stay with the tree builder, so where a decision needs them, use parse() or saxparse rather than the token stream.

Behavior changes:

  • Inside <svg> and <math>, raw-text names are elements and their content is markup. A CDATA section there is text, and the html.parser shim delivers it to handle_data.
  • Breakout tags and integration points return to the HTML rules.
  • On malformed input where implied tags decide the result, the token stream can still differ from the tree.

tokenize(), Tokenizer and the html.parser shim switched to raw text after
any start tag named title, style, script, xmp, plaintext or another raw-text
name, also inside <svg> and <math>. There those are ordinary elements, so
the markup after them came out as one text token, and <![CDATA[ came out as
a comment instead of text. Code reading tokens missed elements a browser
builds.

The tokenizer now keeps the stack of open elements with the namespace a
browser gives each one, pairing tags as written: breakout tags, integration
points (foreignObject, desc, title, annotation-xml with an HTML encoding) and
the scope rules for HTML end tags follow the tree builder.

Ordinary HTML does not pay for the stack. Until the first svg or math start
tag the tokenizer only counts the tags it hands over and keeps the input; that
start tag rebuilds the stack by tokenizing the input again up to it. A
streaming Tokenizer keeps at most about 64K code points this way, then
follows every tag so it can reclaim consumed input.

Fixes tox-dev#1714
@gaborbernat gaborbernat added the bug Something isn't working label Nov 15, 2026
@gaborbernat
gaborbernat marked this pull request as draft November 15, 2026 05:07
@codspeed

codspeed Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 7.24%

2 warnings

⚠️ 1 benchmark with a significant change ran on different hardware

Its base and head results were measured on machines with a different CPU, core count or memory, so the change might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚠️ 1 benchmark with a significant change ran in a different software environment

Its base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the change might come from this difference rather than from the code. Open the benchmark to see what changed.

See affected benchmarks

⚡ 1 improved benchmark
✅ 581 untouched benchmarks
⏩ 89 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_feature[linkify-traversal-wide-callbacks] 2.7 ms 2.5 ms +7.24%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing gaborbernat:sec-fix/a331gv1l (f8095e3) with main (b097116)

Open in CodSpeed

Footnotes

  1. 89 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@gaborbernat
gaborbernat marked this pull request as ready for review November 15, 2026 08:32
The kind check in name_eq never failed in the tests: no font attribute
had the length of "face" or "size" with a code point outside Latin-1.
The new case covers that branch and checks that the font is not treated
as a breakout.
# Conflicts:
#	src/turbohtml/_c/dom/tree.c
#	src/turbohtml/_c/tokenizer/rewrite.c
@gaborbernat
gaborbernat merged commit 148ad9e into tox-dev:main Nov 15, 2026
30 checks passed
gaborbernat added a commit that referenced this pull request Nov 15, 2026
#1988 made the Tokenizer run inline SVG through the full
tree-construction rules for every element inside an `<svg>`. That pushed
the SVG-heavy tokenize rows past the 5% ceiling against the commit
before #1988 (`ed2b89473`). This PR records the children of an SVG
element as keys in the spare slots of the element spine and writes them
out only when a tag needs the full rules. The token output does not
change, and the rows return under the ceiling.

### What changes

Inside an SVG element that is not an integration point, a start tag that
neither breaks out of foreign content nor opens an integration point is
recorded as a bare key. An end tag that names the innermost recorded
element pops it. An `<svg>` opened from HTML, and its end tag, take a
short path too. Any tag that needs the full rules first writes the
recorded elements out, so those rules read the same spine they read
before.

`th_tag_key` in `src/turbohtml/_c/data/tag_atom.h` no longer tests a
readable length. `tools/generate_tags.py` emits that function, so the
header is regenerated. The tokenizer reserves 16 bytes for its name
buffer before any name is written, so the 8-byte read stays in bounds.

### Why the output does not change

Each recorded element gets the namespace, integration-point flag, table
flag and name that the full rules would have assigned. The spine is
complete before any rule reads it, and a tag that changes the shape of
the spine takes the full rules. `tests/tokenizer/test_svg_run.py` pins
the token output of upstream `main` for the new paths: entering and
leaving SVG, every slow-path tag inside a run, mismatched and long end
tags, the depth limit, chunked feeds at every split point, `reset()`
during a run, and `capture_attributes=False`. In the coverage build,
`tests/tokenizer/` covers every changed C line and branch.

### Performance

Callgrind on release LTO builds with `PYTHONHASHSEED=0`. Values are
instructions per call: the 220-repetition count minus the 20-repetition
count, divided by 200. Base is `ed2b89473`, the base of #1988. Main is
`739e421a3`, the commit this branch was built on. Head is this change
measured before the rebase onto `56aa6b062`. Upstream has since moved
with two commits in the selector and c14n code, and no tokenizer source
or header they include changed, so the table keeps the measured base and
main. `svg-icons` is a probe of inline icons: one `<svg>` inside a
`<span>` for each of 2,500 icons. Its base row comes from the base
build, measured with the same child script as the other rows. `escape`
is the untouched control row.

| Row | Base `ed2b89473` | Main `739e421a3` | Head | Head vs base | Head
vs main |
| --- | ---: | ---: | ---: | ---: | ---: |
| svg-mostly | 11,466,041 | 12,246,500 | 11,931,402 | +4.06% | -2.57% |
| svg-tail | 8,602,031 | 9,004,868 | 8,971,907 | +4.30% | -0.37% |
| tokenize | 8,599,402 | 9,001,956 | 8,969,130 | +4.30% | -0.36% |
| tokenize-attributes | 81,360 | 81,554 | 81,560 | +0.25% | +0.01% |
| htmlparser | 7,257,465 | 7,543,308 | 7,530,768 | +3.77% | -0.17% |
| tok-chunk8k | 8,651,553 | 9,054,295 | 9,026,943 | +4.34% | -0.30% |
| tok-x4 | 34,563,510 | 36,175,509 | 36,065,999 | +4.35% | -0.30% |
| parse | 10,350,020 | 10,125,798 | 10,112,447 | -2.30% | -0.13% |
| sax | 11,941,800 | 11,714,360 | 11,704,201 | -1.99% | -0.09% |
| escape | 269,575 | 269,575 | 269,575 | +0.00% | +0.00% |
| svg-icons | 13,047,270 | 14,032,507 | 13,675,010 | +4.81% | -2.55% |

Against base, every row is at or below +4.81%. Against main, no row is
more than +0.01% above.

### Behavior changes

None. The token output is unchanged. The change only affects how fast
the Tokenizer follows SVG content.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tokenize() switches to raw text after SVG title and style start tags

1 participant