Skip to content

🐛 fix(rewrite): stop after a failed body replay - #2540

Merged
gaborbernat merged 2 commits into
tox-dev:mainfrom
gaborbernat:fix/rewrite-comment-exc
Nov 21, 2026
Merged

gaborbernat merged 2 commits into
tox-dev:mainfrom
gaborbernat:fix/rewrite-comment-exc

Conversation

@gaborbernat

Copy link
Copy Markdown
Member

rewrite() raised SystemError instead of MemoryError when an allocation failed at one particular point.

After the first edit, the rewriter replays the input into a tree to find where the body starts (rw_start_following()). If allocating that tree failed, it set MemoryError and returned, but the token loop in turbohtml_rewrite() still handed the current token to its handler. A Python handler then ran with the exception already set, so its next call failed with SystemError: ... returned a result with an exception set.

A minimal trigger is a document with an edit before a comment and a comment handler:

rewrite(
    "<!doctype html><!--old--><p>old</p>",
    comments=lambda comment: comment.set_text("new"),
    doctype=lambda doctype: doctype.before("<!--before-->"),
)

When the tree allocation fails, the comment handler's set_text call raised SystemError. The loop now stops as soon as rw_start_following() reports the failure, so rewrite() raises MemoryError.

The new rewrite-handler-after-edit case in the allocation-failure sweep (tests/_html/fuzz/test_self_test.py) fails every allocation of that call in turn. On main it yields SystemError for one of them; with this change every one raises MemoryError. The scheduled fuzz runs found this crash in fuzz_dom_rewrite.

When the rewriter could not allocate the tree it replays to find the
body, it set MemoryError but still passed the current token to its
handler. The handler then ran with the exception pending, and the next
Python call raised SystemError instead of MemoryError. The token loop
now stops as soon as that allocation fails.
@gaborbernat gaborbernat added the bug Something isn't working label Nov 21, 2026
@codspeed

codspeed Bot commented Nov 21, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 580 untouched benchmarks
⏩ 91 skipped benchmarks1


Comparing gaborbernat:fix/rewrite-comment-exc (30b2aea) with main (a58211e)

Open in CodSpeed

Footnotes

  1. 91 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 merged commit 732f828 into tox-dev:main Nov 21, 2026
65 checks passed
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.

1 participant