Backtestsjsouprun-20261006-181938#2614

Issue #2614 Merged fix PR #2615 Run 6 Oct 2026 · run-20261006-181938 jhy/jsoup

Template contents can parse incorrectly at EOF and around forms

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

The deciding difference is the issue's headline example, `<template><table><form></table></template>`.

Per the HTML spec's "in table" handling of a `form` start tag, the token is ignored when a template is on the stack or the form pointer is set.
- **Patch B** follows this rule. It changes the check to `getFormElement() != null || inTemplateContents()`, so the form is dropped. Its test expects `<template><table></table></template>` with no form in the document, which matches WPT `template.dat`.
- **Patch A** inverts the condition to `getFormElement() != null && !isParsingTemplateContents()`. As a result it inserts a `<form>` inside the template's table, and its test locks in that non-spec output (`<table><form></form></table>`). This would still fail the corresponding WPT case, so Patch A partly misfixes the issue it targets.

**Shared changes.** Both patches:
- route the InTable EOF through InBody,
- replace the recursive template-closing at EOF with a loop, removing the depth-12 cap,
- extend the template checks to template-context fragments for form start and end tags.

**Extra correctness work in Patch B.**
- It stops the fragment form-ancestor search at a template boundary, so `Element.html()` inside template contents does not pick up an outer form.
- It prevents form controls inside template contents from being associated with an outer form pointer. This fits the issue's statement that template forms should not interfere with the surrounding document.
- It guards the post-loop reprocess for template fragment contexts.

**Tests.** Patch B's tests are broader and spec-aligned: table modes at EOF, depth 40, deep nesting in fragments, and form isolation in both document and fragment parsing. Patch A's tests include an incorrect expectation.

Overall, Patch B is more correct and better tested.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

20m 53s

Wall-clock time in the container

Full test suite

No new failures

2,371 passed · 0 skipped · 2,371 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

141vs 93 merged

Changed lines, ours vs merged

While running the HTML tree-construction tests, I found a couple of related gaps in jsoup’s template handling.

Unclosed templates are not always finished correctly when the input ends, particularly when a template contains a table or when templates are deeply nested.

Forms inside template contents can also interfere with forms in the surrounding document.
For example:

<template><table><form></table></template><input name=outside>

The form belongs to the template contents and should not capture the input that follows the template.

The same rules should apply when setting the contents of a template with Element.html().

Together, these account for 16 failures in WPT’s 0.

The two patches

Our patch+121 −20
CHANGES.mdindex 4f3ad1f2..398a8cb0 100644@@ -21,6 +21,7 @@ * `:has()` now correctly matches sibling alternatives and descendants of siblings. Given `<div id=a></div><div><span></span></div>`, both `#a:has(+ div, > span)` and `#a:has(+ div span)` select `#a`. [#2610](https://github.com/jhy/jsoup/pull/2610) * Within node selectors, `:not()` now correctly applies `:contains()` and `:matches()` to the node value. For example, `::comment:not(:contains(foo))` excludes comments containing `foo`. [#2610](https://github.com/jhy/jsoup/pull/2610) * Updated `<select>` parsing to the current HTML spec, retaining elements such as buttons and other markup that the previous rules discarded. [#2611](https://github.com/jhy/jsoup/issues/2611)+* Unclosed `<template>` elements are now closed correctly at the end of input, including when the template contains a table or templates are deeply nested, so the document body is still created. Forms in template contents no longer set or use the document's form element pointer, and form controls in template contents are not associated with a form outside the template. `Element.html()` on a template, or on an element within template contents, applies the same template contents rules.  ## 1.23.2 (2026-Aug-26) src/main/java/org/jsoup/parser/HtmlTreeBuilder.javaindex da239e4a..2f28e19a 100644@@ -130,13 +130,14 @@ public class HtmlTreeBuilder extends TreeBuilder {             resetInsertionMode();              // setup form element to nearest form on context (up ancestor chain). ensures form controls are associated-            // with form correctly+            // with form correctly. Template contents are a separate tree, so don't search beyond a template             Element formSearch = context;             while (formSearch != null) {                 if (formSearch instanceof FormElement) {                     formElement = (FormElement) formSearch;                     break;                 }+                if (formSearch.elementIs("template", NamespaceHtml)) break;                 formSearch = formSearch.parent();             } @@ -353,6 +354,14 @@ public class HtmlTreeBuilder extends TreeBuilder {         return fragmentParsing;     } +    /**+     Tests whether insertion is within template contents: a template is on the stack, or this is a fragment parse with a+     template context (whose element is not on the stack). Forms in template contents don't use the form element pointer.+     */+    boolean inTemplateContents() {+        return onStack("template") || fragmentContextIs("template");+    }+     /** Tests whether this fragment was created with the named HTML context element. */     boolean fragmentContextIs(String normalName) {         return fragmentParsing && contextElement != null && contextElement.elementIs(normalName, NamespaceHtml);@@ -439,7 +448,7 @@ public class HtmlTreeBuilder extends TreeBuilder {         FormElement el = (FormElement) createElementFor(startTag, NamespaceHtml, false);          if (checkTemplateStack) {-            if(!onStack("template"))+            if (!inTemplateContents())                 setFormElement(el);         } else             setFormElement(el);@@ -456,8 +465,9 @@ public class HtmlTreeBuilder extends TreeBuilder {     private void doInsertElement(Element el) {         enforceStackDepthLimit(); -        if (formElement != null && el.tag().namespace.equals(NamespaceHtml) && StringUtil.inSorted(el.normalName(), TagFormListed))-            formElement.addElement(el); // connect form controls to their form element+        if (formElement != null && el.tag().namespace.equals(NamespaceHtml) && StringUtil.inSorted(el.normalName(), TagFormListed)+            && !inTemplateContents())+            formElement.addElement(el); // connect form controls to their form element; template contents are not associated          // in HTML, the xmlns attribute if set must match what the parser set the tag's namespace to         if (parser.getErrors().canAddError() && el.hasAttr("xmlns") && !el.attr("xmlns").equals(el.tag().namespace()))src/main/java/org/jsoup/parser/HtmlTreeBuilderState.javaindex 7c003fe5..8c9b74f4 100644@@ -375,7 +375,7 @@ enum HtmlTreeBuilderState {                     }                     break;                 case "form":-                    if (tb.getFormElement() != null && !tb.onStack("template")) {+                    if (tb.getFormElement() != null && !tb.inTemplateContents()) {                         tb.error(this);                         return false;                     }@@ -695,7 +695,7 @@ enum HtmlTreeBuilderState {                     }                  case "form":-                    if (!tb.onStack("template")) {+                    if (!tb.inTemplateContents()) {                         Element currentForm = tb.getFormElement();                         tb.setFormElement(null);                         if (currentForm == null || !tb.inScope(name)) {@@ -1033,7 +1033,7 @@ enum HtmlTreeBuilderState {                     }                 } else if (name.equals("form")) {                     tb.error(this);-                    if (tb.getFormElement() != null || tb.onStack("template"))+                    if (tb.getFormElement() != null || tb.inTemplateContents())                         return false;                     else {                         tb.insertFormElement(startTag, false, false); // not added to stack. can associate to template@@ -1064,9 +1064,7 @@ enum HtmlTreeBuilderState {                 }                 return true; // todo: as above todo             } else if (t.isEOF()) {-                if (tb.currentElementIs("html"))-                    tb.error(this);-                return true; // stops parsing+                return tb.process(t, InBody); // closes any open templates, then stops parsing             }             return anythingElse(t, tb);         }@@ -1466,16 +1464,18 @@ enum HtmlTreeBuilderState {                     if (!tb.onStack("template")) { // stop parsing                         return true;                     }-                    tb.error(this);-                    tb.popStackToClose("template");-                    tb.clearFormattingElementsToLastMarker();-                    tb.popTemplateMode();-                    tb.resetInsertionMode();-                    // spec deviation - if we did not break out of Template, stop processing, and don't worry about cleaning up ultra-deep template stacks-                    // limited depth because this can recurse and will blow stack if too deep-                    if (tb.state() != InTemplate && tb.templateModeSize() < 12)-                        return tb.process(t);-                    else return true;+                    // close every open template here, rather than reprocessing the EOF once per template. Each+                    // reprocess would route back to this step via InBody, so looping is equivalent and keeps deep+                    // template nesting from recursing+                    while (tb.onStack("template")) {+                        tb.error(this);+                        tb.popStackToClose("template");+                        tb.clearFormattingElementsToLastMarker();+                        tb.popTemplateMode();+                        tb.resetInsertionMode();+                    }+                    if (tb.state() == InTemplate) return true; // template fragment context; nothing further to close+                    return tb.process(t);                 default:                     Validate.wtf("Unexpected state: " + t.type); // XmlDecl only in XmlTreeBuilder             }src/test/java/org/jsoup/parser/HtmlParserTest.javaindex ab8e7200..a4e632c9 100644@@ -2265,6 +2265,96 @@ public class HtmlParserTest {         assertFalse(parser.getErrors().isEmpty());     } +    @ParameterizedTest+    @ValueSource(strings = {"<table>", "<table><tbody>", "<table><tr>", "<table><caption>", "<table><colgroup>"})+    void unclosedTemplateWithTableIsClosedAtEof(String tableHtml) {+        // the EOF in a table mode must close the template, then continue to create the body+        Document doc = Jsoup.parse("<template>" + tableHtml);+        Element template = doc.head().expectFirst("template");+        assertEquals("table", template.child(0).normalName());+        assertNotNull(doc.selectFirst("html > body")); // parsed, not created on demand by doc.body()+    }++    @Test void deeplyNestedUnclosedTemplatesAreClosedAtEof() {+        int depth = 40;+        StringBuilder html = new StringBuilder();+        for (int i = 0; i < depth; i++) html.append("<template>");+        html.append("<table><tr><td>One");+        Document doc = Jsoup.parse(html.toString());++        assertEquals(depth, doc.select("template").size());+        assertEquals("One", doc.expectFirst("td").text());+        assertNotNull(doc.selectFirst("html > body")); // parsed, not created on demand by doc.body()+        assertEquals(0, doc.body().childNodeSize());+    }++    @Test void deeplyNestedUnclosedTemplatesInTemplateFragmentAreClosedAtEof() {+        Document doc = Jsoup.parse("<template id=context></template>");+        Element context = doc.expectFirst("#context");+        StringBuilder html = new StringBuilder();+        for (int i = 0; i < 30; i++) html.append("<template>");+        html.append("<table><tbody>");+        context.html(html.toString());++        assertEquals(31, context.select("template").size()); // includes the context itself+        assertNotNull(context.selectFirst("template > table > tbody"));+    }++    @Test void formInTemplateTableDoesNotCaptureFollowingInput() {+        Document doc = Jsoup.parse("<template><table><form></table></template><input name=outside>");+        assertEquals("<html><head><template><table></table></template></head><body><input name=\"outside\"></body></html>",+            TextUtil.stripNewlines(doc.html()));+        assertTrue(doc.select("form").isEmpty());+    }++    @Test void formInTemplateDoesNotCaptureFollowingInput() {+        Document doc = Jsoup.parse("<template><div><form id=inner></div></template><input name=outside>");+        FormElement inner = (FormElement) doc.expectFirst("#inner");+        assertTrue(inner.elements().isEmpty());+        assertEquals(0, inner.formData().size());+    }++    @Test void formInTemplateFragmentTableIsIgnored() {+        // Element.html() on a template uses the template contents rules, as in a document parse+        Document doc = Jsoup.parse("<template id=context></template>");+        Element context = doc.expectFirst("#context");+        context.html("<table><form></table><input name=outside>");+        assertEquals("<table></table><input name=\"outside\">", TextUtil.stripNewlines(context.html()));+        assertTrue(doc.select("form").isEmpty());+    }++    @Test void formInTemplateFragmentDoesNotCaptureFollowingInput() {+        Document doc = Jsoup.parse("<template id=context></template>");+        Element context = doc.expectFirst("#context");+        context.html("<div><form id=inner></div><input name=outside>");+        FormElement inner = (FormElement) doc.expectFirst("#inner");+        assertTrue(inner.elements().isEmpty());++        // and a second form in the template contents is not dropped by the first+        context.html("<div><form id=one></div><form id=two><input name=two></form>");+        assertEquals(2, context.select("form").size());+        FormElement two = (FormElement) doc.expectFirst("#two");+        assertEquals(1, two.elements().size());+        assertTrue(((FormElement) doc.expectFirst("#one")).elements().isEmpty());+    }++    @Test void formControlsInTemplateNotAssociatedWithOuterForm() {+        // the form is closed (not on the stack) but remains the form element pointer+        Document doc = Jsoup.parse("<div><form id=f></div><template><input name=a></template><input name=b>");+        FormElement form = (FormElement) doc.expectFirst("#f");+        assertEquals(1, form.formData().size());+        assertEquals("b", form.formData().get(0).key());+    }++    @Test void fragmentInTemplateContentsDoesNotUseOuterForm() {+        // the template contents are a separate tree, so the outer form is not the form element pointer+        Document doc = Jsoup.parse("<form id=f><template><div id=d></div></template></form>");+        Element div = doc.expectFirst("#d");+        div.html("<form id=g><input name=y></form>");+        FormElement inner = (FormElement) div.expectFirst("#g");+        assertEquals(1, inner.elements().size());+    }+     @Test void templateTableRowFragment() {         // https://github.com/jhy/jsoup/issues/1409 (per the fragment <tr> use case)         Document doc = Jsoup.parse("<body><table><template></template></table></body"); 
Merged fix · PR #2615+66 −27
CHANGES.mdindex 4f3ad1f2..b7aec082 100644@@ -21,6 +21,7 @@ * `:has()` now correctly matches sibling alternatives and descendants of siblings. Given `<div id=a></div><div><span></span></div>`, both `#a:has(+ div, > span)` and `#a:has(+ div span)` select `#a`. [#2610](https://github.com/jhy/jsoup/pull/2610) * Within node selectors, `:not()` now correctly applies `:contains()` and `:matches()` to the node value. For example, `::comment:not(:contains(foo))` excludes comments containing `foo`. [#2610](https://github.com/jhy/jsoup/pull/2610) * Updated `<select>` parsing to the current HTML spec, retaining elements such as buttons and other markup that the previous rules discarded. [#2611](https://github.com/jhy/jsoup/issues/2611)+* Template parsing now closes unclosed templates at EOF and handles forms correctly in template documents and fragments. [#2614](https://github.com/jhy/jsoup/issues/2614)  ## 1.23.2 (2026-Aug-26) src/main/java/org/jsoup/parser/HtmlTreeBuilder.javaindex da239e4a..042b33e8 100644@@ -358,6 +358,11 @@ public class HtmlTreeBuilder extends TreeBuilder {         return fragmentParsing && contextElement != null && contextElement.elementIs(normalName, NamespaceHtml);     } +    /** Tests whether the parser is inside a template or using a template fragment context. */+    boolean isParsingTemplateContents() {+        return onStack("template") || fragmentContextIs("template");+    }+     void error(HtmlTreeBuilderState state) {         if (parser.getErrors().canAddError())             parser.getErrors().add(new ParseError(reader, "Unexpected %s token [%s] when in state [%s]",@@ -435,14 +440,10 @@ public class HtmlTreeBuilder extends TreeBuilder {         return el;     } -    FormElement insertFormElement(Token.StartTag startTag, boolean onStack, boolean checkTemplateStack) {+    /** Inserts a form and leaves the form pointer unset while parsing template contents. */+    FormElement insertFormElement(Token.StartTag startTag, boolean onStack) {         FormElement el = (FormElement) createElementFor(startTag, NamespaceHtml, false);--        if (checkTemplateStack) {-            if(!onStack("template"))-                setFormElement(el);-        } else-            setFormElement(el);+        if (!isParsingTemplateContents()) setFormElement(el);          doInsertElement(el);         if (!onStack) pop();src/main/java/org/jsoup/parser/HtmlTreeBuilderState.javaindex 7c003fe5..7a8eb4bc 100644@@ -375,14 +375,14 @@ enum HtmlTreeBuilderState {                     }                     break;                 case "form":-                    if (tb.getFormElement() != null && !tb.onStack("template")) {+                    if (tb.getFormElement() != null && !tb.isParsingTemplateContents()) {                         tb.error(this);                         return false;                     }                     if (tb.inButtonScope("p")) {                         tb.closeElement("p");                     }-                    tb.insertFormElement(startTag, true, true); // won't associate to any template+                    tb.insertFormElement(startTag, true);                     break;                 case "plaintext":                     if (tb.inButtonScope("p")) {@@ -695,7 +695,7 @@ enum HtmlTreeBuilderState {                     }                  case "form":-                    if (!tb.onStack("template")) {+                    if (!tb.isParsingTemplateContents()) {                         Element currentForm = tb.getFormElement();                         tb.setFormElement(null);                         if (currentForm == null || !tb.inScope(name)) {@@ -1033,11 +1033,9 @@ enum HtmlTreeBuilderState {                     }                 } else if (name.equals("form")) {                     tb.error(this);-                    if (tb.getFormElement() != null || tb.onStack("template"))+                    if (tb.getFormElement() != null && !tb.isParsingTemplateContents())                         return false;-                    else {-                        tb.insertFormElement(startTag, false, false); // not added to stack. can associate to template-                    }+                    tb.insertFormElement(startTag, false);                 } else {                     return anythingElse(t, tb);                 }@@ -1064,9 +1062,7 @@ enum HtmlTreeBuilderState {                 }                 return true; // todo: as above todo             } else if (t.isEOF()) {-                if (tb.currentElementIs("html"))-                    tb.error(this);-                return true; // stops parsing+                return tb.process(t, InBody);             }             return anythingElse(t, tb);         }@@ -1466,16 +1462,14 @@ enum HtmlTreeBuilderState {                     if (!tb.onStack("template")) { // stop parsing                         return true;                     }-                    tb.error(this);-                    tb.popStackToClose("template");-                    tb.clearFormattingElementsToLastMarker();-                    tb.popTemplateMode();-                    tb.resetInsertionMode();-                    // spec deviation - if we did not break out of Template, stop processing, and don't worry about cleaning up ultra-deep template stacks-                    // limited depth because this can recurse and will blow stack if too deep-                    if (tb.state() != InTemplate && tb.templateModeSize() < 12)-                        return tb.process(t);-                    else return true;+                    while (tb.onStack("template")) {+                        tb.error(this);+                        tb.popStackToClose("template");+                        tb.clearFormattingElementsToLastMarker();+                        tb.popTemplateMode();+                        tb.resetInsertionMode();+                    }+                    return tb.process(t);                 default:                     Validate.wtf("Unexpected state: " + t.type); // XmlDecl only in XmlTreeBuilder             }src/test/java/org/jsoup/parser/HtmlParserTest.javaindex ab8e7200..107bc713 100644@@ -2307,6 +2307,49 @@ public class HtmlParserTest {         assertEquals("<p><template><b>One</b></template><i>Two</i></p>", TextUtil.stripNewlines(template.html()));     } +    @Test void nestedTemplatesCloseAtEof() {+        Document doc = Jsoup.parse("<template><template>");+        doc.outputSettings().prettyPrint(false);+        assertEquals("<html><head><template><template></template></template></head><body></body></html>", doc.html());+    }++    @Test void deeplyNestedTemplatesCloseAtEof() {+        StringBuilder html = new StringBuilder();+        for (int i = 0; i < 16; i++) html.append("<template><div>");++        Parser parser = Parser.htmlParser().setTrackErrors(100);+        Document doc = parser.parseInput(html.toString(), "");+        assertEquals(16, doc.select("template").size());+        assertEquals(16, parser.getErrors().size());+    }++    @Test void tableModeEofClosesTemplate() {+        Document doc = Jsoup.parse("<template><table>");+        doc.outputSettings().prettyPrint(false);+        assertEquals("<html><head><template><table></table></template></head><body></body></html>", doc.html());+    }++    @Test void formInTableUsesTemplateRules() {+        Document doc = Jsoup.parse("<template><table><form></table></template><input name=outside>");+        doc.outputSettings().prettyPrint(false);+        assertEquals("<html><head><template><table><form></form></table></template></head><body><input name=\"outside\"></body></html>", doc.html());+        assertTrue(((FormElement) doc.expectFirst("form")).elements().isEmpty());+    }++    @Test void formsInTemplateFragmentIgnoreFormPointer() {+        Element template = Jsoup.parseBodyFragment("<template></template>").expectFirst("template");+        template.ownerDocument().outputSettings().prettyPrint(false);+        template.html("<form><form>");+        assertEquals("<form><form></form></form>", template.html());+    }++    @Test void formEndInTemplateFragmentUsesScope() {+        Element template = Jsoup.parseBodyFragment("<template></template>").expectFirst("template");+        template.ownerDocument().outputSettings().prettyPrint(false);+        template.html("<form><div>E</form>F");+        assertEquals("<form><div>E</div></form>F", template.html());+    }+     @Test void templateFragment() {         // https://github.com/jhy/jsoup/issues/1315         String html = "<template id=\"lorem-ipsum\"><tr><td>Lorem</td><td>Ipsum</td></tr></template>";