Skip to content

[Fix][Transform-V2] Support decimal range bounds - #11855

Merged
davidzollo merged 1 commit into
apache:devfrom
zhangshenghang:fix-data-validator-decimal-range
Aug 21, 2026
Merged

davidzollo merged 1 commit into
apache:devfrom
zhangshenghang:fix-data-validator-decimal-range

Conversation

@zhangshenghang

Copy link
Copy Markdown
Member

What does this PR do?

Fixes #11804 by comparing BigDecimal field values with numeric range bounds as BigDecimal values. This prevents ClassCastException when a DECIMAL field uses integer min_value or max_value settings.

Tests

  • Adds a DataValidator regression test covering a DECIMAL field with integer range bounds.
  • Ran the focused DECIMAL/integer-bound regression successfully.
  • ./mvnw spotless:apply completed successfully.
  • Maven module and full verification could not complete because the current upstream/dev checkout is missing required seatunnel-config-shade source classes (unrelated to this change).

@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?

Users hit a ClassCastException when a DataValidator RANGE rule validates a DECIMAL field against integer min_value/max_value bounds (e.g. DECIMAL(10,2) column, min_value = 0, max_value = 1000). The row value arrives as java.math.BigDecimal, the config bound is parsed as java.lang.Integer, and the old code called comparableValue.compareTo(minValue) directly — BigDecimal.compareTo is generically typed to Comparable<BigDecimal>, so the JVM's bridge-method cast to BigDecimal throws ClassCastException for any non-BigDecimal argument. The fix adds a small compare() helper that special-cases "value is BigDecimal, bound is any Number" by converting the bound to BigDecimal via new BigDecimal(bound.toString()) before comparing. One-sentence summary: normalize the bound to BigDecimal before calling compareTo whenever the row value is a BigDecimal.

1. Code Change Review

1.1 Core Logic Analysis

Before:

int minComparison = comparableValue.compareTo(minValue);
...
int maxComparison = comparableValue.compareTo(maxValue);

After:

int minComparison = compare(comparableValue, minValue);
...
int maxComparison = compare(comparableValue, maxValue);

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);
}

Runtime path (normal execution, not a recovery/edge path) — confirmed by reading DecimalType (seatunnel-api/.../DecimalType.java:23,31, extends BasicType<BigDecimal>) and DataValidatorTransformConfig.parseComparable (seatunnel-transforms-v2/.../DataValidatorTransformConfig.java:307-325, which returns Integer/Long/Double/String, never BigDecimal):

JDBC source (DECIMAL(10,2) column) -> SeaTunnelRow field value = BigDecimal
  -> DataValidatorTransform.transformRow()            [DataValidatorTransform.java:80-104]
     -> FieldValidator.validate(fieldValue, ctx, ..)  [FieldValidator.java:53-67]
        -> RangeValidationRule.validate(value, ..)    [RangeValidationRule.java:56-88]
           -> compare(comparableValue, minValue)      [RangeValidationRule.java:67, 78, 90-95]
              BEFORE: BigDecimal.compareTo(Integer) -> bridge-method checkcast -> CCE (issue #11804)
              AFTER : value instanceof BigDecimal && bound instanceof Number
                       -> BigDecimal.compareTo(new BigDecimal(bound.toString())) -> correct, no CCE

This is squarely on the normal path any user hits by putting a RANGE rule on a DECIMAL column with a plain-integer bound — not an edge case. I verified the fix is logically sound for the reported case: the surrounding minInclusive/maxInclusive branching is untouched, so once compare() returns a correct signed int, the inclusive/exclusive semantics still hold.

Finding — the fix is narrower than the root cause. I traced BasicType (seatunnel-api/.../BasicType.java:30-37): BYTE_TYPE -> Byte, SHORT_TYPE -> Short, LONG_TYPE -> Long, FLOAT_TYPE -> Float, DOUBLE_TYPE -> Double. parseComparable only ever produces Integer/Long/Double/String for config bounds. That means the exact same ClassCastException family still exists today, unfixed by this PR, for:

  • Any TINYINT/SMALLINT field (Byte/Short value) with any RANGE bound — parseComparable never returns Byte/Short, so Byte.compareTo(Integer) / Short.compareTo(Integer) always throws.
  • Any BIGINT field (Long value) with a small-integer bound, e.g. min_value = 0 — parseComparable("0") returns Integer, so Long.compareTo(Integer) throws.
  • Any FLOAT field (Float value) with any bound — parseComparable never returns Float.
  • A DOUBLE field with an integer-literal bound (min_value = 0 instead of 0.0) — Double.compareTo(Integer) throws.

BIGINT/DOUBLE/FLOAT columns are at least as common in JDBC sources as DECIMAL, so this is very likely to resurface as a near-identical bug report shortly after this one closes. See Issue 1 below — not a regression (these paths were already broken before this PR), so I'm not blocking on it, but it's worth calling out because the general-purpose fix is barely more code than the special-cased one.

1.2 Compatibility Impact

Fully compatible. No Option renamed or removed, no default value changed, no public API/SPI signature changed (the new compare method is private), no serialization/checkpoint format touched (RangeValidationRule is a per-job config object, not checkpointed state). This purely fixes an exception that previously prevented the RANGE rule from ever working on DECIMAL fields with integer bounds — there is no previously-working behavior being changed.

1.3 Performance / Side-Effect Analysis

Negligible. compare() is a stateless, allocation-light helper (one extra BigDecimal construction per bound comparison only when the value is already a BigDecimal); it runs per-row, per-rule, which is the same cost profile as the code it replaces. No new threads, no shared mutable state, no resource lifecycle changes, no concurrency concerns.

1.4 Error Handling and Logging

No new logging or exception paths were introduced here; the pre-existing DataValidatorTransform.transformRow error handling (FAIL/SKIP/route-to-error-table, DataValidatorTransform.java:108-120`) is unaffected and out of scope for this diff. No issues to raise in this subsection.

2. Code Quality Assessment

2.1 Coding Standards

Issue 2 (see table below): the new compare() method has non-obvious behavior (a type-coercion special case) and carries no comment explaining why the BigDecimal/Number special-casing exists. This project's own contribution guide calls for comments on methods with "complex logic," and this qualifies — a future maintainer reading this method without the issue/PR context would not know why the instanceof BigDecimal branch is there. Everything else (import placement, @Data/@NoArgsConstructor usage, formatting) is consistent with the surrounding file and passed the fork's spotless-check / Code style CI job.

2.2 Test Coverage and Test Stability

One new unit test, rangeRuleShouldValidateDecimalFieldAgainstIntegerBounds (seatunnel-transforms-v2/src/test/java/.../DataValidatorTransformTest.java:70-98), builds a DecimalType(10,2) field, a RANGE rule with integer min_value/max_value, and asserts transform.map(row) returns the row unchanged for BigDecimal("99.99"). I confirmed in the fork's own Windows/JDK11 CI run that this test executed and passed as part of the seatunnel-transforms-v2 reactor module (Running org.apache.seatunnel.transform.validator.DataValidatorTransformTest / Tests run: 5, Failures: 0, Errors: 0), so it is not merely aspirational.

Issue 3 (see table below): the new test only proves the fix stops the crash for an in-range value — it never asserts that an out-of-range BigDecimal (below min_value or above max_value) is still correctly rejected, and it doesn't exercise the inclusive/exclusive boundary (minInclusive/maxInclusive combined with the new compare()). A compare() implementation that silently always returned 0 would still pass this test.

Flaky-test-risk rating: Stable. The new test is a pure in-memory unit test with no Thread.sleep, no Awaitility, no shared static state, no timing dependency, and a single deterministic input — path: seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/validator/DataValidatorTransformTest.java:70-98.

2.3 Documentation Updates

docs/en/transforms/data-validator.md and docs/zh/transforms/data-validator.md already document the RANGE rule (min_value/max_value, lines ~77-83) generically, with no prior claim that DECIMAL fields were excluded or handled differently. Since this PR fixes a bug rather than adding/renaming a config option or changing documented behavior, no doc update is required here, and none was made — consistent with the docs already matching the intended (now-restored) behavior.

3. Architectural Soundness

3.1 Elegance: This is a precise, minimal patch for the literal reported bug, but it is a targeted workaround rather than a root-cause fix — it special-cases one direction of one type pair (BigDecimal value vs. any Number bound) instead of generalizing "if both operands are Numbers, compare them as BigDecimal." The more general version is not meaningfully larger:

private int compare(Comparable value, Comparable bound) {
    if (value instanceof Number && bound instanceof Number) {
        return new BigDecimal(value.toString()).compareTo(new BigDecimal(bound.toString()));
    }
    return value.compareTo(bound);
}

That would also close the Byte/Short/Long/Float/Double gaps described in 1.1 at effectively the same cost and risk as what's already here. I'm not blocking on this since the reported issue is correctly fixed and the alternative form is genuinely a "nice to have," but I'd encourage the author to consider it in this PR (or open an immediate fast-follow) rather than waiting for another user to independently discover the same class of bug against a BIGINT or FLOAT column.

3.2 Maintainability: Good — the fix is localized to a single private helper with a clear (if uncommented) purpose, and doesn't leak type-coercion concerns into the caller.

3.3 Extensibility: As discussed in 3.1, extending the special-case condition to cover the other Number subtypes is trivial if/when the author or reviewers want to do it.

3.4 Historical-version compatibility: No historical-version, checkpoint, or upgrade-path concerns — this is a stateless config-object bug fix, not a serialized/persisted structure.

4. Issue Summary

Number Issue Location Severity
Issue 1 compare() only special-cases BigDecimal value vs. Number bound; the identical ClassCastException family remains for Byte/Short/Long/Float fields (and Double fields with integer-literal bounds) against mismatched-type bounds seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/validator/rule/RangeValidationRule.java:90-95 Medium
Issue 2 New compare() helper has no comment explaining the type-coercion special case seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/validator/rule/RangeValidationRule.java:90-95 Medium
Issue 3 New test only covers an in-range value; no assertion for out-of-range rejection or inclusive/exclusive boundary behavior with the new compare() path seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/validator/DataValidatorTransformTest.java:70-98 Medium

Issue 1: Fix scoped to BigDecimal, leaves the same defect for other numeric types

  • Location: seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/validator/rule/RangeValidationRule.java:90-95
  • Problem description: compare() only converts the bound to BigDecimal when the row value is already a BigDecimal. For Byte/Short/Long/Float/Double row values compared against a config bound of a different concrete Number subtype (very achievable given how parseComparable narrows integers to Integer/Long and decimals to Double), value.compareTo(bound) still throws ClassCastException at the type-erasure bridge-method cast.
  • Potential risk: Users with BIGINT, FLOAT, TINYINT, or SMALLINT columns will hit essentially the same crash as issue #11804 and may reasonably assume it's already fixed, generating confusing duplicate bug reports.
  • Best improvement: broaden the condition from value instanceof BigDecimal && bound instanceof Number to value instanceof Number && bound instanceof Number, comparing both via new BigDecimal(x.toString()).
  • Severity: Medium (not a regression — these paths were already broken before this PR; non-blocking recommendation)
  • Raised by another reviewer: No

Issue 2: Missing comment on compare()

  • Location: seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/validator/rule/RangeValidationRule.java:90-95
  • Problem description: The method silently special-cases BigDecimal-vs-Number comparisons with no explanation of why (i.e., no reference to the ClassCastException it avoids, or that config bounds are never parsed as BigDecimal).
  • Potential risk: Low, but a future refactor could easily "simplify" this back to a plain compareTo call without realizing it reintroduces #11804.
  • Best improvement: A short comment above compare() noting that config-parsed bounds are Integer/Long/Double/String (never BigDecimal) while row values for DecimalType fields are always BigDecimal, hence the explicit coercion.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 3: New test doesn't assert rejection or boundary behavior

  • Location: seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/validator/DataValidatorTransformTest.java:70-98
  • Problem description: The single new test case only checks that an in-range BigDecimal value passes without throwing. It does not check that a BigDecimal below min_value or above max_value is correctly reported as invalid, nor does it touch minInclusive/maxInclusive edge values (e.g. value exactly equal to the bound).
  • Potential risk: A compare() bug that always returns 0 (or otherwise mis-signs the comparison) would still pass this test — the test proves "no crash," not "correct validation."
  • Best improvement: Add at least one assertion for an out-of-range decimal value (expect validation failure via the configured ErrorHandleWay) and one boundary-exact case.
  • Severity: Medium
  • Raised by another reviewer: No

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — must be fixed

    • None. No High-severity, regression, or compatibility issues were found.
  2. Recommended fixes — non-blocking

    • Issue 1: broaden compare() to cover all Number subtype mismatches, not just BigDecimal-vs-Number (or file an immediate fast-follow issue if the author prefers to keep this PR narrowly scoped to #11804).
    • Issue 2: add a short comment on compare() explaining the coercion.
    • Issue 3: add a negative-path and a boundary-exact test case alongside the existing positive-path test.

Overall assessment: this is a correct, minimal, low-risk fix for the exact ClassCastException reported in #11804, backed by a passing regression test that I confirmed actually ran in CI (DataValidatorTransformTest, 5/5 passing on the fork's Windows/JDK11 job). Fully backward compatible — no config, API, or serialization changes. The only red CI check (Build) is the well-known Windows Hazelcast "Node failed to start!" flake in the unrelated seatunnel-engine-server module (OptionRulesApiTest.before:73 » IllegalState Node failed to start!, ~311s elapsed) — it fails before/unrelated to anything this PR touches, and the PR is fully up to date with dev (0 commits behind). My one substantive concern (Issue 1) is about the fix's scope, not its correctness for the reported bug, so I'm not blocking on it — but I'd genuinely like to see the broadened version land here rather than waiting for the next duplicate report against a BIGINT or FLOAT column, since the alternative fix is only marginally more code than what's already here.

Thanks for tracking down the root cause and adding a regression test, @zhangshenghang — nice, contained fix.

@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!

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 when RANGE rule validates a DECIMAL field

3 participants