Skip to content

[2.x] Improve multipleOf divisor messages and handle non-finite divisors - #1330

Merged
stevehu merged 10 commits into
networknt:2.xfrom
PHJ2000:fix-1328-2x
Oct 19, 2026
Merged

stevehu merged 10 commits into
networknt:2.xfrom
PHJ2000:fix-1328-2x

Conversation

@PHJ2000

@PHJ2000 PHJ2000 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Refs #1328. Corresponding master PR: #1329.

Display multipleOf divisors in plain notation when the result fits within 32 characters or is no longer than BigDecimal.toString(). Check the length before expansion to avoid excessive padding for extreme scales. Apply this formatting to custom getDivisor() results while preserving trailing zeros.

Ignore zero divisors returned by overrides, regardless of scale, matching the default conversion.

Align the default handling of non-finite divisors and dividends with master's multipleOf behavior. This is a fail-open change: values such as 1e400 that the default reader converts to infinity are now accepted by this constraint instead of causing an exception. A non-finite divisor disables the constraint for all instances; a non-finite dividend skips the check for that instance. Enable DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS to validate these decimal values exactly (see #1293). Exact integral and BigDecimal values remain validated, and custom getDividend() results are still used. Other numeric keywords on 2.x retain their existing behavior.

Update Javadoc and CHANGELOG, and add regression coverage for formatting, zero divisors, non-finite values, exact large decimals, and custom conversions.

Validation: mvn -B -Dtest=MultipleOfValidatorTest test on JDK 8 — 194 tests passed.

@codecov-commenter

codecov-commenter commented Oct 15, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (2.x@f2387c2). Learn more about missing BASE report.
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@          Coverage Diff           @@
##             2.x    #1330   +/-   ##
======================================
  Coverage       ?   79.25%           
  Complexity     ?     2112           
======================================
  Files          ?      202           
  Lines          ?     7023           
  Branches       ?     1272           
======================================
  Hits           ?     5566           
  Misses         ?     1003           
  Partials       ?      454           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@stevehu

stevehu commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Thanks for the PR. Findings from review. Tests pass locally (162 on JDK 8). Points 1–4 are shared with #1329; 5–6 are specific to 2.x.

  1. The 32-character cap doesn't stop large integers ending in 0 from printing in scientific notation (MultipleOfValidator.formatDivisorMessage). The cap measures the whole plain string, not the zeros that plain expansion adds. For example, divisor 123456789012345678901234567890000 (33 digits) prints as 1.2345678901234567890123456789E+32, which is 34 characters versus 33 in plain form. Meanwhile the 34-digit 1234567890123456789012345678901234 prints plain. So whether a large integer shows as …E+n depends only on whether it ends in 0, which is the multipleOf: divisor shown as 1E+2 in messages; 2.x throws on a divisor that overflows double #1328 symptom above 32 digits. Suggestion: cap only the padding zeros (-scale when scale < 0, scale - precision when scale >= precision), or use plain whenever it is no longer than max(32, toString().length()).

  2. The zero-divisor cases in overriddenDivisorMessage pass only because of the chosen dividend. With an override returning 0, validating 1 throws ArithmeticException: BigInteger divide by zero. With 0.00, both 1 and 1.5 throw. The test works only because the dividend changed to 0.00000015, which reaches the early return false in isMultipleOf. Either drop the zero cases, or have the validator ignore zero divisors from overrides (as the default getDivisor already does) and assert that behavior.

  3. divisorMessageBoundsPlainNotation doesn't test the precision term of the length formula. The expected string is built with the same toPlainString()/toString() calls the implementation uses, and every boundary case has a one-digit coefficient. A formula that ignored precision would still pass. Adding multi-digit cases at the cap with literal expected strings would cover it, e.g. 1.5E+30 (32 chars, plain) and 1.5E+31 (33 chars, scientific).

  4. Zero is special-cased only for negative scales. An override returning 0E+100 shows 0, but 0E-100 shows 0E-100, and a zero with scale 30 shows a 32-character 0.000…0. If zero divisors stay supported, one rule for zero would make this consistent.

  5. An instance value that overflows double still throws on 2.x. Schema {"multipleOf":2} validating 1e400 or -1e400 with InputFormat.JSON throws NumberFormatException: the default reader produces DoubleNode(Infinity), and getDividend calls BigDecimal.valueOf(Infinity). Master returns no error here (JsonNodeTypes.isNonFiniteNumber). So the same literal is now safe as a divisor but crashes as a dividend, and the CHANGELOG's "matching master" claim holds only for divisors. Please either handle overflowed dividends too, or narrow the changelog wording.

  6. preservesNonFiniteConversionBehaviorOnJackson2 is partly stale. With the constructor assertThrows removed, the getDivisor override in the loop no longer guards against anything, and only dividend behavior is still "preserved". Consider renaming the test to cover only the dividend, or asserting that constructing with a non-finite node no longer throws.

@stevehu

stevehu commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Thanks for the update. I re-reviewed d56a711.

Fixed: point 3. divisorMessageBoundsPlainNotation now uses literal expected strings and multi-digit coefficients, and it fails if the precision term is dropped from the length formula. MultipleOfValidatorTest passes locally (170 tests on JDK 8).

Still open (the main code hasn't changed):

  1. Large integers ending in 0 still print in scientific notation (same as Use plain notation for short multipleOf divisors in error messages #1329).
  2. The zero-divisor cases in overriddenDivisorMessage still depend on the 0.00000015 dividend; ordinary dividends still throw ArithmeticException.
  3. Zero divisors still print differently depending on the sign of the scale.
  4. Schema {"multipleOf":2} validating 1e400 or -1e400 still throws NumberFormatException, and CHANGELOG line 14 still says "matching master". Please handle overflowed dividends or narrow the wording to divisors.
  5. preservesNonFiniteConversionBehaviorOnJackson2 still has the unneeded getDivisor override and a name that covers more than the dividend case.

Please address these or reply on whether you plan to. If you disagree with any of them, a short note is fine.

@PHJ2000

PHJ2000 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the re-review. The remaining points are now addressed:

  • Point 1: use plain notation when its length is at most max(32, toString().length()), with regression coverage for the reported case.
  • Points 2 and 4: ignore zero divisors returned by overrides across all scales, with tests for the ordinary dividends that previously threw.
  • Point 5: handle non-finite dividends in the default conversion, matching master. Tests cover JSON overflow, Double/Float non-finite values, continued validation of exact large decimals, and custom getDividend() results.
  • Point 6: replace the stale test with explicit coverage of the new behavior and remove the unused getDivisor() override.

The literal, multi-digit boundary tests for point 3 remain in place. Javadoc and CHANGELOG now describe the final behavior.

All 192 MultipleOfValidatorTest cases pass on JDK 8.

@stevehu

stevehu commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Thanks for this. The formatting part matches #1329 and looks correct. I fuzzed the plain-length formula against toPlainString().length() on 2M random values and found no mismatches. Most of my comments are about the non-finite changes that only exist on 2.x.

Behavior

1. Non-finite values now fail open, and the CHANGELOG should say so plainly

With the default reader, {"multipleOf":3} now accepts the instance 1e400 (rounded to Infinity), and {"multipleOf":1e400} accepts every instance. Before this change both threw, and preservesNonFiniteConversionBehaviorOnJackson2 pinned that on purpose. With USE_BIG_DECIMAL_FOR_FLOATS, the same schema and instance give the opposite result (exactDecimalsFromReader expects "3, 1e400, 1" and "1e400, 1, 1" to produce errors). I'm fine with matching master, but please make the CHANGELOG entry explicit that this is a fail-open change. For example: "such values are now accepted rather than rejected or reported; enable DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS to validate them exactly (see #1293)."

2. "Matching master" only holds for multipleOf

On master, JsonNodeTypes.isNumber returns false for non-finite nodes, so every numeric keyword skips them. On 2.x, isNumber still accepts them. For example, {"minimum":0,"multipleOf":2} against DoubleNode.valueOf(Double.NaN) still throws NumberFormatException from MinimumValidator. Either:

  • backport master's isNonFiniteNumber check into JsonNodeTypes.isNumber on 2.x (the more general fix, which may deserve its own PR), or
  • narrow the CHANGELOG wording to "matching master's multipleOf behavior".

Code

3. Reuse JsonNodeTypes.isNonFiniteNumber in getDividend, as master does

This keeps the two branches textually aligned for future cherry-picks:

if (node.isNumber()) {
    if (JsonNodeTypes.isNonFiniteNumber(node)) {
        return null;
    }
    if (node.isIntegralNumber() || node.isBigDecimal()) {
        return node.decimalValue();
    }
    return BigDecimal.valueOf(node.doubleValue());
}

4. Avoid converting to a string twice in formatDivisorMessage (same as on #1329)

String text = value.toString();
if (length > text.length()) {
    return text;
}
return text.indexOf('E') < 0 ? text : value.toPlainString();

5. Update the getDivisor Javadoc

It still says Double/Float nodes are converted with BigDecimal.valueOf(double). Please add the same "non-finite nodes return null" sentence you added to getDividend.

Tests

6. ignoresDividendThatOverflowsDouble can't distinguish "skipped" from "validated"

±10^400 is an exact multiple of 2, so the test passes either way. Using {"multipleOf":3} would actually pin the skip behavior (the exact reader reports 1 error for the same input).

7. Restore coverage for a getDivisor override with a non-finite schema node

Removing preservesNonFiniteConversionBehaviorOnJackson2 dropped the only test that builds a validator from a NaN/Infinity schema node with getDivisor overridden. Something like:

@ParameterizedTest
@ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY})
void nonFiniteDivisorOverrideIsStillUsed(double value) {
    Schema parent = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12)
            .getSchema("{\"multipleOf\":2}");
    for (JsonNode schemaNode : new JsonNode[] {DoubleNode.valueOf(value), FloatNode.valueOf((float) value)}) {
        MultipleOfValidator validator = new MultipleOfValidator(SchemaLocation.of("#/multipleOf"),
                schemaNode, parent, parent.getSchemaContext()) {
            @Override
            protected BigDecimal getDivisor(JsonNode node) {
                return BigDecimal.valueOf(2);
            }
        };
        ExecutionContext context = parent.createExecutionContext();
        JsonNode input = IntNode.valueOf(3);
        validator.validate(context, input, input, new NodePath(PathType.JSON_POINTER));
        assertEquals(1, context.getErrors().size());
    }
}

8. Merge nonFiniteDividendOverrideIsStillUsed into convertedNonFiniteInputDoesNotRoundTheDivisor

Both override getDividend and feed NaN/Infinity nodes. The new test only adds the failing case, which could be a second assertion in the existing test.

9. Simplify inheritedDivisorUsesPlainNotation (same as on #1329)

The delegate = false case is an empty subclass that exactDivisorMessage already covers. Keep only the super.getDivisor override.

@PHJ2000

PHJ2000 commented Oct 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed follow-up. All nine points are now addressed:

  • Points 1, 2, and 5: document the fail-open behavior explicitly, limit the comparison to master's multipleOf behavior, and clarify the non-finite divisor handling in Javadoc. The CHANGELOG also explains how to enable exact decimal reading.
  • Point 3: reuse JsonNodeTypes.isNonFiniteNumber in getDividend, as on master.
  • Points 4 and 9: reuse an already-plain string and keep only the super.getDivisor delegation case in the inheritance test.
  • Point 6: change the overflow test's divisor to 3, so it distinguishes skipping the check from exact validation.
  • Point 7: restore coverage for overridden divisor conversion with NaN and both infinities, using Double and Float schema nodes.
  • Point 8: merge the failing dividend-override case into convertedNonFiniteInputDoesNotRoundTheDivisor, alongside the existing passing case.

All 194 MultipleOfValidatorTest cases pass on JDK 8 and 17, and the full suite passes on JDK 8.

@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, I re-reviewed 8e9b185 and all nine points are addressed:

  • the CHANGELOG states the fail-open behavior and scopes parity to multipleOf;
  • getDividend reuses JsonNodeTypes.isNonFiniteNumber;
  • both Javadocs describe non-finite handling;
  • the overflow test uses divisor 3;
  • getDivisor override coverage for non-finite schema nodes is restored;
  • the dividend-override tests are merged.

MultipleOfValidatorTest passes locally (194 tests on JDK 21) and CI is green on Java 8 through 21.

I'll follow up separately with one small docs tweak, so no changes needed here: the CHANGELOG note on USE_BIG_DECIMAL_FOR_FLOATS should say it needs to be enabled on the registry's NodeReader, since enabling it on an application mapper doesn't affect schema loading.

Approving and merging.

@stevehu
stevehu merged commit 7a17c68 into networknt:2.x Oct 19, 2026
4 checks passed
stevehu added a commit that referenced this pull request Oct 19, 2026
The CHANGELOG note for non-finite multipleOf values did not say where
USE_BIG_DECIMAL_FOR_FLOATS must be enabled. Point to the SchemaRegistry's
NodeReader, and to the caller's mapper for pre-parsed JsonNode
instances. Follow-up to #1330.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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.

3 participants