Skip to content

Compare uniqueItems items without copying them - #1305

Merged
stevehu merged 3 commits into
networknt:masterfrom
ItsDeadlyProgrammer:perf/1302-unique-items
Oct 13, 2026
Merged

stevehu merged 3 commits into
networknt:masterfrom
ItsDeadlyProgrammer:perf/1302-unique-items

Conversation

@ItsDeadlyProgrammer

@ItsDeadlyProgrammer ItsDeadlyProgrammer commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1302

UniqueItemsValidator now compares items through a small key that walks each node in place, instead of building a comparisonKey copy. Numbers are still compared by value, so [1, 1.0] is still a duplicate, but arrays without mixed number types no longer pay for it.

How numbers are compared:

  • A number's value is its decimalValue(), as before. For a double that is its shortest decimal form, so 1e30 equals 10^30 and a double read from 0.1 equals a BigDecimal 0.1.
  • Numbers whose value is whole and fits in a long (ints, longs, and whole doubles, BigIntegers and BigDecimals) are compared as longs.
  • Other doubles are compared as doubles.
  • Only BigIntegers and BigDecimals outside that range are compared as BigDecimals.
  • NaN, Infinity and -Infinity still compare as nodes.
  • A double hashes as Double.hashCode of its value. A BigInteger or BigDecimal outside the long range takes that same hash only when it is exactly a double's value; otherwise it hashes its own exact value. So equal numbers of different types land in the same bucket, while integers that only round to the same double, such as 2^70 and 2^70 + 1, don't. The hash never calls doubleValue() on a big node, which Jackson 3 would throw from for values like 10^400.
  • Objects hash the same regardless of property order, and numbers still never equal booleans or strings.

There is no behaviour change from the current code. Fuzzing 400,000 number pairs (large whole doubles, powers of ten, big integers near them, trailing-zero decimals, and each value in another type) against the current comparisonKey gives the same verdict for every pair, both at the top level and nested.

Items deferred from the #1301 review:

  1. decimalsWithDifferentScaleAreDuplicates now reads the instance with USE_BIG_DECIMAL_FOR_FLOATS, so 1.0 and 1.00 stay BigDecimals with different scales. It fails without numeric folding on master.
  2. The comparisonKey Javadoc is rewritten for the new key, with the indentation fixed.

New tests in UniqueItemsNumericEqualityTest: double vs BigDecimal, 0 vs -0.0, numbers outside the long range, large whole doubles ([1e30, 10^30] is a duplicate, the long 2^60 and the double 2^60 are not), 1,000 consecutive integers from 2^70 (all unique, then one repeated), [10^400] nested and at the top level, and [1e400, 1e401] / [1e400, 1e400] with USE_BIG_DECIMAL_FOR_FLOATS, and object property order. On the first version of this PR, the large-double test failed on both branches and the 10^400 test threw on master. The 2^70 test checks correctness only, so it doesn't depend on timing.

Timing with schema {"uniqueItems":true}: 50 warm-up runs, then the best of 5 rounds of 20 runs, and the median of 3 JVM runs. Times in ms.

master, JDK 25:

Instance Before #1273 (node equality) Current (comparisonKey) This PR
200k ints 6.8 15.6 9.2
20k objects, 10 string fields 7.6 12.1 8.2
200k decimals (i.5) 11.1 62.0 21.0
20k nested arrays ([i, i+1.25, {"a":i}]) 1.4 4.7 1.8

2.x, JDK 17 (I don't have a Java 8 JDK here):

Instance Before #1301 (node equality) Current (comparisonKey) This PR
200k ints 7.2 19.4 8.4
20k objects, 10 string fields 4.0 11.2 7.9
200k decimals (i.5) 9.2 72.5 17.3
20k nested arrays 1.7 5.1 1.8

Against the current code it is 1.5–3x faster on master and 1.4–4.2x on 2.x. It's still a bit slower than plain node equality, mostly from one key object per item and classifying each number. The objects numbers were the noisiest between runs. None of these instances goes through the big-number hash.

Consecutive integers from 2^70, which share a double in runs of 2^18. The first two columns are from your review; the last is one run with no warm-up:

Items Current First version of this PR This PR
20,000 15 ms 3.7 s (master) / 4.6 s (2.x) 4 ms (master) / 19 ms (2.x)
100,000 26 ms (master) / 108 ms (2.x)

mvn verify passes, including the JSON Schema Test Suite: 8768 tests on JDK 25.

comparisonKey built a BigDecimal for every number and copied every
nested array and object, so all arrays paid for the numeric-equality
fix, not only arrays that mix integers and decimals. Wrap each item in
a key that walks the node and compares numbers by value instead: whole
numbers that fit in a long as longs, other doubles as doubles, and only
other BigIntegers and BigDecimals as BigDecimals.

Whole doubles at or above 2^63 are compared by their exact value, the
same as smaller whole doubles, rather than by their shortest decimal
form.

Make decimalsWithDifferentScaleAreDuplicates read BigDecimals so it no
longer passes without numeric folding, fix the comparisonKey Javadoc
indentation by rewriting it, and add tests for the new comparison paths.

Fixes networknt#1302
@stevehu

stevehu commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Code review (xhigh · 8 findings)

Thanks for this. For ordinary arrays the speedup holds up, and the code is easy to follow. I found three problems the existing suites don't cover, and I'd like those fixed before merging.

Verification:

Please change these:

  1. Crash on master. In Jackson 3, BigIntegerNode.doubleValue() and DecimalNode.doubleValue() throw JsonNodeException when the value is outside the double range, and hash() calls it for every BIG number. With the default mapper, {"uniqueItems":true} and the instance [10^400] (a 401-digit integer) throw instead of validating. The same happens nested ([[10^400]], [{"a":10^400}]), and for [1e400, 1e401] with USE_BIG_DECIMAL_FOR_FLOATS. Base returns a verdict for all of them. 2.x doesn't crash, because Jackson 2 returns Infinity.

  2. Quadratic time for big integers, both branches, default settings. Numbers outside the long range are hashed by Double.hashCode(doubleValue()). Distinct integers that round to the same double therefore all land in one bucket, and because ItemKey isn't Comparable, HashMap can't treeify it. Integers near 2^70 share a double in runs of 2^18. An array of consecutive integers starting at 2^70:

    Items Base Compare uniqueItems items without copying them #1305 (master, JDK 25) [2.x] Compare uniqueItems items without copying them #1306 (2.x, Java 8)
    2,000 3 ms 28 ms 42 ms
    10,000 10 ms 858 ms 1,100 ms
    20,000 (460 KB) 15 ms 3,721 ms 4,639 ms

    That is roughly 1.5 minutes at 100,000 items, so a client could tie up a server with one request.

  3. Large doubles change verdicts. Comparing whole doubles of 2^53 and above by their exact binary value also changes ordinary input:

    • [1e30, 1000000000000000000000000000000] and [[1e30], [10^30]] were duplicates on base and are now unique, while {"const":1e30} still accepts 10^30. On master, [1e23, 10^23] changes the same way.
    • The other way round, [1.15292150460684698E18, 1152921504606846976] is now a duplicate, while const still says the two differ.

    Fuzzing pairs against the old comparisonKey found 188 (master) and 220 (2.x) pairs with different verdicts, and every one involves a double of 2^53 or more. This PR is meant to make comparison faster, so please keep the old decimalValue() result for those doubles here. Whether to switch to exact values belongs in Track exact decimal literals and numeric reader compatibility #1293, together with const and enum. The old behaviour also depends on the JDK, because Double.toString changed in JDK 19.

A fix for 1 and 2. I tried this on master: the crash goes away, 20,000 big integers take 16 ms, and the suites pass. I haven't run it on 2.x.

            case DOUBLE:
                return Double.hashCode(node.doubleValue());
            default: // BIG
                BigDecimal value = node.decimalValue();
                double d = value.doubleValue(); // BigDecimal never throws, it returns ±Infinity
                if (Double.isFinite(d) && doubleDecimal(d).compareTo(value) == 0) {
                    // Exactly equal to a double, so it must share that double's hash.
                    return Double.hashCode(d);
                }
                return value.stripTrailingZeros().hashCode();

Here, doubleDecimal(d) is the same conversion sameNumber uses for a double. With item 3 reverted, that is BigDecimal.valueOf(d). Any other BIG number can't equal a double, so it can use a hash of its own exact value.

Tests, please:

  • [10^400] with the default mapper, and [1e400, 1e401] / [1e400, 1e400] with USE_BIG_DECIMAL_FOR_FLOATS.
  • A correctness test with about 1,000 consecutive integers starting at 2^70, all unique. It goes through the collision path without depending on timing.
  • [1e30, 10^30] as a duplicate, if you agree with item 3. largeWholeDoublesAreComparedByExactValue and the 2^63 case of numbersOutsideTheLongRangeAreComparedByValue would then need changing.

Optional:

  1. Longer term, const, enum and uniqueItems should share one numeric-equality helper with a matching hash, so they can't drift apart again. That's fine as a follow-up.
  2. On 2.x, decimalsWithDifferentScaleAreDuplicates still passes without numeric folding. Jackson 2.22 strips trailing zeros when it reads with USE_BIG_DECIMAL_FOR_FLOATS, and even with STRIP_TRAILING_BIGDECIMAL_ZEROES off, DecimalNode equality ignores scale. It's fine to keep the test so the branches stay identical, but the [2.x] Compare uniqueItems items without copying them #1306 description shouldn't say it fails without folding.
  3. numberKind runs again for both sides of every comparison. For BigDecimals with a fractional scale it allocates through stripTrailingZeros() each time, which costs extra with USE_BIG_DECIMAL_FOR_FLOATS. That case isn't in the benchmarks. This is minor.
  4. The decimalValue Javadoc says "Smaller doubles keep their shortest form", but whole doubles between 2^53 and 2^63 currently compare by their exact value. This becomes moot if item 3 is reverted.

The same applies to #1306. Once items 1–3 are in on both PRs, I'm happy to merge them together.

… doubles

BigIntegerNode and DecimalNode throw from doubleValue() in Jackson 3 when the
value is outside the double range, so hash a BIG number from its BigDecimal.
A BIG number that isn't exactly a double's value now hashes its own exact
value, so integers that round to the same double no longer share a bucket.

Whole doubles of 2^53 and above go back to comparing by decimalValue(), their
shortest decimal form, as before. Changing that belongs with const and enum
in networknt#1293.
@ItsDeadlyProgrammer

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. Items 1–3 are in: 8f7408b here and c2cd3f9 on #1306.

1 and 2: I used your hash. A BIG number takes Double.hashCode(d) only when it is exactly the value of BigDecimal.valueOf(d), and otherwise hashes its own stripTrailingZeros() value. It reads the value through decimalValue(), so it never calls doubleValue() on the node. 20,000 consecutive integers from 2^70 now take 4 ms on master and 19 ms on 2.x (JDK 17), and 100,000 take 26 ms and 108 ms.

3: Reverted. Comparison goes back to decimalValue(), so [1e30, 10^30] is a duplicate again, and the long 2^60 and the double 2^60 are not. Whole doubles between 2^53 and 2^63 still go through the long path, but with the long value of their shortest form instead of (long) d. To check it, I fuzzed 400,000 pairs against the old comparisonKey (large whole doubles, powers of ten, big integers next to them, trailing-zero decimals, and each value converted to another type). Every pair got the same verdict, both at the top level and nested. That held on both branches.

Tests added:

  • [10^400] at the top level and nested, plus [10^400, 10^400] and [10^400, 10^401]
  • [1e400, 1e401], [1e400, 1e400] and [1e400, 10e399] with USE_BIG_DECIMAL_FOR_FLOATS
  • 1,000 consecutive integers from 2^70, all unique, then one repeated
  • [1e30, 10^30], nested [[1e30], [10^30]], [1e18, 10^18] as duplicates

largeWholeDoublesAreComparedByExactValue is now largeWholeDoublesAreComparedByTheirShortestDecimalForm. The 2^63 BigInteger/double case moved into it as unique, and numbersOutsideTheLongRangeAreComparedByValue checks 2^70 vs 2^70 + 1 instead. Without the fix, the large-double test fails and the 10^400 test throws.

Item 7 goes away with the revert, and the Javadoc now says the value is decimalValue(). I left 4 and 6 for a follow-up, as you suggested. I updated both descriptions, including item 5 on #1306.

mvn verify: 8768 tests on master (JDK 25), 8625 on 2.x (JDK 17). I still don't have a Java 8 JDK here.

@stevehu

stevehu commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Code review (xhigh · 3 findings)

Thanks. 8f7408b fixes items 1–3, and I checked it merged into the current master tip on JDK 25:

  • The JSON Schema Test Suite (7,261 tests), the extras, all UniqueItems* tests and the const/enum tests pass.
  • Consecutive integers from 2^70: 20,000 now take 20 ms (3.7 s before), and 10,000 take 11 ms.
  • The [10^400] crash is gone.
  • With the base validator put back, all 16 numeric tests still pass, which is what a speed-only change should give.

#1306 (c2cd3f9) on 2.x with Java 8 gives the same results: 20,000 big integers take 33 ms (4.6 s before). The two PRs are still identical apart from the Jackson imports.

Please change this one: the double -2^63. I fuzzed 2.39 million number pairs against the old comparisonKey on JDK 25, 17 and 8. Every pair matched except those involving the double (or float) -2^63:

  • numberKind classes it as WHOLE because of value >= -0x1p63. But its shortest form, -9223372036854776000, is below Long.MIN_VALUE, so decimalValue().longValue() in wholeValue wraps around to +9223372036854775616.
  • [-9.223372036854775808E18, -9223372036854776000] was a duplicate on base, and const says the two are equal, but it's now reported unique.
  • [-9.223372036854775808E18, 9223372036854775616] was unique and is now a duplicate.

Changing the check to value > -0x1p63 classes -2^63 as DOUBLE, and it then compares through decimalValue(). With that change, the fuzz has 0 differences on both branches and the suites pass. Please also correct the comment above it, and add a test for both pairs.

Optional:

  • consecutiveIntegersSharingADoubleAreUnique only checks the verdict, so it would also pass with the old colliding hash. Its Javadoc says the integers "all collide on the double's hash unless the exact value is hashed", which suggests it guards against that. Rewording the Javadoc is enough; a timing check isn't needed.
  • The message "2^60 and 1.15292150460684698E18 differ" quotes the JDK 8–18 form. On JDK 19+ the shortest form is 1.152921504606847E18. The assertion holds either way, so this only affects the message.

Items 4 and 6 from the last round will be a follow-up issue.

The same applies to #1306. Once the -2^63 fix is in on both PRs, I'm happy to merge them together.

@stevehu

stevehu commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Follow-up for items 4 and 6 is now #1307.

@ItsDeadlyProgrammer

Copy link
Copy Markdown
Contributor Author

Thanks, fixed in ba114aa (and bc140e7 on #1306). numberKind now uses value > -0x1p63, so the double -2^63 is classed as DOUBLE and compared through decimalValue(). The comment above it explains why -2^63 is excluded.

minusTwoToSixtyThreeAsADoubleIsComparedByItsShortestDecimalForm checks both pairs. For the duplicate case it builds the shortest form from Double.toString(-0x1p63) rather than hard-coding -9223372036854776000, so it holds on every JDK.

I also took both optional items: the Javadoc on consecutiveIntegersSharingADoubleAreUnique now says it checks the verdict only, and the 2^60/2^63 messages no longer quote a JDK-specific form.

mvn verify: master 8769 tests on JDK 25, 2.x 8642 on JDK 17.

@stevehu stevehu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the quick turnaround. I re-reviewed ba114aa (#1305) and bc140e7 (#1306); the two are identical apart from the Jackson imports.

Verification

  • The -2^63 fix works. [-2^63, its shortest form] is a duplicate and [-2^63, 9223372036854775616] is unique, matching base and const. All 15 -2^63 edge cases match base on Java 8, 17, 21 and 25.
  • Revert check: with the previous commit's validator, minusTwoToSixtyThreeAsADoubleIsComparedByItsShortestDecimalForm fails on JDK 25 and Java 8.
  • On master (JDK 17, 25) and 2.x (Java 8, 21):
    • The JSON Schema Test Suite (7261), the UniqueItems tests (50 + 17), and the const/enum tests pass.
    • The 253k-input and 2.39M-input fuzzes show 0 disagreements.
    • The DoS probe stays at 4–20 ms for 20k items.

Optional, not blocking

  • The test Javadoc says the shortest form is -9223372036854776000 "on JDK 19+". Corretto 8 and 17 give the same form, so the JDK qualifier can go.
  • One more assertion would pin the pair on the boundary that moved: assertTrue(valid(array().add(Long.MIN_VALUE).add(-0x1p63))).
  • value > -0x1p63 relies on decimalValue() of -2^63 being below Long.MIN_VALUE. That holds on every JDK I tested. Deciding that single value from its decimal form would remove the assumption, if you ever touch this again.

Approving both; merging #1305 and #1306 together.

@stevehu
stevehu merged commit 87e8554 into networknt:master Oct 13, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

uniqueItems: comparisonKey allocations slow down validation of all arrays (master and 2.x)

2 participants