Skip to content

[Fix][Transform-V2][DataValidator] Normalize numeric bounds in RANGE rule to fix ClassCastException - #11920

Merged
davidzollo merged 1 commit into
apache:devfrom
BinTaoMa:fix-range-numeric-bounds
Aug 22, 2026
Merged

davidzollo merged 1 commit into
apache:devfrom
BinTaoMa:fix-range-numeric-bounds

Conversation

@BinTaoMa

Copy link
Copy Markdown
Contributor

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.

…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 davidzollo added the First-time contributor First-time contributor label Aug 21, 2026

@davidzollo davidzollo 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.

+1 if CI passes.
LGTM

@DanielLeens DanielLeens 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.

What Problem Does This PR Solve?

  • User pain point: the DataValidator transform's RANGE rule threw ClassCastException whenever a field's runtime value type didn't exactly match the parsed bound type — e.g. a BIGINT/DOUBLE/FLOAT field compared against integer-looking bounds, non-finite DOUBLE values (NaN/Infinity) against integer bounds, or a STRING field holding numeric content compared against numeric bounds. A prior fix (#11855) only covered the BigDecimal-vs-Number case, leaving these other mismatched-type combinations unfixed.
  • Fix approach: replace the narrow value instanceof BigDecimal && bound instanceof Number check with a general Number-vs-Number path (comparing via BigDecimal.toString() round-trip for finite values, and via Double.compare for NaN/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#compare so any combination of numeric/string field values and bounds is compared safely instead of throwing ClassCastException.

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:

  • compareNumbers correctly special-cases NaN/Infinity before attempting a BigDecimal conversion (new BigDecimal(Double.NaN) would throw NumberFormatException), routing those through Double.compare, which — per its own contract — sorts NaN above all finite values and treats +Infinity/-Infinity as the largest/smallest values. I traced this through validate(): for a maxInclusive (default) check, Double.compare(NaN, max) is positive, so maxComparison > 0 is true and the value is correctly rejected as "exceeds maximum" rather than crashing — confirmed by the new rangeRuleShouldRouteNonFiniteDoubleToErrorTableWithIntegerBounds test, which asserts the row is routed to the error table.
  • For finite numeric values, the fix uses new BigDecimal(value.toString()) rather than BigDecimal.valueOf(value.doubleValue()) — this avoids collapsing a Long/BIGINT value through double first (which would lose precision for values beyond 2^53), the same reasoning the sibling PR #11724/#11918 documents. Good choice.
  • compareAsNumberOrString is the path taken whenever value/bound aren't both Number — e.g. a STRING field vs a numeric bound (the PR's stated new use case), or two STRINGs, or a STRING vs a non-numeric Comparable. It tries a BigDecimal parse of both sides first and only falls back to toString().compareTo() on NumberFormatException.
  • This introduces one real, untested behavior change beyond what the PR describes: for two Comparable values that are both plain Strings but happen to look numeric (e.g. a field value "15" against a configured bound "9" — reachable if a user configures min_value/max_value as quoted JSON strings, since minValue/maxValue are typed Comparable and set via Jackson deserialization), the old code did value.compareTo(bound), i.e. plain lexical String comparison ("15" < "9" lexically, since '1' < '9'). The new code now successfully parses both as BigDecimal and does a numeric comparison (15 > 9) instead. I verified there is no pre-existing test anywhere in DataValidatorTransformTest that exercises a String bound against a String field, 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, from DataValidatorTransform's normal row-mapping path (not a recovery/exception path) — this is exactly the path the new unit tests exercise end-to-end via DataValidatorTransform.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 value and bound are plain Strings 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 STRING field being validated with STRING-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 String field + String bound with numeric content, and a one-line doc note in data-validator.md clarifying that RANGE bounds 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.

  1. Blockers — must be fixed before merge:
    • CI must finish and go green. As of this review, the Build workflow on your fork (BinTaoMa/seatunnel, head 09b978264) is still actively running (all-connectors-it-7, jdbc-connectors-it-part-1, kudu-connector-it in progress), and the Apache-side status check shows CANCELLED from an earlier attempt — neither is a final green result yet. None of the in-flight jobs touch seatunnel-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.
  2. 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.

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 davidzollo 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.

+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 😄

@davidzollo
davidzollo merged commit 149cde8 into apache:dev Aug 22, 2026
3 checks passed
zhang-arvin pushed a commit to zhang-arvin/seatunnel that referenced this pull request Aug 25, 2026
…rule to fix ClassCastException (apache#11920)

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug][Transform-V2][DataValidator] ClassCastException still occurs for BIGINT/FLOAT/DOUBLE fields and non-finite values (follow-up of #11804/#11855)

3 participants