Skip to content

Implement out-of-order streaming using <template for> - #76083

Open
hjanuschka wants to merge 1 commit into
WebKit:mainfrom
hjanuschka:template-for-c
Open

hjanuschka wants to merge 1 commit into
WebKit:mainfrom
hjanuschka:template-for-c

Conversation

@hjanuschka

@hjanuschka hjanuschka commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

9e2b7df

Implement out-of-order streaming using <template for>
https://bugs.webkit.org/show_bug.cgi?id=324175

Reviewed by NOBODY (OOPS!).

https://github.com/whatwg/html/issues/13036

Add HTMLTemplateElement.htmlFor and use the `<?marker>`, `<?start>` and
`<?end>` processing instructions from 326324@main as parser insertion points,
so that content arriving later in the stream can be placed into a part of the
document that has already been parsed. Redirect parser output into the
selected insertion point, remove the replaced range and the markers, and keep
parser behaviour across fragments, shadow roots, nested patches and scripts.

This sits behind the new HTMLTemplateForEnabled setting, which is testable and
off, separate from the processing instruction setting so the parser change can
be enabled on its own.

The patching machinery is careful about the following, each covered by a
layout test that fails without the corresponding code:

- Preparing a patch and removing the markers can fire pagehide in removed
  iframes, and mutation events where those are enabled, from inside the tree
  builder. A handler calling document.write() would re-enter it, so both run
  inside a ThrowOnDynamicMarkupInsertionCountIncrementer, as the parser
  already does for custom element constructors. The guard goes on the
  document the parser writes into and on the scope's document, which differ
  when the patch is nested inside another <template for>, owned by a template
  content document, and when script moved the patch target into another
  document mid-parse.

- Removing the markers uses remove() rather than parserRemoveChild(), because
  removeNodeWithScriptAssertion() disconnects every subframe under the parent
  rather than under the removed node, which would take out iframes inside and
  beside the patched content.

- Nodes for patched content are created in the patch target's document, tree
  scope and custom element registry, not in the template content fragment's,
  so custom elements are constructed by the parser rather than upgraded, and
  text honours the target's length limits.

- Patched text merges with a Text node already before the insertion point,
  matching how the parser appends elsewhere.

- Patch target resolution is indexed. Document keeps a map from marker name
  to the <?marker> and <?start> processing instructions, registered on
  insertion and updated on removal, data mutation and document adoption, so
  preparing a patch costs the number of markers with that name instead of a
  walk over every descendant of the scope, which made N patches into an
  N-item document quadratic (2000 patches: ~55ms -> ~3ms). Duplicate names
  resolve to the first marker in tree order at lookup, and markers in
  detached subtrees stay indexed because a patch scope can lie inside one.

- Per whatwg/html#13075, `for` applies whenever no declarative shadow root
  was attached: an invalid shadowrootmode, a context that disallows
  declarative shadow roots such as innerHTML, or a host that cannot have or
  already has a shadow root all leave `for` in effect.

- The scope in which markers are looked up widens from body to html also when
  the enclosing template is itself patching a body child.

- Parser insertions into an element that has already finished parsing run the
  sibling style checks in ChildChangeInvalidation per insertion, instead of
  relying on invalidateAfterFinishedParsingChildren, which only runs when the
  parser finishes an element it opened itself. This keeps `:first-child` and
  friends correct while a patch streams and after it finishes.

The remaining failures in the imported suite are all features WebKit does not
implement: the streaming and append APIs, the Sanitizer, and the HTMLUnsafe
setters. Two upstream test issues are fixed in place and belong upstream too:
template-for-move-cross-document asserted around a <script> it had inserted
itself, and template-for-only-html-001 was missing its
resources/template-for.xhtml support file, so it failed in every engine.

Tests: fast/parser/template-for-mutation-events-cross-document.html
       fast/parser/template-for-mutation-events.html
       fast/parser/template-for-shadowrootmode-not-attached.html
       imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/

* LayoutTests/fast/parser/template-for-mutation-events-cross-document-expected.txt: Added.
* LayoutTests/fast/parser/template-for-mutation-events-cross-document.html: Added.
* LayoutTests/fast/parser/template-for-mutation-events-expected.txt:
* LayoutTests/fast/parser/template-for-mutation-events.html:
* LayoutTests/fast/parser/template-for-shadowrootmode-not-attached-expected.txt: Added.
* LayoutTests/fast/parser/template-for-shadowrootmode-not-attached.html: Added.

* LayoutTests/imported/w3c/web-platform-tests/html/dom/idlharness.https_include=HTML.+-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/reflect-html-for-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-abort-during-patch-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-abort-during-patch.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-append-element-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-append-text-and-element-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-append-to-head-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-case-sensitive-dom-inserted-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-case-sensitive-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-cross-document-pagehide-dynamic-markup-insertion-expected.txt: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-cross-document-pagehide-dynamic-markup-insertion.html: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-custom-element-timing-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-custom-element-timing.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-empty-hash-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-foster-parenting-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-gradual-append-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-html-setters-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-iframe-in-patch-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-iframe-in-patch.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-innerHTML-ambiguous-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-innerHTML-within-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-invokes-pagehide-with-end-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-invokes-pagehide-without-end-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-cross-document-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-cross-document.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-only-html-001-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/resources/template-for.xhtml: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-end-while-appending-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-marker-while-appending-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-start-while-appending-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-while-appending-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-multiple-cases-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-multiple-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-mutation-records-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-body-scope-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-body-scope.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-pagehide-dynamic-markup-insertion-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-pagehide-dynamic-markup-insertion.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-patch-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-null-in-pi-data-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-null-in-pi-data.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-pagehide-dynamic-markup-insertion-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-prepend-element-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-prepend-text-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-replace-children-with-element-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-replace-children-with-text-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-replace-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-sanitization-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-script-children-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-script-eval-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-script-replace-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-shadow-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-shadow-nested-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-shadow-root-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-streaming-positional-styles-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-streaming-positional-styles.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-style-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-style-in-head-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-supersedes-invalid-shadowrootmode-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-text-node-merging-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-text-node-merging.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-title-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-unclosed-content-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/w3c-import.log:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-duplicate-markers-expected.txt: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-duplicate-markers.html: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-marker-name-mutation-expected.txt: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-marker-name-mutation.html: Added.
* Source/WTF/Scripts/Preferences/UnifiedWebPreferences.yaml:
* Source/WebCore/dom/Document.cpp:
* Source/WebCore/dom/Document.h:
* Source/WebCore/dom/Node.cpp:
* Source/WebCore/dom/ProcessingInstruction.cpp:
* Source/WebCore/dom/ProcessingInstruction.h:
* Source/WebCore/html/HTMLTemplateElement.cpp:
* Source/WebCore/html/HTMLTemplateElement.h:
* Source/WebCore/html/HTMLTemplateElement.idl:
* Source/WebCore/html/parser/HTMLConstructionSite.cpp:
* Source/WebCore/style/ChildChangeInvalidation.cpp:
(WebCore::HTMLTemplateElement::htmlFor const):
(WebCore::HTMLTemplateElement::setHTMLFor):
(WebCore::HTMLTemplateElement::insertionTarget):
(WebCore::HTMLTemplateElement::insertionNextChild):
(WebCore::HTMLTemplateElement::prepareContentPatching):
(WebCore::HTMLTemplateElement::finishParsingChildren):
(WebCore::insert):
(WebCore::HTMLConstructionSite::insertHTMLTemplateElement):
(WebCore::HTMLConstructionSite::insertTextNode):
(WebCore::HTMLConstructionSite::treeScopeForCurrentNode):
(WebCore::HTMLConstructionSite::containerForCurrentNode):
(WebCore::HTMLConstructionSite::ownerDocumentForCurrentNode):
(WebCore::registryForCurrentNode):
(WebCore::Style::ChildChangeInvalidation::invalidateAfterChange):

Co-authored-by: Noam Rosenthal <nrosenthal@chromium.org>

9e2b7df

Misc iOS, visionOS, tvOS & watchOS macOS Linux Windows
✅ 🧪 style ✅ 🛠 ios ✅ 🛠 mac ✅ 🛠 wpe ✅ 🛠 win
✅ 🧪 bindings ✅ 🛠 ios-sim-cmake ✅ 🛠 mac-cmake-debug ✅ 🧪 wpe-wk2 ✅ 🧪 win-tests
✅ 🧪 webkitperl ✅ 🧪 ios-cmake-wk2 loading-orange 🧪 api-mac ✅ 🧪 api-wpe
skipped 🧪 webkitpy ✅ 🧪 ios-cmake-wk2-wpt ✅ 🧪 api-mac-cmake-debug ✅ 🧪 jsc-wpe
✅ 🧪 jsc-x86-64 ✅ 🧪 api-ios-cmake loading-orange 🧪 mac-wk2 ✅ 🛠 gtk3-gcc
✅ 🛠 🧪 jsc-debug-arm64 ✅ 🛠 ios-safer-cpp loading-orange 🧪 mac-cmake-debug-wk2 ✅ 🛠 gtk
skipped 🧪 services ✅ 🛠 vision ✅ 🧪 mac-wk2-stress ✅ 🧪 gtk-wk2
✅ 🛠 vision-sim ✅ 🧪 mac-intel-wk2 ✅ 🧪 api-gtk
✅ 🧪 vision-wk2 ✅ 🛠 mac-safer-cpp   🛠 playstation
✅ 🛠 tv ✅ 🧪 mac-site-isolation
✅ 🛠 tv-sim skipped 🧪 mac-webdriver
✅ 🛠 watch
✅ 🛠 watch-sim

@webkit-ews-buildbot webkit-ews-buildbot added the merging-blocked Applied to prevent a change from being merged label Oct 21, 2026
@hjanuschka
hjanuschka marked this pull request as ready for review November 14, 2026 06:42
@nt1m
nt1m requested a review from annevk November 18, 2026 22:23
@annevk

annevk commented Nov 20, 2026

Copy link
Copy Markdown
Contributor
AI-generated review feedback (Claude)

This review was generated by Claude, an AI model, at my request. Findings marked reproduced were observed in a local Debug build of e461cf1; the rest come from reading the code and comparing it with the specification and Chromium. Line links point at e461cf1.

Re-entrancy (blocking)

  1. Nested <template for> bypasses the dynamic markup insertion guard. prepareContentPatching() increments the counter on the template's own document(). A <template for> nested inside another is created in the template contents owner document, because treeScopeForCurrentNode() follows the outer template's content fragment. So the document being parsed is unguarded. Reproduced:

    const doc = iframe.contentDocument;
    doc.open();
    doc.write(`<div id="target"><?start name="outer">old<?end></div>`);
    doc.write(`<template for="outer">before<?start name="inner"><iframe></iframe><?end>after`);
    doc.querySelector("iframe").contentWindow.onpagehide = () => doc.write("<p>Hi");
    doc.write(`<template for="inner">New</template></template>`);

    This hits ASSERTION FAILED: !m_destructionProhibited in HTMLTreeBuilder::constructTree(). With doc.open() in the handler, nothing throws and the document is replaced mid-parse. The same test without nesting correctly throws InvalidStateError for both. Using scope.document() would fix it; that's what Chromium's Patch::Prepare() does and what Parser follow-ups for processing instructions and <template for> whatwg/html#13036 proposes.

  2. Marker removal runs script without the guard. In finishParsingChildren(), startMarker->remove() dispatches DOMNodeRemoved synchronously from inside HTMLElementStack::pop() when mutation events are enabled. They're enabled for non-Safari Apple apps and for apps linked against older SDKs. Reproduced with MutationEventsEnabled=true: a DOMNodeRemoved listener that calls doc.write() when a processing instruction is removed hits the same assertion. The marker removal needs the same incrementer.

  3. Not tested: removing the replaced range runs script synchronously inside the tree builder, possibly while construction tasks are still queued. WebKit's tree builder otherwise only runs script while paused, as it does for custom element construction. The incrementer covers write() and open(), but not window.stop() or detaching the frame of the document being parsed from a pagehide handler. Those cases would be worth an ASan run.

Parser integration

  1. Patched content is created in the template contents owner document. ownerDocumentForCurrentNode(), treeScopeForCurrentNode(), containerForCurrentNode() and registryForCurrentNode() all ignore the insertion target. Chromium's OwnerDocumentForCurrentNode() follows the patch to its target. Consequences:

    • Custom elements in a patch are upgraded after insertion instead of being constructed by the parser. Reproduced: for a normally parsed element the constructor sees isConnected=false and 0 attributes; for a patched one it sees isConnected=true and 1 attribute.
    • Every patch allocates an unused content fragment, and every patched node is adopted on insertion.
    • It's the root cause of item 1.
  2. Patched text never merges with an adjacent Text node. insertTextNode() looks at the template content's last child instead of the node before the insertion point. The specification and Chromium both merge. Reproduced: <p>Hello <?marker name="m"></p><template for="m">world</template> gives two Text nodes, "Hello " and "world". Patch text written in two document.write() chunks gives "wor" and "ld".

  3. shadowrootmode precedence differs from the specification. When declarative shadow roots aren't allowed, as with innerHTML, the specification inserts a template with a valid shadowrootmode as an ordinary template and ignores for. Reproduced: div.innerHTML = '<?start name="z">old<?end><template shadowrootmode="open" for="z">new</template>' patches, giving new. Chromium appears to behave like this PR, so this may be a specification question rather than a WebKit bug, but it needs a WPT either way.

  4. Minor: the else if skips the body-to-html scope step when the scope came from a parent template's insertion target. The specification applies that step to the adjusted insertion location in that case too.

Style invalidation

  1. Positional styles stay stale while a patch streams. They're only fixed at </template>, which is the interval out-of-order streaming is for. Reproduced: with li:first-child styled, <ul><?marker name="m"><li id=l1>A</li></ul><template for="m"><li id=l0>Z</li><script>…</script></template>, both l0 and l1 match li:first-child in the script inside the patch. Also, invalidateStyleForSubtree() on the whole target per patch gets roughly quadratic with many patches into one large list. Since the target finished parsing long ago, not marking these insertions as parser insertions for ChildChangeInvalidation would give targeted invalidation per insertion and make invalidateSiblingAndPositionalStyles() unnecessary. :empty and :has() are fine already, because only the sibling part is skipped for parser insertions.

Performance

  • Each <template for> walks the whole scope, usually the html element, and getAttribute() lazily parses the data of every processing instruction it meets. Checking the target for marker or start first, and using static AtomStrings, makes the walk cheaper.
  • The preload scanner skips <template> contents except for top-level declarative shadow roots (HTMLPreloadScanner.cpp), so resources in patches aren't preloaded. That could be a follow-up.

Code

  • HTMLParserOptions::templateFor is set but never read; insertHTMLTemplateElement() reads document().settings() directly.
  • The for branch duplicates the regular path (attachLater() and push). Handling declarative shadow roots first, then creating the element once and either patching or attaching it, would remove the attribute pre-scan and a level of nesting.
  • The foster parenting path in insertHTMLTemplateElement() looks unreachable, and if (!parent) can't be true for a descendant.
  • invalidateSiblingAndPositionalStyles() can be a static function in the .cpp file.
  • Several comments, the test name template-for-review-repros, and its title ("the three cases raised in review") describe review history rather than behavior.

Tests and expectations

  • Node-appendChild-script-and-default-style-meta-from-fragment-expected.txt is unrelated to this change, and the test is [ Skip ] in LayoutTests/TestExpectations.
  • The commit message says the remaining failures are unimplemented features plus one upstream test bug. There's a second: template-for-move-cross-document fails identically in Chromium's baseline, because the test forgets the <script> between "A" and the <span>. Both tests could be fixed in WPT.
  • template-for-only-html-001 (XHTML) fails before and after this change; it's not mentioned.
  • Each of the reproduced cases above would make a good WPT.

Commit message

The function list sits under HTMLParserOptions.h instead of the files it belongs to, lists executeTask(), which didn't change, and omits insert(), which did.

@annevk

annevk commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Given what AI found we need more test coverage here as well. Especially for the more esoteric scenarios.

@hjanuschka hjanuschka left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

looking forward, let me know if you want me to address anything further 🎉

highlights:

  • nested guard: the counter now goes on scope.document(), so patches nested in patches are guarded too
  • marker removal runs inside the same ThrowOnDynamicMarkupInsertionCountIncrementer (mutation-events test is WebKit-only, WPT can't enable those)
  • patched nodes follow the insertion target for document/tree scope/registry, so custom elements are parser-constructed; text merges with the node before the insertion point, across write() chunks too
  • shadowrootmode wins over for where declarative shadow roots are disallowed, per the "in head" steps
  • body->html widening applies after the insertion-target redirect
  • style invalidation reworked the way you suggested: ChildChangeInvalidation runs the sibling checks for parser insertions into already-finished parents, and invalidateSiblingAndPositionalStyles() is gone
  • perf nits done: PI target checked before parsing its data, unused HTMLParserOptions::templateFor removed, the for branch no longer duplicates the attach path, dead foster-parenting branch gone; preload scanning for patches is a follow-up

each fix has a test that fails without it (7 of the 10 new ones are red on the previous revision). also fixed two upstream test bugs along the way (move-cross-document asserted around its own inserted script, only-html-001 was missing resources/template-for.xhtml). all new and fixed tests are upstream: web-platform-tests/wpt#65568

@annevk

annevk commented Nov 23, 2026

Copy link
Copy Markdown
Contributor
AI-generated review feedback (Claude), second pass

This follow-up was generated by Claude, an AI model, at my request, against 835f9a3. Everything marked reproduced was observed in a local Debug build of that commit.

Fixed

The test cases from the first pass now behave as the specification says (reproduced):

  • Nested pagehide → write()/open() throws InvalidStateError.
  • Marker removal with mutation events no longer re-enters the parser.
  • Patched text merges into one Text node, both after existing text and across document.write() chunks.
  • Patched custom elements are constructed by the parser.
  • :first-child is correct while the patch is still streaming.

Still crashing: the guard is on a node's document, not the parser's

Both guards use a node's document: scope.document() in prepareContentPatching(), and insertionTarget->document() in finishParsingChildren(). Script can move the patch target into another document mid-patch, which template-for-move-cross-document.html does. After that, the document actually being parsed is unguarded. Both of these hit ASSERTION FAILED: !m_destructionProhibited in HTMLTreeBuilder::constructTree() (reproduced):

// A nested patch whose scope moved into the parent document.
const doc = iframe.contentDocument;
doc.open();
doc.write(`<div id="target"><?start name="outer">old<?end></div>`);
doc.write(`<template for="outer"><?start name="inner"><iframe></iframe><?end>`);
document.body.append(doc.getElementById("target"));
document.querySelector("#target iframe").contentWindow.onpagehide = () => doc.write("<p>Hi");
doc.write(`<template for="inner">New</template></template>`);
// Marker removal after the target moved, with MutationEventsEnabled=true.
doc.open();
doc.write(`<div id="target"><?start name="p">old<?end></div>`);
doc.write(`<template for="p">A`);
document.body.append(doc.getElementById("target"));
document.addEventListener("DOMNodeRemoved", e => {
  if (e.target.nodeType == Node.PROCESSING_INSTRUCTION_NODE)
    doc.write("<p>Hi"); // once
});
doc.write(`</template>`);

Guarding the document the construction site parses into (HTMLConstructionSite::document()) would fix both, in addition to the node's document where they differ. It could be passed into prepareContentPatching() and kept for the marker removal. HTMLDocumentParser::runScriptsForPausedTreeBuilder() already guards the parser's document for custom elements. The specification has the same gap, now filed as whatwg/html#13317.

Correction: shadowrootmode precedence

Item 6 of my first pass pushed in the wrong direction. In whatwg/html#13075 the conclusion so far is to align the specification with Chromium: for applies whenever no shadow root gets attached. web-platform-tests/wpt#65117 has template-for-shadowrootmode-not-attached.html, which asserts that for innerHTML, DOMParser, a host that can't have a shadow root, and a host that already has one. The new template-for-innerHTML-shadowrootmode.html in web-platform-tests/wpt#65568 asserts the opposite and would conflict with it. I'd follow #13075 instead: patch whenever no shadow root is attached, including when attaching fails, which the first revision didn't do either. Then drop that test from wpt#65568.

Tests

template-for-multiple-cases.html's "Unclosed element in template content with only start" still fails because the test is wrong. A <?start> without an <?end> replaces everything to the end of the parent, so <span>New</span> is correct and <span>New content</span> isn't. Fixing it in wpt#65568 alongside the other two test fixes would cover it.

@hjanuschka

Copy link
Copy Markdown
Contributor Author

@annevk thanks, both points from your review fixed!

https://bugs.webkit.org/show_bug.cgi?id=324175

Reviewed by NOBODY (OOPS!).

whatwg/html#13036

Add HTMLTemplateElement.htmlFor and use the `<?marker>`, `<?start>` and
`<?end>` processing instructions from 326324@main as parser insertion points,
so that content arriving later in the stream can be placed into a part of the
document that has already been parsed. Redirect parser output into the
selected insertion point, remove the replaced range and the markers, and keep
parser behaviour across fragments, shadow roots, nested patches and scripts.

This sits behind the new HTMLTemplateForEnabled setting, which is testable and
off, separate from the processing instruction setting so the parser change can
be enabled on its own.

The patching machinery is careful about the following, each covered by a
layout test that fails without the corresponding code:

- Preparing a patch and removing the markers can fire pagehide in removed
  iframes, and mutation events where those are enabled, from inside the tree
  builder. A handler calling document.write() would re-enter it, so both run
  inside a ThrowOnDynamicMarkupInsertionCountIncrementer, as the parser
  already does for custom element constructors. The guard goes on the
  document the parser writes into and on the scope's document, which differ
  when the patch is nested inside another <template for>, owned by a template
  content document, and when script moved the patch target into another
  document mid-parse.

- Removing the markers uses remove() rather than parserRemoveChild(), because
  removeNodeWithScriptAssertion() disconnects every subframe under the parent
  rather than under the removed node, which would take out iframes inside and
  beside the patched content.

- Nodes for patched content are created in the patch target's document, tree
  scope and custom element registry, not in the template content fragment's,
  so custom elements are constructed by the parser rather than upgraded, and
  text honours the target's length limits.

- Patched text merges with a Text node already before the insertion point,
  matching how the parser appends elsewhere.

- Patch target resolution is indexed. Document keeps a map from marker name
  to the <?marker> and <?start> processing instructions, registered on
  insertion and updated on removal, data mutation and document adoption, so
  preparing a patch costs the number of markers with that name instead of a
  walk over every descendant of the scope, which made N patches into an
  N-item document quadratic (2000 patches: ~55ms -> ~3ms). Duplicate names
  resolve to the first marker in tree order at lookup, and markers in
  detached subtrees stay indexed because a patch scope can lie inside one.

- Per whatwg/html#13075, `for` applies whenever no declarative shadow root
  was attached: an invalid shadowrootmode, a context that disallows
  declarative shadow roots such as innerHTML, or a host that cannot have or
  already has a shadow root all leave `for` in effect.

- The scope in which markers are looked up widens from body to html also when
  the enclosing template is itself patching a body child.

- Parser insertions into an element that has already finished parsing run the
  sibling style checks in ChildChangeInvalidation per insertion, instead of
  relying on invalidateAfterFinishedParsingChildren, which only runs when the
  parser finishes an element it opened itself. This keeps `:first-child` and
  friends correct while a patch streams and after it finishes.

The remaining failures in the imported suite are all features WebKit does not
implement: the streaming and append APIs, the Sanitizer, and the HTMLUnsafe
setters. Two upstream test issues are fixed in place and belong upstream too:
template-for-move-cross-document asserted around a <script> it had inserted
itself, and template-for-only-html-001 was missing its
resources/template-for.xhtml support file, so it failed in every engine.

Tests: fast/parser/template-for-mutation-events-cross-document.html
       fast/parser/template-for-mutation-events.html
       fast/parser/template-for-shadowrootmode-not-attached.html
       imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/

* LayoutTests/fast/parser/template-for-mutation-events-cross-document-expected.txt: Added.
* LayoutTests/fast/parser/template-for-mutation-events-cross-document.html: Added.
* LayoutTests/fast/parser/template-for-mutation-events-expected.txt:
* LayoutTests/fast/parser/template-for-mutation-events.html:
* LayoutTests/fast/parser/template-for-shadowrootmode-not-attached-expected.txt: Added.
* LayoutTests/fast/parser/template-for-shadowrootmode-not-attached.html: Added.

* LayoutTests/imported/w3c/web-platform-tests/html/dom/idlharness.https_include=HTML.+-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/reflect-html-for-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-abort-during-patch-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-abort-during-patch.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-append-element-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-append-text-and-element-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-append-to-head-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-case-sensitive-dom-inserted-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-case-sensitive-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-cross-document-pagehide-dynamic-markup-insertion-expected.txt: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-cross-document-pagehide-dynamic-markup-insertion.html: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-custom-element-timing-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-custom-element-timing.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-empty-hash-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-foster-parenting-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-gradual-append-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-html-setters-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-iframe-in-patch-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-iframe-in-patch.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-innerHTML-ambiguous-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-innerHTML-within-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-invokes-pagehide-with-end-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-invokes-pagehide-without-end-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-cross-document-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-cross-document.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-only-html-001-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/resources/template-for.xhtml: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-end-while-appending-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-marker-while-appending-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-start-while-appending-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-move-while-appending-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-multiple-cases-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-multiple-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-mutation-records-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-body-scope-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-body-scope.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-pagehide-dynamic-markup-insertion-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-pagehide-dynamic-markup-insertion.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-nested-patch-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-null-in-pi-data-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-null-in-pi-data.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-pagehide-dynamic-markup-insertion-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-prepend-element-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-prepend-text-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-replace-children-with-element-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-replace-children-with-text-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-replace-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-sanitization-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-script-children-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-script-eval-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-script-replace-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-shadow-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-shadow-nested-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-shadow-root-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-streaming-positional-styles-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-streaming-positional-styles.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-style-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-style-in-head-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-supersedes-invalid-shadowrootmode-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-text-node-merging-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-text-node-merging.html:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-title-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-unclosed-content-expected.txt:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/w3c-import.log:
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-duplicate-markers-expected.txt: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-duplicate-markers.html: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-marker-name-mutation-expected.txt: Added.
* LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-template-element/template-for/template-for-marker-name-mutation.html: Added.
* Source/WTF/Scripts/Preferences/UnifiedWebPreferences.yaml:
* Source/WebCore/dom/Document.cpp:
* Source/WebCore/dom/Document.h:
* Source/WebCore/dom/Node.cpp:
* Source/WebCore/dom/ProcessingInstruction.cpp:
* Source/WebCore/dom/ProcessingInstruction.h:
* Source/WebCore/html/HTMLTemplateElement.cpp:
* Source/WebCore/html/HTMLTemplateElement.h:
* Source/WebCore/html/HTMLTemplateElement.idl:
* Source/WebCore/html/parser/HTMLConstructionSite.cpp:
* Source/WebCore/style/ChildChangeInvalidation.cpp:
(WebCore::HTMLTemplateElement::htmlFor const):
(WebCore::HTMLTemplateElement::setHTMLFor):
(WebCore::HTMLTemplateElement::insertionTarget):
(WebCore::HTMLTemplateElement::insertionNextChild):
(WebCore::HTMLTemplateElement::prepareContentPatching):
(WebCore::HTMLTemplateElement::finishParsingChildren):
(WebCore::insert):
(WebCore::HTMLConstructionSite::insertHTMLTemplateElement):
(WebCore::HTMLConstructionSite::insertTextNode):
(WebCore::HTMLConstructionSite::treeScopeForCurrentNode):
(WebCore::HTMLConstructionSite::containerForCurrentNode):
(WebCore::HTMLConstructionSite::ownerDocumentForCurrentNode):
(WebCore::registryForCurrentNode):
(WebCore::Style::ChildChangeInvalidation::invalidateAfterChange):

Co-authored-by: Noam Rosenthal <nrosenthal@chromium.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merging-blocked Applied to prevent a change from being merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants