Backtestsjsouprun-20261006-181938#2628

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

Node.before(Node) / after(Node) throw NPE and detach the node when given the node itself

Better

Our patch was judged better than the merged fix.

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

The two code changes are identical. Both add `if (node == this) return this;` in `Node.before(Node)` and `Node.after(Node)`, after the null validations and before the sibling-removal step. That is the root cause: when `node == this`, the `node.parentNode == parentNode` check is always true, so the node removes itself and `parentNode` becomes null. Returning early restores the 1.15.4 no-op behavior the issue describes, and returning `this` matches the method's existing return contract. Correctness and scope are therefore equal. Patch A's CHANGES.md entry is neutral. Patch B's inline comment is a small clarity gain but not significant.

The difference is in the tests. Both patches add before-self and after-self tests on an Element that would throw an NPE before the fix and pass after it. Both check the return value, the parent, and the child count. Patch A checks the position with `ul.child(1)` and the order with text. Patch B checks `siblingIndex()` and the exact serialized HTML, which is a slightly stronger structural check. Patch B also adds a test on a TextNode. Element overrides `before` and `after` and delegates to `Node`, so this test exercises the base `Node.before/after` directly on a non-Element node type and covers both methods. That broadens coverage of the fixed code path in a meaningful way.

One small risk: Patch B relies on `TextUtil` being imported in NodeTest. It is already used in jsoup's test suite, so this is likely fine.

With identical fixes, Patch B's more thorough tests give it the edge.

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

8m 10s

Wall-clock time in the container

Full test suite

No new failures

2,392 passed · 0 skipped · 2,392 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

38vs 29 merged

Changed lines, ours vs merged

Version

jsoup 1.23.2

Test

@Test
public void test_before_self() {
    Document doc = Jsoup.parse("<ul><li id=a>A</li><li id=b>B</li><li id=c>C</li></ul>");
    Element ul = doc.expectFirst("ul");
    Element b = doc.expectFirst("#b");

    try {
        b.before(b);
    } catch (ValidationException expected) {
        // Rejecting a self-insert may also be reasonable.
    }

    assertSame(ul, b.parent());
    assertEquals(3, ul.childrenSize());
}

Description

Calling before(Node) or after(Node) with the node itself throws a NullPointerException, and the node has already been removed from the document when the exception is thrown:

java.lang.NullPointerException: Cannot invoke "org.jsoup.nodes.Element.addChildren(int, org.jsoup.nodes.Node[])" because "this.parentNode" is null
 at org.jsoup.nodes.Node.before(Node.java:410)
 at org.jsoup.nodes.Element.before(Element.java:1032)

After this, b.parent() is null and the list only contains A and C.

This looks like a regression from 62de0a18, first released in 1.16.1. The test above passes on 1.15.4, where b.before(b) and b.after(b) leave the document unchanged.

Since that commit, when node == this, the check node.parentNode == parentNode is always true, so node.remove() removes this node and clears this.parentNode before parentNode.addChildren(...) runs. The validateChild check from #2558 runs inside addChildren, so it isn't reached.

This can happen when the node being moved and the reference node come from separate lookups and turn out to be the same element.

The two patches

Our patch+38 −0
src/main/java/org/jsoup/nodes/Node.javaindex afef11c2..d0279846 100644@@ -403,6 +403,7 @@ public abstract class Node implements Cloneable {     public Node before(Node node) {         Validate.notNull(node);         Validate.notNull(parentNode);+        if (node == this) return this; // inserting a node next to itself is a no-op          // 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);+        if (node == this) return this; // inserting a node next to itself is a no-op          // if the incoming node is a sibling of this, remove it first so siblingIndex is correct on add         if (node.parentNode == parentNode) node.remove();src/test/java/org/jsoup/nodes/NodeTest.javaindex d8d8c327..90761359 100644@@ -350,6 +350,42 @@ public class NodeTest {         assertEquals("Three One Two", div.text());     } +    @Test void beforeSelfIsNoop() {+        Document doc = Jsoup.parse("<ul><li id=a>A</li><li id=b>B</li><li id=c>C</li></ul>");+        Element ul = doc.expectFirst("ul");+        Element b = doc.expectFirst("#b");++        assertSame(b, b.before(b));+        assertSame(ul, b.parent());+        assertEquals(3, ul.childrenSize());+        assertEquals(1, b.siblingIndex());+        assertEquals("<li id=\"a\">A</li><li id=\"b\">B</li><li id=\"c\">C</li>", TextUtil.stripNewlines(ul.html()));+    }++    @Test void afterSelfIsNoop() {+        Document doc = Jsoup.parse("<ul><li id=a>A</li><li id=b>B</li><li id=c>C</li></ul>");+        Element ul = doc.expectFirst("ul");+        Element b = doc.expectFirst("#b");++        assertSame(b, b.after(b));+        assertSame(ul, b.parent());+        assertEquals(3, ul.childrenSize());+        assertEquals(1, b.siblingIndex());+        assertEquals("<li id=\"a\">A</li><li id=\"b\">B</li><li id=\"c\">C</li>", TextUtil.stripNewlines(ul.html()));+    }++    @Test void beforeAndAfterSelfOnNonElementNode() {+        Document doc = Jsoup.parse("<p>One<b>Two</b></p>");+        Element p = doc.expectFirst("p");+        Node text = p.childNode(0);++        assertSame(text, text.before(text));+        assertSame(text, text.after(text));+        assertSame(p, text.parent());+        assertEquals(0, text.siblingIndex());+        assertEquals("One<b>Two</b>", p.html());+    }+     @Test public void unwrap() {         Document doc = Jsoup.parse("<div>One <span>Two <b>Three</b></span> Four</div>");         Element span = doc.select("span").first(); 
Merged fix · PR #+29 −0
CHANGES.mdindex 3e612d83..5c3c9104 100644@@ -28,6 +28,7 @@ * Fixed a `ConcurrentModificationException` when emptying and reading separate childless elements concurrently. [#2620](https://github.com/jhy/jsoup/pull/2620) * Removed the old `command`, `device`, and `menuitem` tags, as they are no longer in the HTML spec. [#2621](https://github.com/jhy/jsoup/issues/2621) * Double-escaped script tags in body were being closed too early. [#2627](https://github.com/jhy/jsoup/issues/2627)+* `Node.before(Node)` and `Node.after(Node)` now leave the document unchanged when given the node itself, instead of throwing a `NullPointerException`. [#2628](https://github.com/jhy/jsoup/issues/2628)  ## 1.23.2 (2026-Aug-26) src/main/java/org/jsoup/nodes/Node.javaindex afef11c2..608dfcac 100644@@ -403,6 +403,7 @@ public abstract class Node implements Cloneable {     public Node before(Node node) {         Validate.notNull(node);         Validate.notNull(parentNode);+        if (node == this) return this;          // 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);+        if (node == this) return this;          // if the incoming node is a sibling of this, remove it first so siblingIndex is correct on add         if (node.parentNode == parentNode) node.remove();src/test/java/org/jsoup/nodes/NodeTest.javaindex d8d8c327..b6267c96 100644@@ -319,6 +319,19 @@ public class NodeTest {         assertEquals("Three One Two", div.text());     } +    @Test void beforeSelfIsNoOp() {+        // https://github.com/jhy/jsoup/issues/2628+        Document doc = Jsoup.parse("<ul><li id=a>A</li><li id=b>B</li><li id=c>C</li></ul>");+        Element ul = doc.expectFirst("ul");+        Element b = doc.expectFirst("#b");++        assertSame(b, b.before(b));+        assertSame(ul, b.parent());+        assertEquals(3, ul.childrenSize());+        assertSame(b, ul.child(1));+        assertEquals("A B C", ul.text());+    }+     @Test public void after() {         Document doc = Jsoup.parse("<p>One <b>two</b> three</p>");         Element newNode = new Element(Tag.valueOf("em"), "");@@ -350,6 +363,19 @@ public class NodeTest {         assertEquals("Three One Two", div.text());     } +    @Test void afterSelfIsNoOp() {+        // https://github.com/jhy/jsoup/issues/2628+        Document doc = Jsoup.parse("<ul><li id=a>A</li><li id=b>B</li><li id=c>C</li></ul>");+        Element ul = doc.expectFirst("ul");+        Element b = doc.expectFirst("#b");++        assertSame(b, b.after(b));+        assertSame(ul, b.parent());+        assertEquals(3, ul.childrenSize());+        assertSame(b, ul.child(1));+        assertEquals("A B C", ul.text());+    }+     @Test public void unwrap() {         Document doc = Jsoup.parse("<div>One <span>Two <b>Three</b></span> Four</div>");         Element span = doc.select("span").first();