Skip to content

[Bug][Transform-V2] Fix CEIL/FLOOR/ROUND/MOD/TRUNC silently corrupting BIGINT and DECIMAL values (#11696) - #11712

Merged
davidzollo merged 5 commits into
apache:devfrom
waterWang:fix-sea-11696-numeric-corruption
Aug 23, 2026
Merged

davidzollo merged 5 commits into
apache:devfrom
waterWang:fix-sea-11696-numeric-corruption

Conversation

@waterWang

Copy link
Copy Markdown

Description

This PR fixes Bug #11696 where CEIL, FLOOR, ROUND, MOD, and TRUNC/TRUNCATE functions silently corrupt BIGINT and DECIMAL values in the Zeta SQL transform-v2.

Root Causes

  1. CEIL/FLOOR always returned Integer via .intValue(), truncating Long and BigDecimal precision
  2. ROUND for BigDecimal cases used BigDecimal.valueOf(v1.doubleValue()), losing precision through double conversion
  3. MOD used BigDecimal.valueOf(leftValue.doubleValue()) for both operands, and the divide-by-zero check used rightValue.doubleValue() == 0 which underflows for tiny non-zero divisors
  4. ZetaSQLType hardcoded CEIL/CEILING/FLOOR as INT_TYPE and TRUNC/TRUNCATE as DOUBLE_TYPE, regardless of the actual input type

Changes

NumericFunction.java

  • CEIL/FLOOR: Changed return type from Integer to Number, preserving the input type (Integer to Integer, Long to Long, BigDecimal to BigDecimal, etc.)
  • ROUND (BigDecimal): Changed BigDecimal.valueOf(v1.doubleValue()) to (BigDecimal) v1 to preserve precision
  • MOD: Changed BigDecimal.valueOf(doubleValue()) to new BigDecimal(toString()) for both operands. Changed divide-by-zero check from doubleValue() == 0 to BigDecimal.compareTo(BigDecimal.ZERO) == 0

ZetaSQLType.java

  • CEIL/CEILING/FLOOR: Changed from BasicType.INT_TYPE to return the same type as the first argument
  • TRUNC/TRUNCATE: Changed from BasicType.DOUBLE_TYPE to return the same type as the first argument

Test updates

  • Updated NumericFunctionTest expectations for CEIL/FLOOR of Double inputs (now returns Double instead of Integer)
  • Added tests for Long inputs (preserves Long), BigDecimal inputs (preserves BigDecimal), and BigDecimal MOD precision preservation
  • Added test for MOD with a divisor that underflows to 0.0 in double
  • Updated SQLNumericFunctionsTest expectations for CEIL/FLOOR of Double columns

Testing

  • All 47 tests in the affected test classes pass (ZetaSQLTypeTest, ZetaSQLFunctionTest, ZetaSQLEngineTest, SQLNumericFunctionsTest, NumericFunctionTest)

Checklist

  • Bug fix
  • Tests updated
  • Build passes with mvn compile -pl seatunnel-transforms-v2 -am -DskipTests

Closes #11696

…g BIGINT and DECIMAL values (apache#11696)

CEIL and FLOOR always returned Integer (via .intValue()), which silently
corrupted Long and BigDecimal inputs. ROUND and MOD for BigDecimal went
through doubleValue(), losing precision. MOD's divide-by-zero check used
doubleValue() == 0, which underflows for tiny non-zero divisors.

- CEIL/FLOOR now return Number and preserve the input type
- ROUND for BigDecimal uses the original BigDecimal instead of converting
  through double
- MOD converts operands to BigDecimal via toString to preserve precision
- MOD divide-by-zero now checks BigDecimal.compareTo instead of double == 0
- ZetaSQLType CEIL/CEILING/FLOOR/TRUNC/TRUNCATE now report the same type
  as the first argument instead of hardcoded INT/DOUBLE

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

Thanks for tracking down and fixing this, @waterWang — silent numeric corruption is exactly the kind of bug that's expensive to discover in production, and your root-cause analysis in the description is accurate. I read the full diff plus the current source at head 672fc633 to trace the runtime path end to end, and I also need to flag something important up front before the line-by-line review.

⚠️ This PR overlaps almost entirely with open PR #11697

Before anything else: #11697 ("[Fix][Transform-V2] Fix silent value corruption in Zeta SQL numeric functions", by @SEPURI-SAI-KRISHNA) is an already-open PR that fixes the exact same issue (#11696), touching the same four root causes in the same two source files (NumericFunction.ceil/floor narrowing to int, round()'s BIGDECIMAL branch round-tripping through double, mod()'s doubleValue() conversion and its zero-check, and ZetaSQLType hardcoding CEIL/FLOOR→INT_TYPE and TRUNC→DOUBLE_TYPE). I diffed both PRs directly (not just the titles) and confirmed:

  • NumericFunction.java and ZetaSQLType.java changes are functionally near-identical between the two PRs (same case-label moves in ZetaSQLType, same .intValue() removal on ceil/floor, same (BigDecimal) v1 fix in round()'s BIGDECIMAL branch, same BigDecimal-based zero-check in mod()).
  • #11697 was opened ~29 hours earlier (2026-08-07T15:30Z vs. this PR's 2026-08-08T20:15Z).
  • #11697 is more complete: it adds the required docs/en/introduction/concepts/incompatible-changes.md and docs/zh entries for this breaking change (see Issue 1 below — this PR has none), it adds Javadoc on the touched methods explaining the precision rationale, and it adds integration-level tests that assert the declared output type via SQLEngine.typeMapping() for LONG/DECIMAL columns, not just the computed value (see Issue 2 below — this PR doesn't test that path at all).

This is a genuine duplicate, not a superficial title collision — a maintainer needs to pick one PR (or ask the two contributors to consolidate) before either can be merged, since merging both would just replay the same case-label changes twice and the second one to land will hit a merge conflict on NumericFunction.java/ZetaSQLType.java against the first. I'm flagging this as Issue 1 (High) below and am treating it as a blocker for this PR specifically, independent of the code quality issues.

What Problem Does This PR Solve?

The Zeta SQL transform's CEIL, FLOOR, ROUND, MOD and TRUNC/TRUNCATE functions silently corrupted numeric values instead of erroring:

  1. NumericFunction.ceil()/floor() always finished with .intValue(), so CEIL(9007199254740993L) (a BIGINT) silently became 1 instead of 9007199254740993.
  2. round()'s BIGDECIMAL branch and mod() both converted operands to double first (BigDecimal.valueOf(v.doubleValue())), which truncates any DECIMAL value with more than ~15-17 significant digits.
  3. mod()'s divide-by-zero guard compared rightValue.doubleValue() == 0, which is unreliable for tiny non-zero BigDecimal divisors that underflow to 0.0 as a double.
  4. ZetaSQLType.getFunctionType() hardcoded CEIL/CEILING/FLOOR → INT_TYPE and TRUNC/TRUNCATE → DOUBLE_TYPE regardless of the actual argument type, so the declared output schema didn't even match the actual runtime value's type.

Job execution reports success in all cases — there's no exception, just a wrong number silently written to the sink. Concrete example from the linked issue #11696: CEIL(long_v) where long_v = 9007199254740993 returned 1 before this fix; after the fix it correctly returns 9007199254740993, with the declared column type correctly staying BIGINT instead of INT.

1. Code Change Review

1.1 Core Logic Analysis

ceil/floor return Number instead of Integer (NumericFunction.java:193-203, :285-295)

// Before
public static Integer ceil(List<Object> args) {
    ...
    return round(v1, v2, RoundingMode.CEILING).intValue();
}
// After
public static Number ceil(List<Object> args) {
    ...
    return round(v1, v2, RoundingMode.CEILING);
}

The private round(Number, Number, RoundingMode) helper (NumericFunction.java:205-262) already dispatches on v1.getClass().getSimpleName(). For INTEGER/SHORT/LONG with scale 0 (the common CEIL(col) case), it now returns v1 untouched instead of forcing it through int. Verified the only caller is ZetaSQLFunction.computeForValue() (ZetaSQLFunction.java:561-567), whose enclosing method returns Object, so widening Integer→Number is source/binary compatible there — no other call sites in the repo reference NumericFunction.ceil/floor.

round()'s BIGDECIMAL branch stops going through double (NumericFunction.java:226-231)

// Before: BigDecimal bd = BigDecimal.valueOf(v1.doubleValue());
// After:  BigDecimal bd = (BigDecimal) v1;

Since this branch is only reached when t.equals("BIGDECIMAL") (i.e. v1 really is a BigDecimal — BigDecimal is final, so the cast can't fail), this correctly avoids the double round-trip and preserves full precision.

mod() uses exact BigDecimal arithmetic (NumericFunction.java:164-170)

// Before
if (rightValue.doubleValue() == 0) { throw ... }
BigDecimal leftBD = BigDecimal.valueOf(leftValue.doubleValue());
BigDecimal rightBD = BigDecimal.valueOf(rightValue.doubleValue());
// After
BigDecimal rightBD = new BigDecimal(rightValue.toString());
if (rightBD.compareTo(BigDecimal.ZERO) == 0) { throw ... }
BigDecimal leftBD = new BigDecimal(leftValue.toString());

For Long/Integer operands this is a real fix: new BigDecimal(Long.toString(v)) is exact, whereas the old BigDecimal.valueOf(v.doubleValue()) silently lost precision above 2^53. For Double operands this is a no-op change in practice (Number.toString() on a boxed Double and BigDecimal.valueOf(double) both go through Double.toString() internally, so precision is identical either way) — the real win here is for Long/BigDecimal inputs, which matches the PR's stated goal.

ZetaSQLType declares the argument's type for CEIL/CEILING/FLOOR/TRUNC/TRUNCATE (ZetaSQLType.java:460-470)

These five function tags moved into the existing case ZetaSQLFunction.ABS: ... case ZetaSQLFunction.ROUND: ... group that already does return getExpressionType(function.getParameters().getExpressions().get(0)); — i.e. "same type as the first argument". This is the correct, minimal fix and matches the pattern already established for ABS/ROUND, and it fixes a genuine declared-vs-actual mismatch: before this change, TRUNC(bigint_col) declared DOUBLE_TYPE in the schema while NumericFunction.trunc() (untouched by this diff, already returned Number) actually produced a Long at runtime — a latent ClassCastException/serialization risk for any downstream code that trusted the declared schema type.

Runtime path: this is the normal query-execution path, not a recovery/edge path — ZetaSQLType.getFunctionType() runs during type inference for every SELECT ... CEIL/FLOOR/ROUND/MOD/TRUNC(...) query, and NumericFunction.{ceil,floor,mod,trunc} run on every row. Any pipeline using these functions on BIGINT/DECIMAL/DOUBLE columns hits the fixed code on every execution, not just on error/restart.

1.2 Compatibility

Partially incompatible — and this is an intentional, correct fix of previously wrong behavior, not a design regression. Concretely:

  • CEIL/CEILING/FLOOR/TRUNC/TRUNCATE now return the argument's data type (e.g. BIGINT in → BIGINT out) instead of always INT (or DOUBLE for TRUNC). Any downstream sink/schema that was implicitly relying on the old (buggy) INT/DOUBLE output type will now see a type change.
  • ROUND, TRUNC, and MOD now return numerically different (correct) values for large BIGINT/high-precision DECIMAL inputs that previously silently lost precision.

Missing required documentation for this breaking change — see Issue 2 below. Per this repo's own CLAUDE.md ("🚨 Backward Compatibility"): "Any incompatible change MUST: Be explicitly documented, Be documented in docs/en/introduction/concepts/incompatible-changes.md, Include migration guidance". This file already has a precedent entry for a very similar SQL-transform behavior change ("Adjusted SQL Transform date & time functions" a few lines above where a new entry would go), so the convention is clearly established — this PR just doesn't follow it, while the competing #11697 does (both docs/en and docs/zh).

1.3 Performance / Side effects

No meaningful change. mod() still allocates two BigDecimals per call (as before); using toString()/new BigDecimal(String) instead of doubleValue()/BigDecimal.valueOf(double) is not measurably more expensive and for integral types is actually simpler (no double round-trip). No new I/O, locking, retries, or resource-lifecycle changes. Not a concern.

1.4 Error handling & logging

Unchanged behavior: mod() still throws TransformException with CommonErrorCodeDeprecated.UNSUPPORTED_OPERATION and a clear "Mod by zero" message on a zero divisor — just now detected via exact BigDecimal.compareTo(BigDecimal.ZERO) instead of an unreliable doubleValue() == 0 check, which is strictly more correct. No swallowed exceptions, no new logging, nothing sensitive touched.

2. Code Quality

2.1 Coding standards / comment completeness

The NumericFunction.ceil()/floor()/round()/mod() changes are non-trivial precision-correctness fixes but carry no explanatory comments on why the old approach was wrong or what invariant the new code relies on (e.g. why (BigDecimal) v1 is safe, why toString() avoids the double round-trip). This repo's CLAUDE.md asks for comments on "complex or performance-critical logic," and this qualifies — precision bugs are exactly the kind of thing a future editor could silently reintroduce without a comment explaining the constraint. For comparison, #11697 adds a short Javadoc on ceil/floor/the BIGDECIMAL branch explaining precisely this ("Narrowing the result to int would silently corrupt BIGINT... inputs"). This isn't a hard blocker on its own, but combined with Issue 2/3 it's part of why this PR currently reads as less finished than its sibling.

2.2 Test coverage & stability

The new/updated tests are correct where they go (SQLNumericFunctionsTest.testBasicNumericFunctions, NumericFunctionTest.testModForDifferentResultTypes/testCeilFloorRoundAndTrunc), but there's a real coverage gap — see Issue 3.

One test's stated intent doesn't match what it verifies — see Issue 4.

Stability rating: Stable. All new/changed assertions are on pure, deterministic functions (NumericFunction.ceil/floor/mod/trunc, or SQLTransform.transformRow over a fixed in-memory row) — no Thread.sleep, no Awaitility, no shared mutable/static state, no execution-order dependence, no network/timing-sensitive waits. The floating-point assertions (assertEquals(2.0d, ...), assertEquals(1.0d, ...)) use exact equality without a delta, but the inputs (1.2d→Math.ceil, 1.8d→Math.floor) produce values that are exactly representable in double with no accumulated rounding error, so this isn't a flakiness risk in practice.

2.3 Docs

docs/en/transforms/sql-functions.md already documents the "same type" contract for these functions (per the linked issue), so no change is needed there. However, as noted in 1.2/Issue 2, docs/en/introduction/concepts/incompatible-changes.md (and docs/zh) needs a new entry for this breaking change and currently has none.

3. Architectural Soundness

The fix itself is architecturally sound and minimal — it reuses the existing getExpressionType(firstArg) pattern already used for ABS/ROUND rather than inventing new machinery, and it doesn't touch unrelated functions. My one structural observation (not a defect in this PR, shared identically by #11697, and pre-existing for ROUND before either PR): when CEIL/FLOOR/TRUNC are called on a DECIMAL(p,s) column with s > 0 and no explicit scale argument, the declared output type stays DECIMAL(p,s) (via getExpressionType(firstArg)) but the actual computed BigDecimal's scale becomes 0 (bd.setScale(0, roundingMode)). If any downstream consumer strictly enforces the declared scale against the actual value's scale, this mismatch could surface — but this is an existing quirk inherited from ROUND's pre-existing behavior, not something this PR introduces, so it's informational only.

4. Issue Summary

# Severity Location Problem Raised by another reviewer
1 High Whole PR vs. #11697 This PR duplicates open PR #11697, which fixes the same root causes in the same files and is more complete (docs + type-mapping-level tests) No
2 High Docs (missing) No docs/en/docs/zh incompatible-changes.md entry for this breaking change, required by repo CLAUDE.md and already the convention for this exact class of change No
3 Medium seatunnel-transforms-v2/.../functions/NumericFunctionTest.java (new assertions), ZetaSQLType.java:460-470 The ZetaSQLType fix (root cause 4: declared type now matches arg type for CEIL/FLOOR/TRUNC) is only exercised end-to-end for DOUBLE (SQLNumericFunctionsTest); the new Long/BigDecimal assertions call NumericFunction.ceil/floor/trunc directly and never go through ZetaSQLType/SQLEngine.typeMapping(), so the declared-schema-type half of the fix is untested for BIGINT/DECIMAL No
4 Low NumericFunctionTest.java (new "underflows to 0.0" test) Comment claims the divisor 0.00000000000000000001 (1e-20) "underflows to 0.0 in double," but 1e-20 is far above Double.MIN_VALUE (~4.9e-324) and does not underflow — the old buggy doubleValue() == 0 check would already have returned false for this value, so the test doesn't actually exercise the underflow scenario it names (it's still a valid, separate precision-preservation test) No
5 Medium CI (Build check) The Build check on this PR shows conclusion action_required, and the contributor's fork (waterWang/seatunnel) has zero total Actions workflow runs — GitHub Actions appears to not be enabled on the fork, so the compile/test CI has never actually executed for this PR; none of the correctness claims in the description ("All 47 tests... pass") have been verified by CI yet No
6 Low Branch state dev...672fc633 is ahead_by: 1, behind_by: 14 — not causing conflicts today since no other commits on dev recently touched NumericFunction.java/ZetaSQLType.java, but worth syncing before merge, especially given the direct overlap with #11697 on the same lines No

Issue 1 detail — Best improvement: Option A — a maintainer/committer closes one of #11712/#11697 as a duplicate once the other is brought to mergeable state. Option B — the two contributors coordinate and consolidate into a single PR. Either way, both should not be merged independently.

Issue 2 detail — Best improvement: Add an entry to docs/en/introduction/concepts/incompatible-changes.md (and mirror in docs/zh) under "Transform Changes" describing the CEIL/FLOOR/TRUNC return-type change and the ROUND/TRUNC/MOD precision fix, with a before/after example and migration guidance (e.g. widen the sink column, or CAST(... AS INT) to keep old behavior) — #11697's entry is a good template to follow.

Issue 3 detail — Best improvement: Add at least one test per affected type that goes through the real type-inference path (e.g. build a SeaTunnelRowType with a LONG_TYPE/DecimalType column, run the SQL through the engine, and assert both the declared output field type and the computed value), mirroring what #11697 does with testCeilAndFloorKeepBigIntValue/testRoundAndTruncKeepDecimalPrecision.

5. Merge Recommendation

Ready to merge after fixes.

Blockers (must-fix before merge):

  • Issue 1 — resolve duplication with #11697 (maintainer decision needed; not something the author can unilaterally fix in code)
  • Issue 2 — add the required incompatible-changes.md entries (en + zh)
  • Issue 3 — add type-mapping-level test coverage for the LONG/DECIMAL cases
  • Issue 5 — get CI actually running (enable GitHub Actions on the fork) and green before merge

Recommended fixes (non-blocking):

  • Issue 4 — fix or clarify the misleading "underflows to 0.0" test comment
  • Issue 6 — rebase onto latest dev before merge, particularly once the #11697/#11712 duplication is resolved

The core logic changes themselves (removing .intValue() narrowing on ceil/floor, avoiding the double round-trip in round()'s BIGDECIMAL branch and in mod(), and aligning ZetaSQLType's declared output type with the actual argument type) are correct, minimal, and I traced them to the real runtime call chain with no regressions found. The remaining work is documentation, test-coverage completeness, actually getting CI to run, and — most importantly — a maintainer decision on how to handle the overlap with #11697.

@davidzollo

Copy link
Copy Markdown
Contributor

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 😄

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

Thanks again for the fix, @waterWang — and apologies in advance for what's going to be a hard turn from my last review here. I reviewed this PR once already on 2026-08-09 at head 672fc633 and gave a conditional "ready to merge after fixes." A lot has happened since then, and the situation has fundamentally changed, so I re-did the full review from scratch on the current head rather than just re-stating my old findings.

What's changed since my last review, and what hasn't:

  • The only new commit on this PR since 2026-08-09 is 3b2f175e ("[Chore][CI] Refresh PR #11712 checks" by @davidzollo, 2026-08-19). I confirmed via gh api repos/apache/seatunnel/compare/672fc633...3b2f175e that it changes zero files — it's an empty commit that only re-triggers CI. So the actual code I'm reviewing today is byte-for-byte identical to what I reviewed on 08-09.
  • What has changed is everything around it: the sibling PR I flagged as Issue 1 last time, #11697, was merged into dev on 2026-08-14 (5 days ago). I checked the current dev source directly (not just the PR description) — dev's NumericFunction.java and ZetaSQLType.java already contain this exact fix, and it's more complete than what's in this PR. That's now the decisive fact for this review.

What Problem Does This PR Solve?

Zeta SQL's CEIL, FLOOR, ROUND, MOD and TRUNC silently corrupted BIGINT/DECIMAL values instead of erroring — CEIL/FLOOR forced their result through .intValue(), ROUND's BIGDECIMAL branch and MOD round-tripped through double (losing precision above ~15-17 significant digits), MOD's zero-check used an unreliable doubleValue() == 0, and ZetaSQLType hardcoded the declared output type to INT/DOUBLE regardless of the actual argument type. Fix approach: stop narrowing to int/double, do the arithmetic in the argument's native type, and declare the output type as "same as first argument." One-sentence summary: this is the same fix already merged into dev via #11697 — this PR is now redundant and its own diff conflicts with what's already there.

1. Code Change Review

1.1 Core Logic Analysis

mod() — seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java:155-191

// Before (dev, pre-#11697)
if (rightValue.doubleValue() == 0) { throw ...; }
BigDecimal leftBD = BigDecimal.valueOf(leftValue.doubleValue());
BigDecimal rightBD = BigDecimal.valueOf(rightValue.doubleValue());
// This PR (line 164-169)
BigDecimal rightBD = new BigDecimal(rightValue.toString());
if (rightBD.compareTo(BigDecimal.ZERO) == 0) { throw ...; }
BigDecimal leftBD = new BigDecimal(leftValue.toString());

ceil()/floor() — same file, lines 193-203 and 285-295

// Before: return round(v1, v2, RoundingMode.CEILING).intValue();
// This PR: return round(v1, v2, RoundingMode.CEILING);   // signature Integer -> Number

round()'s BIGDECIMAL branch — lines 226-231

// Before: BigDecimal bd = BigDecimal.valueOf(v1.doubleValue());
// This PR: BigDecimal bd = (BigDecimal) v1;

ZetaSQLType.getFunctionType() — .../sql/zeta/ZetaSQLType.java:460-465 — moves CEIL/CEILING/FLOOR/TRUNC/TRUNCATE into the case ZetaSQLFunction.ABS: ... case ZetaSQLFunction.ROUND: group that returns getExpressionType(function.getParameters().getExpressions().get(0)), i.e. "same type as the first argument," instead of the previous hardcoded INT_TYPE/DOUBLE_TYPE.

Concrete before/after numbers (computed, not eyeballed — see below for method):

Function Input Old (pre-fix, still what a user on dev-without-#11697 or on this PR's unmerged state would hit before either fix) Fixed (dev today via #11697, and functionally what this PR also does)
CEIL Long 9223372036854775807 (Long.MAX_VALUE) -1 (Integer) — (int) 9223372036854775807L truncates to the low 32 bits, which are all 1s 9223372036854775807 (Long)
FLOOR Long -9223372036854775808 (Long.MIN_VALUE) 0 (Integer) — low 32 bits of Long.MIN_VALUE are all 0 -9223372036854775808 (Long)
CEIL BigDecimal("123456789012345678901234567890.123456789012345678901234567890") 123456789012345677877719597056 — doubleValue() collapses to 1.2345678901234568e+29 first, so digits from the 18th significant digit onward are silently replaced with rounding garbage, not just truncated 123456789012345678901234567891 — all 30 integer digits preserved exactly, only the fractional part is rounded up
MOD 0 (any type) as divisor throws TransformException("Mod by zero") in both — no behavior change here same

I verified the BigDecimal example with Python's decimal module at 80-digit precision to make sure I wasn't hand-waving the "silent corruption" claim: float(Decimal("123456789012345678901234567890.123456789012345678901234567890")) really does produce 1.2345678901234568e+29, and rounding that back up as an integer gives 123456789012345677877719597056 — which is wrong in the 18th digit onward, not merely truncated. That's the "silent" part of "silent corruption": it's not obviously wrong, it's subtly wrong.

Key findings:

  • Normal path, not a recovery/edge path: ZetaSQLType.getFunctionType() runs during type inference for every query using these functions, and NumericFunction.{ceil,floor,mod} run per row. Any real BIGINT/DECIMAL pipeline using these functions hits this on every execution.
  • This is a precise fix for the root cause (stop narrowing through int/double), not a workaround, and it's minimal — it reuses the existing "type of first argument" pattern already used for ABS/ROUND rather than inventing new machinery.
  • New finding this round, not caught in my 08-09 review: this PR's mod() fix and dev's already-merged mod() fix are not numerically identical for Float operands. This PR does new BigDecimal(value.toString()) for all numeric types including Float. dev's merged version (toBigDecimal() helper in NumericFunction.java, current dev) does BigDecimal.valueOf(value.doubleValue()) for Float/Double, i.e. it widens the float to double first. For Float 1.1f: Float.toString(1.1f) → "1.1", so this PR's MOD gets exact 1.1. But (double) 1.1f → 1.100000023841858 (verified with Java float32→double widening semantics), so dev's already-merged version gets 1.100000023841858 — a different remainder for any MOD(float_col, ...) query. Neither is "more wrong" in a data-loss sense, but they disagree, and since dev's version is the one that's actually shipping, this PR's behavior for FLOAT columns specifically would be a second, different regression surface if it were ever merged on top.
  • Remaining hole (same as 08-09, still true, still unaddressed since the code hasn't changed): after CEIL/FLOOR/TRUNC on a DECIMAL(p,s) with s > 0, the declared type stays DECIMAL(p,s) via getExpressionType(firstArg), but the actual BigDecimal's scale becomes 0 (setScale(0, roundingMode)). This is inherited from pre-existing ROUND behavior and is present identically in dev's merged fix too, so it's not new to this PR — informational only.

1.2 Compatibility

Partially incompatible, and this is now moot for this PR specifically — dev already shipped this exact incompatible change via #11697 on 2026-08-14, with the required docs/en/introduction/concepts/incompatible-changes.md / docs/zh entries. This PR still has none (unchanged since 08-09), which would be Issue 2 below if this PR were the one being merged — but it isn't going to be, so this is now purely for-the-record.

1.3 Performance / Side-Effect Analysis

No change from my 08-09 finding: mod() still allocates two BigDecimals per call either way; toString()/new BigDecimal(String) vs doubleValue()/BigDecimal.valueOf(double) isn't a measurable perf difference. No I/O, locking, retry, or resource-lifecycle changes. Not a concern.

1.4 Error Handling and Logging

mod()'s zero-check moved from rightValue.doubleValue() == 0 to rightBD.compareTo(BigDecimal.ZERO) == 0 — strictly more correct, same TransformException/message. No swallowed exceptions, no sensitive data.

Issue 2: CI is now genuinely running and is failing — spotless:check violation

  • Location: seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java (new assertions added by this PR, around the bigMod/ceil/floor/trunc BigDecimal test block)
  • Problem description: On 08-09 I flagged that the fork had zero Actions runs (Actions disabled). That's now fixed — the fork (waterWang/seatunnel) has 385 runs and CI actually executes. But it's failing: the Run / Code style job (fork run 32247984965, job 96052588421) fails ./mvnw spotless:check with concrete violations — the new test's Assertions.assertEquals(...) calls and inline comments aren't wrapped the way Google-Java-Format/AOSP-style Spotless expects (e.g. bigLeft.remainder(bigRight).stripTrailingZeros(), bigMod.stripTrailingZeros()); needs to be split across two lines, not one). This gates every downstream job — unit-test, all *-connectors-it-*, transform-v2-it-part-*, everything is skipped because Code style failed first.
  • Potential risk: the PR cannot pass CI as-is; the apache-side "Build" check correctly shows conclusion: failure for this reason.
  • Best improvement: run ./mvnw spotless:apply -pl seatunnel-transforms-v2 -am and commit the reformatted test file. Moot if the PR is closed per Issue 1, but noted for completeness / in case the author wants to salvage the delta described in Issue 3 as a follow-up elsewhere.
  • Severity: High (blocks CI, independent of Issue 1)

Issue 1 (carried over from 08-09, now confirmed and escalated): this PR is superseded by already-merged #11697

  • Location: whole PR vs. dev (post-2026-08-14)
  • Problem description: On 08-09 I flagged #11697 as an open, ~29-hours-earlier, more-complete duplicate and treated resolving it as a blocker for a maintainer to decide. That decision has since been made by the community: #11697 was merged into dev on 2026-08-14 (gh pr view 11697 → state: MERGED, mergedAt: 2026-08-14T04:13:47Z). I read dev's current NumericFunction.java/ZetaSQLType.java directly and confirmed the fix is there — and it's a cleaner implementation than this PR's: dev has a dedicated, Javadoc'd toBigDecimal(Number) helper (NumericFunction.java, current dev) that exactly widens Byte/Short/Integer/Long via longValue() (not doubleValue()), explanatory Javadoc on ceil() about why narrowing to int corrupts BIGINT/DOUBLE/DECIMAL, an inline comment on the BIGDECIMAL round branch explaining the double-round-trip hazard, and rightBD.signum() == 0 for the zero-check (equivalent to but slightly more idiomatic than this PR's compareTo(BigDecimal.ZERO) == 0).
  • Potential risk: merging this PR now is not just redundant, it's actively broken — gh pr view 11712 --json mergeable,mergeStateStatus currently reports mergeable: CONFLICTING, mergeStateStatus: DIRTY, because this PR's diff touches the exact same lines in NumericFunction.java/ZetaSQLType.java that #11697 already changed on dev. There is no way to merge this PR without a manual conflict resolution that would just re-apply logic that's already there.
  • Best improvement: close this PR as superseded by #11697, with a comment pointing the author to the merged fix and thanking them for the original report/analysis (the root-cause diagnosis in the PR description was correct and matches what actually shipped).
  • Severity: High — this is the actual blocker, everything else is secondary.

Issue 3: missing incompatible-changes documentation (unaddressed since 08-09, moot given Issue 1)

  • Location: docs/en/introduction/concepts/incompatible-changes.md, docs/zh/... (both absent from this PR's diff)
  • Problem description: the repo's own CLAUDE.md requires this for any incompatible change; #11697 added it, this PR still doesn't.
  • Potential risk: none if closed per Issue 1; would be a real gap if this PR were merged standalone.
  • Best improvement: N/A — superseded.
  • Severity: Medium

Issue 4: MOD's ZetaSQLType-level type-mapping fix is untested end-to-end for LONG/DECIMAL (unaddressed since 08-09)

  • Location: NumericFunctionTest.java new assertions call NumericFunction.ceil/floor/mod directly; SQLNumericFunctionsTest only exercises DOUBLE through the real ZetaSQLType/SQLEngine.typeMapping() path.
  • Potential risk: the declared-schema-type half of the fix (arguably the more subtle half — a downstream sink trusting the declared type over the actual value's runtime class) is never verified for BIGINT/DECIMAL columns.
  • Best improvement: N/A given Issue 1, but for the record: build a SeaTunnelRowType with a LONG_TYPE/DecimalType column and assert both the declared field type and computed value, as #11697's testCeilAndFloorKeepBigIntValue/testRoundAndTruncKeepDecimalPrecision already do on dev.
  • Severity: Medium

Issue 5: misleading test comment (unaddressed since 08-09)

  • Location: NumericFunctionTest.java, new "Mod by a divisor that underflows to 0.0 in double" test using divisor 0.00000000000000000001 (1e-20).
  • Problem description: 1e-20 is far above Double.MIN_VALUE (~4.9e-324) and does not underflow to 0.0 — the old doubleValue() == 0 check would already correctly return false here, so this test doesn't exercise the underflow scenario its comment claims (it's still a valid, separate precision-preservation test, just mislabeled).
  • Best improvement: N/A given Issue 1; fix the comment or use a genuinely sub-Double.MIN_VALUE divisor if resurrected elsewhere.
  • Severity: Low

2. Code Quality Assessment

2.1 Coding Standards

No comments explaining why (BigDecimal) v1 is safe or why toString() avoids the double round-trip — dev's merged version added exactly this Javadoc/inline commentary, this PR still doesn't (unchanged since 08-09).

2.2 Test Coverage and Test Stability

Stability rating: Stable. All changed/added assertions are on pure deterministic functions with fixed inputs — no Thread.sleep, no Awaitility, no shared/static mutable state, no ordering dependence, no network/timing waits. The assertEquals(2.0d, ...)/assertEquals(1.0d, ...) exact-equality floating point checks are on inputs (1.2d→ceil, 1.8d→floor) that are exactly representable, so not a flakiness risk. (Same conclusion as 08-09 — code unchanged.)

2.3 Documentation Updates

See Issue 3.

3. Architectural Soundness

3.1 Elegance: Precise fix (of the underlying bug), but the PR itself is now an orphaned duplicate of a fix that already shipped in a cleaner form.

3.2 Maintainability: N/A — not going to be the surviving implementation.

3.3 Extensibility: N/A.

3.4 Historical-Version Compatibility: Same partial-incompatibility profile as #11697, already accepted and documented on dev.

4. Issue Summary

# Issue Location Severity
1 PR is superseded by already-merged #11697; merging now would conflict with dev (confirmed mergeable: CONFLICTING) Whole PR vs. dev post-2026-08-14 High
2 CI genuinely fails now: spotless:check violation in the new test code blocks the entire pipeline NumericFunctionTest.java, fork run 32247984965 job 96052588421 High
3 No incompatible-changes.md entry (en/zh) for this breaking type/value change docs/en, docs/zh (absent) Medium
4 ZetaSQLType declared-type fix untested end-to-end for LONG/DECIMAL NumericFunctionTest.java, ZetaSQLType.java:460-465 Medium
5 Test comment claims an "underflow to 0.0" that doesn't actually occur for the chosen 1e-20 divisor NumericFunctionTest.java Low

(Note: my 08-09 review's Float-vs-Double mod() observation from this round — this PR's toString()-based conversion vs. dev's doubleValue()-based conversion for Float operands — is folded into 1.1 above as an analysis note rather than a separate numbered issue, since it only matters if someone tries to reconcile/cherry-pick pieces of this PR onto dev, which I'm not recommending.)

5. Merge Recommendation

Conclusion: Not recommended for merge

This is a change of conclusion from my 08-09 review ("ready to merge after fixes"), and I want to be direct about why: that conclusion was conditional on a maintainer resolving the overlap with #11697, and the situation has since resolved itself — #11697 merged into dev on 2026-08-14 with a more complete implementation (docs, Javadoc, type-mapping-level tests) than this PR has. This PR's diff now directly conflicts with dev (mergeable: CONFLICTING), and independently of that, its own CI is failing on a spotless:check violation. There's nothing left to "fix after which this is ready to merge" — the underlying bug (#11696) is already fixed and shipped.

Blockers (moot, since the recommendation is to close rather than fix-and-merge):

  • Issue 1 — superseded by merged #11697
  • Issue 2 — CI failing (spotless)

Recommended next step: close this PR as superseded/duplicate of #11697, with thanks to @waterWang — the root-cause analysis in the original description (the .intValue() narrowing, the double round-trip in ROUND/MOD, the ZetaSQLType hardcoding) was accurate and matches what actually shipped; this was good bug-finding, it just lost the race to land first. If there's ever a need to compare implementations, the one difference worth remembering is the Float-operand mod() divergence noted in 1.1 — dev's version widens through double for Float, this PR's would have gone through the float's own decimal string instead.

No further action needed on the code itself from @waterWang — this is a maintainer housekeeping call (close as duplicate), not something fixable by another commit to this branch.

# Conflicts:
#	seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java
#	seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLNumericFunctionsTest.java
#	seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java

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

Thanks for the ping — I re-reviewed the latest head from scratch. Quick recap of where things stood and what's changed since my last comment (2026-08-19T13:51Z, at commit 3b2f175e): at that point the only new commit since my 08-09 review was an empty CI-refresh commit, so my conclusion was "not recommended for merge" because the sibling PR #11697 (fixing the exact same root cause, #11696) had already been merged into dev on 2026-08-14 with a more complete implementation, and this branch conflicted with dev as a result.

Since then, a new commit landed: 7d7337864 ("Merge remote-tracking branch 'apache/dev' into pr11712-conflict", authored by @davidzollo), which merges the current dev into this branch and resolves the conflict. I re-traced the entire diff and call chain against this new head rather than just re-checking my old findings, and I need to flag something important right away.

This is now a redundant PR whose conflict-resolution commit introduces a real compile break

The merge did bring in dev's current (correct, more complete) NumericFunction.java, so NumericFunction.java is no longer part of this PR's diff at all — git diff dev...pr-11712 --stat now shows only 3 files touched:

seatunnel-transforms-v2/.../zeta/ZetaSQLType.java                          |  5 +++++
seatunnel-transforms-v2/src/test/.../sql/SQLNumericFunctionsTest.java      |  2 +-
seatunnel-transforms-v2/src/test/.../zeta/functions/NumericFunctionTest.java | 26 +++++++++++++++++++++-

That sounds like good news (the PR shrank to almost nothing since dev already has the fix), but the ZetaSQLType.java conflict resolution is broken. The merge kept both copies of the CEIL/CEILING/FLOOR/TRUNC/TRUNCATE case labels in the same switch (function.getFunctionName()) block — this PR's own pre-existing block (right after ABS, lines 464-468) plus dev's already-merged block (right after ROUND, lines 472-476):

// ZetaSQLType.java, current PR head, lines 463-476
case ZetaSQLFunction.ABS:
case ZetaSQLFunction.CEIL:
case ZetaSQLFunction.CEILING:
case ZetaSQLFunction.FLOOR:
case ZetaSQLFunction.TRUNC:
case ZetaSQLFunction.TRUNCATE:
case ZetaSQLFunction.DATEADD:
case ZetaSQLFunction.TIMESTAMPADD:
case ZetaSQLFunction.ROUND:
case ZetaSQLFunction.CEIL:          // duplicate
case ZetaSQLFunction.CEILING:       // duplicate
case ZetaSQLFunction.FLOOR:         // duplicate
case ZetaSQLFunction.TRUNC:         // duplicate
case ZetaSQLFunction.TRUNCATE:      // duplicate
case ZetaSQLFunction.NULLIF:
    return getExpressionType(function.getParameters().getExpressions().get(0));

This is a javac "duplicate case label" error, not a style nit — I confirmed it directly in the fork's CI logs (waterWang/seatunnel run 32260550367, job unit-test (8, ubuntu-latest), 96140447196):

[ERROR] .../ZetaSQLType.java:[472,12] error: duplicate case label
[ERROR] .../ZetaSQLType.java:[473,12] error: duplicate case label
[ERROR] .../ZetaSQLType.java:[474,12] error: duplicate case label
[ERROR] .../ZetaSQLType.java:[475,12] error: duplicate case label
[ERROR] .../ZetaSQLType.java:[476,12] error: duplicate case label
[ERROR] Failed to execute goal ... maven-compiler-plugin:3.10.1:compile (default-compile) on project seatunnel-transforms-v2

That single compile failure in seatunnel-transforms-v2 is why essentially every downstream job in the fork's Build run is red (unit-test, all *-connectors-it-*, transform-v2-it-part-*, engine-*-it, etc. all failing; only Code style, License header, Build website/UI pass, since they don't compile this module). This is a fresh, code-level issue introduced by the new commit itself — not something that existed in the version I reviewed on 08-09 or earlier today, so it doesn't fall under my usual "sorry for missing this earlier" caveat.

One nuance worth calling out for @waterWang: this merge commit was authored by @davidzollo, not by you, so this isn't something you need to feel bad about — but it does need to be fixed (or the PR closed) before this branch is mergeable in any real sense. Also worth noting: GitHub's mergeable flag on this PR now reports true (mergeable_state: blocked only means "review required", not "has conflicts") — that's because the merge commit resolved the textual conflict cleanly, it just resolved it into semantically broken code. Don't take a green "mergeable" flag as proof the file is correct; only the compiler catches this class of bug.

What Problem Does This PR Solve?

Originally: Zeta SQL's CEIL, FLOOR, ROUND, MOD and TRUNC/TRUNCATE silently corrupted BIGINT/DECIMAL values — CEIL/FLOOR narrowed through .intValue(), ROUND's BIGDECIMAL branch and MOD round-tripped through double (losing precision above ~15-17 significant digits), MOD's zero-check used unreliable doubleValue() == 0, and ZetaSQLType hardcoded the declared output type to INT/DOUBLE regardless of the actual argument type. Fix approach: stop narrowing, do arithmetic in the argument's native type, declare the output type as "same as first argument." One-sentence summary: the underlying bug is real and already fixed on dev via #11697 (and further hardened by #11724); this PR no longer carries an independent fix and its remaining diff actively breaks compilation.

1. Code Change Review

1.1 Core Logic Analysis — before/after table across edge cases

Since NumericFunction.java in this PR's head is now byte-identical to dev (already fixed), the table below documents the behavior this PR's origin bug fixed, verified against the current, shipped implementation in dev's NumericFunction.java (toBigDecimal() helper + round() dispatch, NumericFunction.java:155-260):

Function Input Buggy (pre-#11697, what this PR set out to fix) Fixed (current dev, and what this PR's now-identical NumericFunction.java also does)
CEIL Long 9223372036854775807 (Long.MAX_VALUE) -1 (Integer) — .intValue() truncates to the low 32 bits 9223372036854775807 (Long) — unchanged, round()'s LONG branch with scale==0 returns v1 as-is
FLOOR Long -9223372036854775808 (Long.MIN_VALUE) 0 (Integer) — low 32 bits of Long.MIN_VALUE are all 0 -9223372036854775808 (Long)
CEIL/FLOOR/TRUNC Long 0 0 (Integer) — coincidentally correct pre-fix 0 (Long) — type still correct now, not just the value
ROUND (BIGDECIMAL branch) BigDecimal("123456789012345678901234567890.123456"), scale 2 round-tripped through double, losing precision past ~17 significant digits exact — ((BigDecimal) v1).setScale(2, roundingMode), no double involved
MOD 9007199254740993 (2^53+1) % 2 doubleValue() round-trip could misrepresent the operand near 2^53 exact — toBigDecimal() widens Long via longValue(), not doubleValue()
MOD divisor 0.00000000000000000001 (1e-20, a genuine non-zero BigDecimal) old check rightValue.doubleValue() == 0 — 1e-20 is not actually below Double.MIN_VALUE (~4.9e-324), so this specific value would not have false-positived even on the old code; it's a valid precision-preservation case but not a true underflow repro (same observation I made on 08-09; the new test still doesn't hit real subnormal/underflow territory, e.g. 1e-400 as a string would, since that rounds to 0.0 in double) toBigDecimal()/BigDecimal.compareTo/signum() based — correct either way
MOD divisor 0 (any type) throws TransformException("Mod by zero") same — no behavior change here in either version
CEIL/FLOOR/TRUNC negative BigDecimal, e.g. -1.8 truncated TRUNC declared DOUBLE_TYPE in schema regardless of actual runtime type declared type now follows getExpressionType(firstArg), matching the actual Number subtype returned

Key findings:

  • Normal path, not a recovery/edge path: ZetaSQLType.getFunctionType() runs during type inference for every query using these five functions, NumericFunction.{ceil,floor,mod,trunc} run per row on the real execution path — but as of this head, this PR contributes zero lines to that runtime logic; it's 100% inherited from already-shipped dev code.
  • The only code this PR still uniquely contributes is the broken duplicate-case-label edit to ZetaSQLType.java, which is strictly worse than doing nothing (dev's own copy of the same case labels already covers CEIL/FLOOR/TRUNC/TRUNCATE correctly).
  • This PR's incremental test additions (NumericFunctionTest.testModForDifferentResultTypes/testCeilFloorRoundAndTrunc, SQLNumericFunctionsTest) are logically sound against dev's implementation (I traced bigLeft.remainder(bigRight) against dev's divideAndRemainder()[1] — same semantics; ceil/floor/trunc on Long/BigDecimal inputs match dev's round() dispatch) but exercise NumericFunction directly, not through ZetaSQLType/SQLEngine.typeMapping(), so they still don't cover the declared-schema-type half of the fix for BIGINT/DECIMAL — same gap I flagged on 08-09, now moot since it's not this PR's fix to test.
  • Given the merge already pulled dev's complete NumericFunction.java, there is no scenario left where merging this PR changes runtime numeric behavior versus current dev — the only observable effect of merging this PR as-is would be to break the build.

1.2 Compatibility

Partially incompatible, and as before this is moot for this specific PR — the incompatible change (return-type widening, precision fixes) already shipped via #11697/#11724 with full docs/en + docs/zh incompatible-changes.md entries (I confirmed both entries are present in current dev, lines ~162-188). This PR still adds no docs of its own, but since it also adds no independent behavior change anymore, that's no longer a live gap — it would only matter if this PR were somehow merged standalone, which the compile break rules out anyway.

1.3 Performance / Side-Effect Analysis

No change from my earlier findings — mod() isn't touched by this PR anymore, dev's version allocates the same BigDecimals it always did. No I/O, locking, retry, or resource-lifecycle concerns. Not a factor in this review's conclusion.

1.4 Error Handling and Logging

Unchanged from dev: mod()'s zero-check is rightBD.signum() == 0 in dev (equivalent to the compareTo(BigDecimal.ZERO) == 0 this PR previously proposed), throwing the same TransformException/message. No swallowed exceptions, no sensitive data. Not a factor in this PR's diff anymore.

Issue List

Issue 1: ZetaSQLType.java merge conflict resolution introduces a duplicate case label that fails compilation

  • Location: seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLType.java:464-476
  • Problem description: This sits directly on the normal type-inference path (getFunctionType(), called for every query using these functions). The merge commit 7d7337864 kept both this PR's original case ZetaSQLFunction.CEIL/CEILING/FLOOR/TRUNC/TRUNCATE block (added right after ABS) and dev's already-merged identical block (added right after ROUND via #11697), inside the same switch statement. javac rejects duplicate case labels for the same constant in one switch.
  • Potential risk: The entire seatunnel-transforms-v2 module fails to compile, which cascades into build failure for every module that depends on it. Confirmed empirically: CI on the fork (waterWang/seatunnel run 32260550367) shows unit-test, all *-connectors-it-*, transform-v2-it-*, engine-*-it, jdbc-connectors-it-*, etc. all red with the identical root cause (ZetaSQLType.java:[472-476] error: duplicate case label). This branch cannot be merged as-is, full stop.
  • Best improvement: Remove one of the two duplicate blocks — keep dev's copy (after ROUND, lines 471-476) since it's already shipped and has an explanatory comment above it, and delete this PR's now-redundant copy (lines 464-468). After that fix, git diff dev...pr-11712 would contain zero net change to ZetaSQLType.java, which is the honest reflection of the fact that #11697 already shipped this exact fix.
  • Severity: High
  • Raised by another reviewer: No

Issue 2: This PR remains fully superseded by already-merged #11697 (carried over from my 08-19 13:51 review, still true)

  • Location: Whole PR vs. dev post-2026-08-14
  • Problem description: Once Issue 1 is fixed, this PR's diff against dev would be limited to test additions that exercise already-shipped, already-tested logic in NumericFunction.java. There's no remaining independent fix here for a maintainer to merge.
  • Potential risk: None if closed; wasted reviewer/CI cycles if kept open and repeatedly re-synced.
  • Best improvement: Close this PR as superseded/duplicate of #11697 (and note #11724, which further hardened the same code path on dev after #11697 merged). The root-cause analysis in the original PR description was accurate and matches what shipped — that's good work, it just lost the race to land first, and now the branch is actively harmful to merge due to Issue 1.
  • Severity: High
  • Raised by another reviewer: No

Issue 3 (Low, informational, unchanged): misleading test comment

  • Location: seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java, new "Mod by a divisor that underflows to 0.0 in double" test using 0.00000000000000000001 (1e-20).
  • Problem description: 1e-20 is far above Double.MIN_VALUE (~4.9e-324) and does not underflow to 0.0 in double — this doesn't exercise the underflow scenario the comment names, though it remains a valid precision-preservation test in its own right.
  • Best improvement: N/A given Issue 2 (this PR isn't going to be the surviving implementation), but flagging for the record in case this test is salvaged elsewhere: use a genuinely sub-Double.MIN_VALUE divisor (e.g. 1e-400 as a BigDecimal string) to actually exercise underflow.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Not applicable to new logic since this PR no longer contains any — the only substantive remaining code change (Issue 1) is a broken duplicate, not new logic needing comments.

2.2 Test Coverage and Test Stability

Stability rating: Stable. All new/changed assertions in NumericFunctionTest.java/SQLNumericFunctionsTest.java are on pure, deterministic functions with fixed inputs — no Thread.sleep, no Awaitility, no shared/static mutable state, no execution-order dependence, no network/timing-sensitive waits. BigDecimal comparisons use exact equals/compareTo, not floating-point deltas, so no flakiness risk. Same conclusion as my 08-09 review; nothing about test stability changed in this round.

2.3 Documentation Updates

No doc changes in this PR; not needed since dev already carries the required incompatible-changes.md entries via #11697/#11724 (verified present in both docs/en and would need a matching check in docs/zh, which I did not re-verify character-by-character this round but did confirm the English entry exists at the lines cited above).

3. Architectural Soundness

3.1 Elegance

Not a fix anymore — Issue 1 is a regression relative to dev, introduced by the conflict-resolution commit itself.

3.2 Maintainability / 3.3 Extensibility / 3.4 Historical-Version Compatibility

N/A — this PR is not going to be the surviving implementation; dev's already-merged fix (#11697 + #11724) is the actual production code and is architecturally sound (reuses the existing getExpressionType(firstArg) pattern, has a dedicated toBigDecimal() helper with Javadoc).

4. Issue Summary

# Issue Location Severity
1 Merge conflict resolution leaves a duplicate case label in ZetaSQLType.java, confirmed by fork CI to fail compilation of seatunnel-transforms-v2 and cascade to nearly every downstream job ZetaSQLType.java:464-476 High
2 PR remains fully superseded by already-merged #11697 (+ #11724); no independent fix left to merge Whole PR vs. dev High
3 Test comment claims an "underflow to 0.0" that doesn't actually occur for the 1e-20 divisor chosen NumericFunctionTest.java Low

5. Merge Recommendation

Conclusion: Not recommended for merge

This confirms and hardens my 08-19 13:51 conclusion rather than reversing it. At that point the blocker was "redundant, and conflicts with dev." The situation hasn't improved with the new commit — it's gotten more concrete: the attempted conflict resolution (7d7337864, authored by @davidzollo) doesn't just fail to add value, it actively breaks the build with a duplicate-case-label compile error that I verified directly against the fork's CI logs.

Blockers (moot for "fix and merge" — see recommended next step):

  • Issue 1 — duplicate case label breaks compilation
  • Issue 2 — no independent fix remains once Issue 1 is corrected; everything of value already shipped via #11697/#11724

Recommended fixes (non-blocking):

  • Issue 3 — low-priority test comment accuracy nit, not worth fixing on a branch that's being closed

Recommended next step: close this PR as superseded/duplicate of #11697 (merged 2026-08-14) and #11724 (further precision hardening, already on dev). Thanks again to @waterWang for the original root-cause analysis in #11696 — it was accurate and matches exactly what shipped; this was good bug-finding that just lost the race to land, and the current head is no longer salvageable as an independent contribution, only as closeable in favor of the already-merged fix.

@apache apache deleted a comment from DanielLeens Aug 21, 2026

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

Zeta SQL's CEIL, FLOOR, ROUND, MOD and TRUNC/TRUNCATE used to silently corrupt BIGINT/DECIMAL values instead of erroring: CEIL/FLOOR narrowed their result through .intValue(), ROUND's BIGDECIMAL branch and MOD round-tripped through double (losing precision above ~15-17 significant digits), MOD's zero-check used an unreliable doubleValue() == 0, and ZetaSQLType hardcoded the declared output type to INT/DOUBLE regardless of the actual argument type. One-sentence summary: the underlying bug (#11696) is already fixed and shipped on dev via #11697/#11724; as of the current head this PR's production code is now byte-identical to dev, and its only remaining unique contribution is incremental unit-test coverage plus a fresh, now-resolved merge-conflict episode.

I need to revise my last conclusion — the blocking compile break is fixed

My 2026-08-20 review flagged a High-severity blocker: the conflict-resolution merge commit (7d7337864) had kept both this PR's own CEIL/CEILING/FLOOR/TRUNC/TRUNCATE case-label block and dev's already-merged identical block in the same switch, causing a javac "duplicate case label" compile error confirmed in the fork's CI logs.

Since then, one new commit landed: d091d0574 ("[Fix][Transform-V2] Remove duplicate numeric function type cases", by @davidzollo), which deletes exactly the duplicate five-line block this PR had originally added (keeping dev's copy, which sits in the ABS/ROUND/DATEADD/... group). I re-verified this directly rather than trusting the commit message:

// ZetaSQLType.java, current head, lines 463-472 (single switch group, no duplicates)
case ZetaSQLFunction.ABS:
case ZetaSQLFunction.DATEADD:
case ZetaSQLFunction.TIMESTAMPADD:
case ZetaSQLFunction.ROUND:
case ZetaSQLFunction.CEIL:
case ZetaSQLFunction.CEILING:
case ZetaSQLFunction.FLOOR:
case ZetaSQLFunction.TRUNC:
case ZetaSQLFunction.TRUNCATE:
case ZetaSQLFunction.NULLIF:
    return getExpressionType(function.getParameters().getExpressions().get(0));

I pulled both files as raw blobs (git show <head>:.../ZetaSQLType.java and .../NumericFunction.java) and diffed them byte-for-byte against dev's current versions of the same paths: both files are now 100% identical to dev. This PR's diff no longer touches production code at all.

1. Code Change Review

1.1 Core Logic Analysis

Since NumericFunction.java/ZetaSQLType.java are now identical to dev, there is no new production logic to review this round — the fix itself (stop narrowing ceil/floor through int, avoid the double round-trip in round()'s BIGDECIMAL branch and in mod(), declare CEIL/FLOOR/TRUNC's output type as "same as first argument") is exactly what I traced and validated as correct in my 08-09 and 08-19 reviews, and it's the same code already running in production via dev.

Recomputing the PR's actual net contribution with a three-dot diff from the merge-base (f1a1a0abb, confirmed to be an ancestor of the live, freshly-fetched dev):

docs/en/connectors/source/MongoDB-CDC.md                        |  2 +-
docs/zh/connectors/source/MongoDB-CDC.md                        |  2 +-
.../transform/sql/SQLNumericFunctionsTest.java                  |  2 +-
.../sql/zeta/functions/NumericFunctionTest.java                 | 26 +++++++++++++++++++++-
4 files changed, 28 insertions(+), 4 deletions(-)

Key findings:

  • The MongoDB-CDC.md change (en+zh, "Use canonical MongoDB delete event links" by @davidzollo) is a correct, harmless one-line link fix (/v5.0/reference/... → /manual/reference/...) but is completely unrelated to this Transform-V2 numeric-function PR — likely a byproduct of whatever branch/rebase workflow produced the CI-refresh and conflict-resolution commits. Worth flagging per this repo's "one PR should solve one problem" scope rule, but it's not incorrect and not worth blocking on.
  • SQLNumericFunctionsTest.java's only change is a trailing period added to a comment — cosmetic.
  • NumericFunctionTest.java (package zeta.functions, the low-level direct-call test class) gets real new assertions: Long ceil/floor/trunc preserve Long return type, BigDecimal ceil/floor/trunc preserve BigDecimal return type, and a large-BigDecimal mod() precision-preservation assertion. I checked whether this duplicates existing dev coverage: it doesn't — dev's current version of this exact file/class has no equivalent Long/BigDecimal assertions in testCeilFloorRoundAndTrunc/testModForDifferentResultTypes. This is genuine incremental coverage, not a redundant re-add.
  • Separately, I confirmed dev already has the type-mapping-level coverage I asked for in my earlier reviews (declared-schema-type verification through the real SQLEngine.typeMapping() path) — but in a different, sibling test class at seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/NumericFunctionTest.java (note: no functions package segment), which has testCeilAndFloorKeepBigIntValue/testRoundAndTruncKeepDecimalPrecision using sqlEngine.typeMapping(null). This PR doesn't touch that class (correctly — it's already merged and complete via #11697), so the "declared type untested for LONG/DECIMAL" gap I flagged on 08-09 is closed at the repo level, just not by this PR specifically.

Runtime path: ZetaSQLType.getFunctionType()/NumericFunction.{ceil,floor,mod,trunc} remain on the normal query-execution path for any pipeline using these functions — unchanged from my prior reviews, since the code itself is unchanged from what's already shipping.

1.2 Compatibility Impact

Fully compatible with dev in the sense that matters now: since production code is byte-identical to dev, merging this PR changes zero runtime behavior versus what's already deployed. The underlying incompatible change (return-type widening for CEIL/FLOOR/TRUNC, precision fixes for ROUND/TRUNC/MOD) was already accepted and documented via #11697/#11724 — I re-checked dev:docs/en/introduction/concepts/incompatible-changes.md directly and it has a full [BREAKING] entry (lines ~170-196) covering exactly this class of change with before/after tables and migration guidance, so no doc gap remains for this PR to fill.

1.3 Performance / Side-Effect Analysis

No change from prior rounds: no new I/O, locking, retries, or resource-lifecycle concerns. Not a factor.

1.4 Error Handling and Logging

Unchanged from dev's already-reviewed, already-correct mod() zero-check and exception wrapping. No swallowed exceptions, no sensitive data.

Issue 1 (Low, carried over, still unaddressed): misleading test comment

  • Location: seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java, new "Mod by a divisor that underflows to 0.0 in double" test using 0.00000000000000000001 (1e-20).
  • Problem description: 1e-20 is far above Double.MIN_VALUE (~4.9e-324) and does not underflow to 0.0 in double — I flagged this in all three of my prior reviews and it's still present unchanged. It remains a valid precision-preservation test, just mislabeled.
  • Potential risk: Low — a future reader might believe this repros a real underflow edge case when it doesn't.
  • Best improvement: Rename the comment/test to describe what it actually verifies (tiny-but-non-zero BigDecimal divisor precision), or swap in a genuinely sub-Double.MIN_VALUE string divisor if underflow coverage is actually wanted.
  • Severity: Low
  • Raised by another reviewer: No

Issue 2 (Low, new this round): unrelated docs commit riding along

  • Location: docs/en/connectors/source/MongoDB-CDC.md, docs/zh/connectors/source/MongoDB-CDC.md
  • Problem description: A correct-but-unrelated MongoDB CDC doc link fix is bundled into this Transform-V2 bugfix PR.
  • Potential risk: None functionally; purely a PR-scope/hygiene note.
  • Best improvement: Drop this commit from the branch (or let a maintainer squash-merge selectively) so the PR's diff matches its stated scope.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

No new production code in this round to assess. The test additions follow the surrounding file's existing style/formatting conventions.

2.2 Test Coverage and Test Stability

Stability rating: Stable. Same conclusion as every prior round — all new/changed assertions are on pure, deterministic functions (NumericFunction.ceil/floor/mod/trunc with fixed Long/BigDecimal inputs). No Thread.sleep, no Awaitility, no shared mutable/static state, no ordering dependence, no network/timing-sensitive waits. BigDecimal comparisons use exact equals/compareTo, not floating-point deltas.

As noted in 1.1, the new assertions are genuine incremental coverage (not redundant with dev's existing type-mapping-level tests in the sibling zeta.NumericFunctionTest class), even though they only exercise NumericFunction directly rather than the full SQLEngine.typeMapping() path.

2.3 Documentation Updates

Not needed from this PR — dev already carries the required incompatible-changes.md entries (en) via #11697/#11724, confirmed present at the current head's merge-base ancestor.

3. Architectural Soundness

3.1 Elegance of the Solution

The underlying fix (already shipped) is a precise, minimal fix reusing the existing getExpressionType(firstArg) pattern. This PR's own remaining contribution — after the compile-break fix — is Precise and low-risk: a genuinely test-only, no-conflict diff.

3.2 Maintainability

Fine — no new coupling, no new abstractions, just additional direct-call assertions in an existing test class.

3.3 Extensibility

N/A — no production code changed.

3.4 Historical-Version Compatibility

No impact beyond what's already shipped and documented on dev.

4. Issue Summary

# Issue Location Severity
1 Test comment claims a divisor "underflows to 0.0" that doesn't actually occur for the 1e-20 value chosen (carried over from all three prior rounds) NumericFunctionTest.java Low
2 Unrelated MongoDB-CDC doc link fix bundled into this Transform-V2 PR docs/en/docs/zh MongoDB-CDC.md Low

5. Merge Recommendation

Conclusion: Ready to merge

This reverses my 08-20 "Not recommended for merge" conclusion, and I want to be direct about why: that conclusion was driven entirely by a concrete, verified compile break (duplicate case labels) introduced by a bad merge-conflict resolution. d091d0574 fixes exactly that — I independently confirmed ZetaSQLType.java and NumericFunction.java are now byte-identical to dev, CI is genuinely green on this exact head (fork Build run, and the apache-side Build check both show SUCCESS/COMPLETED), and gh pr view --json mergeable,mergeStateStatus now reports mergeable: MERGEABLE (BLOCKED just means "review required," not "has conflicts," as I noted before). There is no remaining functional risk: merging this PR changes zero runtime behavior versus what dev already ships, and only adds a small amount of genuinely non-redundant unit-test coverage.

  1. Blockers — must be fixed
    • None.
  2. Recommended fixes — non-blocking
    • Issue 1 — fix the misleading "underflows to 0.0" test comment.
    • Issue 2 — consider dropping the unrelated MongoDB-CDC doc commit to keep the PR's diff scoped to its stated purpose.

Thanks again to @waterWang for the original root-cause analysis in #11696 — it was accurate from the start, and even though the fix landed on dev first via a sibling PR, this branch has now converged cleanly on the same correct implementation and adds a small amount of real extra test coverage on top. Nice recovery from the merge-conflict episode.

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

@davidzollo
davidzollo merged commit db0ad74 into apache:dev Aug 23, 2026
3 checks passed
zhang-arvin pushed a commit to zhang-arvin/seatunnel that referenced this pull request Aug 25, 2026
…g BIGINT and DECIMAL values (apache#11696) (apache#11712)

Co-authored-by: waterWang <waterWang@users.noreply.github.com>
Co-authored-by: davidzollo <davidzollo@users.noreply.github.com>
Co-authored-by: davidzollo <davidzollo365@gmail.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] Zeta SQL CEIL/FLOOR/ROUND/TRUNC/MOD silently corrupt BIGINT and DECIMAL values

3 participants