Backtestsjsouprun-20261006-181938#2552

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

Element.appendChild allows self-parenting and creates a cyclic DOM tree

Better

Our patch was judged better than the merged fix.

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

Both patches fix the reported `e.appendChild(e)` case. Each adds a check that rejects inserting a node that is the target itself or one of its ancestors, with the same fast exit for childless nodes. Both check every child before moving any, so a rejected batch leaves the tree unchanged.

Patch A puts the check inside `setParentNode`, so it covers any path that reparents a node. To do that it restructures `addChildren`, `replaceChild` and the in-place fast path around a new `setParentNodeUnchecked`. That is broader, but it is more churn in hot code, and it changes the fast path, which now goes through `removeChild` logic it skipped before.

Patch A also misses one case. When a detached node calls `replaceWith(in)`, it borrows `in`'s parent before any check runs. If `in` is a descendant of that node, the node's parent pointer is already set to its own descendant. That is a parent cycle, and it can stay in place when the operation then fails.

Patch B checks at each entry point: `appendChild`, `before`/`after`, `replaceChild`, both `addChildren` overloads, and explicitly that detached `replaceWith` case, before any mutation. It is a smaller, less risky change to the existing code. It also moves `noNullElements` ahead of the fast path, which is a small robustness gain.

On tests, both suites would fail before the fix and pass after. Patch B's suite is broader: self and ancestor checks for append, prepend, insert, `appendTo`, `before`/`after`, `replaceWith`, the fast path, the detached-replace case, and a check that legitimate same-parent moves still work. Patch A tests atomic batch rejection and moving a populated subtree, both useful, but not `before`/`after` or the detached case.

Patch A's CHANGES entry is a minor plus. Overall, Patch B covers more edge cases with less risk and better tests.

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

12m 21s

Wall-clock time in the container

Full test suite

No new failures

2,137 passed · 0 skipped · 2,137 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

106vs 136 merged

Changed lines, ours vs merged

Version

jsoup 1.23.1

Test

@Test
public void test_appendChild_H1_20e4b2() {
    Element e = new Element(Tag.valueOf("div"), "");

    try {
        e.appendChild(e);
        assertNotSame(e, e.parent());
        assertTrue(e.childNodeSize() == 0 || e.childNode(0) != e);
    } catch (RuntimeException expected) {
        // Invalid self-parenting may be rejected.
    }
}

Description

When this test is executed, it does not terminate and appears to enter an infinite loop.
The problem seems to be triggered by:

 e.appendChild(e);

This operation appears to make the element its own parent and child. The subsequent assertion failure may cause JUnit to serialize the cyclic element while constructing the failure message, which also does not terminate.
Should appendChild() reject self-parenting and prevent cyclic DOM structures, or is this behavior considered a problem with the test?

The two patches

Our patch+104 −2
src/main/java/org/jsoup/nodes/Element.javaindex efc34a67..78a9e403 100644@@ -812,6 +812,7 @@ public class Element extends Node implements Iterable<Element> {      */     public Element appendChild(Node child) {         Validate.notNull(child);+        validateNotAncestor(child);          // was - Node#addChildren(child). short-circuits an array create and a loop.         reparentChild(child);src/main/java/org/jsoup/nodes/Node.javaindex 304a51af..461e072d 100644@@ -403,6 +403,7 @@ public abstract class Node implements Cloneable {     public Node before(Node node) {         Validate.notNull(node);         Validate.notNull(parentNode);+        parentNode.validateNotAncestor(node);          // if the incoming node is a sibling of this, remove it first so siblingIndex is correct on add         if (node.parentNode == parentNode) node.remove();@@ -431,6 +432,7 @@ public abstract class Node implements Cloneable {     public Node after(Node node) {         Validate.notNull(node);         Validate.notNull(parentNode);+        parentNode.validateNotAncestor(node);          // if the incoming node is a sibling of this, remove it first so siblingIndex is correct on add         if (node.parentNode == parentNode) node.remove();@@ -530,7 +532,10 @@ public abstract class Node implements Cloneable {      */     public void replaceWith(Node in) {         Validate.notNull(in);-        if (parentNode == null) parentNode = in.parentNode; // allows old to have been temp removed before replacing+        if (parentNode == null && in.parentNode != null) {+            in.parentNode.validateNotAncestor(this); // borrowing in's parent must not make this its own ancestor+            parentNode = in.parentNode; // allows old to have been temp removed before replacing+        }         Validate.notNull(parentNode);         parentNode.replaceChild(this, in);     }@@ -547,6 +552,7 @@ public abstract class Node implements Cloneable {         Validate.isTrue(out.parentNode == this);         Validate.notNull(in);         if (out == in) return; // no-op self replacement+        validateNotAncestor(in);          if (in.parentNode != null)             in.parentNode.removeChild(in);@@ -574,6 +580,9 @@ public abstract class Node implements Cloneable {      protected void addChildren(Node... children) {         //most used. short circuit addChildren(int), which hits reindex children and array copy+        for (Node child: children) {+            validateNotAncestor(child);+        }         final List<Node> nodes = ensureChildNodes();          for (Node child: children) {@@ -587,6 +596,10 @@ public abstract class Node implements Cloneable {         // todo clean up all these and use the list, not the var array. just need to be careful when iterating the incoming (as we are removing as we go)         Validate.notNull(children);         if (children.length == 0) return;+        Validate.noNullElements(children);+        for (Node child : children) {+            validateNotAncestor(child);+        }         final List<Node> nodes = ensureChildNodes();          // fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace@@ -615,7 +628,6 @@ public abstract class Node implements Cloneable {             }         } -        Validate.noNullElements(children);         for (Node child : children) {             reparentChild(child);         }@@ -627,6 +639,21 @@ public abstract class Node implements Cloneable {         child.setParentNode(this);     } +    /**+     Validates that the given node may be inserted as a child of this node: it must not be this node, nor one of this+     node's ancestors, as that would create a cycle in the DOM tree.+     @param child the node to be inserted+     @throws org.jsoup.helper.ValidationException if inserting the node would create a cycle+     */+    void validateNotAncestor(Node child) {+        Validate.notNull(child);+        Validate.isFalse(child == this, "Cannot add a node as a child of itself");+        if (child.childNodeSize() == 0) return; // an ancestor of this must have children; skips the walk for new nodes+        for (Node ancestor = parentNode; ancestor != null; ancestor = ancestor.parentNode) {+            Validate.isFalse(ancestor == child, "Cannot add an ancestor node as a child of its descendant");+        }+    }+     /**      Retrieves this node's sibling nodes. Similar to {@link #childNodes() node.parent.childNodes()}, but does not      include this node (a node is not a sibling of itself).src/test/java/org/jsoup/nodes/ElementTest.javaindex 229fe210..e28116b9 100644@@ -21,6 +21,7 @@ import org.junit.jupiter.params.provider.ValueSource;  import java.util.ArrayList; import java.util.Collection;+import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet;@@ -3542,4 +3543,77 @@ public class ElementTest {         assertEquals(1, actualSize);         assertEquals(1, reported); // was 0 via cache     }++    @Test void appendChildRejectsSelf() {+        Element div = new Element("div");+        assertThrows(ValidationException.class, () -> div.appendChild(div));+        assertNull(div.parent());+        assertEquals(0, div.childNodeSize());+        assertEquals("<div></div>", div.outerHtml());+    }++    @Test void appendChildRejectsAncestor() {+        Document doc = Jsoup.parse("<div id=a><p id=b><span id=c>One</span></p></div>");+        Element a = doc.expectFirst("#a");+        Element c = doc.expectFirst("#c");+        assertThrows(ValidationException.class, () -> c.appendChild(a));+        assertThrows(ValidationException.class, () -> a.appendTo(c));+        // tree unchanged+        assertSame(doc.body(), a.parent());+        assertEquals("<div id=\"a\"><p id=\"b\"><span id=\"c\">One</span></p></div>", TextUtil.stripNewlines(doc.body().html()));+    }++    @Test void prependAndInsertChildrenRejectSelfOrAncestor() {+        Document doc = Jsoup.parse("<div id=a><p id=b><span id=c>One</span></p></div>");+        Element a = doc.expectFirst("#a");+        Element b = doc.expectFirst("#b");+        Element c = doc.expectFirst("#c");+        assertThrows(ValidationException.class, () -> c.prependChild(c));+        assertThrows(ValidationException.class, () -> c.prependChild(a));+        assertThrows(ValidationException.class, () -> c.insertChildren(0, b));+        assertThrows(ValidationException.class, () -> c.insertChildren(-1, Collections.singletonList(a)));+        assertThrows(ValidationException.class, () -> c.appendChildren(Collections.singletonList(c)));+        assertThrows(ValidationException.class, () -> c.prependChildren(Collections.singletonList(b)));+        // the fast path in addChildren (moving all of a parent's children) is checked too+        assertThrows(ValidationException.class, () -> c.insertChildren(0, a.parent().childNodes()));+        assertEquals("<div id=\"a\"><p id=\"b\"><span id=\"c\">One</span></p></div>", TextUtil.stripNewlines(doc.body().html()));++        // moving a node's own children back into it remains fine+        b.insertChildren(0, b.childNodes());+        assertEquals("<div id=\"a\"><p id=\"b\"><span id=\"c\">One</span></p></div>", TextUtil.stripNewlines(doc.body().html()));+    }++    @Test void beforeAfterRejectSelfOrAncestor() {+        Document doc = Jsoup.parse("<div id=a><p id=b><span id=c>One</span></p></div>");+        Element a = doc.expectFirst("#a");+        Element b = doc.expectFirst("#b");+        Element c = doc.expectFirst("#c");+        assertThrows(ValidationException.class, () -> c.before(b));+        assertThrows(ValidationException.class, () -> c.after(a));+        assertThrows(ValidationException.class, () -> c.childNode(0).after(c));+        assertEquals("<div id=\"a\"><p id=\"b\"><span id=\"c\">One</span></p></div>", TextUtil.stripNewlines(doc.body().html()));+    }++    @Test void replaceWithRejectsAncestor() {+        Document doc = Jsoup.parse("<div id=a><p id=b><span id=c>One</span></p></div>");+        Element a = doc.expectFirst("#a");+        Element c = doc.expectFirst("#c");+        assertThrows(ValidationException.class, () -> c.childNode(0).replaceWith(c));+        assertThrows(ValidationException.class, () -> c.childNode(0).replaceWith(a));+        assertEquals("<div id=\"a\"><p id=\"b\"><span id=\"c\">One</span></p></div>", TextUtil.stripNewlines(doc.body().html()));+    }++    @Test void detachedReplaceWithRejectsDescendant() {+        // a detached node borrows in's parent; must not become a child of its own descendant+        Element a = new Element("a");+        Element p = a.appendElement("p");+        Element b = p.appendElement("b");+        b.appendText("x");+        assertThrows(ValidationException.class, () -> a.replaceWith(b));+        assertThrows(ValidationException.class, () -> a.replaceWith(p));+        assertNull(a.parent());+        assertSame(a, p.parent());+        assertSame(p, b.parent());+        assertEquals("<a><p><b>x</b></p></a>", TextUtil.stripNewlines(a.outerHtml()));+    } } 
Merged fix · PR #2558+123 −13
CHANGES.mdindex c4c7e5ed..fca97364 100644@@ -5,6 +5,7 @@ ### Improvements * Improved consecutive `StreamParser.selectFirst(...)` calls during progressive parsing, so later matches are returned with their parsed contents when earlier selections have left them as parser lookahead. E.g., given `<title>One</title><p id=hit>Full</p><p>Next</p>`, selecting `title` and then `#hit` now advances the partial lookahead and returns `<p id="hit">Full</p>`, rather than returning an empty `<p id="hit"></p>` before its content is parsed. The updated readiness tracking follows StreamParser's normal emission order across implicit HTML structure and parser recovery. [#2551](https://github.com/jhy/jsoup/pull/2551) * Improved XML parser performance and memory use for documents with many nested namespace declarations by recording namespace changes within each element scope. [#2556](https://github.com/jhy/jsoup/pull/2556)+* DOM mutation methods, including child insertion and replacement, now reject operations that would create a cycle, such as making a node its own child or moving an ancestor beneath a descendant. [#2552](https://github.com/jhy/jsoup/issues/2552)  ### Bug Fixes * Fixed the JDK `HttpClient` implementation to accept responses without a `Content-Type` header, matching the `HttpURLConnection` implementation. [#2549](https://github.com/jhy/jsoup/pull/2549)src/main/java/org/jsoup/nodes/Node.javaindex 304a51af..b7582804 100644@@ -537,10 +537,36 @@ public abstract class Node implements Cloneable {      protected void setParentNode(Node parentNode) {         Validate.notNull(parentNode);+        assert parentNode instanceof Element;+        parentNode.validateChild(this);+        setParentNodeUnchecked((Element) parentNode);+    }++    /** Reparents this node without cycle validation; callers must validate first. */+    private void setParentNodeUnchecked(Element parentNode) {         if (this.parentNode != null)             this.parentNode.removeChild(this);-        assert parentNode instanceof Element;-        this.parentNode = (Element) parentNode;+        this.parentNode = parentNode;+    }++    private static final String CycleError = "Cannot add a node here because it would create a cycle.";++    /** Checks that the child is neither this node nor an ancestor of this node. */+    private void validateChild(Node child) {+        Validate.isFalse(child == this, CycleError);+        if (child.childNodeSize() == 0) return;++        for (Node ancestor = parentNode; ancestor != null; ancestor = ancestor.parentNode)+            Validate.isFalse(ancestor == child, CycleError);+    }++    /** Checks every child before reparenting any of them. */+    private void validateChildren(Node[] children) {+        Validate.notNull(children);+        for (Node child : children) {+            Validate.notNull(child, "Array must not contain any null objects");+            validateChild(child);+        }     }      protected void replaceChild(Node out, Node in) {@@ -548,16 +574,16 @@ public abstract class Node implements Cloneable {         Validate.notNull(in);         if (out == in) return; // no-op self replacement -        if (in.parentNode != null)-            in.parentNode.removeChild(in);+        Element parent = (Element) this;+        validateChild(in);+        in.setParentNodeUnchecked(parent);          final int index = out.siblingIndex();         ensureChildNodes().set(index, in);-        in.parentNode = (Element) this;         in.setSiblingIndex(index);         out.parentNode = null; -        ((Element) this).childNodes.incrementMod(); // as mod count not changed in set(), requires explicit update, to invalidate the child element cache+        parent.childNodes.incrementMod(); // as mod count not changed in set(), requires explicit update, to invalidate the child element cache     }      protected void removeChild(Node out) {@@ -574,10 +600,14 @@ public abstract class Node implements Cloneable {      protected void addChildren(Node... children) {         //most used. short circuit addChildren(int), which hits reindex children and array copy+        validateChildren(children);+         final List<Node> nodes = ensureChildNodes();+        assert this instanceof Element;+        Element parent = (Element) this;          for (Node child: children) {-            reparentChild(child);+            child.setParentNodeUnchecked(parent);             nodes.add(child);             child.setSiblingIndex(nodes.size()-1);         }@@ -587,7 +617,11 @@ public abstract class Node implements Cloneable {         // todo clean up all these and use the list, not the var array. just need to be careful when iterating the incoming (as we are removing as we go)         Validate.notNull(children);         if (children.length == 0) return;+        validateChildren(children);+         final List<Node> nodes = ensureChildNodes();+        assert this instanceof Element;+        Element parent = (Element) this;          // fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace         final Node firstParent = children[0].parent();@@ -606,21 +640,19 @@ public abstract class Node implements Cloneable {                 firstParent.empty();                 nodes.addAll(index, Arrays.asList(children));                 i = children.length;-                assert this instanceof Element;                 while (i-- > 0) {-                    children[i].parentNode = (Element) this;+                    children[i].setParentNodeUnchecked(parent);                 }-                ((Element) this).invalidateChildren();+                parent.invalidateChildren();                 return;             }         } -        Validate.noNullElements(children);         for (Node child : children) {-            reparentChild(child);+            child.setParentNodeUnchecked(parent);         }         nodes.addAll(index, Arrays.asList(children));-        ((Element) this).invalidateChildren();+        parent.invalidateChildren();     }          protected void reparentChild(Node child) {src/test/java/org/jsoup/nodes/NodeTest.javaindex 51b4f71c..d8d8c327 100644@@ -2,6 +2,7 @@ package org.jsoup.nodes;  import org.jsoup.Jsoup; import org.jsoup.TextUtil;+import org.jsoup.helper.ValidationException; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.jsoup.select.NodeVisitor;@@ -188,6 +189,82 @@ public class NodeTest {                 TextUtil.stripNewlines(children.html()));     } +    @Test void rejectsSelfParenting() {+        Element element = new Element("div");++        ValidationException exception = assertThrows(ValidationException.class, () -> element.appendChild(element));+        assertEquals("Cannot add a node here because it would create a cycle.", exception.getMessage());+        assertNull(element.parent());+        assertEquals(0, element.childNodeSize());+    }++    @Test void rejectsAncestorAsChild() {+        Element root = new Element("root");+        Element child = root.appendElement("child");+        Element descendant = child.appendElement("descendant");+        String originalHtml = root.outerHtml();++        assertThrows(ValidationException.class, () -> descendant.appendChild(root));+        assertEquals(originalHtml, root.outerHtml());+        assertNull(root.parent());+        assertSame(root, child.parent());+        assertSame(child, descendant.parent());+    }++    @Test void rejectsAncestorReplacement() {+        Element root = new Element("root");+        Element child = root.appendElement("child");+        child.appendElement("descendant");+        String originalHtml = root.outerHtml();++        assertThrows(ValidationException.class, () -> child.replaceWith(root));+        assertEquals(originalHtml, root.outerHtml());+        assertNull(root.parent());+        assertSame(root, child.parent());+    }++    @Test void rejectsCyclicBatchAtomically() {+        Element source = new Element("source");+        Element movable = source.appendElement("movable");+        Element ancestor = new Element("ancestor");+        Element target = ancestor.appendElement("target");+        String sourceHtml = source.outerHtml();+        String ancestorHtml = ancestor.outerHtml();++        assertThrows(ValidationException.class, () -> target.insertChildren(0, movable, ancestor));+        assertEquals(sourceHtml, source.outerHtml());+        assertEquals(ancestorHtml, ancestor.outerHtml());+        assertSame(source, movable.parent());+        assertNull(ancestor.parent());+        assertSame(ancestor, target.parent());+    }++    @Test void rejectsCyclicWholeSourceMove() {+        Element source = new Element("source");+        Element ancestor = source.appendElement("ancestor");+        Element target = ancestor.appendElement("target");+        String originalHtml = source.outerHtml();++        assertThrows(ValidationException.class, () -> target.insertChildren(0, source.childNodes()));+        assertEquals(originalHtml, source.outerHtml());+        assertNull(source.parent());+        assertSame(source, ancestor.parent());+        assertSame(ancestor, target.parent());+    }++    @Test void allowsPopulatedSubtreeMove() {+        Element source = new Element("source");+        Element subtree = source.appendElement("subtree");+        subtree.appendElement("child").text("One");+        Element target = new Element("target");++        target.appendChild(subtree);+        assertEquals(0, source.childNodeSize());+        assertSame(target, subtree.parent());+        assertSame(subtree, target.childNode(0));+        assertEquals("One", target.text());+    }+     @Test public void ownerDocument() {         Document doc = Jsoup.parse("<p>Hello");         Element p = doc.select("p").first();