Repository navigation
Conversation
…irectly
When an element/document handler returns a rejected promise, HTMLRewriter
was calling vm.unhandled_rejection() to route the error to the capture
slot via the quiet handler. Two problems:
1. The promise was never marked handled, so handleRejectedPromises()
reported it again on the next event loop turn: with no listener that
crashes the process with exit 1 even though the caller caught the
error; with a listener it fires unhandledRejection spuriously.
2. vm.unhandled_rejection() dispatches to process.on('unhandledRejection')
before reaching the capture handler. If a listener exists it returns
early and the capture slot stays empty, so the caller sees the
generic 'The rewriter has been stopped.' instead of the original
error.
Fix: set_handled() before wait_for_promise (so the promise is skipped by
handleRejectedPromises whether it was already rejected or rejects during
the wait), and write the rejection value straight to the capture slot
instead of routing through unhandled_rejection(). Same pattern JSBundler
uses.
|
Warning Review limit reached
Next review available in: 1 minute Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (3)
Comment |
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
|
Updated 10:14 AM PT - Jul 25th, 2026
⏳ @robobun, your commit be48445 is still building in
Add |
||||||||||||||||||||||||||||||||||||||||||||||||||||||
Install the handler-error capture scope inside run_output_sink so it is live for both the synchronous body path (init() still on the stack) and the asynchronous one (init() already returned). The async error arm now delivers the captured JS value via ValueError::JSValue instead of the generic lol-html message, so a Bun.file/fetch body catches the original error just like a string body. Also drop the two exc_value.protect() calls in the sync-throw arm: the slot is drained by create_lolhtml_error without a matching unprotect, so each caught handler throw leaked one protected Exception root. The slot is a stack local (conservatively scanned) and no JSC allocation occurs between the write and the read, so protect was never needed. Tests: expand the handler-error matrix to 4 handler shapes x 2 body kinds x 2 listener modes (16 subprocess tests), and add a heapStats regression test for the protected-Exception leak. Fixes #31804
handler_callback now marks the promise handled and writes directly to unhandled_pending_rejection_to_capture, so overriding on_unhandled_rejection to the quiet handler is no longer needed, and doing so would silently swallow any unrelated unhandled rejection that happens while wait_for_promise spins the event loop. run_output_sink now saves/sets/ restores only the capture slot. init() no longer needs its own capture scope at all (run_output_sink covers both the sync and async body paths), so drop it and keep only the tmp_sync_error channel back to init()'s throw. Dedupe the three capture-slot writes into capture_handler_error().
There was a problem hiding this comment.
Both of my earlier concerns are now addressed — the async body path installs its own capture slot in run_output_sink and forwards the original rejection as ValueError::JSValue, and the scope was narrowed to just the slot save/set/restore so unrelated rejections during wait_for_promise still hit the default handler. I didn't find further issues, but this reworks GC-sensitive state (drops the .protect() on the sync-throw arm, relies on the stack-local Cell being conservatively scanned across the lol-html error return) and rearranges VM-global unhandled_pending_rejection_to_capture ownership between init() and run_output_sink, so it's worth a maintainer pass.
What was reviewed:
- Traced sync and async paths through
init→on_finished_buffering→run_output_sink→handler_callback→create_lolhtml_error/deliver_async; the capture slot is live at every write and drained before the scopeguard restoresprev_capture. - Checked the removed
protect(): no JSC allocation betweencapture_handler_error's write and the reader; the sync path'sprotect/unprotectpair inon_finished_buffering/initis still balanced. - Confirmed
unhandled_rejection()inMode::Bunno longer reaches the quiet-capture handler (onlyunhandled_pending_rejection_to_captureis set now, noton_unhandled_rejection), so unrelated rejections aren't swallowed. tmp_sync_erroris only dereferenced on theis_async == falsepath whileinit()is on the stack; the dangling pointer on the async path is never read.
Extended reasoning...
Overview
Fixes a bug where an HTMLRewriter handler returning a rejected promise both surfaced the error to the caller AND fired unhandledRejection (setting exit code 1), and where installing an unhandledRejection listener degraded the caught error to the generic "rewriter has been stopped" message. Also fixes #31804 (leaked protected Exception roots per handler throw). Touches src/runtime/api/html_rewriter.rs (handler_callback, run_output_sink, BufferOutputSink::init, new capture_handler_error helper) plus 16 subprocess tests and one heapStats-based leak test.
Security risks
None. No untrusted-input parsing, auth, or network changes. The VM-global unhandled_pending_rejection_to_capture slot is a raw pointer to a stack local; the save/set/restore is scoped by scopeguard::defer! on both paths.
Level of scrutiny
High — this is unsafe Rust manipulating raw pointers into stack locals across re-entrant lol-html callbacks and JSC GC boundaries. The doc comment on capture_handler_error asserts "read back before any JSC allocation" as the justification for dropping .protect(); I traced the return path (handler_callback's scopeguard → directive_result → lol-html error propagation → run_output_sink reads captured) and found no JSC allocations, and the JSValue lands in a conservatively-scanned stack Cell, but this is exactly the invariant class the repo's REVIEW.md flags as most-blocked.
Other factors
This PR went through three revisions in response to my two prior reviews (async body path regression, then over-broad capture scope swallowing unrelated rejections). Both were addressed with dedicated commits and the test matrix was extended to cover the async (Bun.file) body path. The final shape is a net simplification — init() no longer touches VM rejection state at all; run_output_sink owns the capture slot for both sync and async. The comment-cop bot flags on lines 13/620/864/1268/1284 look like noise to me: the flagged comments are SAFETY/provenance notes and a doc comment referencing #31804, all shortened from the previous revision. Given the GC-safety subtlety and the iteration count, a maintainer sign-off is warranted.
There was a problem hiding this comment.
Beyond the inline nit, I re-verified my two earlier concerns against the current diff: the async-body path now installs its own capture slot in run_output_sink (so Bun.file/fetch bodies see the original error), and only unhandled_pending_rejection_to_capture is touched (unrelated rejections during wait_for_promise are no longer swallowed). Also checked that the remaining protect() in on_finished_buffering is balanced by the unprotect() in init() on the sync-error return.
Extended reasoning...
The two 🔴 findings from my prior runs are resolved in 6642419: run_output_sink now owns the capture slot on both sync and async body paths, and init() no longer installs on_unhandled_rejection/unhandled_rejection_scope() at all, so an unrelated rejection that fires while a handler awaits reaches the default handler. The capture_handler_error helper drops the protect() that leaked (#31804); the one remaining protect() on this path — on_finished_buffering protecting the sync return before write_tmp_sync_error — is paired with captured.unprotect() in init(). Deferring rather than approving: this is VM-level error routing and GC-root bookkeeping, not a mechanical change.
The third stop arm of handler_callback (handler returns an Error instance
directly) was left without a capture_handler_error call, so
element(){ return new Error(...) } still surfaced as the generic
'rewriter has been stopped'. Add the one-line capture and a fifth
handler shape to the test matrix (now 5 x 2 x 2 = 20 cases).
There was a problem hiding this comment.
All three prior findings are addressed in the current revision and I found nothing new on this pass, but this reworks GC rooting (dropping the protect() on the captured Exception) and VM-level unhandled_pending_rejection_to_capture management across the sync/async body paths — worth a maintainer's eye before merge.
Re-checked on be48445:
run_output_sinknow owns the capture slot on both body paths;init()no longer toucheson_unhandled_rejection, so unrelated rejections duringwait_for_promisereach the default handler instead of being swallowed/mis-attributed.protect()/unprotect()balance on the remaining synctmp_sync_errorpath (on_finished_bufferingprotects,init()unprotects) — paired on every exit.- The
is_error()return arm now capturesresult, and the test matrix covers it (5 handler shapes × 2 bodies × 2 listener states).
Extended reasoning...
Overview
The PR fixes two related defects in src/runtime/api/html_rewriter.rs: (1) an HTMLRewriter handler that throws or returns a rejected promise was double-reported — once to the caller and again as an unhandledRejection on the next tick — and with a listener installed the caller only saw the generic "rewriter has been stopped" message; (2) the sync-throw arm protect()ed the captured Exception without a matching unprotect() in the reader, leaking one root per caught throw (#31804). The fix marks the handler's promise handled before wait_for_promise, writes the thrown value/rejection directly into a stack-local capture slot owned by run_output_sink (covering both sync and async body paths), delivers it as ValueError::JSValue on the async path, and drops the protect(). init() no longer installs an on_unhandled_rejection override or a rejection scope. Two test files add a 20-case subprocess matrix and a heapStats().protectedObjectTypeCounts.Exception leak regression.
Prior review history
I raised three findings on earlier revisions, all now resolved: the async-body path not being covered by the capture slot (fixed by moving it into run_output_sink), the capture scope in run_output_sink being broader than needed and swallowing unrelated rejections (fixed by narrowing to only the slot pointer), and the third is_error() stop arm not calling capture_handler_error (fixed in be48445 with a matching test variant). On this pass I re-traced the sync path (init → on_finished_buffering → run_output_sink → create_lolhtml_error), the async path (deliver_async → StrongOptional::create), nested-rewriter re-entry (save/restore of prev_capture), and the remaining protect/unprotect pair on tmp_sync_error — all balanced. unhandled_pending_rejection_to_capture is otherwise only written by on_quiet_unhandled_rejection_handler_capture_value in VirtualMachine.rs, which is no longer installed here, so the default handler cannot pollute captured with an unrelated rejection.
Security risks
None. This is error-propagation plumbing in a content-transformation API; no auth, crypto, or untrusted-length arithmetic is touched.
Level of scrutiny
High. The change removes a GC root and relies on conservative stack scanning of a Cell<JSValue> local across a lol-html callback boundary, mutates a VM-wide field (unhandled_pending_rejection_to_capture) with save/restore semantics, and changes when process.on('unhandledRejection') fires. All of these fall under REVIEW.md's most-blocked categories (JSValue rooting, error-path completion, refcount balance). The fix looks correct to me and is well-tested, but the architectural choice — repurposing the VM's unhandled_pending_rejection_to_capture slot as a side-channel between handler_callback and run_output_sink rather than storing the error on the sink itself — is the kind of decision a maintainer should sign off on.
Other factors
Test coverage is strong: 20 subprocess cases (5 handler shapes × string/Bun.file body × with/without listener) each assert the caller catches the original error class, stderr is empty, the listener never fires, and exit is 0; plus a protectedObjectTypeCounts.Exception delta-zero leak test. All comment-cop and prior review threads on the PR are marked resolved.
|
CI on be48445: the new HTMLRewriter tests pass on every lane. Remaining reds are unrelated:
Ready for review. |
|
#31804 (the protected Exception leak) was fixed on main by #36511 (4454cc5), and the error routing this PR changes was reworked by #36733: handler errors now go to the pipe's All 21 tests added here (the 20 handler / body / listener subprocess cases and the protected Exception leak test) pass unchanged on current main (165dc9f, debug build), so closing. |
An element/document handler that throws or returns a rejected promise was delivering the error on two channels: once to the caller awaiting
.text(), and again as an unhandled rejection on a later event loop turn. With nounhandledRejectionlistener that sets exit code 1 even though the caller caught the error; with a listener installed it fires (twice), and the error the caller catches degrades to the genericHTMLRewriterError: The rewriter has been stopped.instead of the original. On an asynchronously-buffered body (Bun.file,fetch) the caller only ever saw the generic message.Fixes #31804.
Repro
Cause
handler_callbacknever marked the returned promise as handled, sohandleRejectedPromises()reported it again on the next tick (and insidewait_for_promise's own tick for a handler that awaits). It also routed the rejection throughvm.unhandled_rejection(), which dispatches toprocess.on("unhandledRejection")before the quiet capture handler; with a listener installed the capture slot stayed empty and the caller got the generic lol-html message.The capture slot was only live while
BufferOutputSink::init()was on the stack, so for an asynchronously-buffered body the handler's error was lost even without a listener.The sync-throw arm of the same function
protect()ed the Exception it wrote to the capture slot, but the reader (create_lolhtml_error) never unprotected it, leaking one protected Exception root per caught handler throw (#31804).Fix
In
handler_callback: mark the promise handled beforewait_for_promise, and write the thrown value / rejection directly to the capture slot viacapture_handler_error()(noprotect(), no detour throughvm.unhandled_rejection()).In
run_output_sink: install the capture slot aroundwrite()/end()so it is live on both the sync and async body paths, and have the async error arm deliver the captured JS value asValueError::JSValueinstead of the stringified lol-html error. Only the capture slot is touched;on_unhandled_rejectionis left alone so an unrelated rejection that happens while a handler awaits is still reported normally.init()no longer needs its own capture scope (dropped).Tests
html-rewriter.test.js: 16 subprocess cases (sync throw / async throw before first await /Promise.reject/ async throw after await, each against a string body and aBun.filebody, each with and without anunhandledRejectionlistener). All assert the caller catches the original error class, stderr is empty, the listener never fires, and exit code is 0.html-rewriter-leak.test.ts:heapStats().protectedObjectTypeCounts.Exceptionstays flat across 200 caught handler throws.[review] gate passed · iteration 2 · 3 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 1 rejected · iteration 2
evidence per changed file