Repository navigation
[Test][Transform-V2] Cover the MOD divisor type contract and its overflow bounds - #12182
davidzollo merged 4 commits into
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point:
ZetaSQLType.getExpressionType(ZetaSQLType.java:516-518) plans the result type ofMOD(dividend, divisor)as the divisor's own type. When the divisor is aTINYINT/SMALLINTcolumn, the planner promises aByte/Shortoutput, butNumericFunction.mod(pre-fix) only dispatched onInteger,Long,Float,DoubleandBigDecimal. Any job withMOD(x, tinyint_col)orMOD(x, smallint_col)compiled fine and then failed at row-evaluation time withUnsupported arg type java.lang.Byte/Short of function MOD— a runtime failure on a query the type system had already accepted. - Fix approach: add the two missing
instanceof Byte/instanceof Shortbranches toNumericFunction.mod, mirroring the exact pattern already used byabs()/sign()(fixed for the same two types in #11937), and narrow theBigDecimalremainder tobyteValue()/shortValue()with no additional range check — justified becauseBigDecimal.divideAndRemainderguarantees|remainder| < |divisor|, so aTINYINT/SMALLINTdivisor can never produce a remainder that overflows its own type. - One-sentence summary: A precise two-branch fix that makes
NumericFunction.mod's runtime dispatch match the result typeZetaSQLTypeand the documentation already promised forTINYINT/SMALLINTdivisors.
1. Code Change Review
1.1 Core Logic Analysis
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java:227-232:
BigDecimal[] res = leftBD.divideAndRemainder(rightBD);
// The result keeps the type of the divisor, which is what ZetaSQLType declares for MOD.
// No range check is needed for the narrow types: divideAndRemainder guarantees that
// |remainder| < |divisor|, so the remainder always fits the divisor's type.
if (rightValue instanceof Byte) {
return res[1].byteValue();
}
if (rightValue instanceof Short) {
return res[1].shortValue();
}
if (rightValue instanceof Integer) {
return res[1].intValue();
}Traced the full runtime path: ZetaSQLFunction.MOD (ZetaSQLFunction.java:559) dispatches unconditionally to NumericFunction.mod(args) for the explicit MOD(a, b) call (the % operator is a separate path and unaffected, confirmed by reading the Modulo handling nearby). mod() converts both operands to BigDecimal via toBigDecimal (already handles Byte/Short at lines 197-198, so that half of the pipeline was already correct), computes the remainder with divideAndRemainder, and previously fell through every instanceof check for a Byte/Short divisor straight into the terminal throw new TransformException(... "Unsupported arg type ..."). This is a normal-path defect, not an edge case: any MOD(x, tinyint_col) expression hits it on the very first row, 100% reproducible, not conditional on data values. I independently re-derived the arithmetic in the two new min-value test cases ((byte) 44 from 300 mod Byte.MIN_VALUE and (short) 1696 from 100000 mod Short.MIN_VALUE) and both check out against BigDecimal.divideAndRemainder's truncate-toward-zero/sign-of-dividend semantics.
I also independently verified the "no range check needed" claim: divideAndRemainder's remainder always has the same sign as the dividend and strict magnitude < |divisor|. For a Byte divisor the tightest case is divisor = Byte.MIN_VALUE = -128, bounding the remainder to (-128, 128), i.e. at most [-127, 127] in practice — inside byte's [-128, 127] range. Same reasoning holds for Short.MIN_VALUE = -32768 against short's [-32768, 32767] range. The claim is correct; no follow-up guard is needed.
This is not commutative — the code correctly reads rightValue (the divisor) for the type dispatch, matching ZetaSQLType's "result has the same type as second argument" contract (ZetaSQLType.java:517). Confirmed there is no other call site in the module that reaches NumericFunction.mod with a different argument order.
1.2 Compatibility Impact
Fully compatible. Before this change, MOD with a TINYINT/SMALLINT divisor always threw TransformException at runtime — there is no existing successful behavior being altered, only a previously-100%-failing path that now succeeds and returns the type the planner already declared. Integer/Long/Float/Double/BigDecimal divisor branches are untouched (only reordered relative to the two new ifs, with no change to their logic). No config, protocol, checkpoint/state, or serialization surface is touched. No documentation change is required — docs/en/transforms/sql-functions.md:541 (MOD(dividendNumeric, divisorNumeric) -> type(divisorNumeric)) already stated the now-correct contract; verified this file needs no edit.
1.3 Performance / Side-Effect Analysis
No measurable impact. Two additional cheap instanceof checks ahead of the existing Integer check in a per-row scalar function; no new allocations, no new object construction beyond what divideAndRemainder already produced. No thread-safety, resource, or lifecycle concerns — this is a pure static utility method with no shared mutable state.
1.4 Error Handling and Logging
No issues found. The terminal throw new TransformException(...) for genuinely unsupported types is preserved unchanged and still reachable for any future numeric wrapper type not yet handled.
2. Code Quality Assessment
2.1 Coding Standards
The new branches are covered by a 4-line comment that explains why no range check is needed (the actual non-obvious reasoning, not a restatement of the code) — this meets the project's "explain why/constraints, not what" comment bar. No new class/field is introduced, so no missing-Javadoc concern. Style/ordering matches the pre-existing abs()/sign() pattern in the same file.
2.2 Test Coverage and Test Stability
Two tests added, both deterministic, no Thread.sleep, no async waiting, no shared static state, no ordering dependency between test methods — Stable.
seatunnel-transforms-v2/src/test/java/.../functions/NumericFunctionTest.java(unit level, extends the existingtestModForDifferentResultTypes): asserts both the runtime value and the runtimeClassforByte/Shortresults, plus the two documented worst-case min-value inputs (Byte.MIN_VALUE,Short.MIN_VALUE) that would be the first to overflow if the "no range check" reasoning were wrong.seatunnel-transforms-v2/src/test/java/.../zeta/NumericFunctionTest.java(testModSupportsTinyIntAndSmallIntDivisors, integration level throughSQLEngine): exercises the reported path end-to-end — assertstypeMapping()declaresBYTE_TYPE/SHORT_TYPE(the planner side) andtransformBySQLreturns values of exactly those types (the runtime side), so a future regression in either half alone would be caught.
I confirmed both test classes actually ran and passed in this PR's own fork CI run (unit-test (8, ubuntu-latest), job 101784973331): NumericFunctionTest (zeta package, 8 tests) and NumericFunctionTest (functions package, 21 tests) both report Failures: 0, Errors: 0.
2.3 Documentation Updates
None required, and the PR correctly does not add any — the documented contract in docs/en/transforms/sql-functions.md:541 already matched the fixed behavior; it was only the implementation lagging behind it.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. This closes the actual gap between the planner (ZetaSQLType), the documentation, and the runtime (NumericFunction.mod) with the minimum possible diff — two instanceof branches, no new abstraction, no behavior change to any existing path. It reuses an established precedent in the same file (abs()/sign() fixed identically for the same two types in #11937) rather than inventing a new pattern.
3.2 Maintainability
High — the added comment documents the invariant (|remainder| < |divisor|) that makes the missing range check a deliberate choice rather than an oversight, which will save the next reader from re-deriving it or wrongly "fixing" it by adding an unnecessary guard.
3.3 Extensibility
Neutral; this is a leaf-level bug fix in a switch-like instanceof chain, not a change to any extension point.
3.4 Historical-Version Compatibility
Fully compatible, applies only to the unreleased dev branch as stated in the PR description. No prior release ever returned a value for this code path — it always threw — so there is no historical successful-job behavior to preserve or break, and no upgrade/restore/checkpoint concern applies here since this transform is stateless and evaluates per-row.
4. Issue Summary
No issues found. I traced the runtime dispatch chain, independently re-derived the arithmetic bound for both new test cases, checked for other call sites and for interference from the % operator path, confirmed the documentation already matched the fixed behavior, and confirmed dev has had zero commits touching seatunnel-transforms-v2 since this PR's branch point (so there is no merge-drift risk to re-verify).
| Number | Issue | Location | Severity |
|---|---|---|---|
| — | None found | — | — |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers — none.
- Recommended fixes — none; this is about as clean and well-scoped as a bug-fix PR gets.
Overall assessment: this is a textbook root-cause fix — it closes exactly the gap the linked issue (#12179) identified between the planner's type contract and the runtime dispatch, reuses an established in-repo precedent instead of inventing new patterns, and ships with tests that pin both the planner side and the runtime side of the contract plus the two mathematically worst-case inputs. No alternative implementation (Option A/B) is warranted here; a two-branch dispatch fix is the natural and minimal shape for this defect.
On CI: the fork's Build workflow run shows overall cancelled/failure, but I dug into the actual jobs rather than taking that at face value. The only genuine test failure in the run is SinkErrorToMysqlIT.testSinkMaxErrorRatioThreshold (ConditionTimeout from an Awaitility untilAsserted, unrelated MySQL-sink error-threshold E2E) inside connector-seatunnel-e2e-base's engine-v2-it job — nothing in this PR's diff touches that module, the sink error-threshold path, or anything engine-related. The kudu-connector-it job shows cancelled, consistent with a sibling-job failure triggering the workflow's overall cancellation, not a defect in this PR. Both unit-test jobs (JDK 8 and 11, ubuntu and windows) that actually execute seatunnel-transforms-v2's tests — including both new NumericFunctionTest additions from this PR — passed cleanly. I would not ask the contributor to sync with dev for this: dev has zero commits touching seatunnel-transforms-v2 since this branch point, so there is nothing to resolve and the observed failure is plausibly a pre-existing/environmental flake unrelated to this change, not something a rebase would fix. mergeable_state: blocked here reflects the required Build check's non-green status rather than an actual merge conflict (mergeable: true).
Since my review access on this repository is comment-level, a maintainer with write-level review permission will still need to formally approve and merge once the required check is green (rerun if it's still red for the same unrelated reason above).
|
Thanks for the detailed review @DanielLeens. One correction on the CI reading, and then agreement on the conclusion. The run has two failing jobs, not one. Alongside
It is also an already known flake. #12116, filed by @davidzollo on 09-05, names this exact test and this exact config and lists three unrelated PRs hitting it, including #11503 with the identical The failing leg matches that issue too.
Agreed on the rest. Both |
|
Thanks for the correction, @SEPURI-SAI-KRISHNA — and for the detailed #12116 evidence trail on You were right about the original run ( Since then the picture has moved again because of your own rerun. Checking
So, as of right now, live: this PR has exactly one outstanding failing job, |
|
CI update. The rerun cleared one job and reproduced the other.
One clarification on the attempt-2 reading, since it affects how many times this has actually been seen. In attempt 2 only It has now genuinely been observed twice, on attempt 3, job Practically that means a rerun is not a reliable way to get this check green: two executions of that job on this head, two failures. The unit test legs, which are what actually exercise this change, are green throughout. @davidzollo this is ready from my side whenever you have time. Since #12116 is yours, you will know better than me whether it is worth waiting for a green |
|
Thanks for the update, @SEPURI-SAI-KRISHNA — I independently re-checked the fork's check-runs for the current head ( I also checked #12116 itself: still open, still under root-cause investigation, no fix PR yet (your comment there a few minutes ago adding this PR's two occurrences is the latest activity). So a third rerun of Concrete next step: since I'm a comment-only reviewer here and can't waive the required check myself, this now needs @davidzollo (or another maintainer with write access) to make the call on merging with |
|
Thanks for the update. GitHub is currently reporting merge conflicts between this branch and the latest |
…flow bounds apache#12215 added the Byte and Short branches to NumericFunction.mod, and covers them with value assertions in SQLNumericFunctionsTest. Three things it did not cover are added here. The planner side is now asserted alongside the runtime. The defect was a disagreement between ZetaSQLType, which derives the MOD result type from the divisor, and the runtime dispatch, which did not handle two of those types. A test that checks only the returned value would still pass if typeMapping stopped declaring TINYINT, so the new engine-level test pins both halves against each other in one place. Byte.MIN_VALUE and Short.MIN_VALUE divisors are covered. They are the widest divisors of each type, and so the inputs that would fail first if the reasoning behind the absent range check were wrong. That reasoning is now written down at the call site: divideAndRemainder bounds the remainder below the divisor in magnitude, so the result always fits the divisor's type and no range check is needed. Without the comment the omission reads like an oversight, and the next reader is likely to add a guard. Both tests fail against the dispatch chain with the two branches removed, and pass with them.
08b4cd2 to
445cec7
Compare
|
Thanks @DanielLeens. Rather than resolve the conflict, I have rebased this onto current The planner-side assertion, so The That reasoning written down at the call site, so the next reader does not add a guard that cannot fire. The title and description are updated to match. Both tests fail against No objection at all to #12215 having gone first. The fix was the same in both, and this is the part worth keeping. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the update, @SEPURI-SAI-KRISHNA. Splitting this the way you did is the right call: the fix landed via #12215 first, so re-proposing it here would just be redundant, and what's left — the three test-coverage gaps I flagged when comparing the two PRs — is a clean, self-contained follow-up on its own. I don't have anything from my last round to walk back here (the earlier review was of the fix itself, which is no longer part of this diff), so this is a full from-scratch re-review of the current head (445cec7), not a diff against the old review.
What Problem Does This PR Solve?
- Gap being closed: #12215 fixed
NumericFunction.mod's missingByte/Shortdivisor branches, but its own test (SQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors) only asserts the output value of a fullSQLTransform.transformRow(...)call — it never inspects the declared output schema. That leaves three things genuinely uncovered: (1) a regression where the planner (ZetaSQLType.getExpressionType, caseMODatZetaSQLType.java:516-517) and the runtime dispatch (NumericFunction.mod) disagree again — e.g. iftypeMapping()reverted to declaringINT_TYPEfor aTINYINTdivisor while the runtime still happily returned aByte, the old test could still pass on value alone; (2) the two divisor values (Byte.MIN_VALUE,Short.MIN_VALUE) that are the actual worst case for the "no range check needed" reasoning in the fix; (3) that reasoning itself was nowhere in the code, so a future reader could "fix" the missing guard with a check that can never fire. - Fix approach: no production behavior change. Adds a 3-line comment at the call site, plus two test additions: a unit-level extension of
testModForDifferentResultTypes(asserts.getClass()for both new branches and the two min-value boundary inputs) and a new integration-level test that assertstypeMapping()andtransformBySQLagree onBYTE_TYPE/SHORT_TYPE. - One-sentence summary: A precise, non-overlapping coverage follow-up to #12215 that pins the planner/runtime type contract and the overflow-boundary reasoning that the original fix's own test left unchecked.
1. Code Change Review
1.1 Core Logic Analysis
I independently verified there is no production logic left in this diff, not just from the PR description — I pulled NumericFunction.java at the PR head (445cec7) directly from GitHub and confirmed the instanceof Byte / instanceof Short branches (lines 227-232) are unchanged from what's already on dev; the diff's only touch to that file is the 3-line comment at NumericFunction.java:224-226:
BigDecimal[] res = leftBD.divideAndRemainder(rightBD);
// The result keeps the type of the divisor, which is what ZetaSQLType declares for MOD.
// No range check is needed for the narrow types: divideAndRemainder guarantees that
// |remainder| < |divisor|, so the remainder always fits the divisor's type.
if (rightValue instanceof Byte) {I also independently confirmed the planner side the comment and the new test both rely on: ZetaSQLType.java:516-517 — case ZetaSQLFunction.MOD: return getExpressionType(function.getParameters().getExpressions().get(1)); — i.e. "result has the same type as the second argument" is the real, current planner behavior, not just an assumption from the PR body.
Do the new tests actually catch what they claim to?
functions/NumericFunctionTest.java:150-156(unit level) — addsByte.class/Short.classruntime-type assertions alongside the existing value checks, then (:161-163) exercisesByte.MIN_VALUEandShort.MIN_VALUEas divisors. I re-derived both by hand againstBigDecimal.divideAndRemainder's truncate-toward-zero, sign-of-dividend semantics:300 mod -128gives quotient trunc(-2.34) = -2, remainder300 - (-2 * -128) = 44, matching the test;100000 mod -32768gives quotient trunc(-3.05) = -3, remainder100000 - (-3 * -32768) = 1696, matching the test. Both are the widest possible divisor of each type, so they're the tightest test of the "no range check" invariant.Assertions.assertEquals((byte) 44, ...)also implicitly re-checks the runtime type, sinceByte.equals(Object)returnsfalseagainst a same-valuedInteger— a class regression would fail this even without the explicit.getClass()check above it, so the two assertion styles aren't redundant, they cover different failure shapes (value-only regression vs. class-only regression can each be caught independently).zeta/NumericFunctionTest.java:194-217(integration level, throughSQLEngine) — this is the one that actually closes the "planner and runtime could quietly diverge" gap. It callssqlEngine.typeMapping(null)and assertsBYTE_TYPE/SHORT_TYPEon the declared output schema, independently of the value assertions that follow. I checked this against #12215's own test (SQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors, still ondev) to make sure this isn't just re-testing the same thing: that test only ever readsoutRow.getField(...)fromSQLTransform.transformRow(...), which never surfacestypeMapping()'s declared schema — so the claim that this is new coverage, not duplicate coverage, holds up.- Minor, non-blocking observation, not a defect: the new test passes
outRowType(the schema fromtypeMapping()) as the second argument tosqlEngine.transformBySQL(inputRow, outRowType), where the three sibling tests just above it in the same file pass the inputrowTypeinstead. I checkedZetaSQLEngine.transformBySQL(ZetaSQLEngine.java:285-315) — that second parameter is only read in thelateralViewsbranch, which this query never hits, so both call shapes are behaviorally identical here, andoutRowTypeis arguably the more correct name-to-usage match against the interface's own parameter name (SQLEngine.java:31,outputRowType). Not asking for a change.
This is a normal, always-reachable code path (any MOD(x, tinyint_col)/MOD(x, smallint_col) expression), not a boundary/recovery/exception path — consistent with how the underlying #12215 defect was originally described.
1.2 Compatibility Impact
Fully compatible, by construction. No production code changes any observable behavior — the diff to NumericFunction.java is comment-only. No API, config, protocol, serialization, or checkpoint/state surface is touched. The two test files only add assertions/methods; nothing existing is weakened, removed, or renamed.
1.3 Performance / Side-Effect Analysis
None. A source comment has zero runtime cost, and the added tests are plain JUnit methods with no new shared state, no new external dependency, and no lifecycle/resource concerns — SQLEngineFactory.getSQLEngine(...) returns a fresh ZetaSQLEngine() per call (verified in SQLEngineFactory.java), so there's no caching or static state between test methods to worry about.
1.4 Error Handling and Logging
No issues found — no error handling or logging is touched by this diff.
2. Code Quality Assessment
2.1 Coding Standards
The new testModSupportsTinyIntAndSmallIntDivisors method has a standard multi-line Javadoc-style comment explaining why the test exists (the planner/runtime contract), matching the file's existing convention for the other tests around it. The added lines in functions/NumericFunctionTest.java are inline comments inside an existing test method, also explaining the non-obvious "why" (worst-case divisor reasoning) rather than restating the code. No new class/field is introduced, so no missing-Javadoc concern beyond the one method, which is covered.
2.2 Test Coverage and Test Stability
Both new/extended tests are deterministic: no Thread.sleep, no async waiting or polling, no hard-coded ports or timing, no shared static state (fresh SQLEngineFactory instance per test, as above), and no ordering dependency on other test methods — pure arithmetic and in-process SQL-engine calls. Stable.
I confirmed both actually ran and passed in this PR's own fork CI (run 34736822963): all four unit-test legs (JDK 8/11 × ubuntu/windows) that execute seatunnel-transforms-v2 completed success. The unrelated transform-v2-it-part-1 (11, ubuntu-latest) job failed, but I pulled that job's log directly rather than trusting the check-run summary: the failure is TestFilterRowKindIT.testFilterRowKindMultiTable:53 expected: <0> but was: <1> — the same signature already tracked in #12116 (AssertSinkWriter's static JVM-wide row counters), and the same one this PR's own comment thread already reproduced twice on earlier heads. That test's config (filter_row_kind_exclude_insert_multi_table.conf) has no SQL transform in it at all, so nothing in this diff is on its path even in principle — this is a pre-existing, independently-tracked flake, not something this change introduced or could fix.
2.3 Documentation Updates
None required. I re-checked docs/en/transforms/sql-functions.md:541 on current dev — it already states MOD(dividendNumeric, divisorNumeric) -> type(divisorNumeric), which is exactly what the new tests pin down; no doc drift to fix.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise, minimal follow-up. This is the smallest possible diff that closes the three specific gaps identified against #12215's own test, with no new abstraction and no behavior change. Reuses the existing SQLEngine/typeMapping test pattern already established by the other tests in the same file (e.g. testCeilAndFloorKeepBigIntValue) rather than inventing a new one.
3.2 Maintainability
High. The call-site comment plus the boundary-value tests together mean a future contributor won't need to re-derive BigDecimal.divideAndRemainder's bound-by-divisor guarantee from scratch, and won't be tempted to "fix" the absent range check with a guard that can never trigger.
3.3 Extensibility
Not applicable — this is test/documentation-of-invariant work on a leaf function, not a change to any extension point.
3.4 Historical-Version Compatibility
Fully compatible. Applies only to dev; no released version ever exercised this code path successfully (it either threw, pre-#12215, or wasn't reachable), so there's no historical behavior at risk, and no checkpoint/restore/upgrade concern applies to a stateless per-row scalar function.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| — | No blocking issues found | — | — |
Residual, non-blocking observation already covered in 1.1: the new integration test passes outRowType instead of the sibling tests' rowType as transformBySQL's second argument — confirmed behaviorally identical here since the lateralViews branch that parameter feeds is never hit by this query. Not something I'd ask to change.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers — none.
- Recommended fixes — none.
Overall assessment: this does exactly what the PR description says and nothing more — the production diff is a comment, and the test diff closes three specific, verifiable gaps in #12215's own coverage (planner/runtime type-contract divergence, both types' true overflow-boundary inputs, and the previously-undocumented "why no range check" reasoning) without duplicating what #12215 already tests. I independently re-derived both new arithmetic test cases, re-checked the planner's actual MOD type-derivation logic in ZetaSQLType.java, and diffed this test's assertions against #12215's existing test to confirm the non-overlap claim in the PR description holds.
On CI: at the time of this review the fork's Build workflow (run 34736822963) was still in progress (a handful of jobs, e.g. all-connectors-it-4 (11), connector-redis-it (11), connector-file-local-it (11), hadn't finished). Of what has completed: all four unit-test legs — the only jobs that actually exercise this PR's changed files — are green. transform-v2-it-part-1 (11, ubuntu-latest) failed on the known #12116 TestFilterRowKindIT flake, unrelated to this diff as explained above. A batch of otherwise-unrelated jobs (several all-connectors-it-* legs, engine-v2-it, paimon-connector-it) show ##[error]The operation was canceled / a runner shutdown signal rather than any test assertion failing — that reads as infra-level cancellation across the matrix, not a defect surfaced by this diff, which touches only seatunnel-transforms-v2 test files and one comment. I wouldn't ask for a sync-with-dev here (the PR is already rebased and mergeable: true/no conflicts as of this check); a rerun of the affected jobs, or simply waiting for the in-progress ones to finish, is the right next step rather than any code change.
Since my review access on this repository is comment-level, a maintainer with write-level review permission will still need to formally approve and merge once the required check is green (or the TestFilterRowKindIT/cancellation noise is accepted as known-unrelated).
|
CI finished. 71 passed, 12 failed, 11 skipped, and none of the failures are reachable from this diff, which is two test methods and a three line comment in The clearest evidence is the overlap with my other open PR, #12290. That one is a one line swap to
Where I read the logs the causes are environmental rather than assertion failures:
The failures are also spread across roughly four hours, from 04:47Z to 08:52Z, rather than clustered at one moment, which fits intermittent upstream availability rather than a single runner event. Two failures unique to this run are worth naming separately. All four I am rerunning the failed jobs now that other PRs have started going green again, which suggests the window has eased. Nothing in the diff changes. |
|
Thanks for the very thorough cross-PR CI breakdown — that matches what I'd expect from a two-test/one-comment diff, and I appreciate you tracing the shared failures against #12290 to make the "environmental, not code" case concrete rather than just asserting it. One correction worth flagging on the None of this changes my "Ready to merge" conclusion from the full review — the diff itself is unchanged and the only jobs that actually exercise it ( |
|
Agreed, and that matches what I found independently before reading this. Syncing now. Three notes from the attempt 2 logs. The MinIO failures are wider than That last one means On the registry state, what is observable from outside is that anonymous pulls are denied, rather than that the repository is definitely gone. An anonymous manifest request for After the sync I expect The remaining two are unaffected by the sync, as you say: |
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- Gap being closed: #12215 fixed
NumericFunction.mod's missingByte/Shortdivisor branches, but its own test only asserted the output value, never the declared output schema, the true overflow-boundary divisors, or documented the "why no range check" reasoning. This PR closes those three specific coverage gaps with no production behavior change. - Fix approach: a 3-line explanatory comment at the call site in
NumericFunction.java, plus a unit-level extension asserting.getClass()/boundary values, and a new integration-level test asserting the planner (typeMapping()) and the runtime (transformBySQL) agree onBYTE_TYPE/SHORT_TYPE. - One-sentence summary: a precise, non-overlapping test-coverage follow-up to #12215, unchanged since my full review on the prior head.
This is my second formal review round on this PR. There is no new commit that changes the diff's content: the only new commit since my last review (445cec7 -> 40b4a431d) is a merge of upstream/dev into the branch, picking up an unrelated CI fix (#12287, the minio/minio -> quay.io/minio/minio mirror switch) that the extensive comment-thread CI investigation between myself and @SEPURI-SAI-KRISHNA had already identified as the right next step. I independently re-diffed origin/dev...HEAD on the current head and confirmed it is byte-for-byte the same 3 files / 50 insertions / 0 deletions I fully reviewed last round — so this is a confirmation pass, not a re-review of new logic.
1. Code Change Review
1.1 Core Logic Analysis
Unchanged from my last review, re-verified against the current head directly (not from memory): the only production touch is the 3-line comment at NumericFunction.java:224-226 explaining why divideAndRemainder's bound-by-divisor guarantee makes a range check unnecessary for the narrow Byte/Short branches; the two test additions (functions/NumericFunctionTest.java unit level, zeta/NumericFunctionTest.java integration level through SQLEngine.typeMapping()) are unchanged, and I already independently re-derived both new BigDecimal.divideAndRemainder boundary-value assertions by hand last round. No new commit touches these files.
This remains a normal, always-reachable code path (any MOD(x, tinyint_col)/MOD(x, smallint_col) expression), not a boundary/recovery/exception path.
1.2 Compatibility Impact
Fully compatible, by construction, unchanged from last round. The only production diff is a source comment. No API, config, protocol, serialization, or checkpoint/state surface is touched.
1.3 Performance / Side-Effect Analysis
None, unchanged from last round — a source comment has zero runtime cost, and the two added test methods introduce no new shared state, external dependency, or lifecycle concern.
1.4 Error Handling and Logging
No issues — no error handling or logging is touched by this diff.
2. Code Quality Assessment
2.1 Coding Standards
Unchanged from last round: the new test method carries a standard multi-line comment explaining why it exists, matching the surrounding file's convention.
2.2 Test Coverage and Test Stability
Rating: Stable. Both tests remain deterministic — no Thread.sleep, no async waiting, no shared static state, no ordering dependency — confirmed again on this head. On the sync-triggering-CI-triage front, the joint investigation with the author since my last review is the most thorough CI root-causing I've seen on a coverage-only PR, and it is worth recording precisely because it changes what "green" will mean on the next run:
- The recurring
minio/miniopull failures (all-connectors-it-2/6/7,paimon-connector-it) were correctly root-caused as Docker Hub having stopped serving anonymous/unauthenticated pulls for that image (401/404, not rate-limiting) — already fixed ondevvia #12287 (quay.io/minio/miniomirror). The dev-sync in this round's only new commit picks that fix up, exactly as both of us expected in the comment thread. - The author already flagged, ahead of running the synced CI, that one leg (
S3FileConnectDryRunITinconnector-file-s3-e2e, added by #12242 after #12287 landed) still points at Docker Hub on currentdevand will need #12302 separately — I have not independently verified #12302's state, but the reasoning (same module asS3FileWithFilterIT, added after the mirror fix, so missed by it) is sound and consistent with grep-checkingS3FileWithFilterIT's package. - The remaining two failure classes —
TestFilterRowKindIT.testFilterRowKindMultiTable(the already-tracked #12116 flake, now reproduced a third time on this head family, in a config with no SQL transform at all) and theengine-v2-itBackpressureSlowSinkIT/SplitClusterFaultToleranceITAwaitility timeouts — are both outside this PR's changed-file list (seatunnel-transforms-v2test files and one comment only) and are not expected to clear from the sync. - The only jobs that actually execute this PR's added tests are the four
unit-testlegs (JDK 8/11 x ubuntu/windows), and those have been green on every head so far, including the one directly preceding this sync.
2.3 Documentation Updates
None required, unchanged from last round — docs/en/transforms/sql-functions.md:541 already documents the MOD(...) -> type(divisor) contract this PR's tests pin down.
3. Architectural Soundness
3.1 Elegance of the Solution
Unchanged from last round: the smallest possible diff that closes three specific, verifiable gaps in #12215's own test, with no new abstraction and no behavior change.
3.2 Maintainability
High, unchanged — the call-site comment plus the boundary-value tests mean a future contributor won't need to re-derive BigDecimal.divideAndRemainder's guarantee from scratch.
3.3 Extensibility
Not applicable — test/invariant-documentation work on a leaf function.
3.4 Historical-Version Compatibility
Fully compatible, unchanged — applies only to dev; no released version ever exercised this code path successfully, so no checkpoint/restore/upgrade concern applies to a stateless per-row scalar function.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| — | No blocking issues found | — | — |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers — none.
- Recommended fixes — none.
CI status: the current head's fork run (34799789086, SEPURI-SAI-KRISHNA/seatunnel) was still queued at review time, having just been triggered by the dev-sync merge — I have not personally triggered anything. Based on the joint root-causing above, I expect it to clear the MinIO-related legs and continue to show only the two already-tracked, diff-unrelated flakes (#12116's TestFilterRowKindIT, and the engine-v2-it Awaitility timeouts) plus possibly the separately-tracked S3FileConnectDryRunIT/#12302 gap — none of which are reachable from this PR's seatunnel-transforms-v2-only diff. The four unit-test legs, which are the only jobs that actually exercise this PR's added tests, have been green on every prior head.
Overall assessment: nothing has changed in the substance of this PR since my full review last round — it remains a precise, minimal, non-overlapping coverage follow-up to #12215 with zero production behavior change. The dev-sync in this round's sole new commit is exactly the CI housekeeping step both the author and I had already converged on in the comment thread, and the thoroughness of that joint CI investigation (correctly distinguishing a real, fixed infra regression from pre-existing unrelated flakes, log by log rather than by check-run summary) reflects well on the coverage claims in the PR description too. I'm approving this.
SEZ9
left a comment
There was a problem hiding this comment.
Thanks for working on this. I reviewed the latest head 7c343d90c9be.
What this PR fixes
- User pain: After #12215 fixed
MODwith TINYINT/SMALLINT divisors, nothing in the test suite pinned the planner half (ZetaSQLTypedeclaring the divisor's type as the result type,ZetaSQLType.java:516-518) together with the runtime half (NumericFunction.modreturningByte/Short,NumericFunction.java:227-231), so either side could regress independently; the absence of a range check on the narrow branches also read like an oversight to anyone skimming the code. - Fix approach: Test-only PR plus a comment. Adds
NumericFunctionTest.testModSupportsTinyIntAndSmallIntDivisors(zeta package) assertingtypeMapping()yieldsBYTE_TYPE/SHORT_TYPEandtransformBySQLreturns(byte) 2/(short) 3; extendsfunctions/NumericFunctionTest.testModForDifferentResultTypeswith.getClass()assertions andByte.MIN_VALUE/Short.MIN_VALUEdivisors; documents atNumericFunction.java:224-226thatdivideAndRemainderbounds|remainder| < |divisor|so no range check is needed. - One-line summary: The
typeMapping()assertions are genuinely new coverage, but the "widest divisor" cases (300 % -128 = 44, 100000 % -32768 = 1696) never approach ±127/±32767 so they do not exercise the bound the comment describes; the comment's "always fits" overstates the guarantee for fractional dividends, wherebyteValue()/shortValue()still truncate; and the engine-level test largely duplicatesSQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors(lines 88-106) rather than extending it.
Runtime chain I rechecked
Planner side (what the new typeMapping assertions pin):
ZetaSQLEngine.typeMapping() ZetaSQLEngine.java:215
-> zetaSQLType.getExpressionType(expression) ZetaSQLEngine.java:262
-> ZetaSQLType.getFunctionType(Function)
-> case ZetaSQLFunction.MOD: return getExpressionType(params.get(1)) ZetaSQLType.java:516-518 (result type = divisor type)
Runtime side (what the value/class assertions pin):
ZetaSQLEngine.transformBySQL(inputRow, outRowType) ZetaSQLEngine.java:285 (outRowType only forwarded to lateralView at :313-314; no coercion of projected values)
-> project(inputFields) ZetaSQLEngine.java:322
-> zetaSQLFunction.computeForValue(expression, inputFields) ZetaSQLEngine.java:339
-> ZetaSQLFunction.executeFunctionExpr case MOD
-> NumericFunction.mod(args) NumericFunction.java:208
-> toBigDecimal(left/right) NumericFunction.java:217-218 (Byte/Short/Integer/Long -> exact via longValue(); Float/Double -> BigDecimal.valueOf(double))
-> leftBD.divideAndRemainder(rightBD) NumericFunction.java:223
-> [new comment] NumericFunction.java:224-226
-> rightValue instanceof Byte -> res[1].byteValue() NumericFunction.java:227-228
-> rightValue instanceof Short -> res[1].shortValue() NumericFunction.java:230-231
Existing sibling coverage the new engine test overlaps:
SQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors SQLNumericFunctionsTest.java:88-106 (INT/BYTE/SHORT schema, MOD(a, tiny)/MOD(a, small); asserts (byte) 2 / (short) 10 values only, not the declared row type)
Findings
Issue 1: The "widest divisor" assertions never produce a remainder near the type boundary, so they cannot detect the overflow they claim to guard against
- Location:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java:161 - Why it matters: - The new assertions use dividends 300 and 100000 against
Byte.MIN_VALUE/Short.MIN_VALUE, which yield remainders 44 and 1696. Both sit far inside thebyte(±127) andshort(±32767) ranges, sores[1].byteValue()/res[1].shortValue()atNumericFunction.java:228/231would return the same value even if the narrowing were lossy for out-of-range numbers. The test therefore only proves that the divisor-type branch is dispatched, which the(byte) 1/(short) 1assertions a few lines above already prove. - The boundary the comment talks about is the remainder magnitude, not the divisor magnitude.
divideAndRemaindergives |remainder| ≤ |divisor| - 1, so the extreme outputs areMOD(127, Byte.MIN_VALUE) == 127,MOD(-127, Byte.MIN_VALUE) == -127,MOD(32767, Short.MIN_VALUE) == 32767andMOD(-32767, Short.MIN_VALUE) == -32767. None of those, and no negative dividend at all, is exercised for the narrow types in either test file, so BigDecimal's sign-follows-dividend behaviour is also unasserted forByte/Shortresults. - Impact: if someone later adds a guard such as
abs(remainder) >= Byte.MAX_VALUE, or switches tobyteValueExact()with an off-by-one, these tests stay green whileMOD(127, tiny_col)starts failing jobs at runtime. - Fix: replace or complement the two assertions with the four boundary cases above (max positive and max negative remainder for each type), and reword the comment at lines 158-160 so it points at the remainder bound rather than the divisor width.
- Evidence:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java:163 (short) 1696, NumericFunction.mod(Arrays.asList(100000, Short.MIN_VALUE)));;seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java:160 // would fail first if that reasoning were wrong.;seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java:158 // The remainder is always smaller in magnitude than the divisor, so even the widest - Suggested fix: These two inputs don't actually reach the boundary the comment describes:
300 % -128is 44 and100000 % -32768is 1696, both far inside the byte/short range, so a lossybyteValue()/shortValue()or a mis-written range guard would still pass. The extreme remainders are what matter (|remainder| ≤ |divisor| - 1), so I'd assertMOD(127, Byte.MIN_VALUE) == (byte) 127,MOD(-127, Byte.MIN_VALUE) == (byte) -127,MOD(32767, Short.MIN_VALUE) == (short) 32767andMOD(-32767, Short.MIN_VALUE) == (short) -32767. That also gives us the first negative-dividend coverage for the narrow types (sign follows the dividend). - Severity: Medium
Issue 2: New engine-level MOD test duplicates SQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors from #12215; only the typeMapping() assertions are new
- Location:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/NumericFunctionTest.java:194 - Why it matters: -
testModSupportsTinyIntAndSmallIntDivisors(seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/NumericFunctionTest.java:194) builds the sameINT/BYTE/SHORTschema, runs the sameMOD(int, tiny), MOD(int, small)projection and asserts(byte)/(short)output values, exactly asSQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors(lines 88-106, landed with #12215) already does with different input values. - The genuinely new coverage is the two
typeMapping()assertions at lines 211-212. InZetaSQLEngine.transformBySQL(lines 285-315) theoutRowTypeargument is only forwarded tolateralViewand never coerces projected values, so the runtime-type check at lines 215-216 is real — but it is the same runtime check the #12215 test already performs. - Our convention is to extend the existing test that owns the scenario rather than spread near-identical cases across classes. I'd either fold the planner-side check into the #12215 test (the produced row type is reachable through the
SQLTransformit already builds), or keep this test but trim it to thetypeMapping()assertions and reference the sibling test in its Javadoc so future readers know where the value assertions live. - Evidence:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/NumericFunctionTest.java:208 "select MOD(int_v, tiny_v) as tiny_mod, MOD(int_v, small_v) as small_mod from test");;seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/NumericFunctionTest.java:215 Assertions.assertEquals((byte) 2, outRow.getField(0));;seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/NumericFunctionTest.java:210 SeaTunnelRowType outRowType = sqlEngine.typeMapping(null); - Suggested fix: This mirrors
SQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors(from #12215) almost line for line — sameINT/BYTE/SHORTschema, same query shape, same(byte)/(short)value assertions. The only new coverage is thetypeMapping()check at lines 211-212, which is the valuable part. Could we either add that planner-side assertion to the existing #12215 test (the produced row type is reachable through theSQLTransformit already builds) or trim this one down to thetypeMapping()assertions and point to the sibling test in the Javadoc? That keeps the MOD scenario in one place, per our "extend the existing test" convention. - Severity: Low
Issue 3: New comment says the remainder "always fits the divisor's type", but byteValue()/shortValue() silently truncate a fractional remainder when the dividend is FLOAT/DOUBLE/DECIMAL
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java:226 - Why it matters: - The statement is correct for integer range:
|remainder| < |divisor|guarantees no overflow ofbyte/short. - It is not lossless, though.
toBigDecimal(NumericFunction.java:193-206) keeps the fractional part of a FLOAT/DOUBLE/DECIMAL dividend, so with aByte/Shortdivisorres[1]can carry a fraction andres[1].byteValue()/res[1].shortValue()drop it:MOD(5.5, (byte) 2)returns1, not1.5. The same applies to the pre-existing Integer/Long branches, and it is consistent withZetaSQLTypedeclaring the divisor's type for the result — but "fits" reads as "no information is lost" to the next maintainer. - Since the explicit goal of the comment is to stop a future reader from adding an unnecessary guard, it should also make the deliberate fractional truncation explicit so nobody "fixes" it in the other direction or files it as a bug.
- Fix: extend the comment with one sentence, e.g. "A fractional remainder (FLOAT/DOUBLE/DECIMAL dividend) is truncated to the divisor's integral type, matching the type ZetaSQLType declares." and pin it with
Assertions.assertEquals((byte) 1, NumericFunction.mod(Arrays.asList(5.5d, (byte) 2)))intestModForDifferentResultTypes. - Evidence:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java:226 // |remainder| < |divisor|, so the remainder always fits the divisor's type.;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java:225 // No range check is needed for the narrow types: divideAndRemainder guarantees that - Suggested fix: "always fits" is true for range, but not for precision: when the dividend is FLOAT/DOUBLE/DECIMAL and the divisor is Byte/Short,
res[1].byteValue()/shortValue()drop the fractional part (MOD(5.5, (byte) 2)->1). Since the point of this comment is to stop the next reader from adding a guard, please also spell out that fractional remainders are intentionally truncated to the divisor's integral type (consistent with whatZetaSQLTypedeclares), and pin that with aMOD(5.5d, (byte) 2) == (byte) 1assertion intestModForDifferentResultTypes. - Severity: Low
Review conclusion
Conclusion: final approval remains pending on the previous comments
2. Remaining follow-ups
- Issue 1: The "widest divisor" assertions never produce a remainder near the type boundary, so they cannot detect the overflow they claim to guard against
- Issue 2: New engine-level MOD test duplicates SQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors from #12215; only the typeMapping() assertions are new
- Issue 3: New comment says the remainder "always fits the divisor's type", but
byteValue()/shortValue()silently truncate a fractional remainder when the dividend is FLOAT/DOUBLE/DECIMAL
Thanks for the updates so far. Happy to discuss the remaining points.
Assert the real remainder boundaries. The previous inputs, 300 % -128 and 100000 % -32768, give 44 and 1696, both far inside byte and short range, so they only proved the divisor-type branch was dispatched. What bounds the result is the remainder: divideAndRemainder gives |remainder| <= |divisor| - 1, so the extremes are MOD(+-127, Byte.MIN_VALUE) and MOD(+-32767, Short.MIN_VALUE). Those are now asserted, which also gives the narrow types their first negative-dividend coverage. Record that a fractional remainder is truncated rather than rounded. The comment said the remainder "always fits" the divisor's type, which is true of range but not of precision: a FLOAT, DOUBLE or DECIMAL dividend keeps its fraction and byteValue() drops it, so MOD(5.5, (byte) 2) is 1. Pinned with an assertion so it is not "fixed" into rounding later. Trim the engine-level test to the planner side. Its value assertions duplicated SQLNumericFunctionsTest#testModWithTinyIntAndSmallIntDivisors from apache#12215; only the typeMapping() check was new. The Javadoc now points at the sibling test. No behaviour change. NumericFunction.java is byte-identical to dev once comments are stripped.
|
Thanks @SEZ9, all three are right and all three are addressed in the push above. Issue 1. You were right that the inputs never reached the boundary. I checked your failure scenario directly rather than taking it on reasoning. Adding the exact guard you described, Issue 3. Agreed, "always fits" conflated range with precision. The comment now says the remainder is within the divisor's range but that a FLOAT, DOUBLE or DECIMAL dividend keeps its fraction and Issue 2. Taken, but via your second option rather than the first. You offered either folding the planner-side assertion into the #12215 test or trimming this one to the 1158 tests pass in |
DanielLeens
left a comment
There was a problem hiding this comment.
Sorry for missing this in the last review: in my earlier approval I described the Byte.MIN_VALUE / Short.MIN_VALUE dividend inputs (300 and 100000) as the tightest test of the "no range check needed" reasoning, and @SEZ9 is right that they were not. 300 mod -128 = 44 and 100000 mod -32768 = 1696 sit far inside the byte and short ranges, so they never approached the remainder bound the comment talks about. I re-derived the arithmetic but did not ask which quantity the invariant actually bounds. Thanks @SEPURI-SAI-KRISHNA for taking the point on board so quickly, and thanks @SEZ9 for the careful review. This is a re-review of the current head af865a73ad0b; all three points from @SEZ9's review are resolved in the new commit, and my earlier APPROVED still stands at this head.
What Problem Does This PR Solve?
- User pain point: #12215 made
NumericFunction.modreturnByte/Shortfor TINYINT / SMALLINT divisors, matching whatZetaSQLTypedeclares forMOD(ZetaSQLType.java:516-518, "Result has the same type as second argument"). Nothing pinned the planner-declared row type, the exact boundary outputs, or the reason the narrowing needs no range check. - Fix approach: no production behavior change. A comment at the call site (
NumericFunction.java:224-230) plus test additions in two existing test classes: boundary and type assertions infunctions/NumericFunctionTest#testModForDifferentResultTypes, and a planner-sidetypeMapping()test inzeta/NumericFunctionTest. - One-sentence summary: a coverage and documentation follow-up to #12215 that pins the divisor-type contract and the true extreme remainders for narrow divisors.
- Before / after (test behavior): before,
MOD(127, Byte.MIN_VALUE)andMOD(-127, Byte.MIN_VALUE)were unasserted, so a guard such asabs(remainder) >= Byte.MAX_VALUEwould have passed the suite; after, both inputs are asserted and such a guard fails.
1. Code Change Review
1.1 Core Logic Analysis
Effective diff vs dev (merge base ea3df1667, no stacked or foreign commits): 3 files, 61 insertions, 0 deletions. The only production-file change is the comment block at NumericFunction.java:224-230. NumericFunction.mod itself is unchanged: toBigDecimal for both operands, Mod by zero check on rightBD.signum(), divideAndRemainder, then the instanceof chain keyed on the divisor type (:231-258).
Changes since the approved head 7c343d90c9be (one commit, af865a73ad0b):
functions/NumericFunctionTest.java:158-174: the300 / 100000cases are replaced by the four extreme remainders and one fractional case.zeta/NumericFunctionTest.java:189-213: the test is renamedtestModDeclaresTheDivisorTypeForTinyIntAndSmallIntand trimmed to thetypeMapping()assertions only, with a Javadoc that points atSQLNumericFunctionsTest#testModWithTinyIntAndSmallIntDivisors.NumericFunction.java:224-230: comment reworded from "always fits" to "in range, not lossless".
Verification of the asserted numeric semantics against the implementation at this head (hand-derived from BigDecimal.divideAndRemainder, truncate toward zero, remainder takes the sign of the dividend; I did not run the code):
MOD(127, Byte.MIN_VALUE): quotient 0, remainder 127,byteValue()gives(byte) 127. Correct, and it is the maximum positive remainder for a byte divisor of magnitude 128.MOD(-127, Byte.MIN_VALUE): quotient 0, remainder -127, gives(byte) -127. Correct; first negative-dividend coverage for the narrow types.MOD(32767, Short.MIN_VALUE)gives(short) 32767,MOD(-32767, Short.MIN_VALUE)gives(short) -32767. Correct for the same reason.MOD(5.5d, (byte) 2):toBigDecimal(5.5d)isBigDecimal.valueOf(5.5), the remainder is1.5,BigDecimal.byteValue()truncates the fraction, so the result is(byte) 1. Correct. It also matches the comment: truncation is deliberate, not rounding.Assertions.assertEquals((byte) 127, <Number>)resolves toassertEquals(Object, Object)after boxing, andByte.equals(Integer)is false, so the value assertions also pin the runtime class. The explicitgetClass()checks at:151and:155cover the ordinary5 mod 2case.- Type promotion: the result type follows the divisor only (
ZetaSQLType.java:516-518and theinstanceofchain agree), never the dividend.MOD(5, (byte) 2)returnsByte, andMOD(5.5d, (byte) 2)also returnsByte, consistent with the planner. - Zero divisor is not part of this diff. It is already covered by
functions/NumericFunctionTest#testModByZeroThrows(:86) andSQLNumericFunctionsTest#testModByZero(:109), so nothing is missing there.
Key Findings:
- The invariant that matters is
|remainder| <= |divisor| - 1, and the extreme outputs are reached with dividends+/-127and+/-32767against theMIN_VALUEdivisors; the new assertions hit exactly those. - The comment now says the narrowing is in range but not lossless for FLOAT / DOUBLE / DECIMAL dividends, and that this must not be "fixed" into rounding or a wider type. That is accurate against
NumericFunction.java:231-236. - The planner-side test asserts
BYTE_TYPEandSHORT_TYPEfromtypeMapping(null)and nothing else, which is the part of the contract the existing tests could not see. - Normal path:
MOD(x, tinyint_col)is an always-reachable user path, so the invariant guarded here is on the main path and not only on recovery or error handling.
1.2 Compatibility Impact
Fully compatible. The only production change is a source comment. No config option, default, serialization, checkpoint state, or public API is touched. No existing test was removed or weakened; the diff contains 0 deletions.
1.3 Performance / Side-Effect Analysis
None. A comment has no runtime cost, and the tests are in-process and cheap. SQLEngineFactory.getSQLEngine(...) creates a fresh engine per call, so there is no shared state across test methods.
1.4 Error Handling and Logging
Status of the points raised by other reviewers on the previous head:
- @SEZ9 Issue 1 (Medium), boundary assertions never reached the remainder bound: FIXED.
functions/NumericFunctionTest.java:158-170now asserts(byte) 127,(byte) -127,(short) 32767,(short) -32767, and the comment at:158-162points at the remainder bound rather than the divisor width. +1 @SEZ9: this was a real gap and my earlier review missed it (carryover, not introduced by the new commit). The author also reports that adding anabs(remainder) >= Byte.MAX_VALUEguard passes the old assertions and fails the new ones; I did not run that, but it follows directly from the arithmetic above (127 mod -128 = 127trips that guard). - @SEZ9 Issue 2 (Low), duplicate engine-level value assertions: FIXED.
zeta/NumericFunctionTest.java:196-213keeps onlytypeMapping()assertions and the Javadoc at:189-194names the sibling test. The author chose the "trim and reference" option so that the file that #12364 is editing is not touched; that is a reasonable reading of the "extend the existing test" convention. - @SEZ9 Issue 3 (Low), comment overstated "always fits": FIXED.
NumericFunction.java:227-230spells out the deliberate fractional truncation, pinned byfunctions/NumericFunctionTest.java:174.
Formal issue for the current head:
Issue 1: PR description no longer matches the diff
- Location: PR description, "How was this patch tested?" and "The planner side is asserted alongside the runtime" paragraphs.
- Problem: the description still names
testModSupportsTinyIntAndSmallIntDivisors, says it asserts thattransformBySQLreturns exactlyBYTE_TYPE/SHORT_TYPE, and quotesTests run: 29/1149and a failure atNumericFunctionTest.testModSupportsTinyIntAndSmallIntDivisors:214. After the latest commit the method istestModDeclaresTheDivisorTypeForTinyIntAndSmallInt, it no longer callstransformBySQL, and the value / runtime-class half is carried byfunctions/NumericFunctionTest#testModForDifferentResultTypesand the #12215 sibling test. The claim that "both new tests fail against the dispatch chain with #12215's two branches removed" is also no longer true for the planner-only test, which does not depend on the runtime branches at all. - Potential risk: a future reader (or the merge commit message) will look for a test that does not exist under that name and will assume the planner and runtime halves are asserted in one place.
- Best improvement: refresh the description to the current test names, the current counts, and say explicitly that the planner half (
typeMapping()) and runtime half (value plusgetClass()) are covered by different tests on purpose. - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Good. New comments explain why (remainder bound, deliberate truncation) rather than restating code. The new test method has a Javadoc explaining the contract it pins. No new class or field is introduced, no license-header issue, and formatting is confirmed by the green Code style job on the fork run.
2.2 Test Coverage and Test Stability
Coverage: the ordinary case (5 mod 2), the four extreme remainders, the negative-dividend sign rule, the fractional-truncation case, and the planner-declared row type are all pinned for both narrow divisor types. Zero divisor and the wide-type branches were already covered on dev.
Stability rating: Stable. Evidence: all assertions are pure arithmetic or a single in-process SQLEngine.init / typeMapping call (zeta/NumericFunctionTest.java:197-212); no Thread.sleep, no polling or unbounded waits, no ports, no files, no static mutable state (a fresh engine per test via SQLEngineFactory), no ordering dependency between methods (functions/NumericFunctionTest.java:143-174).
2.3 Documentation Updates
None required. docs/en/transforms/sql-functions.md already documents MOD(dividendNumeric, divisorNumeric) -> type(divisorNumeric), which is what the tests pin; the behavior is unchanged, so docs/zh needs no change either.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. Test and comment only, in the existing test classes, with no new abstraction.
3.2 Maintainability
High. The comment now states both the range guarantee and the precision caveat, and the boundary tests make a wrong "defensive" guard fail immediately. One trade-off worth naming: the planner and runtime halves now live in two classes, so no single test fails for both; that is acceptable because each half is independently pinned.
3.3 Extensibility
Not applicable; leaf scalar function.
3.4 Historical-Version Compatibility
Fully compatible. Nothing in the runtime, config, state, or serialization changes, and NumericFunction.mod behavior is identical to dev.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | PR description no longer matches the diff (test name, counts, "both tests fail" claim) | PR description | Low |
No blocking issues found. Remaining risk is CI only, described below.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers - none.
- Recommended fixes - non-blocking: refresh the PR description (Issue 1).
Overall assessment: the update does what @SEZ9 asked, and the arithmetic checks out against the implementation. My earlier APPROVED at 7c343d90c9be still stands at af865a73ad0b, with the correction above that the earlier boundary inputs were weaker than I said. @SEZ9's review is still in the "pending" state, so a quick re-look from @SEZ9 would close that out. No better alternative is needed.
CI status at this head (fork run 35583085561 in SEPURI-SAI-KRISHNA/seatunnel; the apache-side Build check is still in progress and is only a pointer):
Transforms : V2module: SUCCESS in the JDK 11 ubuntu unit-test job, withzeta.NumericFunctionTest(8 tests),zeta.functions.NumericFunctionTest(21 tests) andSQLNumericFunctionsTest(16 tests) all at 0 failures.unit-test (8, windows-latest)is green, andCode style,License header,Dead linksandDependency licensesare green.unit-test (8, ubuntu-latest)failed before any test ran:wgetgot429 Too Many Requestsfetching the Maven wrapper jar from Maven Central, thenCould not find or load main class org.apache.maven.wrapper.MavenWrapperMain. Infrastructure, not this PR. A rerun of that job should pass.unit-test (11, ubuntu-latest)failed inseatunnel-engine-server:TaskExecutionServiceTest.testStaleTaskDoneCleansOnlyOwnedGenerationResources:639(Wanted but not invoked: scheduledFuture.cancel(false)). That test came in with #12238, this PR touches nothing underseatunnel-engine, and #12394 is an open PR that describes this exact test failing from execution-ID reuse across fixtures. This reads as a known engine test flake, not caused by this diff (my inference from the test source and #12394's description; I did not run it). Rerun the failed job.unit-test (11, windows-latest)failed inconnector-http-paypal:PayPalClientTest.closeWakesRetryWait:416 expected: <true> but was: <false>, a timing test in a connector this PR does not touch. Unrelated; rerun the failed job.- The remaining fork jobs (connector and engine ITs) were still queued or running when I looked, so I am not treating them as failures.
The contributor should rerun only the failed unit-test jobs (no code change and no dev sync needed for these; a sync would not change any of the three).
|
Thanks @DanielLeens. Description refreshed for Issue 1: the renamed test, the removed |
SEZ9
left a comment
There was a problem hiding this comment.
Thanks for the follow-up. I checked the latest changes at af865a73ad0b against my previous review comments.
The scope of this pass is limited to the findings from the previous review; it does not introduce a new set of review items.
What this PR fixes
The commits since the previous review touch only the three files already under review: a comment expansion in NumericFunction.java (no executable change), a rewrite of the boundary assertions plus one truncation assertion in functions/NumericFunctionTest#testModForDifferentResultTypes, and a trimmed, renamed planner-side test in zeta/NumericFunctionTest that asserts only typeMapping() returns BYTE_TYPE/SHORT_TYPE. Each change maps directly onto one of the three prior findings, and no new concerns were introduced.
Resolved previous findings
PR12182-F1The "widest divisor" assertions never produce a remainder near the type boundary, so they cannot detect the overflow they claim to guard againstPR12182-F2New engine-level MOD test duplicates SQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisors from #12215; only the typeMapping() assertions are newPR12182-F3New comment says the remainder "always fits the divisor's type", butbyteValue()/shortValue()silently truncate a fractional remainder when the dividend is FLOAT/DOUBLE/DECIMAL
Review conclusion
Conclusion: LGTM, can merge
Nice work — the previous concerns are addressed. Thanks again for the contribution.
|
@davidzollo this one is ready whenever you have a moment, if you are happy to take it. It has two approvals, @DanielLeens on 09-14 and again after the latest commit, and @SEZ9 on 09-22 after his three findings were addressed. CI is green on the current head The four failures on the previous attempt were all environmental and cleared on a rerun with no code change: a The change itself is three files in It is 8 commits behind |
|
Thanks @SEPURI-SAI-KRISHNA. Confirmed the description now matches the diff - that closes out Issue 1 from my last review, and I have nothing further on the code or tests. Also thanks @SEZ9 for the quick re-check and approval - glad the three findings are fully resolved. I independently re-checked the current head ( No need to sync with |
davidzollo
left a comment
There was a problem hiding this comment.
+1
LGTM, appreciate your solid contribution, keep up the excellent work
Purpose of this pull request
Follow-up to #12215, which closed #12179.
This PR originally carried the same two-branch fix. #12215 landed that first, so the fix is dropped here and only the coverage that #12215 did not include remains. The production change is now a comment.
@DanielLeens compared the two PRs on #12215 and identified three gaps. @SEZ9 then reviewed the result and found that two of the three were closed less tightly than they looked. All of it is addressed here.
The planner side is asserted, deliberately in its own test. The defect was a disagreement between
ZetaSQLType, which derives theMODresult type from the divisor, and the runtime dispatch, which handled only some of those types.SQLNumericFunctionsTest.testModWithTinyIntAndSmallIntDivisorsfrom #12215 asserts the returned values, which would still pass iftypeMappingstopped declaringTINYINT.zeta/NumericFunctionTest.testModDeclaresTheDivisorTypeForTinyIntAndSmallIntasserts thattypeMapping()declaresBYTE_TYPEandSHORT_TYPE, and nothing else. The value and runtime-class half is carried byfunctions/NumericFunctionTest.testModForDifferentResultTypesand by the #12215 sibling test, which the Javadoc names. The two halves are split on purpose: @SEZ9 pointed out that asserting the values here as well only duplicated the sibling, and folding the planner check into that sibling would collide with #12364, which is open against the same file.The true remainder boundaries are covered. An earlier revision used
MOD(300, Byte.MIN_VALUE)andMOD(100000, Short.MIN_VALUE)on the grounds that those are the widest divisors. @SEZ9 showed that this misses the point: the results are 44 and 1696, far inside byte and short range, so they never approach the bound the comment describes. What bounds the result is the remainder, not the divisor, anddivideAndRemaindergives|remainder| <= |divisor| - 1. The extremes are thereforeMOD(±127, Byte.MIN_VALUE)andMOD(±32767, Short.MIN_VALUE), which are now asserted and which also give the narrow types their first negative-dividend coverage.The reasoning is recorded at the call site, including what it does not promise.
divideAndRemainderbounds the remainder below the divisor in magnitude, so the result is always within the divisor's range. The comment originally said it "always fits", which conflated range with precision: a FLOAT, DOUBLE or DECIMAL dividend keeps its fractional part andbyteValue()truncates it, soMOD(5.5, (byte) 2)is 1 and not 1.5. The comment now says both, and says the truncation is deliberate so nobody "fixes" it into rounding or a wider return type.Does this PR introduce any user-facing change?
No. Tests and one comment.
NumericFunction.javais byte-identical todevonce comments are stripped.How was this patch tested?
The runtime-side test fails against the dispatch chain with #12215's two branches removed and passes with them. The planner-side test does not depend on those branches at all, by design, so it is unaffected by that mutation.
The boundary assertions were checked against the failure @SEZ9 described rather than accepted on reasoning. Adding his exact guard,
abs(remainder) >= Byte.MAX_VALUE, to the byte branch:Mutating the narrowing to round instead of truncate fails the new
MOD(5.5d, (byte) 2)assertion.Full module on current
dev:./mvnw -pl seatunnel-transforms-v2 spotless:checkpasses.