Skip to content

Add streaming HTML insertion methods - #12758

Merged
zcorpan merged 6 commits into
mainfrom
noamr/stream-html
Nov 5, 2026
Merged

zcorpan merged 6 commits into
mainfrom
noamr/stream-html

Conversation

@noamr

@noamr noamr commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Introduce safe and unsafe streaming HTML parsing and insertion methods returning a WritableStream:

  • Element & ShadowRoot: streamHTML(), streamHTMLUnsafe(), streamAppendHTML(), streamAppendHTMLUnsafe(), streamPrependHTML(), and streamPrependHTMLUnsafe()
  • NonDocumentTypeChildNode: streamBeforeHTML(), streamBeforeHTMLUnsafe(), streamAfterHTML(), streamAfterHTMLUnsafe(), streamReplaceWithHTML(), and streamReplaceWithHTMLUnsafe()

Key behaviors and parser updates:

  • Stream operations: writeAlgorithm and closeAlgorithm convert chunks to DOMString, append chunks (or an explicit "EOF" character on close) to the parser's input stream, and run the fragment parser. closeAlgorithm waits for any pending parser-blocking scripts via fragment parser close promise. abortAlgorithm aborts the fragment parser (deferring via fragment parser abort requested if currently running), marks open script elements on the stack as already started, and unblocks rendering on pending scripts.
  • Displaced reference child: If referenceChild is no longer a child of target when a node would be inserted before it or when another chunk is written, invalid reference child steps error the stream (and reject fragment parser close promise if closing) with a "HierarchyRequestError" DOMException and abort the fragment parser. Elements that would be inserted before a displaced referenceChild are created in the appropriate template contents owner document with a null custom element registry and dropped, and the adoption agency algorithm skips removing lastNode.
  • Validation, Trusted Types & DOM mutations: Target validation (throwing "NotSupportedError" for HTML/SVG script context elements, or "HierarchyRequestError" for html targets or invalid parent for HTML streaming), HTMLTemplateElement redirection to template contents, and Trusted Types / SanitizerConfig validation occur synchronously before returning the stream or mutating the DOM.
  • Scripts, custom elements & fragment parsing:
    • Extracts initialize an HTML fragment parser. When runScripts is true, script target document is context's node document; otherwise it is the temporary inert document.
    • Parser-blocking, defer, async, and module scripts follow normal HTML parser pausing and execution order.
    • Custom element upgrades/callbacks when inserting into a connected target run before any subsequent script via a dedicated element queue; other reactions when streaming HTML use the backup element queue.
    • The speculative HTML parser is not started in the fragment case. Speculative fetches from the fragment parser are still allowed, except when sanitizing or for elements that will be dropped. The end (stops parsing) returns early for fragment parsers.
    • Elements whose intended parent is the fragment root html element are created directly in the target's (or fragment's) node document.
    • SVG script elements are only processed when the parser's script target document is not the parser's Document and the script element is connected (which also applies to document parsing when an ancestor of an SVG script was disconnected before </script>).
    • Elements removed or replaced with their children by the sanitizer are created in the appropriate template contents owner document with a null custom element registry and not inserted into the DOM. Their descendants look up a null registry from them too. This also applies to the non-streaming methods that use the HTML fragment parsing algorithm with a sanitizer (setHTML(), setHTMLUnsafe(), etc.), where previously the whole fragment was parsed (and custom elements upgraded) before sanitization.

Note: Pre-existing adoption agency algorithm edge cases (#13093) are out of scope for this PR.

Closes #2142

(See WHATWG Working Mode: Changes for more details.)


/dynamic-markup-insertion.html ( diff )
/index.html ( diff )
/infrastructure.html ( diff )
/parsing.html ( diff )
/references.html ( diff )
/scripting.html ( diff )
/xhtml.html ( diff )

@noamr noamr changed the title Add streaming HTML insertion methods Streaming HTML insertion methods Aug 5, 2026
@noamr noamr changed the title Streaming HTML insertion methods Stream HTML into element or ShadowRoot Aug 5, 2026
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 7b105e3 to e24c23b Compare August 5, 2026 09:31
@noamr
noamr force-pushed the noamr/stream-html branch from df24ea2 to e416732 Compare August 5, 2026 09:32
@noamr noamr closed this Aug 5, 2026
@noamr noamr reopened this Aug 5, 2026
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from e24c23b to aae1d67 Compare August 6, 2026 13:24
@noamr
noamr force-pushed the noamr/stream-html branch from e416732 to 5106e9d Compare August 6, 2026 16:23
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from aae1d67 to 4ff3705 Compare August 6, 2026 19:31
@noamr
noamr force-pushed the noamr/stream-html branch from deb55bb to e97c374 Compare August 6, 2026 19:46
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 4ff3705 to 8551681 Compare August 7, 2026 20:17
@noamr
noamr force-pushed the noamr/stream-html branch from d5a18a7 to b19b385 Compare August 7, 2026 20:17
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
Comment thread source Resolved
@noamr
noamr force-pushed the noamr/stream-html branch from d87ab8d to 4880d38 Compare August 11, 2026 15:49
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from c374a0b to e8c7cba Compare August 11, 2026 20:09
@noamr
noamr force-pushed the noamr/stream-html branch from 2de75ec to ce9f49b Compare August 11, 2026 20:18
noamr added a commit to web-platform-tests/wpt that referenced this pull request Aug 12, 2026
See whatwg/html#12758

Note that tests that assert how this works with <template for>
are still tentative as that PR is still not landed.

@zcorpan zcorpan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM % spaces

Comment thread source Resolved
Comment thread source Resolved
@noamr
noamr force-pushed the noamr/stream-html branch from 421aa3f to 043dcdf Compare August 12, 2026 13:02
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 2e1181e to 1d9e935 Compare August 12, 2026 13:25
@noamr
noamr force-pushed the noamr/stream-html branch from 043dcdf to 286c499 Compare August 12, 2026 13:25
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 1d9e935 to 4453c2a Compare August 12, 2026 16:07
@noamr
noamr force-pushed the noamr/stream-html branch from 286c499 to 146266b Compare August 12, 2026 16:08
@zcorpan zcorpan mentioned this pull request Aug 14, 2026
5 tasks done
@noamr
noamr force-pushed the noamr/streaming-sanitizer branch from 4453c2a to 931141c Compare August 14, 2026 08:52
@noamr
noamr force-pushed the noamr/stream-html branch from 146266b to 6e5c251 Compare August 14, 2026 08:56
@noamr noamr closed this Aug 14, 2026
@noamr noamr reopened this Aug 14, 2026
@annevk

annevk commented Oct 20, 2026

Copy link
Copy Markdown
Member
AI feedback

Reviewed at c471a4f, with web-platform-tests/wpt#61748 at 40837d5. The Build check passes. Line numbers are for source at c471a4f; links go to the PR diff, and lines outside it are marked "unchanged". I traced write/close/abort re-entrancy, the pause and resume around parser-blocking scripts, prepare the script element (including the #13080 async behavior for createContextualFragment() and setHTMLUnsafe()), and the Trusted Types and Streams calls, and they look right. All 18 IDL members have matching method steps, and [CEReactions] is on exactly the methods that mutate synchronously.

Blockers

  • Nodes dropped after the reference node is displaced still have side effects, and the loss isn't reported. If the reference node is moved or removed by script that runs during parsing (a streamed script, a custom element reaction, or the parser-blocking script the parser was waiting on), the rest of that run is still parsed, but nodes that would be inserted before the reference node are dropped:
    • create an element for a token redirects intendedParent to the target (source:146977), so the element is created in the live document. insert an element at the adjusted insertion location then drops it (source:147280), but it's still pushed onto the stack of open elements and its descendants are built inside it. So image and media fetches can start, and custom element constructors run (through the upgrade queued at creation), for markup that never reaches the DOM.
    • The sanitizing parser goes out of its way to keep markup that doesn't reach the DOM inert: no speculative fetches while sanitizing (source:146960, unchanged), removed elements created in the appropriate template contents owner document so they "do not invoke side effects such as loading images" (source:147013), and a null registry so no constructor runs (source:147032, unchanged). Dropped nodes get none of that, so the safe methods have effects outside their sanitized result whenever the config allows images, media, or custom elements (the built-in default allows none of them). The Unsafe methods behave the same way.
    • The loss is silent and timing-dependent. The write resolves and so does close() (WPT E1); an error is only reported if another write follows, and moving the node back lets the stream carry on (WPT E2). For example, take loading.streamBeforeHTMLUnsafe({runScripts: true}) with markup that ends in <script>loading.remove()</script> followed by more content. If the trailing content arrives in the same chunk, it's silently dropped; if it arrives later, pipeTo() rejects. If the parser was waiting on a <script src> near the end, close() has often already been called, so whatever follows that script and would go before loading disappears while close() succeeds.
    • Chromium does the same: HTMLConstructionSite::CreateElement() takes its document from OwnerDocumentForCurrentNode(), which resolves to the target's document, and Insert() returns early when InsertionLocation::IsValid() fails. So this needs a decision in the spec rather than an implementation fix.
    • Consider checking when the element is created, since checking at insertion is too late: in create an element for a token, if the redirect's reference child is no longer a child of its target parent, create the element in the appropriate template contents owner document with a null registry, like an element the sanitizer removes, so its whole subtree stays inert. Also consider erroring the stream at that point (Streams' "error a WritableStream") and rejecting a pending fragment parser close promise, which abort a parser doesn't settle today. WPT E1 and E2 would need to change. A test like the existing removeElements one, but with a config that keeps img and a custom element, would cover the side effects.

Suggestions

  • PR description (commit message):
    • It says isStream is set to true; the Trusted Types parameter is throwIfMissing.
    • It says the script target document is "the redirected target's node document", but initialize an HTML fragment parser uses the context element's node document (source:153054). They differ for template.
    • Consider listing the normative changes to existing APIs:
      • the end now returns early for fragment parsers. On main it spins the event loop unconditionally, even for innerHTML.
      • Elements whose intended parent is the root are now created directly in the fragment's node document, not in the inert document and then adopted.
      • Fragment parsers that don't run scripts no longer process SVG script (source:151589), although the description calls SVG script processing (Define SVG's script element #902) out of scope.
      • Elements the sanitizer removes or replaces with their children are now created in the appropriate template contents owner document, also for parseHTML().
    • Consider condensing it; it's long for a commit message.
    • The MDN box is ticked, but the issue hasn't been filed yet.
  • create an element for a token note (source:146982): it says "When streaming HTML", but the redirect changes which document elements are created in for all fragment parsing. Consider rewording.
  • Microtask timing between streamed scripts depends on what drives the parser. During a write the JavaScript execution context stack is never empty (the write runs under writer.write() or a Streams reaction), so neither the </script> checkpoint (source:150156, unchanged) nor "clean up after running script" runs microtasks between scripts. In the task that resumes after a parser-blocking script, both do. So <script>queueMicrotask(…)</script><script>…</script> can order differently depending on network timing. Consider at least documenting this.
  • Intro (source:127264): document.write() from a streamed inline script implies document.open() whenever the live document has no insertion point, which includes while it's still loading, not only after it has finished parsing. Consider rewording.
  • Note in the in head script steps (source:148075): "document.write() calls … will execute in-line" isn't true for streamed scripts, which write to the live document. Consider saying it applies to a document's own parser.
  • The script-created parser dfn (source:126038, unchanged) still describes only document.open() and document.close(), but the streaming parser is now also script-created (source:128028). Consider updating it the way the "EOF" paragraph was.
  • XSLT guidance (source:69472, unchanged): the cross-document check moved from parser document to intended document, so XSLT-created scripts now also need an intended document to keep that check. Consider updating the bullet.
  • New parser state (source:144031): consider a sentence each for script target document, fragment parser running, aborted, fragment parser abort requested, and fragment parser close promise, especially script target document, which decides whether scripts may run.
  • stream HTML (source:127977) takes a boolean safe where its siblings take a fragment parser mode, and derives runScripts differently from fragment parsing algorithm steps. Consider aligning them.
  • Domintro (source:127349, source:127380, and siblings): streams don't "reject" (writing rejects, or the stream errors); "no longer a child of its parent" can't happen as written ("of node's original parent"); "at the time of calling the method" is awkwardly placed; and "executed as they are parsed" only holds for connected targets.
  • XML fragment parsing algorithm (source:153548, unchanged) still computes context inline, linked to a dfn that now reads contextElement. Consider using parser context element there too.
  • Intro (source:127289): the blocking="render" sentence only applies to defer and module scripts when the stream is never closed (parser-blocking scripts are unblocked when they run), and only before the document has a body. Consider making that explicit.

Nits

  • Intro (source:127251): setHTML() never runs scripts; compare with setHTMLUnsafe() instead.
  • parent for HTML streaming note (source:127965): only beforeHTML(), afterHTML(), replaceWithHTML(), and their Unsafe versions do nothing without a parent, and the streaming methods aren't "HTML insertion methods" under that dfn.
  • abortAlgorithm note (source:128131): the last sentence reads like a non sequitur.
  • Streams dependency (source:2822): lowercase "set up", like the other entries.
  • source:128136: Streams' own convention is "with writeAlgorithm set to writeAlgorithm, …".
  • source:127983, source:128401, source:153031: the "Assert: … is non-null" is redundant, since parser context element never returns null.
  • adjusted insertion location (source:147180): "Return the parser's insertion target redirection map[targetParent]" would do; "target container" (source:147184) isn't a defined term; source:147194 wraps early.
  • source:153005: "disconnected DocumentFragment" → one whose host is null.
  • source:149701: the continuation line is indented 4 spaces instead of 3.
  • source:151992: avoid referring to "Step 3".
  • the end (source:151683): "the Document's" and "the parser's Document" in the same step.
  • execute the pending parsing-blocking scripts: "until A, or B and C" is ambiguous (source:151858); the stream can also be errored by a failed write, not only aborted (source:151878); "the insertion point" and "the parser pause flag" should be parser's (source:151889).
  • source:150221: "connected element" → "connected target" (shadow roots too).
  • initialize an HTML fragment parser: consider a parser variable (source:153045), and setting allow declarative shadow roots unconditionally alongside the other "Set the parser's …" steps (source:153100).
  • start the speculative HTML parser (source:152116): add a "(fragment case)" marker.
  • source:128053 duplicates the intro at source:127281.

@noamr

noamr commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

AI feedback

Changed the behavior of mid-chunk reference child displacement to error the stream.
Constructed elements already in the chunk might still have side effects (like in the main parser today if you have an <img src> after targetParent.remove() in the same stream or some such), but the stream would be errored and thus not "silent".

Applied all nits and suggestions.

@annevk

annevk commented Oct 20, 2026

Copy link
Copy Markdown
Member
AI feedback

Reviewed at 0bcd1ee (follow-up to my earlier comment), with web-platform-tests/wpt#61748 at 8c22eae. The Build check passes. Line numbers are for source at 0bcd1ee; links go to the full diff against main, and lines outside it are marked "unchanged". The displacement fix works on the main path: elements created while the reference node is displaced, and their subtrees, are now inert, the stream errors, and a pending close() rejects. I traced this for errors during a write, during a close, and in the task that resumes after a parser-blocking script. Almost all earlier suggestions and nits are applied.

Blockers

  • The adoption agency algorithm can still remove content that was already inserted and build what follows into the live document. It computes the insertion location, which runs the invalid reference child steps, but then still removes lastNode unconditionally (source:150039, unchanged) and can't reinsert it, because the location is stale. For example, with parent connected and window.ref set to the reference node:

    const w = ref.streamBeforeHTMLUnsafe({runScripts: true}).getWriter();
    await w.write("<b><p>Hello");                                       // inserted before ref; resolves
    await w.write("<script>ref.remove()</script></b><img src=/pixel>"); // rejects

    </b> runs the adoption agency algorithm with the root as common ancestor. The <p> holding "Hello", inserted by an earlier write that already resolved, is removed from the DOM. Afterward the current node is that detached <p>, which isn't redirected, so the <img> is created in the live document, fetches /pixel, and never reaches the DOM. Consider skipping the removal of lastNode when refNode is non-null and isn't a child of target; then the <p> stays in the DOM and the <img> goes into it. A WPT test for this case would help.

Suggestions

  • The optional speculative mock element step at the start of create an element for a token (source:146999, unchanged) runs before the new staleness check, so for Unsafe streams without a sanitizer a user agent can still speculatively fetch for dropped elements. Consider moving the check before it, or skipping that step for fragment parsers.
  • Any node that would go before a displaced reference node now errors the stream, including whitespace: a stream ending in <script>loading.remove()</script>\n makes pipeTo() reject because of the trailing newline. Consider calling this out in the intro, or exempting whitespace-only text.
  • Commit message:
    • It's still long; consider condensing it.
    • The SVG item says fragment parsers with parser scripting disabled no longer process SVG script, but the spec's condition only checks the script target document (source:151653).
    • The end returns early for all fragment parsers, not only non-streaming ones.
    • "Any elements created while referenceChild is no longer a child of target are created in the appropriate template contents owner document" doesn't hold for the adoption agency case above.
    • The closing note still calls SVG script processing (Define SVG's script element #902) out of scope, while the list includes the SVG change.
    • The MDN box is ticked, but the issue is deferred to Blink shipping.

Nits

  • source:147014: the note still says "before intendedParent is possibly redirected in the next step", but intendedParent is no longer redirected; targetParent is computed instead.
  • source:147027: wraps early.
  • source:147053 and the step after it repeat the same staleness test; consider computing it once.
  • source:127261: "JS execution stack" should be "JavaScript execution context stack", and checkpoints also happen at </script> before the script is prepared, so "only when the script finishes executing" isn't quite right.
  • source:127283: the stream only errors once a node would be inserted before the moved node or another chunk is written, which the new WPT test for moving the node back relies on.
  • source:144072: abort a fragment parser sets aborted only by calling abort a parser.
  • source:127407, source:127593: the streamAfterHTML() domintros still say "node's parent" rather than its original parent.
  • These new lines exceed 100 columns: source:127253, 127271, 127636, 127763, 128156, 144099.

@zcorpan

zcorpan commented Oct 20, 2026

Copy link
Copy Markdown
Member

Consider moving the check before it, or skipping that step for fragment parsers.

I think we shouldn't skip it for fragment parsers; speculative fetches there should be allowed.

@zcorpan

zcorpan commented Oct 21, 2026 •

Copy link
Copy Markdown
Member
AI review

Reviewed at 1f7ee1a, together with web-platform-tests/wpt#61748 at 8c22eae. This covers the whole spec diff and all 53 test files. Each finding below was checked against the spec text and the test source. The spec diff has no new blockers. The test PR hasn't been updated since before the last three spec commits, and four of its tests are broken.

Blockers

  • wpt domparsing/stream-html-reentrancy.html:128-157: since 1f7ee1a this test contradicts the spec.
    • Setup: the parser resumes from the queued task after slow.js. No write is in progress, so the inline script's abort() runs the sink's abort algorithm synchronously, and that sets fragment parser abort requested.
    • The tokenizer now stops when that flag is set (source:144213-144216), so <p id='b'> and the rest_parsed script are never parsed.
    • The test still expects ["a", "b"] and rest_parsed === true.
    • Before 1f7ee1a an abort during a write and an abort from the task both parsed the rest of the input. Now only the write case does.
    • Either update the test to expect ["a"], or confirm the asymmetry is intended. If it is, the note at source:128168-128171 should say parsing stops after the current token, not just that the abort is deferred.
  • wpt domparsing/stream-html-parser-blocking-script.html:315-332 (D5) and 366-383 (D7) can't fail. The unclosed script was never prepared, so it's still parser-inserted. Appending text reaches the post-connection steps, which return early for parser-inserted scripts (source:68511-68518) whether or not already started is set. Consider inserting script.cloneNode(true) instead, as unclosed-script-already-started.html does: cloning copies already started, and the clone isn't parser-inserted.
  • wpt domparsing/stream-html-parser-blocking-script.html:406-433 (F5) and stream-html-stylesheet-does-not-block-scripts.html:48-65 can't fail. A <link> made with createElement() never contributes a script-blocking style sheet, because it wasn't created by the document's parser (source:19484-19491). The tests would pass even in a browser that wrongly waited on the live document's sheets. Consider creating the pending sheet through a parser, e.g. an iframe with an unclosed document.open()/document.write('<link rel=stylesheet href=slow.css?pipe=trickle(d3)><div id=target>').
  • wpt domparsing/stream-html-parser-blocking-script.html:522-543 (F12) can't fail. After iframe.remove(), parent is null in the iframe (source:98451-98454), so parent.iframe_blocked_ran = true would throw even if the script ran. Consider having the streamed script call a function defined in the parent's realm.

Suggestions

  • source:151674-151677: the new "the script element is connected" condition also applies to document parsing. For example, <div id=d><script>d.remove()</script><svg><script>…</script></svg> no longer processes the SVG script. I think this matches engines, but it changes behavior outside streaming. Consider mentioning it in the commit message and adding a test.
  • PR description: the SVG bullet is inverted. It says SVG scripts are processed only when the script target document "is the parser's Document", but the spec processes them when it is not. The bullet also leaves out the new connected condition.
  • wpt: these behaviors from 39eb4dc, b07a79f and 1f7ee1a have no tests:
    • Adoption agency at the root after the reference node is displaced, e.g. <b><p>x then <script>ref.remove()</script></b>. The <p> should stay and the write should reject.
    • <template for> after the reference node is displaced.
    • A chunk whose only token after displacement is whitespace or a comment should error the stream.
    • close() after displacement with no further write should resolve, since only the write algorithm checks (source:128093-128096).
    • An SVG script with runScripts: true that isn't connected (disconnected target, or an ancestor removed by the sanitizer) must not run.
    • Displacement with a ShadowRoot target. The domintro promises an error for shadowRoot.streamPrependHTML(), but only element targets are tested.
    • Displacement for streamAfterHTML, which is left out of every displacement loop in stream-insertion-logic.html (lines 90 and 218).
  • wpt domparsing/stream-insertion-logic.html:313-392: the parser now stops right after the first token following displacement. So the nested custom elements, <section> subtree and later <img>s in these two tests are never tokenized, and their assertions don't test what the test names say. Consider one test per kind of first token: a custom element, an <img>, and a child of a replaceWithChildrenElements element.
  • wpt domparsing/stream-html-with-trusted-types-adopt.tentative.html:59-70 and stream-html-with-trusted-types-from-non-tt.tentative.html:51-56: these expect Trusted Types enforcement to follow the node document after adoption. The method steps use this's relevant global object, which adoption doesn't change. Either switch the spec to the node document's relevant global object (which existing Trusted Types adoption tests for setAttribute() assume), or flip these expectations.
  • wpt domparsing/stream-sanitizer-resource-fetch.html:135: the control expects exactly one request. The spec now allows an extra speculative fetch for non-sanitizing fragment parsers (source:147032), and deduplication is left to caching rules that aren't specified. Consider asserting at least one request.
    • [Edit: It may be true that deduplication/caching isn't properly specified yet, but double-fetching I would say would be considered a bug. So I think the test should still assert one request.]
  • wpt html/semantics/scripting-1/the-template-element/template-for/stream-append-has-invalidation.html:37-41: "Green (no span)" has no <?start name="content"?>, and </template> removes the consumed start marker. From the second iteration on, <template for=content> matches nothing, so only the first iteration tests anything. Consider prefixing that content with a new start marker.
  • wpt domparsing/move-head-during-prepend-before-close-crash.html:9-15: per spec documentElement.streamPrependHTML() throws, so a conforming implementation always takes the body fallback and the head removal doesn't matter. Consider documentElement.streamHTML(), which is allowed, and class="test-wait" until close() settles.
    • [Edit: since this was a crash test, keeping the tested path seems valuable even if the spec requirements have changed. Could maybe change it to a regular test to expect the exception, and add a separate test for streamHTML()+close().]
  • wpt domparsing/stream-html-abort-unblocks-rendering.html:33-49, 82-98: both streams start at once, so if the defer case fails to unblock rendering, the first test's requestAnimationFrame check fails too. Consider running them one after the other, or splitting them into two files.

Nits

  • wpt domparsing/stream-fragment-context.html:188: >= 1 passes for Before and After even if nothing is inserted, since initialTd stays. Consider asserting the exact tr.innerHTML.
  • wpt domparsing/stream-html-stylesheet-does-not-block-scripts.html:84-88: the comment says close() doesn't wait for the parser, but it does (source:128144-128151), so the step_wait isn't needed.
  • wpt domparsing/stream-insertion-logic.html:145: if (await stream_insert_before(...)) is always true, so the if can go. Lines 115 and 135 pass "DOMException" as the description argument to promise_rejects_dom.
  • wpt template-for/stream-append-has-invalidation.html:47 and stream-append-positional-pseudo-class-invalidation.html:81: the test names are empty strings.
  • wpt domparsing/stream-html-sanitizer.html:305: in the test name, "effect" should be "affect".

@noamr

noamr commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

AI review

Thanks! Addressed in here in the WPT.

Blockers

  • stream-html-reentrancy.html: Updated the expectation to ["a"] and rest_parsed to false. Also clarified the note in stream HTML's abortAlgorithm to explain that when the parser is running from a queued task, fragment parser abort requested is set and the tokenizer stops after the current token.
  • stream-html-parser-blocking-script.html (D5 & D7): Updated to insert script.cloneNode(true) so it tests that already started was copied to a non-parser-inserted clone.
  • stream-html-parser-blocking-script.html (F5) & stream-html-stylesheet-does-not-block-scripts.html: Created the pending <link rel="stylesheet"> via an unclosed iframe.contentDocument.open()/write() (plus a task turn) so it contributes a script-blocking style sheet.
  • stream-html-parser-blocking-script.html (F12): Passed a callback from the parent's realm instead of accessing parent after iframe.remove().
    Suggestions & Nits
  • SVG script connected check: Mentioned in the commit message and PR description (and fixed the inverted script target document bullet), and added a document-parsing test in stream-html-run-scripts-option.html.
  • Added WPT coverage for: adoption agency at the root after displacement, <template for> after displacement, whitespace/comment-only chunk after displacement, close() after displacement with no further write, disconnected/sanitized-ancestor SVG <script> with runScripts: true, ShadowRoot displacement, streamAfterHTML displacement, and split first-token displacement tests (custom element, <img>, and replaceWithChildrenElements child).
  • stream-html-with-trusted-types-adopt.tentative.html & stream-html-with-trusted-types-from-non-tt.tentative.html: Flipped expectations to match this's relevant global object.
  • stream-sanitizer-resource-fetch.html: Kept assert_equals(requestCount, "1") per your edit.
  • template-for/stream-append-has-invalidation.html & stream-append-positional-pseudo-class-invalidation.html: Re-emitted <?start name="content"?> before "Green (no span)" and added test names.
  • move-head-during-prepend-before-close-crash.html: Kept the documentElement.streamPrependHTML() crash path and added documentElement.streamHTML() + head.remove() + await writer.close() with test-wait (stream-html-element.html already asserts the HierarchyRequestError throw).
  • stream-html-abort-unblocks-rendering.html: Switched to promise_test so the two tests run sequentially.
  • Applied all WPT nits (tr.innerHTML assertion, removed step_wait, cleaned up stream-insertion-logic.html, "affect" typo).

@zcorpan

zcorpan commented Oct 22, 2026 •

Copy link
Copy Markdown
Member
AI review and fixes

Reviewed at 60f91db and again at b9dec97, together with web-platform-tests/wpt#61748 at 5b249c3 and 49e13af

All findings from the previous review are addressed. I've pushed fixes for the new findings below to both branches, one commit each, and self-reviewed them: lint.sh and ./wpt lint are clean. With these fixes, all 47 test files load in Chrome Canary with experimental features and no harness error. The remaining failures are cases where Chrome hasn't caught up with the spec. The new document-parsing SVG test (stream-html-run-scripts-option.html), plus a srcdoc variant, passes in Firefox Nightly, Chrome Canary and Safari TP.

Blockers

  • wpt domparsing/stream-insertion-logic.html:599: the JS comment contains a literal </script>, which ends the test's <script> element early. The whole file has failed with a SyntaxError since web-platform-tests/wpt@8c22eae (my earlier review missed this). Fixed in web-platform-tests/wpt@b9f9b63.
  • wpt domparsing/stream-insertion-logic.html:487: in the new adoption agency test, p.textContent is "xwindow.remove_ref();", because the second write's <script> is inserted inside the still-open <p>. So the test fails in a conforming implementation. Fixed in web-platform-tests/wpt@4c40ec8 by asserting p.firstChild.data.
  • wpt domparsing/stream-html-run-scripts-option.html:153: the new test name contains a literal </script>, which ends the inline script. The file failed with a SyntaxError and none of its subtests ran. Fixed in web-platform-tests/wpt@2afe799.

Suggestions

  • source:152171: before 60f91db, the first speculative fetch rule only applied when the speculative HTML parser met a base or meta element. 60f91db made it apply to every element created in a document with a browsing context. For example, an innerHTML <base href> on a detached div would change URLs for later speculative fetches, even though it's never inserted or processed. Fixed in b9dec97 by restoring the original "If the speculative HTML parser encounters one of the following elements" wording.
  • wpt domparsing/move-head-during-prepend-before-close-crash.html:19-21: my earlier suggestion was off. streamHTML() removes head synchronously (source:127642-127643), so document.head?.remove() did nothing. Fixed in web-platform-tests/wpt@49e13af: the test writes <head></head> first, so there's a head to detach before close().
  • wpt domparsing/stream-html-with-trusted-types-adopt.tentative.html and stream-html-with-trusted-types-from-non-tt.tentative.html: my earlier suggestion offered flipping these, but I hadn't checked engines. After adoption, Chrome Canary and Firefox Nightly enforce Trusted Types based on the node document for innerHTML and setHTMLUnsafe() (Chrome for the streaming methods too), even though HTML passes this's relevant global object for all of them. The existing trusted-types/Element-setAttribute-respects-Elements-node-documents-globals-CSP-after-adoption-* tests assume the node document too. Fixed in web-platform-tests/wpt@38f96d8 by reverting the flip, so these tentative tests match engines. The spec mismatch covers every Trusted Types sink, so a separate issue for it seems better than changing only the streaming methods here.

Nits

  • source:147111: the note said descendants of elements the sanitizer replaces with their children get no speculative fetch. Those descendants are redirected into the real target (adjusted insertion location), so they do get one. Fixed in e0bc188 to say "descendants of removed or dropped elements".
  • source:147007: inside the speculative parser, "the parser's Document" could be read as the isomorphic copy that parser writes into (source:152237-152240). That copy's list of speculative fetch URLs resets on every restart. Fixed in 58be8b0 by saying which Document is meant.
  • wpt domparsing/stream-insertion-logic.html:430: if an implementation wrongly loads the dropped <img>, the load can happen after cleanup has deleted window.on_dropped_img_event. That gives a harness ERROR instead of a clean FAIL. Fixed in web-platform-tests/wpt@e8b1f5b by calling the handler with ?.().

@zcorpan

zcorpan commented Oct 22, 2026 •

Copy link
Copy Markdown
Member
AI review and fixes

Reviewed at b9dec97, together with web-platform-tests/wpt#61748 at 38f96d8

This was a fresh full pass: separate reviews of the spec's API layer, its tree construction changes, and the tests. I also ran all test files in Chrome Canary with experimental features, and in Firefox Nightly, which doesn't implement streaming, to catch tests that pass anyway. Line numbers below are at the reviewed commits.

I pushed a fix for each finding, one commit each, except where noted, and self-reviewed them: lint.sh and ./wpt lint are clean, and the changed test files run in Chrome Canary and Firefox Nightly with no harness errors. Of the two new tests, Chrome Canary passes the SVG one and fails the registry one, because it still uses the old document's definition.

Open questions

  • @noamr: content inside an element the sanitizer replaces with its children is silently dropped when script moves the foster-parenting table it was stored against (see the source:147337 suggestion below). Do you want a fallback there, e.g. to the stream's own insertion point, or is dropping fine?

Blockers

  • source:151682-151686: a streamed SVG script still ran after the target was moved to another document. With runScripts: true into a target in document A, if script moves the target into an iframe's document B, a later <svg><script> is created in B, is connected, and the script target document (A) isn't the parser's Document, so it was processed in B. HTML scripts are stopped by the intended-document check (source:68687). Fixed in 604b4c7 by also requiring the script target document to be null (document parsing) or the script element's node document. Test: web-platform-tests/wpt@41f8fb7.
  • wpt domparsing/stream-html-abort-unblocks-rendering.html:72-99: the defer test couldn't fail, and my earlier suggestion caused this. Once the tests ran one after the other, the defer test started after <body> existed, so the document no longer allows adding render-blocking elements (source:12419-12421), and there was nothing for the abort to unblock. Fixed in web-platform-tests/wpt@b32d9bc by moving it into stream-html-abort-unblocks-rendering-defer.html.

Suggestions

  • source:147034-147046: top-level elements got their registry from the parser's root html element. That root is created with the target's registry (source:153201-153204) and isn't updated when the target is adopted into another document. So after a move, new top-level elements were created in the new document with the old document's global registry. Fixed in 6e3cc21 by looking up the registry from the target in that case. Test: web-platform-tests/wpt@a052219.
  • source:147337: for an element the sanitizer replaces with its children, the stored (targetParent, referenceChild) can be a foster-parenting table. If script moves the table, every later child of the replaced element is silently dropped, and the stream doesn't error, because the stream's own referenceChild is fine (source:128061-128062). Without the sanitizer, those children go into the element. Falling back to (redirectedParent, null) would append after the stream's referenceChild when redirectedParent is the target, so I didn't change the behavior (see the open question above). f4fb692 fixes the note at source:147274-147281, which said this case errors the stream.
  • wpt: about 50 subtests passed in Firefox Nightly without the feature. The "throws TypeError" Unsafe cases passed because calling a missing method also throws a TypeError. Fixed in web-platform-tests/wpt@544374d by asserting the method exists first.
  • wpt domparsing/stream-html-with-trusted-types-createParserOptions-order.html:40: for Append and Prepend the receiver was a div, which never reaches the html-element check (source:127726, source:127749). So the ordering wasn't tested for those two. Fixed in web-platform-tests/wpt@c8aaf82.
  • wpt domparsing/stream-html-parser-blocking-script.html:35-56: both scripts pushed "slow", so the order wasn't observable. Fixed in web-platform-tests/wpt@d5ab8e7 with an optional tag parameter for slow.js.
  • wpt domparsing/stream-html-parser-blocking-script.html: several cleanups, and waitForResource(), wait on promises that never settle when the behavior is missing or wrong. One failure then stalled the rest of the file with a harness timeout instead of failing. Fixed in web-platform-tests/wpt@676cdb1 by giving up after 3s.

Nits

  • source:127294-127296: the note said scripts stop executing once the target moves to another document. That's only true while the target is in that document. If the target is disconnected at </script>, the script runs when the target is later inserted, as with document parsing. Fixed in 1cc0458.
  • wpt domparsing/stream-html-run-scripts-option.html:113, 212: the queries could match elements left in #placeholder by the previous test. Fixed in web-platform-tests/wpt@af63853.

@zcorpan

zcorpan commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

@noamr: content inside an element the sanitizer replaces with its children is silently dropped when script moves the foster-parenting table it was stored against (see the source:147337 suggestion below). Do you want a fallback there, e.g. to the stream's own insertion point, or is dropping fine?

I discussed this with @noamr. We think dropping in this case is best. I'll add a test. Edit: web-platform-tests/wpt@f50b348

@zcorpan

zcorpan commented Oct 26, 2026

Copy link
Copy Markdown
Member
AI review and fixes

Reviewed at 604b4c7, together with web-platform-tests/wpt#61748 at f50b348

All findings from my previous review are addressed, and f50b348 covers the decision to drop children of a replaced element after its table moves. I've pushed a fix for each new finding below to both branches, one commit each, and self-reviewed them: lint.sh, the html-build build and ./wpt lint are clean. All 49 changed test files run in Chrome Canary (experimental features) and Firefox Nightly with no harness errors or timeouts. The remaining Chrome failures are places where Chrome doesn't match the spec yet. The new document-parsing SVG test passes in Chrome Canary and Firefox Nightly, and fails in Safari TP.

Open questions

  • @noamr: Chrome Canary differs from the spec on two of the new tests. It still runs a streamed script when a microtask at that script's </script> checkpoint aborts the stream (see the source:152107 suggestion). And it doesn't run connectedCallback synchronously for a reconstructed formatting element (see the source:147550 suggestion). Are these worth Chromium bugs?
  • Follow-up: in Document.parseHTML() with a sanitizer, associating a form control with the form pointer based on targetParent would match the unsanitized parse. The PR made that change, and I reverted it (see the source:147229 suggestion). If you want it, it seems better as a separate change with a test.

Blockers

  • source:147295-147355, insert an element at the adjusted insertion location: the PR moved the structural early returns after the sanitizer step, which made Assert: if targetParent is a Document, then action is not "Replace with children" reachable. Example: a streamed script runs document.replaceChild(t, document.documentElement) on the foster-parenting table, then a replaceWithChildrenElements element follows. Fixed in f0e859b: the three checks from main come first again, and the abort and displacement checks stay after the sanitizer step. Test: web-platform-tests/wpt@6f78c59 (Chrome Canary puts the children inside the table, though its document parsing drops them).
  • wpt domparsing/stream-insertion-logic.html:538-560: the whitespace and comment tests removed ref_node between writes, so the write algorithm rejected before parsing. The new early returns in insert a character and insert a comment were never reached. Fixed in web-platform-tests/wpt@c031e51 by displacing it in the same chunk.
  • wpt domparsing/stream-fragment-context.html:327-341: the textarea test can't fail for popping, since a textarea's value follows its children either way. Fixed in web-platform-tests/wpt@3e855ed with a <style>, whose sheet is only created once it's popped.
  • wpt domparsing/stream-insertion-logic.html:605-609: close() on an errored stream rejects with a TypeError (Streams' WritableStreamClose step 2), not HierarchyRequestError. Fixed in web-platform-tests/wpt@a8e5af7, which also checks that writer.closed rejects with HierarchyRequestError.

Suggestions

  • source:147036-147047: children of an element the sanitizer replaces with its children took their registry from that element. It's never inserted, so it isn't updated when the target is adopted. My 6e3cc21 only fixed this for the root html element. Fixed in dc4940b by looking up from targetParent whenever the insertion is redirected. Test: web-platform-tests/wpt@54b8afb.
  • source:152107-152113, abort a fragment parser: </script> performs a microtask checkpoint before the script is prepared. If a microtask there (e.g. a mutation observer) aborted the stream, the abort was only deferred and the script still ran. Fixed in 7bcc78b by marking the scripts on the stack of open elements as already started when deferring, as abort a parser does later anyway. Test: web-platform-tests/wpt@826ac2a.
  • source:151690-151694: the rewritten SVG script condition only checked the node document when script target document is non-null. So document parsing still processed an SVG script that was moved to another document before its end tag, unlike HTML scripts. Fixed in 143c028. Test: web-platform-tests/wpt@5490fce. Chrome Canary and Firefox Nightly already don't run it; Safari TP does.
  • source:147550, 147631 and 147659: insert a character, insert a comment and insert a processing instruction didn't check fragment parser abort requested, unlike elements. So text after an abort from a reaction in the same token was still inserted, e.g. after a reconstructed <b is=…> whose connectedCallback aborts. Fixed in 8aa768f, which also updates the abortAlgorithm note. Tests: web-platform-tests/wpt@d8948cc, plus web-platform-tests/wpt@f814dda for the existing element branch.
  • source:147229: form association changed from intendedParent to targetParent. This step only runs for the document parser, so the change only affected Document.parseHTML() with a sanitizer, where it was unannounced and untested. Fixed in c02ebee by keeping intendedParent (see the follow-up above).
  • wpt: several awaits on promises that only streamed scripts resolve, or on close() while a parser-blocking script is pending, had no timeout. One failure stalled the rest of the file. Fixed in web-platform-tests/wpt@b103b02. Also, stream-html-reentrancy.html tests could pass on globals left over from earlier ones. Fixed in web-platform-tests/wpt@1523d4e.
  • wpt stream-html-with-trusted-types-runScripts-off.html and …-runScripts-cannot-be-turned-on.html: the safe-method cases couldn't fail, since safe methods always remove scripts. Fixed in web-platform-tests/wpt@4b13962 and web-platform-tests/wpt@b745071. The second file is renamed to …-runScripts-can-be-turned-on.html, which is what it tests.
  • wpt domparsing/stream-html-run-scripts-option.html:141-154: the document-parsing SVG test isn't about streaming. Moved to svg/scripted/ in web-platform-tests/wpt@527d0ba.
  • wpt coverage: streaming into an element in an XML document (web-platform-tests/wpt@2c7f8ce), streamHTML() replacing template contents (web-platform-tests/wpt@80373e6), and abort() while a write that aborts the parser is in flight, which reaches abortAlgorithm's aborted check (web-platform-tests/wpt@879e633). I didn't add a test for the realm of the rejection errors, since it seems low priority.

Nits

  • source:127363-127374, 127528-127546: the ShadowRoot streamPrependHTML() domintros didn't cover an empty shadow root. Fixed in 3eee9c6.
  • source:127631: the streaming section had no warning that the Unsafe methods don't sanitize by default. Fixed in 3a768ab.
  • source:127285, 128169: the notes overstated what's still parsed. After displacement the rest of the chunk isn't parsed. After an abort from a script in the chunk, parsing only continues up to any parser-blocking script. Fixed in 8ea13dd.
  • source:147392: the backup element queue note said it avoids chunk-boundary-dependent timing; it's the reverse. Fixed in 21a87b2.
  • source:150319: the note said a streamed script only blocks with a connected target, but a disconnected target's open element can be moved into a document. Fixed in a07bada.
  • source:69553 and 153654-153678: the noscript content model and the XML fragment parsing algorithm still linked to the renamed context dfn. Fixed in de4a74b and 6f7656e.
  • I didn't change the "tasks that invoke the tokenizer" wording in execute the pending parsing-blocking scripts. It predates this PR and is harmless for fragment parsers.
  • wpt: added streamReplaceWithHTML() to the sanitizer img test (web-platform-tests/wpt@4071ec8), removed a duplicate no-policy test (web-platform-tests/wpt@c69db15), replaced named access (web-platform-tests/wpt@37ad36b), dropped an assertion that couldn't fail (web-platform-tests/wpt@843232f), and dropped a streaming help link from a <template for> test (web-platform-tests/wpt@89a69f6). I also replaced a 20 ms wait for a dropped <img> with a control image (web-platform-tests/wpt@7e6b213).

@noamr

noamr commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Pushed a rebase onto main along with follow-up fixes from reviewing the rebased diff and web-platform-tests/wpt#61748:

Normative fixes

  • Confined "in head" <template for> the body element → parent scope promotion to when scope is in the stack of open elements (d5f6d7aef), so streaming into document.body cannot patch markers in <head>, while document.documentElement.streamHTMLUnsafe() and main document parsing still can.
  • Returned early in "in head" <template> start-tag handling if fragment parser abort requested became true during <template> element creation (d5f6d7aef, e.g., writer.abort() from a customized built-in <template is="..."> constructor when resuming from a task), avoiding attaching a declarative shadow root or patching live markers after abort.

Editorial & markup fixes

  • Clarified external defer and non-async "module" script timing in the streaming intro, domintros, and closeAlgorithm note; updated the *Unsafe domintros to describe script connectedness/same-document checks at parse time; and replaced undefined "of the target" in Element.streamPrependHTML(Unsafe) domintros (9b528ebf1).
  • Bound <var>script</var> before popping in #scriptForeignEndTag so bullets link to <var>script</var> instead of HTML's #the-script-element (8663374ad).
  • Caught the DOMString conversion exception <var>e</var> explicitly in writeAlgorithm, aligned promise realm phrasing (in realm) with Web IDL, reset fragment parser close promise to null after resolving in stop parsing (2dca01c07), and wrapped remaining <ul> <li> / <dl class="switch"> <dd> contents in <p> (8663374ad, 0add57caf).

WPT updates (web-platform-tests/wpt#61748)

  • Added html/semantics/scripting-1/the-template-element/template-for/stream-head-scope.html and customized built-in <template> constructor abort() subtests in domparsing/stream-html-reentrancy.html (6a7f22fbbf).
  • Expanded ShadowRoot, CharacterData (Text, Comment, ProcessingInstruction), [NewObject], and Document/DocumentFragment non-exposure coverage, guarded against vacuous passes in unimplemented browsers, fixed <link rel="help"> URLs, and added missing test cleanups (6af5565108, 701e761419, 559eccc65e, b977a8f5c9).

@noamr

noamr commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

AI review

Review rounds 3–4: findings and fixes

I reviewed again from the current heads and fixed what I found. A second, independent pass over the result found nothing further in the spec, and only the three small test items listed at the end. Those are fixed too, so this has converged.

Note on one of my own earlier changes: web-platform-tests/wpt@9610b68516 from round 2 had a bug, fixed in web-platform-tests/wpt@42c8629746 (see below).

Spec (#12758)

  • invalid reference child steps could wrongly error the stream (cff6c14). adjusted insertion location step 6 runs invalid reference child steps whenever any stored (redirectedParent, redirectedReferenceChild) pair is invalid. That includes the (section, table) pair stored for a replaceWithChildrenElements element that was foster parented before a streamed <table>. stream HTML's steps only checked "If referenceChild's parent is target, then return", without checking which reference child was invalid. So if script moved that <table> while referenceChild was also temporarily out of place, the next insertion into the replaced element errored the stream with "HierarchyRequestError". That contradicts the note saying such content is silently dropped. Fix: pass the invalid reference child to invalid reference child steps, and return unless it is referenceChild and referenceChild is still out of place. Test: web-platform-tests/wpt@c99e5a0816. It passes in Chrome Canary, and would fail under the old wording.
  • Unprepared script elements in fragment parsing kept a non-null parser document and intended document (299cdf3). With the Fragment scripting mode gone, an unclosed <script> at EOF, or one left open when the parser is aborted, is marked already started but never prepared. So it kept pointing at the parser's Document. In the fragment case, these are now set to null at "text" mode EOF, in abort a parser, and in the deferred branch of abort a fragment parser. This can't be observed: already started stays true and force async is unchanged, so .async stays false for an unclosed <script>, which is intentional and matches document parsing. Because it's unobservable, there's no test.
  • Editorial: missing commas after "e.g." in the #html-streaming-methods intro (e51821e).

Tests (web-platform-tests/wpt#61748)

  • Bug from my round 2 commit in stream-html-reentrancy.html (web-platform-tests/wpt@42c8629746). My </template> abort test filtered <?start name="m">Old<?end> by Node.COMMENT_NODE, but these are ProcessingInstruction nodes. Once an engine got past the preceding assertion, the check could never pass. It now checks Node.PROCESSING_INSTRUCTION_NODE (['start:name="m"', "end:"]) and #patched.textContent === "Old". The commit also adds the remaining streamed-script globals to delete_script_globals().
  • Displaced foster-parenting <table> with a temporarily displaced ref_node, plus cross-realm checks (web-platform-tests/wpt@c99e5a0816, web-platform-tests/wpt@4a1effb72b). This covers the spec fix above. A new test also checks that the WritableStream and the displacement "HierarchyRequestError" are created in this's relevant realm, using promise_rejects_dom with the iframe's DOMException.
  • Up to 18s of stalls when aborted script fetches are cancelled (web-platform-tests/wpt@7a51c2bfc1, web-platform-tests/wpt@fcfc25546a). Six abort subtests in stream-html-parser-blocking-script.html waited for a PerformanceResourceTiming entry. Engines that cancel the fetch never emit one, so each subtest waited out the 3s fallback. waitForResource now races against an un-aborted control request, which settles quickly when the fetch is cancelled. The control is delayed d0.6 against the script's d0.2, so an engine that wrongly keeps the script still runs it before the check. The F12 iframe is also cleaned up.
  • Unneeded allow_uncaught_exception removed from both stream-html-abort-unblocks-rendering*.html files (web-platform-tests/wpt@67ba40bc13). The commit also fixes the blocking="render" comment in the -defer file.
  • Assertions that could pass without the feature working (web-platform-tests/wpt@63ab5f3da3):
    • Mid-stream adoption now checks that the new document's registry constructs and connects the element, not just that the old one didn't.
    • New fresh-iframe test: a streamed <script type="importmap"> must resolve a specifier imported by a later streamed module script.
    • chained-streaming-templates-with-custom-element.html used <?marker>, which marks a single point, so "Original Target" was never replaced. It now uses a <?start?>…<?end?> range and asserts the text was replaced.
  • Element streamHTMLUnsafe sink missing from the createParserOptions order tests (web-platform-tests/wpt@19a30aee3b, web-platform-tests/wpt@00abb31e3c). Added it, with a check that existing children aren't cleared when createParserOptions throws, and updated the title.

Verification

  • specfmt and ../build.sh pass.
  • ./wpt lint is clean.
  • Chrome Canary (experimental web platform features): every new subtest passes, and nothing regressed compared with the previous head. The remaining failures are known implementation gaps that were already failing.
  • Firefox, which doesn't implement streaming: every subtest in the changed files fails cleanly, with no harness errors or timeouts.

noamr added 4 commits November 3, 2026 08:47
Introduce safe and unsafe streaming HTML parsing and insertion methods returning a `WritableStream`:
* `Element` & `ShadowRoot`: `streamHTML()`, `streamHTMLUnsafe()`, `streamAppendHTML()`, `streamAppendHTMLUnsafe()`, `streamPrependHTML()`, and `streamPrependHTMLUnsafe()`
* `NonDocumentTypeChildNode`: `streamBeforeHTML()`, `streamBeforeHTMLUnsafe()`, `streamAfterHTML()`, `streamAfterHTMLUnsafe()`, `streamReplaceWithHTML()`, and `streamReplaceWithHTMLUnsafe()`

Key behaviors and parser updates:
* **Stream operations**: `writeAlgorithm` and `closeAlgorithm` convert chunks to `DOMString`, append chunks (or an explicit `"EOF"` character on close) to the parser's input stream, and run the fragment parser. `closeAlgorithm` waits for any pending parser-blocking scripts via `fragment parser close promise`. `abortAlgorithm` aborts the fragment parser (deferring via `fragment parser abort requested` if currently running), marks open `script` elements on the stack as already started, and unblocks rendering on pending scripts.
* **Displaced reference child**: If `referenceChild` is no longer a child of `target` when a node would be inserted before it or when another chunk is written, `invalid reference child steps` error the stream (and reject `fragment parser close promise` if closing) with a `"HierarchyRequestError"` `DOMException` and abort the fragment parser. Elements that would be inserted before a displaced `referenceChild` are created in the `appropriate template contents owner document` with a null custom element registry and dropped, and the adoption agency algorithm skips removing `lastNode`.
* **Validation, Trusted Types & DOM mutations**: Target validation (throwing `"NotSupportedError"` for HTML/SVG `script` context elements, or `"HierarchyRequestError"` for `html` targets or invalid `parent for HTML streaming`), `HTMLTemplateElement` redirection to `template contents`, and Trusted Types / `SanitizerConfig` validation occur synchronously before returning the stream or mutating the DOM.
* **Scripts, custom elements & fragment parsing**:
  - Extracts `initialize an HTML fragment parser`. When `runScripts` is true, `script target document` is `context`'s node document; otherwise it is the temporary inert document.
  - Parser-blocking, `defer`, `async`, and module scripts follow normal HTML parser pausing and execution order.
  - Custom element upgrades/callbacks when inserting into a connected target run before any subsequent `script` via a dedicated element queue; other reactions when streaming HTML use the backup element queue.
  - The speculative HTML parser is not started in the fragment case. Speculative fetches from the fragment parser are still allowed, except when sanitizing or for elements that will be dropped. *The end* (`stops parsing`) returns early for fragment parsers.
  - Elements whose intended parent is the fragment root `html` element are created directly in the target's (or fragment's) node document.
  - SVG `script` elements are only processed when the parser's `script target document` is not the parser's `Document` and the `script` element is connected (which also applies to document parsing when an ancestor of an SVG `script` was disconnected before `</script>`).
  - Elements removed or replaced with their children by the sanitizer are created in the `appropriate template contents owner document` with a null custom element registry and not inserted into the DOM.

Note: Pre-existing adoption agency algorithm edge cases (#13093) are out of scope for this PR.

Closes #2142.

Tests: web-platform-tests/wpt#61748.
…hunk is parsed

When the fragment parser runs from a task after a parser-blocking script, a streamed script that writes to the stream invokes writeAlgorithm synchronously; run a fragment parser returns early because the parser is already running, so the write promise resolves before the chunk is parsed. Qualify the intro's claim and extend the writeAlgorithm note.
With streaming, both the parser's Document and the target's document can have a pending parsing-blocking script; say which one is meant, matching the other references the PR added.
@noamr

noamr commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor Author
AI review

Round 5 (after squashing both PRs at the author's request; the WPT PR was also rebased onto current master, which had no changes in the PR's directories).

Follow-ups / for the author

  • PR description updated. Under "Scripts, custom elements & fragment parsing" it now says that the null-registry treatment of elements removed (or replaced with their children) by the sanitizer also applies to the existing sanitizing methods (setHTML(), setHTMLUnsafe(), …), and that it reaches the removed elements' descendants. Before this PR, the Sanitizer's parse-then-sanitize model upgraded a scoped-registry custom element nested in a removed ancestor before sanitization. Now it never gets a registry. stream-html-custom-element-sanitizer.html tests this. Chrome Canary fails the "removeElements: ancestor div" variants for both streaming and non-streaming methods, and Firefox passes the setHTML/setHTMLUnsafe ones.

Findings and fixes

HTML (whatwg/html, on top of the squashed commit)

  1. Suggestion: the intro says the write promise "is settled once the chunk has been parsed". That's not true when the chunk is written by script running during parsing. After a parser-blocking script, the parser runs from a task. A streamed inline script that calls writer.write() then invokes writeAlgorithm synchronously, and run a fragment parser returns early because the parser is already running. The promise therefore resolves, and its await continuations run at the next microtask checkpoint, before the outer run parses the chunk. Fix: qualify the intro sentence and extend the writeAlgorithm note. 8447e37
  2. Nit: "At this stage, if the pending parsing-blocking script is not null" (#scriptTagParserResumes) didn't say which Document's. With streaming, both the parser's Document and the target's document can have one. It now says "the parser's Document's", matching the other references the PR added. 3f643b4
  3. Nit: rejoined a needlessly wrapped line in create an element for a token. 55eedc8

WPT (web-platform-tests/wpt)

  1. Suggestion: two tests asserted that deferred/module scripts don't run after an abort, but only waited a fixed 0 ms or 50 ms. A data: script fetch can outlast that, so an engine that wrongly keeps the scripts could still pass. They now wait for defer/module scripts in a freshly streamed and closed control target, then assert that only the control ran. The two tests are stream-html-parser-blocking-script.html (close() rejecting on a displaced reference child) and stream-html-defer-async-script.html (abort()). c4aaaab1b3
  2. Nit: stream-html-custom-element-sanitizer.html had a duplicate help link. Removed it, and added a link to the HTML fragment parsing algorithm, since the file covers setHTML() and friends too. 2f09177e21
  3. Nit: stream-html-with-trusted-types-error-in-policy.html: changed to assert the exact rethrown error with assert_throws_exactly, dropped a stale comment, and fixed the indentation. 3013212d9d
  4. Nit: stream-html-with-trusted-types-createParserOptions-order.html: the try/assert_unreached/catch pattern swallowed its own AssertionError when nothing threw, giving a misleading failure message. Changed to assert_throws_exactly. 8a64ccb5dd
  5. Nit: retitled stream-html-defer-async-script.html, since it covers more than streamAppendHTMLUnsafe defer scripts. 237a8db905

Verification

  • Spec: build.sh succeeds and specfmt is clean. The html-spec-review static checks (Web IDL and algorithm lint) flag nothing new on lines the PR adds. The remaining reports are references flagged as re-declarations, plus ;/, endings in "all of the following" lists.
  • WPT: wpt lint is clean.
  • Chrome Canary (--enable-experimental-web-platform-features), all 50 test files:
    • No harness errors or timeouts.
    • The remaining failures are Chrome gaps, and the review checked each failure group against the spec:
      • mid-chunk reference-child displacement
      • deferred abort from a microtask, custom element reaction, or task-run inline script
      • registry change when the target is adopted mid-stream
      • close() rejecting after a pending script
      • foster parenting before a table that became the document element
      • <template for> scope when streaming into body (Chrome widens it to html)
      • <template for="">
      • <noscript> in template contents (scripting flag)
      • scoped registry under a removed ancestor
    • After the fixes, the changed files have no new failures, and the rewritten abort test passes with its control.
  • Firefox release (no streaming support), all 50 files: no harness errors or timeouts. The only passing subtests cover features Firefox already ships (setHTML/setHTMLUnsafe, innerHTML, createContextualFragment, document-parser SVG <script>).

@annevk

annevk commented Nov 3, 2026

Copy link
Copy Markdown
Member
AI feedback

Reviewed at 55eedc8. Lint and the full build (including the developer edition) pass, and the findings from my October 20 comments are addressed. The first two points are about the abort checks this PR adds to tree construction. None of the checks produces a wrong tree today, but several are unreachable or duplicate each other, and one has a reachable case that its placement doesn't account for. I also commented on web-platform-tests/wpt#61748 about a test that contradicts the spec (third point).

Suggestions

  • Consider deriving the fragment parser abort requested checks from one rule. Once the flag is set, the tokenizer stops before its next step. So the flag can only already be set when a token starts processing in two cases. Either (a) the token is being reprocessed after an earlier step of its own handling set the flag, or (b) it is a later token of a tokenizer step that emits several, which is always a character token or EOF (e.g., < followed by EOF at the end of the input). Measured against that:

    • Needed:
      • the inert creation in create an element for a token;
      • the four insertion helpers (element, character, comment, processing instruction);
      • the adoption agency checks;
      • the end. Example: the last chunk ends in a top-level <, and the reference node is removed before close(). The < errors the stream and rejects close(), but EOF still reaches the end. Without the check, any defer scripts already streamed would still be queued to run.
    • Unreachable: "before head" and "after head".
      • These modes only occur with an html context element, which never has a reference child: streamAppendHTML(), streamPrependHTML(), and the sibling methods throw for html, and streamHTML() passes null.
      • Inserting a head or body without attributes can't run script.
    • Duplicated: "in table text" versus the body start tag and the </template> end tag.
    • Redundant: the template start tag check.
      • It can only see the flag set by the template's own creation: at the top level, or inside an element the sanitizer replaces with its children. In exactly those cases, the declarative shadow root and patching steps already bail out.
      • The motivation given when it was added, an abort from a customized built-in template constructor, doesn't apply. Fragment parsers only queue the upgrade, and the wpt tests now assert that it runs after the attach or patch.
    • Unguarded but fine: "in table" col and td/th/tr, and "in table body" th/td. These have the same insert-then-reprocess shape as the guarded steps, but only reach the insertion helpers.

    Consider keeping the checks only where the DOM is mutated directly:

    • the insertion helpers;
    • the body attribute merge;
    • </template> marker removal;
    • template shadow root attachment and patching;
    • the adoption agency algorithm;
    • the end.

    Then drop the three reprocess checks, and state the rule in a note at the flag's definition. That way, the next parser feature that mutates the DOM directly (as content patching does) knows it needs a check.

  • The adoption agency algorithm's check before inserting newElement (L150242–L150255) is half dead, and it runs after the children are moved. Its Document clause is reachable:

    const w = div.streamHTML({sanitizer: {replaceWithChildrenElements: ["section"]}}).getWriter();
    await w.write("<table><b><section>"); // b is foster-parented before the table; section redirects into b
    doc.replaceChild(div.querySelector("table"), doc.documentElement); // the table becomes doc's document element
    await w.write("</b>");

    Foster parenting for </b> resolves to (doc, table). section's redirect is updated to that location, and newElement goes to the same place. Without the clause, newElement would be inserted into a document that already has an element child.

    The host-including inclusive ancestor clause is dead, since newElement is new and only gets furthestBlock's former children. The check also runs after those children are moved into newElement. That's only harmless because, in the reachable case, furthestBlock is replaced with its children and so has none. Consider dropping the dead clause, checking before moving the children, and adding a note for the Document case.

  • What should an abort in the middle of a <template for> patch leave behind?

    • Prepare content patching removes the old content when the start tag is processed (as Chromium does).
    • After an abort, the </template> check keeps the markers. So the target ends up with the old content gone, partial new content, and the markers. That does at least let a later patch reuse the range.
    • wpt stream-html-reentrancy.html L404 instead expects the old content to survive. If that's the intent, the spec needs to buffer patched content until </template>. Otherwise, the test needs fixing (details on the WPT PR).
  • PR description (it will be the commit message):

    • "This also applies to the non-streaming methods …, where previously the whole fragment was parsed (and custom elements upgraded) before sanitization": main already does this, since Sanitize while parsing #12756 (9485706). Removed elements get a null registry, and their descendants inherit it. For setHTML() and friends, this PR only changes which inert document removed or replaced elements are created in, which isn't observable.
    • "Their descendants look up a null registry from them too" only holds for removed elements. Replaced elements get their registry set after creation, so their children get the normal one (L147194–L147197).
    • "Speculative fetches … are still allowed, except when sanitizing": they are allowed when streaming with a sanitizer, for elements the sanitizer keeps (L147164–L147171).
    • The SVG bullet leaves out that an SVG script moved to another document before its end tag is no longer processed, also in document parsing (L151776–L151777).
  • Creating top-level elements directly in the target's node document (L147068–L147070, L147110) fixes the top-level case of Media element attributes resolve against the fragment parser's inert document's base URL #13068 for non-sanitizing fragment parsing. For example, div.setHTMLUnsafe('<video src=movie.mp4>') now resolves against the target document instead of about:blank. Consider saying so in the commit message, and noting on Media element attributes resolve against the fragment parser's inert document's base URL #13068 that only the sanitizing case remains.

Nits

  • (Optional) The commit message is still long; consider condensing it.
  • (Optional) Consider linking the Chromium bug in the checklist.

@noamr

noamr commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor Author

AI review

Thanks, addressed in a62174f and web-platform-tests/wpt@b4147689cd:

  • Abort checks derived from one rule. I added a note after the fragment parser abort requested definition. It states the rule (only reprocessed tokens, or later character/EOF tokens of the same tokenizer step, can see the flag) and says that tree construction steps that mutate the DOM must check it. I dropped the "before head", "after head", and "in table text" reprocess checks, so those three steps are now identical to main. I kept the checks in the insertion helpers, create an element for a token, the body attribute merge, </template>, the adoption agency algorithm, and the end.
    • I kept the template start tag check, against the "redundant" point. With the table-text check gone, a <template for> token can be reprocessed from "in table text" after an earlier token set the flag. That's the stream-html-reentrancy.html subtest you linked. The insertion helper then refuses to insert the template, but the patch target is already in the tree, so the patch steps would not bail out. This falls under "template shadow root attachment and patching" in your keep list.
    • The <html> attribute merge in "in body" has no check, which is fine: in the fragment case it only touches the parser's own html root, which is never inserted.
    • Added a wpt test for the end: a trailing < with the reference child removed before close(). close() rejects and the streamed defer script doesn't run.
  • Adoption agency Document check. The "Keep" branch now checks first that newElementParent is not a Document with an element child, and only then moves the children. I dropped the dead host-including inclusive ancestor clause and added a note on the Document case. Your example is now a wpt test in stream-html-sanitizer.html.
  • Abort during a <template for> patch. The spec stays as is: old content is removed at the start tag (as in Chromium), and the markers survive an abort so a later patch can reuse the range. I fixed the test to match instead of buffering the patch. It now expects start, B, A, TABLE, end with text "1".
  • PR description. Not updated yet; your four points (and the Media element attributes resolve against the fragment parser's inert document's base URL #13068 mention) will be addressed in a separate edit.
  • Chromium bug link. Added https://issues.chromium.org/issues/581018331 to the checklist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

addition/proposal New features or enhancements

Development

Successfully merging this pull request may close these issues.

A way to stream content into an element

5 participants