Repository navigation
[Fix][Transform-V2][DataValidator] Normalize numeric bounds in RANGE rule to fix ClassCastException - #11920
Conversation
…rule to fix ClassCastException Follow-up of apache#11855, which only covered DECIMAL fields. This change compares any pair of numeric values as BigDecimal and falls back to numeric/string comparison for mixed types, so the RANGE rule no longer throws ClassCastException for BIGINT/DOUBLE/FLOAT fields, non-finite values (NaN/Infinity) or STRING fields with numeric bounds. Co-Authored-By: Claude <noreply@anthropic.com>
davidzollo
left a comment
There was a problem hiding this comment.
+1 if CI passes.
LGTM
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point: the
DataValidatortransform'sRANGErule threwClassCastExceptionwhenever a field's runtime value type didn't exactly match the parsed bound type — e.g. aBIGINT/DOUBLE/FLOATfield compared against integer-looking bounds, non-finiteDOUBLEvalues (NaN/Infinity) against integer bounds, or aSTRINGfield holding numeric content compared against numeric bounds. A prior fix (#11855) only covered theBigDecimal-vs-Numbercase, leaving these other mismatched-type combinations unfixed. - Fix approach: replace the narrow
value instanceof BigDecimal && bound instanceof Numbercheck with a generalNumber-vs-Numberpath (comparing viaBigDecimal.toString()round-trip for finite values, and viaDouble.compareforNaN/Infinity), plus a fallback path that tries a numeric (BigDecimal) comparison first and falls back to string comparison when either side isn't numeric. - One-sentence summary: Generalizes
RangeValidationRule#compareso any combination of numeric/string field values and bounds is compared safely instead of throwingClassCastException.
1. Code Change Review
1.1 Core Logic Analysis
Before:
private int compare(Comparable value, Comparable bound) {
if (value instanceof BigDecimal && bound instanceof Number) {
return ((BigDecimal) value).compareTo(new BigDecimal(bound.toString()));
}
return value.compareTo(bound); // throws ClassCastException whenever value/bound are different Comparable types
}After:
private int compare(Comparable value, Comparable bound) {
if (value instanceof Number && bound instanceof Number) {
return compareNumbers((Number) value, (Number) bound);
}
return compareAsNumberOrString(value, bound);
}Key Findings:
compareNumberscorrectly special-casesNaN/Infinitybefore attempting aBigDecimalconversion (new BigDecimal(Double.NaN)would throwNumberFormatException), routing those throughDouble.compare, which — per its own contract — sortsNaNabove all finite values and treats+Infinity/-Infinityas the largest/smallest values. I traced this throughvalidate(): for amaxInclusive(default) check,Double.compare(NaN, max)is positive, somaxComparison > 0is true and the value is correctly rejected as "exceeds maximum" rather than crashing — confirmed by the newrangeRuleShouldRouteNonFiniteDoubleToErrorTableWithIntegerBoundstest, which asserts the row is routed to the error table.- For finite numeric values, the fix uses
new BigDecimal(value.toString())rather thanBigDecimal.valueOf(value.doubleValue())— this avoids collapsing aLong/BIGINTvalue throughdoublefirst (which would lose precision for values beyond2^53), the same reasoning the sibling PR #11724/#11918 documents. Good choice. compareAsNumberOrStringis the path taken whenever value/bound aren't bothNumber— e.g. aSTRINGfield vs a numeric bound (the PR's stated new use case), or twoSTRINGs, or aSTRINGvs a non-numericComparable. It tries aBigDecimalparse of both sides first and only falls back totoString().compareTo()onNumberFormatException.- This introduces one real, untested behavior change beyond what the PR describes: for two
Comparablevalues that are both plainStrings but happen to look numeric (e.g. a field value"15"against a configured bound"9"— reachable if a user configuresmin_value/max_valueas quoted JSON strings, sinceminValue/maxValueare typedComparableand set via Jackson deserialization), the old code didvalue.compareTo(bound), i.e. plain lexicalStringcomparison ("15" < "9"lexically, since'1' < '9'). The new code now successfully parses both asBigDecimaland does a numeric comparison (15 > 9) instead. I verified there is no pre-existing test anywhere inDataValidatorTransformTestthat exercises aStringbound against aStringfield, so this specific combination was previously untested and its behavior is now silently different. Arguably the new numeric-first behavior is what most users actually want (nobody configures numeric-looking string bounds expecting"15"to sort below"9"), but it is a genuine, silent semantic change for anyone who did rely on lexical ordering of numeric-looking strings — see Issue 1. - Runtime path:
RangeValidationRule.validate()is invoked per-row, per-configured-rule, fromDataValidatorTransform's normal row-mapping path (not a recovery/exception path) — this is exactly the path the new unit tests exercise end-to-end viaDataValidatorTransform.map(row), not just the rule class in isolation, which gives good confidence the fix works through the whole transform.
1.2 Compatibility Impact
Partially incompatible, in one narrow, previously-untested corner: two-String, both-numeric-looking RANGE bound comparisons switch from lexical to numeric ordering, as detailed above. All other combinations described in the PR (BIGINT/DOUBLE/FLOAT vs integer bounds, NaN/Infinity vs integer bounds, STRING-with-numeric-content vs numeric bounds) are pure bug fixes — they previously crashed with ClassCastException, so there is no prior "working" behavior to be incompatible with.
1.3 Performance / Side-Effect Analysis
Negligible. One extra Number instanceof check and, on the numeric path, one BigDecimal string-round-trip per comparison — same order of cost as the code it replaces, and this runs per-row only when a RANGE rule is configured on a field.
1.4 Error Handling and Logging
No logging is involved in this rule; validation failures are surfaced through the existing ValidationResult.failure(...) / error-routing mechanism, unchanged by this PR.
Issue 1: Silent behavior change for String-vs-String numeric-looking bounds is untested and undocumented
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/validator/rule/RangeValidationRule.java:118-124(compareAsNumberOrString) - Problem: When both
valueandboundare plainStrings that happen to parse as numbers, comparison silently switched from lexical (old) to numeric (new). No test in this PR (or pre-existing) exercises this specific case, and the docs (docs/en/transforms/data-validator.md,docs/zh/...) aren't updated to mention it. - Potential risk: Low probability of hitting real users (a
STRINGfield being validated withSTRING-typed numeric bounds is an unusual config to begin with, and the old lexical behavior for numeric strings was arguably already a latent footgun, not a documented guarantee), but it is a real, silent semantic change that should be called out rather than discovered later. - Best improvement: Add one test asserting the intended (numeric) behavior for
Stringfield +Stringbound with numeric content, and a one-line doc note indata-validator.mdclarifying thatRANGEbounds are compared numerically whenever both sides can be parsed as numbers, regardless of their declared/JSON type. - Severity: Medium
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Both new private methods (compareNumbers, compareAsNumberOrString) carry clear Javadoc explaining the "why" (avoiding ClassCastException, why NaN/Infinity need special-casing, why BigDecimal.toString()-round-trip instead of doubleValue()) — this is exactly the kind of comment the project's conventions ask for, and better than what many experienced-contributor PRs include. Nice work for a first PR.
2.2 Test Coverage and Test Stability
Good, focused coverage added to DataValidatorTransformTest: BIGINT field vs integer bounds, DOUBLE field vs integer bounds, NaN routed to the error table, and STRING field with numeric content vs integer bounds — covering every scenario explicitly listed in the PR description. All tests go through the full DataValidatorTransform.map(row) path rather than unit-testing the comparator in isolation, which is the right level. No Thread.sleep/hard waits, no shared static state, no floating-point-without-delta assertions, nothing order-dependent — these are plain, deterministic unit tests. Stability rating: Stable.
One gap (see Issue 1): no test for the String-vs-String numeric-bound case, which is where the one real behavior change lives.
2.3 Documentation Updates
Not updated. Since this PR is purely a bug fix (fixing crashes, not adding new user-facing config), that's acceptable for the documented scenarios; I'd only ask for a doc touch if Issue 1's behavior is intentionally kept (see recommendation below).
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. It replaces a narrow, special-cased type check with a general one that actually matches the rule's purpose (numeric range validation), and correctly isolates the "can't represent as BigDecimal" edge case (NaN/Infinity) rather than letting it throw. Good instinct to special-case those before attempting the BigDecimal conversion instead of catching a NumberFormatException there.
3.2 Maintainability
Splitting into compareNumbers (both sides Number) and compareAsNumberOrString (mixed/string sides) keeps each method's responsibility clear and matches how the Javadoc explains them — easy to follow and extend.
3.3 Extensibility
If a future numeric type needs different handling (e.g. BigInteger), it's a one-place change in compareNumbers.
3.4 Historical-Version Compatibility
No Option/config-key changes, no SPI changes, no serialized/checkpoint state involved — RangeValidationRule is a pure in-memory per-row comparator. The only compatibility nuance is the narrow String-vs-String case in Issue 1, which I'm treating as a non-blocking recommendation given how unlikely it is to be relied upon in practice.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Silent lexical→numeric behavior change for String-vs-String numeric-looking RANGE bounds; untested, undocumented |
RangeValidationRule.java:118-124 |
Medium |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
Welcome to the project, and thank you for this contribution — this is a genuinely solid piece of work for a first PR: you traced the fix all the way from the field-value type through to the transform's row-routing behavior, added Javadoc explaining why each edge case needs special handling (not just what the code does), and wrote tests that exercise the full transform rather than just the comparator in isolation. That's a level of care I don't always see even from experienced contributors.
- Blockers — must be fixed before merge:
- CI must finish and go green. As of this review, the Build workflow on your fork (
BinTaoMa/seatunnel, head09b978264) is still actively running (all-connectors-it-7,jdbc-connectors-it-part-1,kudu-connector-itin progress), and the Apache-side status check showsCANCELLEDfrom an earlier attempt — neither is a final green result yet. None of the in-flight jobs touchseatunnel-transforms-v2, so I have no reason to expect a real failure here, but per project policy the PR needs a completed, green run before merge.
- CI must finish and go green. As of this review, the Build workflow on your fork (
- Recommended fixes — non-blocking:
- Add a test for the
String-field-vs-String-bound numeric case, and a one-line doc note confirming numeric comparison is intentional there (Issue 1). This is a nice-to-have, not something you need to fix before merge — I'm confident the current behavior (numeric comparison) is the more correct one, I just want it to be an intentional, documented choice rather than an undocumented side effect for whoever reads this code next.
- Add a test for the
I agree with @davidzollo's LGTM — I independently reached the same technical conclusion after tracing the NaN/Infinity handling and the full Number-vs-Number/mixed-type comparison logic; the only thing I'd add on top is the Issue 1 observation above, which is a follow-up-suitable nice-to-have rather than a blocker. No Option A/B trade-off applies — this is the right, minimal fix for the described bug.
davidzollo
left a comment
There was a problem hiding this comment.
+1
LGTM
Thanks for your contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!
Please ignore the following message if you have joined in the Slack~
To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack
This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄
…rule to fix ClassCastException (apache#11920) Co-authored-by: Claude <noreply@anthropic.com>
Purpose of this pull request
Closes #11919. Follow-up of #11855, which only covered DECIMAL fields.
This PR normalizes any pair of numeric values to BigDecimal and falls back
to numeric/string comparison for mixed types, so the RANGE rule no longer
throws ClassCastException for:
Does this PR introduce a user-facing change?
No.