Skip to content

HTMLRewriter: stop the rewriter when worker terminate() interrupts an awaited async handler - #36100

Closed
robobun wants to merge 11 commits into
mainfrom
farm/69496f5a/htmlrewriter-worker-terminate-assert
Closed

robobun wants to merge 11 commits into
mainfrom
farm/69496f5a/htmlrewriter-worker-terminate-assert

Conversation

@robobun

@robobun robobun commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Repro

// worker.mjs
postMessage("start");
const doc = "<p>a</p>".repeat(100);
await new HTMLRewriter()
  .on("p", {
    async element(el) {
      el.setAttribute("x", "1");
      postMessage("in-handler");
      await new Promise(() => {});
    },
  })
  .transform(new Response(doc))
  .text();
// main.mjs  (run on an assert-enabled build: debug or release-asan)
const w = new Worker(new URL("./worker.mjs", import.meta.url).href);
w.onmessage = ev => { if (ev.data === "in-handler") w.terminate(); };
ASSERTION FAILED: !exception()
JavaScriptCore/ExceptionScope.h(61) : void JSC::ExceptionScope::assertNoException()

Deterministic on debug+ASAN. Needs two or more matching tokens; a single-token document is clean. Release builds survive (no JSC asserts) and the worker exits with code 1.

Cause

Every lol-html handler bridge (on_element / on_comment / on_text / on_doctype / on_end / on_end_tag) funnels into handler_callback, which spins the event loop via wait_for_promise when a handler returns a promise. If terminate() arrives during that wait, the loop breaks on execution_forbidden() with the promise still Pending and a TerminationException set on the VM. handler_callback then checked only promise.status() == Rejected, returned false, and lol-html dispatched the next matching token's handler. cb.call() → JSC::call → Interpreter::executeCallImpl then asserts !exception() and aborts the process.

Fix

handler_callback now checks for a pending exception:

  • on entry (before allocating the token wrapper and before cb.call()), so a stale pending exception from any path never reaches executeCallImpl;
  • immediately after wait_for_promise, so an interrupted wait returns the stop directive;
  • in the Err arm and the post-call check, where scope.clear_exception() would otherwise clear a TerminationException raised at a safepoint inside the handler body.

Returning true maps to lol-html's stop directive and unwinds the rewrite without re-entering JS. This matches the existing gate EventLoop::run_callback already carries for the same failure mode.

create_lolhtml_error now recognizes a pending TerminationException (which tryClearException() leaves set) and returns undefined instead of the Exception cell, so the termination propagates rather than being surfaced as the transform's rejection value.

Verification

test/js/workerd/html-rewriter-worker-terminate.test.ts spawns a worker that parks inside an async handler, terminates it once it reports in-handler, and checks the parent prints survived and exits 0. The matrix covers every handler bridge (element with both a never-settling promise and a timer await, text, comments on .on(), and comments / text on .onDocument()). Without the fix all six abort on assert builds and stdout is empty; with the fix the worker closes and all six pass.


[review] gate passed · iteration 1 · 2 files touched

fails on main (without fix)
ASAN without fix: 8 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/workerd/html-rewriter-worker-terminate.test.ts
bun test v1.4.0 (89ce58105)

test/js/workerd/html-rewriter-worker-terminate.test.ts:
108 |       stderr: "pipe",
109 |     });
110 | 
111 |     const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
112 | 
113 |     expect({ stdout, stderr, exitCode }).toEqual({ stdout: "survived\n", stderr: "", exitCode: 0 });
                                               ^
error: expect(received).toEqual(expected)

  {
-   "exitCode": 0,
-   "stderr": "",
-   "stdout": 
- "survived
- "
+   "exitCode": 134,
+   "stderr": 
+ "ASSERTION FAILED: (null)
+ !exception()
+ /root/.bun/build-cache/webkit-549170099226f816-debug-asan/include/JavaScriptCore/ExceptionScope.h(61) : void JSC::ExceptionScope::assertNoException()
+ no stacktrace available"
  ,
+   "stdout": "",
  }

- Expected  - 5
+ Received  + 7

      at <anonymous> (/workspace/bun/test/js/workerd/html-rewriter-worker-terminate.test.ts:113:42)
(fail) terminate() while HTMLRewriter is parked
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (4d5388465)

test/js/workerd/html-rewriter-worker-terminate.test.ts:
(pass) terminate() while HTMLRewriter is parked in an async handler > onDocument comments [24.48ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > text [25.94ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > element (timer await) [40.07ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > element (never-settling) [46.90ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > comments [47.40ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > onEndTag [45.11ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > onDocument text [46.40ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > element (Bun.file body) [45.04ms]

 8 pass
 0 fail
 8 expect() calls
Ran 8 tests across 1 file. [203.00ms]
__F:0:S:0
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/workerd/html-rewriter-worker-terminate.test.ts
bun test v1.4.0 (89ce58105)

test/js/workerd/html-rewriter-worker-terminate.test.ts:
(pass) terminate() while HTMLRewriter is parked in an async handler > element (never-settling) [490.52ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > element (timer await) [459.38ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > comments [466.24ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > text [486.16ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > onDocument comments [472.90ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > onDocument text [453.94ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > onEndTag [461.47ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > element (Bun.file body) [449.88ms]

 8 pass
 0 fail
 8 expect() calls
Ran 8 tests across 1 file. [2.96s]
__F:0:S:0

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 662ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/5] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited
[1/5] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_runtime v0.0.0 (/workspace/bun/src/runtime)
�[1m�[92m   Compiling�[0m bun_bin v0.0.0 (/workspace/bun/src/bun_bin)
�[1m�[92m    Finished�[0m `release` profile [optimized + debuginfo] target(s) in 4m 00s
[2/5] link bun-profile
[3/5] bun-profile --revision
1.4.0-canary.1+89ce58105
[5/5] strip bun
[build] done
bun test v1.4.0-canary.1 (89ce58105)

test/js/workerd/html-rewriter-worker-terminate.test.ts:
(pass) terminate() while HTMLRewriter is parked in an async handler > element (never-settling) [56.40ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > comments [72.32ms]
(pass) terminate() while HTMLRewriter is parked in an async handler > onEndT
... (truncated)
diff hotspot
src/runtime/api/html_rewriter.rs                   |  68 ++++++++----
 .../workerd/html-rewriter-worker-terminate.test.ts | 115 +++++++++++++++++++++
 2 files changed, 162 insertions(+), 21 deletions(-)

gate history · 6 passed · 0 rejected · iteration 1

evidence per changed file
file                                                    reads  edits  tests
src/runtime/api/html_rewriter.rs                           11     11      0
test/js/workerd/html-rewriter-worker-terminate.test.ts      4     15      0

…an awaited async handler

When a worker's transform() is parked inside wait_for_promise for an
async element/document handler and terminate() arrives, the wait breaks
with the promise still Pending and a TerminationException set on the VM.
handler_callback then returned false, so lol-html dispatched the next
matching handler into JS with that exception pending, tripping
Interpreter::executeCallImpl's assertNoException() and aborting the
process on assert-enabled builds.

Check the scope for a pending exception both on entry to
handler_callback and immediately after wait_for_promise, and return the
stop directive so lol-html unwinds instead of re-entering JS.
@robobun

robobun commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

Reproduced on debug+ASAN with bun bd test test/js/workerd/html-rewriter-worker-terminate.test.ts (aborts at ExceptionScope::assertNoException). Passes with the fix; existing test/js/workerd/html-rewriter* and test/regression/issue/htmlrewriter-additional-bugs.test.ts remain green.

The test matrix covers element/text/comment handlers on .on(...), el.onEndTag(...), and comment/text on .onDocument(...), plus a Bun.file-backed body for the is_async == true buffering arm of run_output_sink.

CI: the diff is green for HTMLRewriter. Build 83335 failed on test/bake/deinitialization.test.ts (dev-server ASAN UAF) and build 83387 failed on test/js/bun/http/serve.test.ts (darwin x64 EPIPE in request-body backpressure), both unrelated to this change and reported to main-break triage. The remaining failures on 83387 are flaky on other lanes (fastutf8stream-reopen, node-tls-getpeercert-leak, require-cache, 20144). Ready for review.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

HTMLRewriter now preserves pending termination exceptions across output and callback paths, stops processing after worker termination, and adds concurrent coverage for blocked asynchronous handlers across multiple entry points and input types.

HTMLRewriter termination handling

Layer / File(s) Summary
Output error preservation
src/runtime/api/html_rewriter.rs
Async write and end failures skip additional error propagation when a JavaScript exception is already pending.
Termination-aware callback control flow
src/runtime/api/html_rewriter.rs
Checks exceptions before callbacks, after callbacks, and after promise waits, returning early for termination exceptions.
Worker termination regression coverage
test/js/workerd/html-rewriter-worker-terminate.test.ts
Tests blocked element, text, comment, end-tag, and document handlers with inline and file-backed HTML input.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely summarizes the main fix: stopping HTMLRewriter when terminate() interrupts an awaited async handler.
Description check ✅ Passed It covers the repro, cause, fix, and verification, though it uses custom section headings instead of the exact template.

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. ASAN CI: ExceptionScope::assertNoException during worker terminate (worker-transfer-terminate-stress, separate from #34095) #34690 - Fixes the ASSERTION FAILED: !exception() crash in ExceptionScope::assertNoException during worker terminate, by adding exception guards in handler_callback before calling into JS and after wait_for_promise

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #34690

🤖 Generated with Claude Code

@robobun

robobun commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator Author

This does not fix #34690. Same ExceptionScope::assertNoException signature but a different call path: #34690 hits it during MessagePort transfer / worker bootstrap (worker-transfer-terminate-stress.test.ts), whereas this PR only touches html_rewriter.rs::handler_callback. The HTMLRewriter crash has a deterministic stack through Bun__JSValue__call ← on_element/handler_callback ← lol-html's handlers_dispatcher::handle_start_tag, which is not on the #34690 path.

Comment thread src/runtime/api/html_rewriter.rs Resolved
…or in test

The entry-guard ran after Z::init + ref_() (refcount=2) but before to_js
adopted the second +1 into a GC wrapper, so returning true there would
strand one ref. Move the handler/global/scope setup and the check above
the allocation so every return true is refcount-balanced.

Also wire the worker 'error' event in the test fixture to reject the
in-handler wait so a future regression before the handler is reached
surfaces its message instead of an empty-stdout diff.
Comment thread src/runtime/api/html_rewriter.rs Resolved
Comment thread src/runtime/api/html_rewriter.rs Resolved
Comment thread src/runtime/api/html_rewriter.rs Resolved
Comment thread src/runtime/api/html_rewriter.rs Resolved
Comment thread src/runtime/api/html_rewriter.rs Resolved
Comment thread src/runtime/api/html_rewriter.rs Resolved
@robobun

robobun commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 8:06 AM PT - Jul 27th, 2026

❌ @robobun, your commit 89ce581 has 1 failures in Build #83387 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 36100

That installs a local version of the PR into your bun-36100 executable, so you can run:

bun-36100 --bun

…it and in create_lolhtml_error

Extend the stop-on-termination check to the remaining paths where
handler_callback observes a pending exception: the Err arm and the
post-call check both call scope.clear_exception(), which (unlike
tryClearException) clears a TerminationException. Return the stop
directive with it still pending instead.

create_lolhtml_error now recognizes a pending TerminationException and
returns undefined rather than the Exception cell, so the termination
propagates instead of being surfaced as the transform's rejection.

Test covers every lol-html handler bridge (element/text/comments on
.on() and comments/text on .onDocument(), plus both timer-await and
never-settling promise shapes).
Comment thread src/runtime/api/html_rewriter.rs Resolved
Comment thread src/runtime/api/html_rewriter.rs Resolved
Comment thread src/runtime/api/html_rewriter.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/workerd/html-rewriter-worker-terminate.test.ts`:
- Around line 92-97: In the subprocess test’s result assertions, remove the bare
console.error(stderr) call and add an if (exitCode !== 0) block that asserts
stderr is empty immediately before expect(exitCode).toBe(0). Preserve the
existing concurrent Promise.all draining of stdout, stderr, and process exit,
along with the stdout assertion.
- Around line 4-16: Extend the test cases collection in the worker termination
test to include the missing onDocument doctype and end handlers. Keep the
existing comments and text cases, and configure the new cases through the same
handler_callback path so every onDocument bridge listed in the test header is
exercised.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5ad2ed6b-4db7-4937-b0cd-4562c7b0798d

📥 Commits

Reviewing files that changed from the base of the PR and between 4eb6f99 and 027c313.

📒 Files selected for processing (2)
  • src/runtime/api/html_rewriter.rs
  • test/js/workerd/html-rewriter-worker-terminate.test.ts

Comment thread src/runtime/api/html_rewriter.rs Resolved
The sync arm of run_output_sink goes through create_lolhtml_error, which
already bails on a pending TerminationException. The is_async twin calls
to_error_instance directly; skip it when an exception is pending so the
body-promise reject path cannot re-enter JS during worker teardown.

Add a Bun.file-backed body cell so the is_async=true buffering path is
exercised under the same terminate-during-wait scenario.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
test/js/workerd/html-rewriter-worker-terminate.test.ts (1)

81-112: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert stdout, stderr, and exit together
The stderr check is skipped on the success path, so a passing run can still emit errors. Fold all three results into one assertion so every case checks the full subprocess result.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/js/workerd/html-rewriter-worker-terminate.test.ts` around lines 81 -
112, Update the subprocess result assertions in the terminate() test to validate
stdout, stderr, and exitCode together for every case. Remove the conditional
stderr check and assert the complete expected result, preserving the existing
expected output, empty stderr, and zero exit code.

Source: Coding guidelines

src/runtime/api/html_rewriter.rs (1)

1435-1439: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Preserve the termination path here. JSValue::UNDEFINED is not a no-error sentinel on the sync path: it gets stored in sink_error and later treated as a throwable value, so termination can surface as throw undefined. Thread an explicit termination/no-error result through the caller and skip sink_error storage for that case.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime/api/html_rewriter.rs` around lines 1435 - 1439, Update the
termination handling around tryClearException() and its caller so termination is
represented by an explicit no-error outcome rather than JSValue::UNDEFINED.
Propagate that outcome through the synchronous transform path and avoid storing
it in sink_error, while preserving normal error values and termination behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/workerd/html-rewriter-worker-terminate.test.ts`:
- Around line 66-79: Update the worker lifecycle flow in mainMjs so worker error
events reject a separate workerError promise, rather than only rejecting
inHandler. Race workerError with both inHandler and closed, ensuring any
subprocess failure after the handler resolves still rejects instead of allowing
“survived” to print.

---

Outside diff comments:
In `@src/runtime/api/html_rewriter.rs`:
- Around line 1435-1439: Update the termination handling around
tryClearException() and its caller so termination is represented by an explicit
no-error outcome rather than JSValue::UNDEFINED. Propagate that outcome through
the synchronous transform path and avoid storing it in sink_error, while
preserving normal error values and termination behavior.

In `@test/js/workerd/html-rewriter-worker-terminate.test.ts`:
- Around line 81-112: Update the subprocess result assertions in the terminate()
test to validate stdout, stderr, and exitCode together for every case. Remove
the conditional stderr check and assert the complete expected result, preserving
the existing expected output, empty stderr, and zero exit code.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 62db5781-3ddb-4be0-853c-129c776c2199

📥 Commits

Reviewing files that changed from the base of the PR and between 027c313 and c0ab6a6.

📒 Files selected for processing (2)
  • src/runtime/api/html_rewriter.rs
  • test/js/workerd/html-rewriter-worker-terminate.test.ts

The previous create_lolhtml_error special-case returned UNDEFINED on a
pending TerminationException, which on the sync path was stored via
write_tmp_sync_error and later passed to throw_value. Guard both sync
and async arms at the same place and drop the UNDEFINED branch so
termination never reaches either error path.

Test: race a dedicated workerError promise with both inHandler and
closed so a worker error after the handler resolves is surfaced; assert
stdout/stderr/exitCode together via toEqual.
…h; drop create_lolhtml_error UNDEFINED special-case

Returning UNDEFINED from create_lolhtml_error on the sync path was stored
via write_tmp_sync_error and later passed to throw_value. Guard both
sync and async arms together and let create_lolhtml_error stay on its
pre-PR shape (callers now never reach it with termination pending).
Comment thread src/runtime/api/html_rewriter.rs Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found — all prior review threads (refcount balance on the entry guard, the async run_output_sink arm, test dedup, onEndTag coverage) are resolved in the current diff. Deferring only because this is JSC exception-scope handling across a worker-termination boundary; worth a human glance at the global.has_exception() gates in run_output_sink and the sync-path return None under a pending TerminationException.

What was reviewed:

  • handler_callback reorder: Z::init/ref_()/scopeguard now sit below the entry scope.has_exception() check, so every return true is refcount-balanced (2→1 via guard, 1→0 via GC wrapper on paths after to_js; nothing allocated on the entry path).
  • is_termination_exception() early-returns precede scope.clear_exception() so the termination stays pending for run_output_sink to observe.
  • run_output_sink guards are hoisted above the is_async branch so both sync and async error arms skip JS re-entry; create_lolhtml_error no longer needs a special case.
  • Test matrix covers all six repeated-dispatch bridges plus the async-body arm; error is wired to reject via a raced workerError promise; combined {stdout, stderr, exitCode} assertion.
Extended reasoning...

Overview

Two files: src/runtime/api/html_rewriter.rs (+47/−21) and a new test at test/js/workerd/html-rewriter-worker-terminate.test.ts (+115). The fix adds four TerminationException/pending-exception guards to the shared handler_callback<H, Z, L> generic (entry, cb.call Err arm, post-call check, post-wait_for_promise) and two global.has_exception() gates to run_output_sink (after write() and end() fail). The wrapper-allocation block (Z::init → ref_() → scopeguard) was moved from above top_scope! to below the new entry guard.

Security risks

None. This is a crash-on-worker-terminate fix; no user-controlled input reaches new parsing or allocation. The only behavioral change is that an interrupted async handler now stops the rewriter instead of re-entering Interpreter::executeCallImpl with a pending exception.

Level of scrutiny

High. This is unsafe Rust bridging lol-html callbacks into JSC, with intrusive refcounting, exception scopes, and re-entrancy across wait_for_promise. The changes are additive guards plus one code-motion, and I traced refcount balance on every terminal path — but JSC exception-scope semantics under validateExceptionChecks and the interaction between TerminationException and try_take_exception()/clear_exception() are subtle enough that a maintainer familiar with the JSC bindings should confirm the run_output_sink sync-path return None (which lets init() return Ok(response_js_value) with the termination still pending) is the intended shape.

Other factors

This PR went through five review rounds: my earlier passes flagged the entry-guard refcount leak (fixed by moving Z::init below the check), the unguarded is_async arm (fixed by hoisting the has_exception() gate above the branch), test duplication (folded into the matrix), and the missing onEndTag cell (added). CodeRabbit's stderr-assertion and workerError-race feedback was applied. The github-actions comment-cop flags on the two-line guard comment were reasonably declined. Evidence in the PR body shows 5/7 cells crash on main (debug+ASAN) and 7/7 pass with the fix; release-build behavior is unchanged. is_termination_exception() is an established pattern used identically in fetch.rs, TopExceptionScope.rs, and JSGlobalObject.rs.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No further issues found — all four prior rounds of feedback (wrapper-alloc ordering, async run_output_sink arm, fixture dedup, onEndTag cell) are addressed and the 8-cell matrix passes on assert builds. Deferring to a human because the fix sits at the intersection of TerminationException propagation, scope.clear_exception(), and wait_for_promise re-entry, which is subtle enough to warrant a maintainer's sign-off.

What was reviewed:

  • handler_callback: entry guard now precedes Z::init/ref_() so the early-return path does not leak the wrapper's second +1; is_termination_exception() gates both clear_exception() sites.
  • run_output_sink: has_exception() hoisted above the is_async branch on both write() and end() Err arms; sync-path None return leaves the pending termination for JSC to unwind on host-fn return (entering JS is what asserts, not returning).
  • is_termination_exception() / has_exception() usage matches the established pattern in TopExceptionScope.rs and report_active_exception_as_unhandled.
  • Test: describe.concurrent + test.each over 8 cells, pipes drained concurrently, combined {stdout, stderr, exitCode} assertion, Bun.file cell exercises is_async == true.
Extended reasoning...

Overview

Fixes a debug/ASAN-build process abort (ASSERTION FAILED: !exception() in Interpreter::executeCallImpl) when Worker.terminate() lands while an HTMLRewriter async content handler is parked in wait_for_promise. Touches src/runtime/api/html_rewriter.rs (guards in handler_callback and run_output_sink; wrapper allocation reordered after the entry guard) and adds test/js/workerd/html-rewriter-worker-terminate.test.ts (8-cell subprocess matrix).

Security risks

None. No user-controlled input parsing, no auth/crypto, no new API surface. The change adds early-return guards on an existing termination path.

Level of scrutiny

High. This is native JSC exception handling around worker termination — the exact category REVIEW.md calls out ("Never clearException()", "Exception checks after every call that can enter JS"). The fix is small and pattern-matched to existing is_termination_exception() usage, but the interaction between TerminationException (which tryClearException refuses to clear), scope.clear_exception() (which would clear it), lol-html's next-token dispatch, and the sync/async run_output_sink twins is subtle enough that a maintainer should confirm the guard placement is complete.

Other factors

This PR has been through four automated review rounds; every inline comment (mine, CodeRabbit's, comment-cop's) is resolved. The evidence block shows the test fails on main (exit 134, JSC assert in stderr) and passes on both debug+ASAN and release with the fix. The create_lolhtml_error special-case mentioned in the PR description was superseded by the hoisted run_output_sink guard in 4d53884 — I confirmed no other caller of create_lolhtml_error is reachable with a pending termination. The one open judgment call — whether global.has_exception() (vs. a scope-based check) is the right probe in run_output_sink — looks fine given it's only gating a bail-out, not paired with a fresh throwing call, but that's the kind of thing a maintainer familiar with the top_scope! validation rules should confirm.

@robobun

robobun commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: this is fixed on current main by #36733, which removed the nested wait_for_promise from the HTMLRewriter handler callback (async handlers now suspend the rewriter instead), so there is no longer a pending TerminationException to trip over when a worker is terminated mid-handler. This PR's test file (test/js/workerd/html-rewriter-worker-terminate.test.ts, all 8 cases) passes unmodified against a debug build of main at 04148c8, twice in a row.

@robobun robobun closed this Aug 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants