Backtestsjsouprun-20261006-181938#2633

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

Source position tracking changes parsing of repeated formatting tags

Better

Our patch was judged better than the merged fix.

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

Both patches fix the root cause the issue names. Each makes `Attributes.equals()` skip internal keys and compare public `size()` instead of the raw `size` field, and each rewrites `hashCode()` as an order-independent sum over non-internal entries. Both would correct the Noah's Ark reconstruction with tracking on.

Patch A changes `equals()` minimally: it skips internal keys and keeps the existing `indexOfKey` lookup. That is correct, because the public sizes match and every public key is looked up on the other side. Its `hashCode` uses `key.hashCode() ^ Objects.hashCode(val)`, which is exactly the `Map.Entry`/`AbstractMap` convention. That fits the Javadoc's stated Map-like equality semantics. Its tests cover the exact issue scenario with tracking both on and off, plus an attributed variant. They also check equality with mixed order, internal keys and user data, and a negative case where an internal `/Two` must not match the public `Two`. The issue test and the source-range equality test would fail before the change.

Patch B swaps the lookup in `equals()` for an O(n²) duplicate-counting scheme that runs on every comparison, including the parser's Noah's Ark checks. This goes beyond the issue's ask and adds complexity and cost to a hot path. It handles duplicate attributes from `add()`, an edge case the original code never handled and the issue doesn't raise. Its `31*k+v` hash avoids name/value swap collisions, which is a minor quality gain but not needed for correctness. Its tests are decent, though the parser test only checks the tracking-on path. The CHANGES entry is nice but carries little weight.

On correctness and tests the two are about equal. Patch A delivers the fix with less risk and less churn, and it follows standard Map hashing conventions, so it is the better fix.

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

6m 51s

Wall-clock time in the container

Full test suite

No new failures

2,421 passed · 0 skipped · 2,421 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

70vs 97 merged

Changed lines, ours vs merged

Source tracking can impact the parse, due to how attributes are compared.

String html = "<p><b><b><b><b><p>x";
for (boolean track : new boolean[] {false, true}) {
    Document doc = Parser.htmlParser().setTrackPosition(track).parseInput(html, "");
    System.out.println(track + ": " + doc.body().child(1).outerHtml());
}

Expected in both cases: <p><b><b><b>x</b></b></b></p>

Actual with tracking enabled: <p><b><b><b><b>x</b></b></b></b></p>

The first paragraph retains all four original <b> elements, but only three identical formatting elements should be active for reconstruction in the second paragraph (per the _Noah's Ark_ clause). Source tracking adds internal range data to each element’s attributes; comparing that data prevents jsoup from recognising the three identical entries. Attributes.equals() and hashCode() should exclude internal attributes.

The two patches

Our patch+64 −6
src/main/java/org/jsoup/nodes/Attributes.javaindex 38fbc5d2..f1f3b3cc 100644@@ -597,7 +597,8 @@ public class Attributes implements Iterable<Attribute>, Cloneable {      /**      * Checks if these attributes are equal to another set of attributes, by comparing the two sets. Note that the order-     * of the attributes does not impact this equality (as per the Map interface equals()).+     * of the attributes does not impact this equality (as per the Map interface equals()). Internal attributes (such as+     * source range data and user data) are not included in the comparison.      * @param o attributes to compare with      * @return if both sets of attributes have the same content      */@@ -607,10 +608,11 @@ public class Attributes implements Iterable<Attribute>, Cloneable {         if (o == null || getClass() != o.getClass()) return false;          Attributes that = (Attributes) o;-        if (size != that.size) return false;+        if (size() != that.size()) return false;         for (int i = 0; i < size; i++) {             String key = keys[i];             assert key != null;+            if (isInternalKey(key)) continue;             int thatI = that.indexOfKey(key);             if (thatI == NotFound || !Objects.equals(vals[i], that.vals[thatI]))                 return false;@@ -619,14 +621,20 @@ public class Attributes implements Iterable<Attribute>, Cloneable {     }      /**-     * Calculates the hashcode of these attributes, by iterating all attributes and summing their hashcodes.+     * Calculates the hashcode of these attributes, by iterating all attributes and summing their hashcodes. Internal+     * attributes are excluded, and the order of attributes does not impact the hashcode, consistent with+     * {@link #equals(Object)}.      * @return calculated hashcode      */     @Override     public int hashCode() {-        int result = size;-        result = 31 * result + Arrays.hashCode(keys);-        result = 31 * result + Arrays.hashCode(vals);+        int result = 0;+        for (int i = 0; i < size; i++) {+            String key = keys[i];+            assert key != null;+            if (isInternalKey(key)) continue;+            result += key.hashCode() ^ Objects.hashCode(vals[i]);+        }         return result;     } src/test/java/org/jsoup/nodes/AttributesTest.javaindex f82cfb95..17cc6cea 100644@@ -311,6 +311,42 @@ public class AttributesTest {         assertEquals(2, a.asList().size()); // excluded from lists     } +    @Test public void equalsAndHashCodeIgnoreInternal() {+        Attributes a = new Attributes();+        a.put("One", "One");+        a.put("Two", "Two");+        Attributes b = new Attributes();+        b.put("Two", "Two");+        b.put(Attributes.internalKey("baseUri"), "example.com");+        b.put("One", "One");+        b.userData("foo", "bar");++        assertEquals(a, b);+        assertEquals(b, a);+        assertEquals(a.hashCode(), b.hashCode());++        Attributes c = new Attributes();+        c.put("One", "One");+        c.put("Three", "Three"); // same public size as a, so the key lookup is exercised+        c.put(Attributes.internalKey("Two"), "Two"); // internal "/Two" is not the same as "Two"+        assertNotEquals(a, c);+        assertNotEquals(c, a);+    }++    @Test public void equalsIgnoresSourceRanges() {+        Document doc = Jsoup.parse("<p><b id=1 class=x>One</b><b class=x id=1>Two</b><b class=y id=1>Three</b>",+            Parser.htmlParser().setTrackPosition(true));+        Element b1 = doc.expectFirst("b");+        Element b2 = b1.nextElementSibling();+        Element b3 = b2.nextElementSibling();+        assertNotNull(b2); assertNotNull(b3);+        assertTrue(b1.attribute("id").sourceRange().isTracked());++        assertEquals(b1.attributes(), b2.attributes());+        assertEquals(b1.attributes().hashCode(), b2.attributes().hashCode());+        assertNotEquals(b1.attributes(), b3.attributes());+    }+     @Test public void testBooleans() {         // want unknown=null, and known like async=null, async="", and async=async to collapse         String html = "<a foo bar=\"\" async=async qux=qux defer=deferring ismap inert=\"\">";src/test/java/org/jsoup/parser/PositionTest.javaindex e2486ff0..af5827d6 100644@@ -951,4 +951,18 @@ class PositionTest {         assertEquals(html.indexOf("alpha"), text.sourceRange().startPos());         assertEquals(html.indexOf("</body>"), text.sourceRange().endPos());     }++    @Test void trackingDoesNotChangeNoahsArkReconstruction() {+        // only three identical formatting elements should be reconstructed; range data must not make them differ+        String html = "<p><b><b><b><b><p>x";+        String withAttrs = "<p><b class=a><b class=a><b class=a><b class=a><p>x";+        for (boolean track : new boolean[]{false, true}) {+            Document doc = Parser.htmlParser().setTrackPosition(track).parseInput(html, "");+            assertEquals("<p><b><b><b>x</b></b></b></p>", doc.body().child(1).outerHtml());++            Document doc2 = Parser.htmlParser().setTrackPosition(track).parseInput(withAttrs, "");+            assertEquals("<p><b class=\"a\"><b class=\"a\"><b class=\"a\">x</b></b></b></p>",+                TextUtil.stripNewlines(doc2.body().child(1).outerHtml()));+        }+    } } 
Merged fix · PR #+84 −13
CHANGES.mdindex 881e7dad..ee407436 100644@@ -12,6 +12,7 @@ ### Changes * Removed APIs previously deprecated and scheduled for removal in 1.24.1. [#2597](https://github.com/jhy/jsoup/pull/2597) * `Response.bodyStream()` now observes the configured max body size and request timeout, consistent with the other response body methods. The default max size is 2 MB. You can configure that with `maxBodySize(0)` before executing the request to disable the cap. `Response.isTruncated()` reports when the decoded response content exceeded the configured limit. [#2598](https://github.com/jhy/jsoup/pull/2598)+* `Attributes.equals()` and `hashCode()` now exclude internal attributes, such as source ranges and user data. [#2633](https://github.com/jhy/jsoup/issues/2633)  ### Bug Fixes * Standardized parser normalization of tag and attribute names so that HTML comparisons use ASCII-only case folding, and accepted control characters are preserved, aligning name handling to the HTML and XML specs. [#2594](https://github.com/jhy/jsoup/issues/2594)@@ -33,6 +34,7 @@ * `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) * Fixed HTML parse of `<dialog>`, `<main>`, and `<search>` so their start and end tags close open paragraphs correctly. [#2629](https://github.com/jhy/jsoup/issues/2629) * Updated the parse of malformed end tags such as `</ COMMENT >` to match the spec (`<!-- COMMENT -->`). [#2631](https://github.com/jhy/jsoup/issues/2631)+* Source position tracking no longer impacts the adoption algo when repeated HTML formatting tags are reconstructed after a paragraph closes. [#2633](https://github.com/jhy/jsoup/issues/2633)  ## 1.23.2 (2026-Aug-26) src/main/java/org/jsoup/nodes/Attributes.javaindex 38fbc5d2..7cfff577 100644@@ -596,10 +596,11 @@ public class Attributes implements Iterable<Attribute>, Cloneable {     }      /**-     * Checks if these attributes are equal to another set of attributes, by comparing the two sets. Note that the order-     * of the attributes does not impact this equality (as per the Map interface equals()).-     * @param o attributes to compare with-     * @return if both sets of attributes have the same content+     Checks if these attributes have the same names and values as another set, ignoring attribute order. Internal+     attributes, such as source ranges and user data, are excluded.++     @param o attributes to compare with+     @return if both sets of attributes have the same content      */     @Override     public boolean equals(@Nullable Object o) {@@ -607,26 +608,38 @@ public class Attributes implements Iterable<Attribute>, Cloneable {         if (o == null || getClass() != o.getClass()) return false;          Attributes that = (Attributes) o;-        if (size != that.size) return false;+        if (size() != that.size()) return false;         for (int i = 0; i < size; i++) {             String key = keys[i];             assert key != null;-            int thatI = that.indexOfKey(key);-            if (thatI == NotFound || !Objects.equals(vals[i], that.vals[thatI]))-                return false;+            if (isInternalKey(key)) continue;++            int here = 0, there = 0;+            for (int j = 0; j < size; j++) {+                if (key.equals(keys[j]) && Objects.equals(vals[i], vals[j])) here++;+            }+            for (int j = 0; j < that.size; j++) {+                if (key.equals(that.keys[j]) && Objects.equals(vals[i], that.vals[j])) there++;+            }+            if (here != there) return false;         }         return true;     }      /**-     * Calculates the hashcode of these attributes, by iterating all attributes and summing their hashcodes.-     * @return calculated hashcode+     Calculates an order-independent hash code from attribute names and values, excluding internal attributes.++     @return calculated hashcode      */     @Override     public int hashCode() {-        int result = size;-        result = 31 * result + Arrays.hashCode(keys);-        result = 31 * result + Arrays.hashCode(vals);+        int result = 0;+        for (int i = 0; i < size; i++) {+            String key = keys[i];+            assert key != null;+            if (!isInternalKey(key))+                result += 31 * key.hashCode() + Objects.hashCode(vals[i]);+        }         return result;     } src/test/java/org/jsoup/nodes/AttributesTest.javaindex f82cfb95..72fb09ab 100644@@ -374,11 +374,59 @@ public class AttributesTest {         assertEquals(two, three);         assertEquals(three, three);         assertEquals(three, three.clone());+        assertEquals(one.hashCode(), three.hashCode());         assertEquals(four, four);         assertEquals(four, four.clone());         assertNotEquals(one, four);     } +    @Test void equalsIgnoresInternalData() {+        Element first = Parser.htmlParser().setTrackPosition(true)+            .parseInput("<b id=one></b><b id=one></b>", "").select("b").first();+        Element second = Parser.htmlParser().setTrackPosition(true)+            .parseInput("<p><b id=one></b>", "").expectFirst("b");+        assertNotNull(first);+        assertNotEquals(first.sourceRange(), second.sourceRange());++        Attributes one = first.attributes();+        Attributes two = second.attributes();+        two.userData("owner", "second");+        assertEquals(one, two);+        assertEquals(one.hashCode(), two.hashCode());+        Attributes untracked = Parser.htmlParser().parseInput("<b id=one>", "").expectFirst("b").attributes();+        assertEquals(one, untracked);+        assertEquals(one.hashCode(), untracked.hashCode());++        two.put("id", "two");+        assertNotEquals(one, two);+    }++    @Test void hashCodeIgnoresAttributeOrder() {+        Attributes one = new Attributes().add("a", "b").add("c", "d");+        Attributes reordered = new Attributes().add("c", "d").add("a", "b");++        assertEquals(one, reordered);+        assertEquals(one.hashCode(), reordered.hashCode());+    }++    @Test void hashCodeDistinguishesSwappedNameAndValue() {+        Attributes one = new Attributes().add("a", "b");+        Attributes swapped = new Attributes().add("b", "a");++        assertNotEquals(one.hashCode(), swapped.hashCode());+    }++    @Test void equalsCountsDuplicateAttributes() {+        Attributes one = new Attributes().add("a", "1").add("a", "1").add("b", "2");+        Attributes two = new Attributes().add("b", "2").add("a", "1").add("a", "1");+        Attributes three = new Attributes().add("b", "2").add("a", "1").add("a", "2");++        assertEquals(one, two);+        assertEquals(one.hashCode(), two.hashCode());+        assertNotEquals(one, three);+        assertNotEquals(three, one);+    }+     @Test void cloneAttributes() {         Attributes one = new Attributes()             .add("Key1", "Val1")src/test/java/org/jsoup/parser/HtmlParserTest.javaindex eb33dc1f..bb165e28 100644@@ -1082,6 +1082,14 @@ public class HtmlParserTest {         assertEquals("<b>1</b>\n<p><b>2</b>3</p>", doc.body().html());     } +    @Test void sourceTrackingHonorsFormattingElementLimit() {+        String input = "<p><b><b><b><b><p>x";+        Document doc = Parser.htmlParser().setTrackPosition(true).parseInput(input, "");++        assertEquals("<b><b><b><b></b></b></b></b>", doc.body().child(0).html());+        assertEquals("<b><b><b>x</b></b></b>", doc.body().child(1).html());+    }+     @ParameterizedTest(name = "fragment={0}")     @ValueSource(booleans = {false, true})     void preservesAdoptionBookmarkAfterRemovingFormattingElement(boolean fragment) {