Skip to content

Preserve exact multipleOf operands - #1290

Merged
stevehu merged 14 commits into
networknt:masterfrom
PHJ2000:fix-multipleof-precision-master
Oct 13, 2026
Merged

stevehu merged 14 commits into
networknt:masterfrom
PHJ2000:fix-multipleof-precision-master

Conversation

@PHJ2000

@PHJ2000 PHJ2000 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1286. Corresponding 2.x PR: #1291.

Preserve exact integral and BigDecimal operands in multipleOf validation. For example, 9007199254740993 is rejected as a multiple of 2 and accepted as a multiple of 3. The conversion hooks are used for both directly constructed validators and subclasses, and validation checks their returned values without substituting a rounded divisor.

Mixed integer/Double or Float inputs retain the exact integer value instead of rounding it through double. For example, multipleOf: 2.0 now rejects integer 9007199254740993. Integer divisor 9007199254740993 also rejects input 9007199254740993.0, which the default reader has already rounded to 9007199254740992. Double/Float conversion itself still uses BigDecimal.valueOf(doubleValue()). Reader precision remains a separate issue in #1293.

The integer fast path checks whether the returned dividend can be represented exactly as a long. Other values use coefficient/scale arithmetic without constructing exponent-sized powers. The default divisor conversion retains trailing-zero normalization, while error messages preserve the representation returned by custom divisor hooks. Javadoc and the CHANGELOG describe the exact conversion and its effect on integral dividend scale (for example, 2 instead of 2.0). Zero/negative divisor handling, type-loose conversion and this branch's non-finite-number behavior are unchanged.

Tests cover exact values, mixed inputs, conversion overrides, messages and extreme scales. Forked tests check whether forced termination succeeds and retain the timeout failure if the child is still alive.

Validation: mvn -B -ntp clean verify passes on Java 17 and 21; 8,983 tests reported, 30 skipped, no failures or errors on each JDK. All 138 MultipleOfValidatorTest cases pass.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot review overview

🟢 Approval recommended

The focused implementation addresses the precision defect while retaining existing floating-point behavior and includes comprehensive regression coverage.

Review effort: Balanced
Findings: None

What changed in this PR

Preserves exact numeric operands during multipleOf validation, preventing precision loss for large integers and extreme decimals.

Changes:

  • Uses exact BigDecimal representations for integral and decimal operands.
  • Adds regression coverage for large integers, BigInteger, and extreme decimal values.
File Description
MultipleOfValidator.java Preserves exact divisors and dividends.
MultipleOfValidatorTest.java Adds precision regression tests.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@stevehu

stevehu commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Code review(xhigh · 8 findings)
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
● 66 [correctness] The new exact divisor branch drops the old limit that came from converting through double. A BigDecimal divisor with a huge negative exponent is now used as-is, and divideAndRemainder then does work that grows with the exponent difference.
● 98 [security] An attacker who controls the instance can make getDividend/validate burn CPU for a long time with a short string (type-loose mode) or a short BigDecimal literal. The huge exponent goes straight into divideAndRemainder. This already happens before the PR, but it is in the functions this PR rewrites.
● 94 [correctness] Issue #1286 is only fixed for integer literals. With the default mapper, an integer-valued float literal is still a DoubleNode, so it gets rounded through double on both the dividend and divisor sides.
● 66 [correctness] The new integer branch calls stripTrailingZeros() on values that already have scale 0. The error message then shows round integer divisors in scientific notation, because line 50 uses divisor.toString().
● 67 [correctness] The new exact branch's guard is signum() != 0, so it accepts negative divisors. The spec requires multipleOf to be strictly greater than 0.
● 94 [simplification] The isIntegralNumber() || isBigDecimal() ? decimalValue() : BigDecimal.valueOf(doubleValue()) split is unnecessary. For DoubleNode and FloatNode, decimalValue() already returns exactly BigDecimal.valueOf(doubleValue()).
● 47 [efficiency] The most common case, an int or long divisor with an int or long instance, still allocates two BigDecimals and runs divideAndRemainder on every validation. A long fast path would avoid all of that.
src/test/java/com/networknt/schema/MultipleOfValidatorTest.java
● 191 [test-coverage] No test checks the error message for the new exact divisor branch. The decimal edge cases also use hand-built DecimalNodes instead of a USE_BIG_DECIMAL_FOR_FLOATS reader, so the configuration that actually produces such divisors is never exercised.

I found 8 issues in PR #1290. The fix works for integer literals, but there are two problems worth raising before merge:

  • New slowdown from extreme divisors: a divisor like 1e-20000000 used to be ignored and now makes each validation take about 40 seconds. This only happens when the schema is read with BigDecimal floats or built in code.
  • Incomplete fix: 9007199254740993.0 is still accepted as a multiple of 2 with the default parser.

I also flagged an existing slowdown in the same functions that untrusted instance data can trigger: with typeLoose enabled, the string instance "1e5000000" took 3.8 seconds to validate.

I ran each of these on the PR branch to get the timings and behavior. I used a temporary worktree and branch, both now removed, and your feat/validation-execution-limits checkout was not touched.

@PHJ2000

PHJ2000 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Both PRs have been updated (55e08f1 on master, d4a390c on 2.x).

  1. Small divisors: divisibility uses modular powers of ten instead of constructing an expanded quotient. The large-exponent divisor case has a timeout regression test.
  2. Large instance exponents: the same calculation handles DecimalNode and loose-type string inputs, with tests for both.
  3. Decimal literals: the default JSON and YAML readers now enable USE_BIG_DECIMAL_FOR_FLOATS. 9007199254740993.0 is rejected as a multiple of 2 without custom configuration. Tests cover both operands, exponent notation, strings and streams. Custom mappers remain caller-configurable.
  4. Error messages: integral divisors retain their plain integer representation, so 100 is reported as 100, not 1E+2.
  5. Non-positive divisors: zero and negative values now throw SchemaException with multipleOf must be greater than zero. Tests cover integer, decimal and BigInteger values.
  6. Conversion: getDividend uses node.decimalValue(), retaining each branch’s non-finite handling.
  7. Integral fast path: int/long operands use a cached long divisor and %, avoiding per-instance decimal conversion. Tests cover zero, negative instances and long boundaries. MultipleOfBenchmark is included: local JMH measurements on pre-parsed valid inputs changed from 43/46 to 29/28 ns/op (int/long, Java 17), and 102/114 to 90/89 ns/op (Java 8). Each measurement used 2 forks, 3 warmup and 3 measurement iterations of 500 ms; these are workload-specific results.
  8. Coverage: message assertions, default and configured decimal readers, extreme scales, and 2,000 comparisons against BigDecimal remainder are covered.

Full mvn -B verify passed: master on Java 17, 8,631 tests with 30 skipped; 2.x on Java 8, 8,545 tests with 15 skipped. The README documents exact default parsing and rejection of non-positive divisors.

@stevehu

stevehu commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Code review(xhigh · 14 findings)
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
● 76 [correctness] dividend.stripTrailingZeros() throws ArithmeticException("Overflow") when the dividend's unscaled value has trailing zeros and its scale is near Integer.MIN_VALUE, so validate() crashes instead of reporting a result.
● 76 [security] On JDK 17 (the project baseline) and Java 8 (2.x), stripTrailingZeros() strips one zero per BigInteger division. That is quadratic in the number of trailing zeros, so a type-loose numeric string reintroduces the instance-controlled CPU burn from the previous review.
● 111 [correctness] With a custom double-based mapper, which the README says remains supported, a positive divisor literal that underflows to 0.0 now throws SchemaException("multipleOf must be greater than zero") at schema load.
● 142 [correctness] In type-loose mode, new BigDecimal(node.asString()) throws NumberFormatException for numeric strings whose exponent exceeds the int range. Strings.isNumeric accepts these strings, so the exception escapes validate().
● 43 [simplification] longDivisor and divisorText are derived from schemaNode, not from the computed divisor, and the int/long fast path skips getDividend. Overrides of the protected getDivisor/getDividend are bypassed, and integral DecimalNode divisors (2.0, 1e2, now the default node type for those literals) miss the fast path and still render as 1E+2.
● 103 [simplification] getDivisor keeps two branches with duplicated throws even though DoubleNode.decimalValue() already equals BigDecimal.valueOf(doubleValue()) (getDividend relies on this). divisor != 0 on line 114 is now dead after the <= 0 throw.
● 83 [efficiency] this.divisor.unscaledValue().abs() allocates a new BigInteger (two when compact) on every decimal-path validation, even though it depends only on the divisor.
src/main/java/com/networknt/schema/serialization/JsonMapperFactory.java
● 31 [correctness] With USE_BIG_DECIMAL_FOR_FLOATS on by default, untrusted instances now reach EnumValidator and UniqueItemsValidator as arbitrary-scale DecimalNodes. Their existing stripTrailingZeros() calls overflow and throw. The same applies to YamlMapperFactory.
● 31 [compatibility] JsonMapperFactory.getInstance() and YamlMapperFactory.getInstance() are public, and doc/quickstart.md and doc/walkers.md tell users to call them. Enabling USE_BIG_DECIMAL_FOR_FLOATS on the singleton changes every caller's untyped deserialization, not just schema/instance node reading.
● 31 [correctness] Large integral literals above double range used to parse as Infinity and fail type: integer. They now parse as integral DecimalNodes, pass the type check, and hit node.asLong() in the integer branches of Minimum/Maximum/ExclusiveMinimum/ExclusiveMaximum, which throws JsonNodeException.
● 32 [efficiency] Making DecimalNode the default for every float roughly doubles retained memory for float-heavy instances and slows numeric validation. Every default-reader user pays this cost for a multipleOf precision fix.
● 32 [compatibility] Switching schema literals to DecimalNode changes user-visible messages for exponent-notated numbers, and makes previously loadable schemas with out-of-int-range counts fail to load.
src/test/java/com/networknt/schema/MultipleOfValidatorTest.java
● 255 [test-coverage] The extreme-scale tests only use unscaled values with no trailing zeros (3, 1), so the stripTrailingZeros overflow and the type-loose trailing-zero cost are untested. Nothing exercises enum/uniqueItems or integer min/max against the new default DecimalNodes.
● 234 [test-coverage] exactDecimalsFromReader and largeExponentsFromReaderAndLooseType build a custom USE_BIG_DECIMAL_FOR_FLOATS mapper that is now identical to the default. They no longer test a separate configuration, and their rows duplicate exactDecimalsWithDefaultReaders. The plain-double custom mapper, which the README still supports, has no test.

I reviewed PR #1290 again after the updates, and three new problems block merge. Most of the eight items from the last review are fixed, but the new code and the switch to BigDecimal default readers bring in new crashes and a slowdown. The 14 findings are in the review panel; I reproduced the behavior findings on the PR branch and compared them with master.

Blocking:

  • New crash in multipleOf: the instance 100e2147483647 now makes validate() throw ArithmeticException. Master handled it normally.
  • Same crash in enum and uniqueItems: these keywords now receive the same values because of the new default readers, and they throw the same exception.
  • Slowdown is back: with type-loose mode on JDK 17 (the project's minimum Java version), a 200,000-digit string ending in zeros takes 8.2 s to validate; master takes 0.35 s. It doesn't show up on JDK 25, which is probably why the author's runs missed it.

Compatibility costs of the new default readers:

  • JsonMapperFactory.getInstance() is public and the docs tell users to call it. It now returns BigDecimal instead of Double for decimal numbers in maps, so existing user code that casts to Double will break.
  • Instance numbers above about 1e308 under an integer schema with a minimum or maximum now throw instead of failing the type check. Master already threw for 1e19 to 1e308.
  • Error messages change: a schema value written as 1e2 now reads 1E+2 instead of 100.0.
  • A document of 2M floats now uses about twice the memory (58 MB → 119 MB).

With a user-supplied mapper: a positive divisor like 1e-400 rounds to 0.0 and is now rejected as "multipleOf must be greater than zero". Master ignored it.

The rest are an error in type-loose mode that predates this PR, a few cleanups, and missing tests. I removed the temporary worktrees and the pr-1290 branch I created; your checkout wasn't touched.

Handle extreme numeric scales and trailing-zero inputs without
normalization overflow or excessive computation.

Preserve exact numeric values in default validation readers while
retaining public mapper defaults and compact doubles where lossless.

Fix related enum, uniqueness, bounds, and count-limit handling.
Preserve custom-mapper behavior and protected validator hooks.

Add regression coverage and update the Numeric Precision documentation.

Validation: mvn -B verify on JDK 17; 8,647 tests, 30 skipped, 0 failures or errors.
@PHJ2000

PHJ2000 commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the reproductions and the detailed review. I have addressed the three merge blockers and added regression coverage.

Updates are pushed in c84af35 (master, #1290) and 15cda47 (2.x, #1291).

  • Fixed normalization overflow for extreme numbers such as 100e2147483647 in multipleOf, enum, and uniqueItems.
  • Reduced repeated large-integer operations when processing numbers with many trailing zeros. In my local JDK 17 reproduction, validation of the 200,000-digit input went from approximately 10 seconds to 0.39 seconds.
  • Restored the existing behavior of the public JSON/YAML mappers while preserving exact numeric values in the default readers used for validation. Ordinary decimals remain DoubleNodes when that representation preserves their decimal value. Locally measured retained memory for two million decimal values was approximately 56.8 MiB for both the baseline and the updated implementation.

I also addressed underflow with a user-supplied double-based mapper, protected-method overrides, bounds validation for large numbers, count limits outside the int range, and error messages. The README's Numeric Precision section is updated accordingly.

Exact numeric handling is needed beyond multipleOf. In an experiment that bypassed exact parsing for schemas without multipleOf or range constraints, six valid inputs covering const, enum, $ref, allOf, uniqueItems, and integer validation failed. The implementation therefore preserves numeric accuracy throughout the default reader while reducing the processing cost for ordinary numbers.

Full mvn verify, including the existing multipleOf tests, passed on both branches.

Performance on JDK 17 (10,000-number arrays): ordinary decimals were 7.5% faster and scientific notation 5.7% faster; integer parsing took 4.2% longer (95% CI +0.9% to +7.5%). Decimals with nine fractional digits averaged 4.9% longer (95% CI −0.3% to +10.0%). Component-isolation measurements point to parser wrapping as the source of the integer overhead in the current exact-reading implementation. Details below.

Performance measurements and full test results

The baseline is master commit 51dab248335c4e738652b7c88d5ed7b6bf9fb71c.

The following measurements cover parsing an array of 10,000 numbers on JDK 17, pinned to logical CPU 0 with taskset -c 0, with a fixed 512 MiB heap, four one-second warmup iterations, and four one-second measurement iterations. The JMH GC profiler was enabled. Each version was measured in six independent JVM forks, with execution order alternated across rounds. Confidence intervals are 95% intervals for the paired relative changes across rounds.

Input Baseline → updated Mean time change 95% confidence interval
Integers 105.81 → 110.26 µs +4.2% +0.9% to +7.5%
Ordinary decimals 195.24 → 180.59 µs −7.5% −11.1% to −3.8%
Decimals with nine fractional digits 237.00 → 248.55 µs +4.9% −0.3% to +10.0%
Scientific notation 230.31 → 217.04 µs −5.7% −8.7% to −2.8%

Ordinary decimals and scientific notation improved, while integer parsing showed additional cost. For decimals with nine fractional digits, the observed mean increased, with a confidence interval that includes zero.

On 2.x, nextFieldName() now delegates to the underlying parser's fast path. On JDK 8, stream parsing of 2,000 objects averaged 167.47 µs before this delegation change and 163.44 µs afterward. The mean relative change was −2.4%, with a 95% confidence interval of −4.9% to +0.2%: a small improvement trend within measurement uncertainty.

Branch JDK Reported test count Failures / errors Skipped
master 17 8,647 0 / 0 30
2.x 8 8,561 0 / 0 15

Please take another look at the updated changes.

@stevehu

stevehu commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Code review(xhigh · 14 findings)
src/main/java/com/networknt/schema/keyword/MaximumValidator.java
● 103 [correctness] Min/max comparisons switched from new BigDecimal(node.asString()) to decimalValue(). In Jackson 3.2.3, FloatNode.decimalValue() widens the float to double first (f2d then BigDecimal.valueOf), so 0.1f compares as 0.10000000149011612 instead of "0.1". The same change appears in Minimum, ExclusiveMaximum and ExclusiveMinimum, on both the schema side and the instance side.
● 104 [correctness] The lines this commit edits in minimum, maximum, exclusiveMinimum and exclusiveMaximum still call new BigDecimal(node.asString()) on type-loose numeric strings. A NumberFormatException for an out-of-range exponent escapes validate(). The same commit catches exactly this case in MultipleOfValidator.
● 70 [simplification] Inside the else if (node.isString()) branch, the new node.isNumber() ? node.decimalValue() : ... ternary can never take its first arm, because a string node is never a number.
src/main/java/com/networknt/schema/serialization/ExactMapperFactory.java
● 183 [correctness] With locationAware(), JsonNodes.readTree replaces ExactNumberNodeFactory with LocationJsonNodeFactory. That factory never converts back to double, so a literal on the BIG_DECIMAL path always becomes a DecimalNode, while short literals still become DoubleNode. Numerically equal values can therefore end up as different node classes, and nested object equality fails.
● 55 [correctness] The default readers disable STRIP_TRAILING_BIGDECIMAL_ZEROES, and DecimalNode.equals uses BigDecimal.equals, which compares scale. Two values that cannot be represented as doubles, are numerically equal, and differ only in trailing zeros therefore produce unequal nodes.
● 170 [robustness] getDoubleValue() returns compactValue whenever compact is true, but only getNumberTypeFP() resets the flag. A caller that reads a later float token's double without calling getNumberTypeFP() first gets the previous token's value.
● 198 [efficiency] Float literals that miss the compact fast path now cost several conversions each, where the base reader did one double parse. This covers anything over 17 chars or over 15 significant digits, which includes typical machine-serialized doubles. Each such literal goes through a BigDecimal parse, BigDecimal.doubleValue() (a string round trip for non-compact coefficients on JDK 17), Double.toString, a second BigDecimal parse, and compareTo.
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
● 79 [correctness] A type-loose numeric string whose exponent overflows BigDecimal is always reported as invalid, even when the value is mathematically a multiple of the divisor.
src/main/java/com/networknt/schema/keyword/MaxItemsValidator.java
● 38 [correctness] In a touched constructor, maxItems still falls back to max = 0 for non-integral or non-finite values, while maxLength and maxProperties fall back to Integer.MAX_VALUE.
● 35 [correctness] The min* validators gained exceedsIntegerRange so their messages report the original schema value. The max* validators saturate negative out-of-range limits to Integer.MIN_VALUE and report that value instead.
src/main/java/com/networknt/schema/keyword/MinLengthValidator.java
● 37 [correctness] The new exceedsIntegerRange initializer dereferences schemaNode before the existing schemaNode != null guard on line 40. That makes the guard dead code and adds an NPE where the old code tolerated null.
README.md
● 578 [documentation] The README says "With the default validation readers, zero and negative divisors raise SchemaException". In fact, integer 0, negative integers and negative doubles throw with any reader. Only a double zero from a custom double mapper is ignored.
src/main/java/com/networknt/schema/keyword/MinimumValidator.java
● 110 [efficiency] The non-integer threshold calls schemaNode.decimalValue() inside crossesThreshold, so it rebuilds the schema's BigDecimal on every validation instead of computing it once in the constructor.
src/main/java/com/networknt/schema/keyword/MinItemsValidator.java
● 39 [reuse] The same saturating int conversion, canConvertToInt() ? intValue() : decimalValue().signum() > 0 ? MAX : MIN, is copied into six validators, and the exceedsIntegerRange expression into three. A count already saturated to Integer.MAX_VALUE makes the exceedsIntegerRange || branch in the conditions redundant.

I reviewed the PR owner's latest commit, c84af35 ("Fix numeric edge cases and preserve mapper compatibility"), and reported 14 findings. I checked Jackson's behaviour against the 3.1.1 sources and the actual 3.2.3 classes, but ran no tests.

The four that matter most:

  1. Float values now compare wrongly in min/max checks. The bound validators switched from parsing the node's text to decimalValue(). In Jackson 3.2.3, a 32-bit float such as 0.1f then becomes 0.10000000149011612. Validating a tree built with valueToTree from a POJO with float fields against maximum: 0.1 now fails; it passed before.
  2. Location-aware reading breaks equality inside objects. With locationAware(), the PR's number handling is bypassed for long literals. So 1.10 and 1.1000000000000000000 end up as different node types, and const or enum comparisons on objects fail where they matched before.
  3. Huge exponents still crash min/max in type-loose mode. A numeric string like "1e2147483648" throws an exception out of minimum/maximum. The same commit fixes exactly this case for multipleOf only.
  4. Equal high-precision decimals can compare unequal. The default reader keeps trailing zeros on values a double can't hold exactly, and Jackson's equality check counts those zeros. So 9007199254740993.0 and 9007199254740993.00 don't match inside a nested const.

The rest are lower priority: a few smaller edge cases, a README line that misstates when zero or negative multipleOf values throw, extra parsing cost for long machine-written doubles (the benchmark only covers integers), and some duplicated or dead code.

I also suspected the compact-double shortcut might be wrong on JDK 17 (the library's minimum Java version), but I couldn't test that here. The PR's 10,000-case random test reportedly passes on Java 17, so I left it out.

@PHJ2000

PHJ2000 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. Updated in 1ffd27f, with the 2.x port in #1291 (59c4691).

  • 1–3, 13: All four bounds now preserve FloatNode decimal text, compare loose numbers beyond BigDecimal's scale range, remove the unreachable ternaries, and cache finite thresholds during construction.
  • 4–5: Type selection is in the parser, so ordinary and location-aware readers receive consistent node types. Remaining decimals use overflow-safe normalization for nested equality and hashes.
  • 6: The compact-value cache is tied to the current input context and token offset, with a stateless fallback when locations are unavailable. Tests cover token/name/container advancement and parser sequences that restart at the same offset.
  • 7: Canonical finite, nonzero Double.toString output avoids decimal parsing. Added JSON/YAML conversion-count regressions and NumericReaderBenchmark.
  • 8: Loose multipleOf operands outside BigDecimal's range use coefficient/exponent arithmetic. The fallback carries the value selected by getDividend, including overrides that transform the original input, and does not swallow unrelated hook exceptions.
  • 9–11, 14: CountLimit shares conversion, fallback and error arguments. Non-integral/non-finite maxItems now defaults to Integer.MAX_VALUE, matching the other maxima. Original out-of-range values appear in errors, and MinLength tolerates null again. The minimum-overflow distinction remains necessary: minItems=2147483648 must reject size()=2147483647; a regression checks that boundary without allocating billions of elements.
  • 12: README now distinguishes exact-zero/finite-negative rejection from floating-point-zero and non-finite compatibility.

Full local verify passed: Java 17, 8,740 tests reported / 30 skipped; Java 8 on 2.x, 8,654 / 15 skipped. No failures or errors. The new 93 regressions cover the reviewed behavior and compatibility cases.

I also measured parsing arrays of 1,000 values before/after this update, using JMH on one pinned CPU, 2 forks, 3×300 ms warmup and 3×300 ms measurement per fork (microseconds per array):

Input Java 17 before → after Java 8 before → after
Short decimals (i.25) 26.89 → 24.32 24.20 → 26.49
Serialized doubles (Double.toString(Math.PI * (i+1))) 364.93 → 207.89 364.27 → 295.60
High-precision decimals 636.16 → 617.91 427.78 → 413.77

Java 17 allocation for serialized doubles fell from about 590 KB to 139 KB per array. Java 8's allocation profiler returned implausibly small values, so I am not using those allocation numbers. The short-decimal Java 8 timings have overlapping JMH error ranges; this small local run does not establish a general performance guarantee.

@stevehu

stevehu commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Code review(xhigh · 14 findings)
src/main/java/com/networknt/schema/keyword/MaximumValidator.java
✓ 103 [correctness] Min/max comparisons switched from new BigDecimal(node.asString()) to decimalValue(). In Jackson 3.2.3, FloatNode.decimalValue() widens the float to double first (f2d then BigDecimal.valueOf), so 0.1f compares as 0.10000000149011612 instead of "0.1". The same change appears in Minimum, ExclusiveMaximum and ExclusiveMinimum, on both the schema side and the instance side.
✓ 104 [correctness] In type-loose mode, the four bound keywords still call new BigDecimal(node.asString()), so a NumberFormatException from an out-of-range exponent escapes validate().
✓ 70 [simplification] A node.isNumber() ternary sat inside an isString() branch, where it could never be true.
src/main/java/com/networknt/schema/serialization/ExactMapperFactory.java
✓ 183 [correctness] With locationAware(), JsonNodes.readTree replaces ExactNumberNodeFactory with LocationJsonNodeFactory, so numerically equal values can end up as different node classes and nested object equality fails.
✓ 55 [correctness] Disabling STRIP_TRAILING_BIGDECIMAL_ZEROES together with the scale-sensitive DecimalNode.equals makes numerically equal decimals unequal.
✓ 170 [robustness] getDoubleValue() relied on a compact flag that only getNumberTypeFP() reset, so a caller could read a stale value.
✓ 198 [efficiency] Non-compact floats went through several conversions each: two BigDecimal parses plus doubleValue and toString.
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
✓ 79 [correctness] A type-loose numeric string whose exponent overflows BigDecimal is always reported as invalid, even when the value is mathematically a multiple of the divisor.
src/main/java/com/networknt/schema/keyword/MaxItemsValidator.java
✓ 38 [correctness] maxItems falls back to max = 0 for non-integral or non-finite values, while maxLength and maxProperties fall back to Integer.MAX_VALUE.
✓ 35 [correctness] The max* messages reported Integer.MIN_VALUE for huge negative limits instead of the original schema value.
src/main/java/com/networknt/schema/keyword/MinLengthValidator.java
✓ 37 [correctness] The new exceedsIntegerRange initializer dereferenced schemaNode before the existing null guard.
README.md
✓ 578 [documentation] The README misstated which readers make non-positive divisors throw.
src/main/java/com/networknt/schema/keyword/MinimumValidator.java
✓ 110 [efficiency] The schema bound's BigDecimal was rebuilt on every validation.
src/main/java/com/networknt/schema/keyword/MinItemsValidator.java
✓ 39 [reuse] The saturating int conversion was copy-pasted into six validators.

● Code review(xhigh · 4 findings)
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
● 174 [correctness] The bounds validators now read FloatNode values through DecimalNumber.decimalValue() to keep the float's decimal spelling. getDividend still uses node.decimalValue(), which widens the float to double, so multipleOf (the keyword this PR is about) gives a different answer for the same node than maximum does.
src/main/java/com/networknt/schema/serialization/ExactMapperFactory.java
● 182 [simplification] The fix for the stale compact value identifies the token by comparing streamReadContext() identity and currentTokenLocation() offset. It also falls back to rescanning the text whenever no cached value exists. Overriding nextToken() to clear the cache would give the same guarantee with less code.
src/main/java/com/networknt/schema/keyword/MaximumValidator.java
● 101 [correctness] max == null ? schemaNode.decimalValue() : max only falls back when the schema bound is non-finite and not a ±Infinity DoubleNode. That leaves NaN, or a FloatNode infinity, and in both cases decimalValue() throws, so the fallback is dead code that only fails. The same line appears in Minimum:108, ExclusiveMaximum:88 and ExclusiveMinimum:94.
src/main/java/com/networknt/schema/keyword/DecimalNumber.java
● 100 [reuse] The new decimal helpers (DecimalNumber, which is package-private in keyword) sit apart from the public com.networknt.schema.utils.DecimalUtils that this PR also adds. That leaves numeric-precision helpers split across two places.

The new commit (1ffd27f) fixes all 14 findings from my last review, and I've marked each one fixed. The PR's numeric test classes pass locally (NumericReviewRegressionTest, NumericBoundsReviewTest, CountLimitsReviewTest, MultipleOfExponentReviewTest, ExactMapperRegressionTest, MultipleOfValidatorTest); I didn't run the full suite.

How the main ones were fixed:

  • Float values in min/max: they now keep the float's own decimal spelling instead of the widened double.
  • Location-aware reader: the parser now picks the number type itself, so it no longer depends on which node factory is in use.
  • Trailing zeros: decimal values are normalized as they're read, so equal values compare equal.
  • Huge exponents in type-loose mode: min/max and multipleOf now compare them correctly instead of crashing or always failing.
  • Count limits: the logic is now shared in a new CountLimit class; it fixes the maxItems fallback, the null crash in minLength and the wrong values in error messages.

This pass found four new issues:

  1. multipleOf still mishandles float values. The float fix went into the min/max keywords but not into multipleOf. I confirmed it with a quick test on the PR branch: a float 0.3 against multipleOf: 0.1 reports an error, while a float 0.1 against maximum: 0.1 passes. The base branch already behaved this way, but multipleOf is the keyword this PR exists to fix.
  2. The stale-value fix in the parser is more complex than it needs to be. It identifies each number by its position in the input, which allocates objects and re-scans text for every float. Clearing the cached value whenever the parser moves to the next token would be simpler and cheaper.
  3. A NaN or float-infinity bound crashes at validation time. In the four min/max validators, a NaN or float-infinity bound throws on every validation call instead of being rejected when the schema loads. This predates the PR, but the reworked code is the natural place to fix it.
  4. The decimal helpers are in two places. The float-safe conversion is private to the keyword package, so const, enum and uniqueItems can't use it. Moving it into the public DecimalUtils class this PR adds would let every keyword share one conversion.

@PHJ2000

PHJ2000 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for checking the previous fixes. Addressed all four follow-ups in 79c0536, with the same changes in 85d9ce6 for #1291.

  • Both getDividend and getDivisor now use the shared float-safe conversion, including FloatNode divisors.
  • Parser advancement clears the cached value. This also covers the name/value and container methods that bypass nextToken(). Number reads no longer compare token locations or rescan uncached text.
  • NaN and FloatNode infinity bounds now raise SchemaException during validator initialization. Existing DoubleNode infinity behavior is preserved.
  • Decimal conversion, comparison, normalization, and the large-exponent representation now live in DecimalUtils; the separate keyword-package helper is removed.

Added 19 regression cases covering both float operands, invalid bound initialization, existing infinity behavior, and parser advancement/cache reads. Full mvn -B -ntp clean verify passed on both branches: 8,759 tests on Java 17 (30 skipped) and 8,673 on Java 8 (15 skipped), with no failures or errors.

@stevehu

stevehu commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Code review(xhigh · 9 findings)
src/main/java/com/networknt/schema/utils/DecimalUtils.java
● 131 [correctness] DecimalNumber.parse builds a BigInteger from the exponent text, however long it is. JDK 17's BigInteger(String) is quadratic, so one type-loose numeric string can pin a CPU for a long time in maximum/minimum/multipleOf.
src/main/java/com/networknt/schema/serialization/ExactMapperFactory.java
● 230 [correctness] exactNumberType calls delegate.getDecimalValue(). For YAML explicit floats with underscores, YAMLParser builds that BigDecimal from the raw text, so !!float 1_000 no longer parses through the default reader.
● 225 [behavior-change] The exact reader always turns zero literals (0.0, -0.0, !!float 0) into DecimalNode(0). This changes walker-applied defaults, error messages, and drops the sign of -0.0.
● 163 [efficiency] Every float token pays extra parsing work. YAML copies its text twice per token (getStringLength and getStringCharacters both call getString(), and the latter does toCharArray). Literals over 17 chars always go through a double parse, Double.toString and getString, and non-canonical ones add two BigDecimal parses.
src/main/java/com/networknt/schema/keyword/ContainsValidator.java
● 65 [altitude] CountLimit was added for six count keywords, but minContains/maxContains still call intValue() (here and in MinMaxContainsValidator:33-51), and Jackson 3 throws on that for values beyond the int range.
src/main/java/com/networknt/schema/keyword/EnumValidator.java
● 143 [correctness] Bounds and multipleOf now read a FloatNode by its decimal text (DecimalUtils.decimalValue), but the enum and uniqueItems lines this PR touched (UniqueItemsValidator:84) still use node.decimalValue(), which widens through double. A float therefore has two different values depending on the keyword.
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
● 182 [altitude] The protected getDividend hook now uses a private IllegalArgumentException subclass to pass the parsed DecimalNumber out to validate(). That changes the exception type subclass overrides see, and puts a non-serializable field inside a Throwable.
src/main/java/com/networknt/schema/keyword/MaximumValidator.java
● 57 [simplification] Four bound validators (Maximum, Minimum, ExclusiveMaximum, ExclusiveMinimum) each get the same copy of the non-finite guard, the integerMax/max precomputation, and the DecimalUtils.compare branches.
src/test/java/com/networknt/schema/serialization/ExactMapperRegressionTest.java
● 343 [test-maintainability] The new tests are spread across classes named after review rounds (CountLimitsReviewTest, NumericFollowUpTest, NumericReviewRegressionTest, MultipleOfExponentReviewTest, NumericBoundsReviewTest), and they use reflection to construct the private ExactMapperFactory$ExactNumberParser.

I reviewed PR #1290 at xhigh and reported 9 findings. The top four I reproduced by running the PR build on JDK 17; the rest come from reading the source.

Reproduced bugs:

  • Slow exponent parsing in type-loose mode: a numeric string with a very long exponent is parsed in quadratic time. A 2.4M-digit exponent took about 49 s for a single maximum check. Before the PR it failed immediately with an exception.
  • YAML regression: explicit floats with underscores (!!float 1_000) no longer parse through the default reader. YAMLMapper.shared(), the previous default, accepts them.
  • minContains/maxContains left out: the PR fixes out-of-range limits for six count keywords but not these two. maxContains: 3000000000 still fails schema loading.
  • Zero becomes DecimalNode(0): the new reader turns 0.0 and -0.0 into DecimalNode(0). Applied defaults now come out as 0 instead of 0.0, the sign of -0.0 is dropped, and error messages say "0".

The other five, found by reading the code:

  • float values are treated as "0.1" by minimum/maximum/multipleOf but as their widened double value by enum, const and uniqueItems.
  • An exception is used to carry the parsed number out of the protected getDividend hook.
  • The same non-finite guard is copied into four bound validators.
  • The reader does extra parsing and copying for every float token.
  • The new test classes are named after review rounds and use reflection to reach a private class.

The probes ran in a scratch worktree of the PR branch; nothing in your checkout changed. The worktree is still registered with your repo's git, so remove it with git worktree remove when you're done.

@PHJ2000

PHJ2000 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the additional review. The YAML parsing and zero-representation regressions show that changing the default readers has taken this PR well beyond the original integer-precision fix. I should have separated those changes earlier.

Would you be open to splitting the work as follows?

  • Keep Preserve exact multipleOf operands #1290 and [2.x] Preserve exact multipleOf operands #1291 focused on multipleOf loses precision for large integer operands #1286: preserve exact integral operands in multipleOf, retain support for already-exact BigDecimal operands, and include the arithmetic safeguards and regression tests needed for those conversions. Leave the default JSON/YAML readers and unrelated keywords unchanged.
  • Move exact parsing of decimal literals and the related cross-keyword changes into a separate follow-up, with the reader design and compatibility expectations agreed first. That work would need to address the YAML, zero-representation, performance, and numeric-consistency findings before it could be merged.

Under this split, a decimal-spelled literal such as 9007199254740993.0 would remain a follow-up rather than being claimed as fixed by these two PRs. Any findings that still apply to the narrowed multipleOf implementation would be addressed there.

Does that scope work for you? I have left both branches unchanged pending your feedback.

@stevehu

stevehu commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Thanks, that split works for me. Changing the default readers is where most of the risk came from, and #1286 only needs multipleOf to stop rounding integral operands through double. Please go ahead with the narrowed scope on both #1290 and #1291.

A few things for the narrowed version:

  1. Huge exponents in type-loose mode. On the base branch, a loose string such as "1e99999999999" makes multipleOf throw NumberFormatException. Please either keep that behavior and leave the full handling to the follow-up, or handle it without parsing the exponent at full length. The current DecimalNumber.parse path builds a BigInteger from the whole exponent text, which is quadratic on JDK 17 (a 2.4M-digit exponent took about 49 s for one check), so please don't carry it over unchanged. That also removes the need for the exception that carries the parsed number out of the protected getDividend hook.
  2. Zero and negative divisors. The PR currently throws SchemaException for a zero or negative divisor, where the base branch ignores it. The spec does require a positive divisor, but this changes behavior for existing schemas. Please either move it to the follow-up or call it out in the PR description as a deliberate behavior change.
  3. Floats. Please leave the FloatNode decimal-text handling to the follow-up as well. Otherwise multipleOf would treat floats differently from enum/const until that lands.
  4. Tracking. Please open an issue for exact decimal literals and the reader design, linked from multipleOf loses precision for large integer operands #1286, so the 9007199254740993.0 case isn't lost, and update the descriptions of Preserve exact multipleOf operands #1290 and [2.x] Preserve exact multipleOf operands #1291 to match the narrower scope. The open findings on readers, zero representation, performance, minContains/maxContains and cross-keyword numeric consistency can move to that issue.
  5. Tests. Please put the remaining regression tests in MultipleOfValidatorTest rather than separate classes named after review rounds.

I'll review again once the narrowed version is pushed. Thanks again for the careful work on this.

@PHJ2000

PHJ2000 commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Updated both PRs: 7fedb4a on master and 7579163 on 2.x. Each now changes only MultipleOfValidator and MultipleOfValidatorTest relative to its base.

The default readers and other keywords are restored. Integral operands and values already supplied as BigDecimal stay exact; the arithmetic safeguards and protected conversion hooks remain. Float conversion and loose exponent overflow keep their base behavior. Zero divisors remain ignored; finite negative divisors are still checked for divisibility as before, without a new SchemaException policy.

All remaining tests are in MultipleOfValidatorTest. Full clean verify passed on Java 17 (8,629 tests, 30 skipped) and Java 8 (8,543 tests, 15 skipped), with no failures or errors. Both PR descriptions are updated, and #1293 tracks the decimal-literal reader design and deferred findings.

@stevehu

stevehu commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Code review(xhigh · 8 findings)
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
● 118 [correctness] Integral divisors are now exact, but decimal-literal dividends still go through double. When both values are large, the mismatch rejects true multiples that the base branch accepted.
● 148 [correctness] Integral dividends are now exact, but DoubleNode divisors still go through double. Large integer instances that are true multiples of a decimal-literal divisor are now rejected, and the message shows a number the schema never contained.
● 44 [altitude] The long fast path depends on getClass() == MultipleOfValidator.class, so every subclass loses it, including subclasses that override neither conversion hook. The hooks could be protected without checking the exact class.
● 61 [correctness] The error-message text for the divisor now depends on the schema node type: 100 prints "100", 100.0 still prints "1E+2", and a DecimalNode 2.0 now prints "2.0" where base printed "2".
● 106 [efficiency] Each validation that reaches the positive-scale-difference branch with a nonzero remainder runs BigInteger.modPow, even when the scale difference is tiny. In the negative branch, numerator.abs() is computed twice.
● 68 [simplification] integralDivisor's scale() > 0 and precision guards repeat checks that longValueExact already makes. The scale guard also keeps integral DecimalNode divisors such as 2.0 or 100.00 off the fast path.
src/test/java/com/networknt/schema/MultipleOfValidatorTest.java
● 341 [test-quality] conversionOverridesAreNotBypassed builds new ExecutionContext() and writes the package-private evaluationPath field directly. It is the only test in the suite that does this; Schema.createExecutionContext() already exists.
● 261 [test-quality] largeScaleDifferences and largeExponentsFromReaderAndLooseType use assertTimeoutPreemptively. On timeout it abandons a worker thread doing non-interruptible BigInteger work, which keeps using CPU for the rest of the suite.

The narrowed PR still introduces a real regression. Because only one side of multipleOf is now exact, it rejects some numbers the base branch correctly accepted. I reported 8 findings: 4 are about correctness and the rest are cleanup and test quality.

  • What breaks: a large integer schema value paired with a decimal instance, or a large decimal schema value paired with an integer instance, now fails validation. For example, {"multipleOf": 9007199254740993} now rejects 9007199254740993.0. The base rounded both sides the same way and accepted it. I confirmed this by running the same inputs against both branches.
  • PR description: it treats this rounding as unchanged behavior. It doesn't mention that some correct accepts become rejects, and no test covers these mixed cases.
  • Tests: MultipleOfValidatorTest passes on the PR head.

I removed the temporary worktree I used for testing, and your repo is as I found it.

@PHJ2000

PHJ2000 commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for checking both branches. I reproduced the two mixed-input cases and fixed them so they pass again. I also added regression tests for both directions and preserved the integer-only precision fix.

Exact decimal literal handling and reader changes remain in #1293, as agreed. This fix retains the existing rounding behavior for mixed inputs.

I also addressed the remaining findings:

  • Conversion hooks run before selecting the long remainder path, including for subclasses.
  • Divisor messages consistently normalize trailing zeros. If normalization would overflow the scale, they use the original representation; arithmetic retains the original value and scale.
  • Small scale differences use a bounded power of ten instead of modPow, and the repeated abs() call is removed.
  • longValueExact handles integral divisor conversion, so 2.0 and 100.00 can use the fast path too.
  • The tests use Schema.createExecutionContext(). The two extreme-exponent tests run in separate JVMs that are terminated on timeout.

On Java 17, mvn -B -ntp clean verify passes: 8,673 tests reported, 30 skipped, no failures or errors.

@stevehu

stevehu commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Code review(xhigh · 9 findings)
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
● 77 [correctness] Overrides are detected by checking whether the dividend equals BigDecimal.valueOf(node.doubleValue()). Any getDividend override that transforms the base value (abs, negate, scaling) is treated as exact, so the exact divisor is compared against a rounded dividend and the mixed-rounding mismatch this commit fixes comes back.
● 51 [altitude] The mixed-operand rule is spread over three heuristics with different equality semantics: floatingPointSchema uses compareTo (line 50), floatingPointDivisor uses scale-sensitive equals (line 52), and validate uses compareTo against a fresh double conversion (line 77). Some rounding happens inside the protected getDividend hook and some outside the hooks.
● 91 [correctness] For an integral schema with a Double/Float instance, the comparison uses the double-rounded floatingPointDivisor, but the error message now prints the exact divisorMessage. A rejected value that is a true multiple of the printed divisor therefore gets a self-contradicting message.
● 83 [efficiency] The long fast path now runs only after getDividend allocates node.decimalValue(). It then calls node.decimalValue() again for the compareTo guard, so every int/long validation allocates two BigDecimals before the long remainder.
● 76 [efficiency] Every Double/Float instance pays BigDecimal.valueOf(node.doubleValue()) twice per validation: once in getDividend and again for the override check. This happens even when floatingPointDivisor is numerically identical to divisor, which covers almost every schema (2, 3, 100, any integer ≤ 2^53).
● 82 [simplification] The effectiveDivisor == this.divisor reference check in the fast-path condition is always true when it matters. effectiveDivisor only changes for Double/Float nodes, and the fast path also requires node.isInt() || node.isLong().
● 97 [reuse] The private isFloatingPoint(node) re-derives node.isDouble() || node.isFloat() from isFloatingPointNumber() && !isBigDecimal(), duplicating the predicate inside JsonNodeTypes.isNonFiniteNumber. Its name also collides with Jackson's isFloatingPointNumber, which includes DecimalNode.
src/test/java/com/networknt/schema/MultipleOfValidatorTest.java
● 391 [test-quality] runInFork asserts inside finally (process.waitFor(5s) after destroyForcibly), and evaluates Files.readString(output) eagerly as the message on every run, including passing ones.
● 382 [test-coverage] The child JVM is started with only -Xmx128m and the classpath, so it does not get surefire's argLine. That argLine carries the jacoco prepare-agent javaagent and -Duser.language=en -Duser.region=GB.

The latest commit (1ade33c) fixes the regression from our last round. Every mixed integer/Double/Float case now gets the same accept/reject verdict as base, and all-exact cases match a BigDecimal oracle. I reported 9 findings: two correctness, the rest efficiency, cleanup and tests.

What I ran: a JDK 17 comparison of 16,638 combinations covering every number node type and type-loose strings, on base (51dab24) and the PR head.

  • Mixed cases: no verdict differences where either side is a Double or Float.
  • Exact cases: 6,840 exact-operand combinations checked against BigDecimal.remainder, with no mismatches and no exceptions.
  • Base errors: a few combinations that threw on base (e.g. integers too large for a double, which Jackson 3 refuses to convert) now validate normally.

Two correctness findings:

  • Subclass regression (reproduced): the PR guesses whether getDividend was overridden by comparing values. An override that returns super.getDividend(node).abs() with divisor 9007199254740993 now rejects -9007199254740993.0, which base accepted. The positive value is still accepted.
  • Error message: for {"multipleOf": 9007199254740993}, the input 27021597764222979.0 (exactly 3× the divisor) is rejected with "must be multiple of 9007199254740993". The check actually used the rounded divisor 9007199254740992. Base gave the same verdict but printed the number it compared.

Speed: the PR is still 3–5× faster than base. Two paths are slower than the previous commit (7fedb4a):

┌───────────────┬─────────┬─────────┬─────────┐
│ Path │ Base │ 7fedb4a │ PR head │
├───────────────┼─────────┼─────────┼─────────┤
│ int/int │ 43.7 ns │ 1.27 ns │ 7.9 ns │
├───────────────┼─────────┼─────────┼─────────┤
│ double/double │ 39.5 ns │ 10.5 ns │ 14.5 ns │
└───────────────┴─────────┴─────────┴─────────┘

The other findings are cleanup and test-harness issues.

I created two temporary worktrees for the probes and removed them; your checkout is unchanged. Three stale worktree entries from earlier sessions are still listed; git worktree prune removes them.

Preserve overridden dividend conversions and report the divisor used for validation. Remove redundant conversion checks and retain coverage and locale settings in forked tests.
Use direct integer remainder for the default validator and concrete IntNode/LongNode inputs. Keep subclass conversion hooks and their existing integer fast path. Add boundary and custom-node regression coverage.

Local JDK 17 JMH measurements keep varying int/long inputs near 2 ns/op. A getDividend override returning 6.0 changes from about 6.9 to 7.5 ns/op.
@PHJ2000

PHJ2000 commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I fixed mixed-number validation when a getDividend() override applies abs, negate, or scaling. Error messages now show the divisor actually used for the check.

The default integer-only fast path now skips BigDecimal conversions. Subclasses still use the conversion hooks and retain their existing integer fast path. I kept this optimization in a separate commit, 0fe8e80, from the other review fixes in 80a0abf.

I also unified the mixed-input divisor comparison rule and removed the redundant conversions, condition, and helper. Forked tests no longer assert during cleanup, and they read the output log only on failure. They now inherit the JaCoCo agent and locale settings.

mvn verify passed on Java 17 and Java 21. Each run reported 8,702 tests, with 30 skipped and no failures or errors.

In local JDK 17 JMH measurements before and after the optimization commit (80a0abf → 0fe8e80), the ordinary integer paths were similar or faster. One subclass case where getDividend() returns 6.0 increased from about 6.9 ns/op to 7.5 ns/op.

@stevehu

stevehu commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Code review(xhigh · 7 findings)
src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
● 101 [correctness] The update's unified mixed-input rule only applies to Double/Float nodes. A subclass whose getDividend still rounds integer inputs through double (the old base body) is checked against the now-exact integral divisor, so it rejects the divisor itself.
● 54 [correctness] Overrides are still detected by value equality. A getDivisor override that deliberately returns the exact integral value equals defaultDivisor, so for Double/Float inputs the validator quietly swaps in the double-rounded divisor instead of the override's result.
● 93 [correctness] The divisor is now chosen by input node type, ignoring what getDividend returned. A hook that returns the same value for every node gets different verdicts for LongNode and DoubleNode inputs, and the update flipped a test to expect rejecting a dividend equal to the schema divisor.
● 200 [api-contract] The contract of the protected hooks changed silently: getDividend must now return exact integers and depends on private floatingPointSchema state, and getDivisor results that equal the default get rounded for floating-point inputs. The Javadoc still just says "Gets the dividend/divisor to use".
● 74 [efficiency] Any Double-typed schema, such as 2.0 or 100.0, disables directIntegerValidation, so every IntNode/LongNode instance still goes through decimalValue(), doubleValue(), BigDecimal.valueOf(double) (Double.toString plus a parse), and another BigDecimal.valueOf plus compareTo. The rounding changes nothing when |value| ≤ 2^53.
● 97 [simplification] The second integer fast path keys on the node type (isInt/isLong, node.longValue()) and then allocates BigDecimal.valueOf(value) to compare against the hook result. It could test the dividend itself: scale()==0 && precision()<=18 → dividend.longValue() % longDivisor.
src/test/java/com/networknt/schema/MultipleOfValidatorTest.java
● 406 [test-harness] If destroyForcibly fails to stop the child within 5 s, the return value of waitFor is ignored. The outer finally's Files.deleteIfExists can then throw on Windows, because the live child still holds the log open as stdout, and that exception replaces the "Timed out" assertion.

I reviewed the latest update to PR #1290 (80a0abf and 0fe8e80) and the author's comment, and reported 7 findings. The PR's own MultipleOfValidatorTest passes on the PR head (131 tests on JDK 25); I didn't run the full suite. To check the hook findings, I ran a small probe against both the base commit and the PR head. The top three findings come from that probe and are confirmed; the other four come from reading the code.

What the comment claims:

  • Holds up:
    • Error messages now show the divisor that was actually used.
    • Built-in IntNode/LongNode inputs skip the BigDecimal conversions.
    • Subclasses still have an integer fast path.
    • The forked tests no longer assert during cleanup, and they inherit the JaCoCo agent and locale.
  • Only partly holds: "fixed mixed-number validation when a getDividend() override applies abs, negate, or scaling" is true only for Double/Float inputs. The rule is chosen by input node type, so:
    • A subclass that still rounds integer inputs through double (the old base body) now rejects the divisor itself.
    • A getDivisor override that returns the exact integer is quietly swapped for the rounded value.
    • The update changed an existing test so that a hook returning exactly the schema's divisor is now expected to fail.

I removed the two worktrees I created, and your checkout is unchanged. git worktree list still shows three entries marked prunable from earlier sessions, including a pr-1290 branch under an old scratchpad. git worktree prune removes them.

@PHJ2000

PHJ2000 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

I reviewed the agreed integer-precision scope alongside the custom-conversion regressions and protected hook contract issues in your latest review.

Locally, I tried applying exact integer arithmetic through the built-in validator factory while retaining the existing conversion hooks and behavior for validators created through the public constructor, including subclasses. This avoids using reflection or comparing returned values to infer whether a hook was overridden.

The built-in path fixes the large-integer precision cases, and the custom-conversion cases I checked match the base branch. However, directly constructed validators and subclasses, including those that do not override either hook, would not receive the precision improvement. Consequently, the current PR test expecting exact integer handling in a subclass without overrides still fails with this approach.

Would you accept this limit on where the precision fix applies in order to preserve the existing extension behavior?

@stevehu

stevehu commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Thanks for trying the factory-only approach and for asking before pushing it. I'd prefer not to limit the fix that way. The built-in factory is MultipleOfValidator::new, the same public constructor, so the class would need a second mode based on how it was created. A subclass that overrides nothing would also quietly keep the #1286 bug, and subclassWithoutConversionOverridesRetainsIntegerPrecision would have to flip.

I think the real problem is a requirement I asked for on 10-09: keeping base's double-rounded verdicts for mixed integer/Double operands. All the guessing about hooks comes from that requirement (floatingPointSchema, floatingPointDivisor/Denominator/Message, the getClass() check, and comparing values to detect overrides). Sorry for steering you there. Please drop it instead:

  1. The default getDivisor/getDividend return exact values for integral and BigDecimal nodes. Double/Float nodes keep BigDecimal.valueOf(doubleValue()), as on base, and the type-loose path is unchanged.
  2. validate compares whatever the hooks return. It never infers whether a hook was overridden, and it never switches the divisor based on the input node type.
  3. Remove floatingPointSchema, the floatingPoint* fields, and the getClass() == MultipleOfValidator.class condition. Keep the long fast path only where it's safe without inference, either for built-in IntNode/LongNode inputs or by testing the dividend itself (scale() == 0 && precision() <= 18).
  4. Update the Javadoc on both hooks to say that integral nodes are now exact, and add a Changed entry to the CHANGELOG for custom-validator authors. The project already allows custom-validator breaks in minor versions.

What this costs: mixed operands above 2^53, such as integer schema 9007199254740993 with the instance 9007199254740993.0, can change verdict compared with base. Those decimal values are already rounded when they're parsed, so the proper fix is #1293. Please drop or adjust the mixed-input tests that pin base's rounded verdicts, keep a test showing the large-integer precision fix, and note the mixed-input change in the PR description.

Two smaller items from the last round still apply after this:

  • The forked-test cleanup should check the result of waitFor after destroyForcibly, so a stuck child can't replace the timeout assertion with an exception from Files.deleteIfExists.
  • The same direction applies to [2.x] Preserve exact multipleOf operands #1291 on 2.x.

Once that's pushed, I'll review both PRs again with an oracle comparison like the earlier rounds.

@PHJ2000

PHJ2000 commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

No worries, and thanks for taking another look at the compatibility requirement. That makes the direction much clearer.

I removed the mixed-input compatibility fields and hook-override detection from both PRs. Directly constructed validators and subclasses now validate the values returned by getDivisor and getDividend. The long fast path is used only when the returned dividend can be represented without loss.

I updated the mixed-input tests, Javadoc, CHANGELOG and PR descriptions to reflect the changed behavior. The default divisor normalization and custom divisor message representations are preserved. I also documented that integral dividends can have a different scale, such as 2 instead of 2.0. Double/Float conversion is unchanged; precision lost during parsing remains in #1293.

The forked tests now check whether forced termination succeeds. Full clean verify passes on Java 17 and 21 for #1290, and Java 8 and 17 for #1291. A separate comparison against BigDecimal remainder covered 97,760 cases per branch with no mismatches.

Replacing the direct integer shortcut with checks on the hook result increased local JMH timings by roughly 0.3–1 ns/op in integer/plain-subclass cases and 4.6–5.8 ns/op in a subclass returning 6.0, compared with the previous published PR head. The integer-with-Double-divisor and Double cases were faster. These are method-level measurements.

@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 sticking with this through all the rounds. The final version does exactly what we agreed: validation uses what the hooks return, the override detection is gone, and the forked-test cleanup checks waitFor.

Verification (each PR merged into the current base)

  • MultipleOfValidatorTest: 138 on master (JDK 17, 25), 136 on 2.x (Java 8, 21). The JSON Schema Test Suite (7261) and the extras pass. The full suite passes on master/JDK 25 (9002) and 2.x/Java 8 (8876).
  • Revert check: with the base validator, 45 of 138 tests fail on master and 41 of 136 on 2.x.
  • 60k random divisor/value pairs across Int/Long/BigInteger/BigDecimal/Double/Float nodes, compared with an exact BigDecimal remainder check: no wrong verdicts, messages or exceptions on either branch. The base code gave about 170 wrong verdicts and over 4,000 wrong messages on the same inputs.
  • I checked isMultipleOf by hand, including the modular-exponentiation path.

What I pushed to both branches
Both PRs conflicted with their base in CHANGELOG.md after #1326/#1327 merged. I merged the current base and kept both entries. I also changed this entry's reference to the issue, (#1286), so it matches on both branches. CI passes on the new heads.

For later, outside this PR

  • multipleOf: 100 still reports must be multiple of 1E+2, which you kept on purpose.
  • On 2.x, a divisor the reader turns into Infinity (such as 1e400) still throws when the schema loads. The reader side is #1293.

Merging #1290 and #1291 together.

@stevehu
stevehu merged commit 47d2fe6 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.

multipleOf loses precision for large integer operands

3 participants