Repository navigation
[Fix][Transform-V2] Widen vector operands before arithmetic - #12337
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
The six vector arithmetic UDFs (VECTOR_NORM, INNER_PRODUCT, COSINE_DISTANCE, L1_DISTANCE, L2_DISTANCE, VECTOR_NORMALIZE) — implemented twice, once as Calcite UDFs (seatunnel-transforms-v2/.../calcite/udf/*Function.java) and once as native Zeta SQL functions (.../sql/zeta/functions/VectorFunction.java) — accumulate into a double via IntStream.mapToDouble(...)/Arrays.stream(...).mapToDouble(...), but the element-wise multiplication/subtraction itself was happening in float precision before being widened to double. Since vector elements are stored as Float, an expression like vector1[i] * vector2[i] unboxes both operands to float, multiplies in float, and only the result is widened to double when returned from the lambda.
For finite but large-magnitude float elements (e.g. anything whose square exceeds Float.MAX_VALUE ≈ 3.4e38, well within double range) this silently overflows to Infinity in the float multiply before it ever reaches the double accumulator — and for very small elements it can silently underflow to 0.0f. Concretely:
COSINE_DISTANCEon two exact opposite-direction large vectors previously returnedNaN(Infinity - Infinity) instead of2.0.VECTOR_NORMALIZEon a vector containing only subnormal-magnitude floats previously treated it as a zero vector (magnitude == 0.0) and skipped normalization, instead of producing a correctly normalized unit vector.
The fix casts one operand to (double) before each multiplication/subtraction ((double) vector1[i] * vector2[i]), which by JLS binary numeric promotion (5.6.2) forces the entire operation into double precision, eliminating the intermediate float overflow/underflow.
1. Code Change Review
1.1 Core Logic Analysis
Before (e.g. CosineDistanceFunction.java):
double dotProduct =
IntStream.range(0, vector1.length).mapToDouble(i -> vector1[i] * vector2[i]).sum();
double norm1 = Arrays.stream(vector1).mapToDouble(v -> v * v).sum();After:
double dotProduct =
IntStream.range(0, vector1.length)
.mapToDouble(i -> (double) vector1[i] * vector2[i])
.sum();
double norm1 = Arrays.stream(vector1).mapToDouble(v -> (double) v * v).sum();The identical pattern is applied consistently to all 6 hot spots in both engines: CosineDistanceFunction, InnerProductFunction, L1DistanceFunction, L2DistanceFunction, VectorNormFunction, VectorNormalizeFunction (Calcite path) and their mirror-image equivalents inside VectorFunction (Zeta native SQL path).
Correctness across the actual "type pairs" here. Unlike general SQL arithmetic, every vector element is a single type (Float), so there is no int/long/double promotion matrix to worry about — the real dimension that matters is magnitude class (huge / tiny / normal / zero / NaN / ±Infinity), and I traced/verified each:
- Cast placement is correct:
(double) a * band(double) a - bboth forcedoublebinary numeric promotion of the other operand too (JLS 5.6.2), so only one explicit cast per expression is needed — there is no asymmetric/one-sided widening bug. - I hand-verified
testLargeProductsCancelWithoutOverflow(InnerProductFunction.eval({MAX,MAX},{MAX,-MAX})expected0.0,CosineDistanceFunctionexpected1.0): with the fix,dotProduct = MAX_d² − MAX_d² = 0.0exactly (exact IEEE cancellation); with the old code,MAX*MAXoverflows tofloatInfinity,MAX*(-MAX)overflows to-Infinity, andInfinity + (-Infinity) = NaN— i.e. the old code returnedNaNfor a case that has an exact, well-defined answer. This is a real, previously-silent correctness bug, not just a cosmetic precision nit. - Underflow direction is also fixed, not just overflow:
VectorNormalizeFunction/VectorFunction.vectorNormalizeon a vector ofFloat.MIN_VALUE(~1.4e-45) squares to ~2e-90 in real terms — representable indoublebut underflows to0.0finfloat, which previously hit themagnitude == 0.0short-circuit and silently returned the unnormalized vector. The new e2e cases (tiny_norm,tiny_normalizedin both.conffiles) exercise exactly this. RANDOM_PROJECTION/SPARSE_RANDOM_PROJECTION(VectorFunction.applyProjection) still accumulates infloatand is intentionally not touched by this PR — correctly disclosed in all three doc files ("random-projection arithmetic is unaffected"). I grepped the fullVector*.javasurface at the PR head and confirmed these are the only remaining float-precision-accumulation call sites; nothing was missed.- NaN/±Infinity element behavior is unchanged by this fix (verified:
Infinity * Infinityoverflows toInfinityin bothfloatanddouble,NaNpropagates identically either way) and is covered by the newtestVectorArithmeticSpecialValuesregression tests in bothVectorUdfTestandVectorFunctionTest.
I also traced the call chain end-to-end to confirm this is the normal execution path, not a recovery/exception branch: SQLTransform.transformRow() → Zeta SQL expression evaluator → VectorFunction.cosineDistance/... for the Sql transform, and CalciteSQLEngine → registered CalciteUdf → CosineDistanceFunction.eval/... for the Calcite transform. Both are exercised directly by the new SQLVectorFunctionTest.testFiniteVectorArithmeticThroughSql and CalciteSQLEngineTest.testFiniteVectorArithmetic, which go through transform.transformRow(...) / a full SQL query rather than calling the static UDF methods directly — so the fix is proven to be reachable from real SQL jobs, not just from unit-isolated helper calls.
1.2 Compatibility Impact
Output type: unchanged. All 6 functions keep their existing return types — Double for VECTOR_NORM/INNER_PRODUCT/COSINE_DISTANCE/L1_DISTANCE/L2_DISTANCE, and a byte[]/ByteBuffer encoding of Float[] for VECTOR_NORMALIZE. I checked every changed method signature — none of them changed. So there is no schema/column-type break for downstream sinks (this is the single most important compatibility question per the review brief, and it is clean).
Output value: intentionally changes, and this is correctly disclosed. This is not limited to the extreme overflow/underflow corner cases — because the old code rounded every intermediate product/difference to float (24-bit mantissa) precision before widening, and the new code keeps full double (53-bit) precision throughout, results can differ in low-order digits for essentially any non-trivial input, not just huge/tiny magnitudes. The PR's own incompatible-changes.md entry (added in both docs/en and docs/zh) states this explicitly: "Results can also differ in their low-order digits," and gives migration guidance ("Review thresholds and previously computed vector metrics or normalized embeddings before replaying data"). This matches repository policy (CLAUDE.md: incompatible changes must be documented with migration guidance) and is accurate based on my own trace above — I did not find any additional undisclosed behavior change.
Classification: Behavior correction (bug fix), not a breaking change to config/schema/state. No Option, config default, checkpoint/state format, or SPI contract is touched.
1.3 Performance / Side-Effect Analysis
The added (double) cast compiles to a single f2d (float-to-double widening) bytecode instruction per element — no allocation, no branching, no boxing introduced by this PR. (The Float[]/unboxing already existed on this hot path before the change; this PR does not add or remove any unboxing.) This runs inside per-element vector-distance loops, so it scales with vector dimensionality exactly as before — asymptotically and constant-factor-wise, the impact is negligible.
1.4 Error Handling and Logging
No exceptions, error codes, or log statements were added or modified in this PR. No issues found in this category.
2. Code Quality Assessment
2.1 Standards
Follows the AOSP/Spotless formatting used by the rest of the module (the diff is consistent with what spotless:apply would produce), no wildcard imports, no new dependencies. All 19 changed files are modifications to existing files — no new files are added, so the ASF license header requirement doesn't apply here.
2.2 Test Coverage + Stability Rating
Coverage is strong and precision-aware:
- Unit tests (
VectorUdfTest,VectorFunctionTest) add a@ParameterizedTestsweeping{Float.MAX_VALUE, 1e20f, 1e-30f, Float.MIN_NORMAL, Float.MIN_VALUE, 3f, 0.1f}— i.e. every magnitude class that matters for this bug (extreme-large, large, small, min-normal, subnormal-min, ordinary) — plus dedicated tests for exact large-magnitude cancellation, zero/empty vectors, and NaN/±Infinity propagation (regression coverage for behavior this PR must not change). - Expected values in the parameterized tests are derived via
BigDecimal(exact arithmetic) rather than hand-computed doubles, and tolerances are calibrated per-quantity:1e-14relative for pure-double results, but a deliberately looser1e-7specifically for theVECTOR_NORMALIZEoutput elements (which genuinely lose precision tofloaton output) — I checked this is not accidental laxity, it correctly reflects where afloatrounding step actually occurs in the algorithm. - I independently hand-verified the
CalciteSQLEngineTest.testFiniteVectorArithmetic"1e-14 delta onVECTOR_NORM(VECTOR_NORMALIZE(vec1))expecting1.0" case, since a tight delta around a value with afloat-rounding step in front of it looked suspicious at first glance — it uses single-element vectors (floatVec(Float.MAX_VALUE)), wherevalue/magnitudeis exactly1.0with no rounding error, so the tight tolerance is actually fine. No flakiness risk found. - SQL-path tests (
SQLVectorFunctionTest,CalciteSQLEngineTest) exercise the fix through the real SQL evaluation call chain, confirming the normal path is hit (see 1.1). - E2E (
seatunnel-transforms-v2-e2e-part-2): bothfunc_vector.conf(ZetaSqltransform) andcalcite_builtin_functions.conf(Calcitetransform) get new large/tiny-magnitude scenarios throughFakeSource → transform → Assertfull pipeline execution, per repo convention that an existing IT must be extended alongside a source fix. - New tests correctly extend existing test classes rather than adding new ones, consistent with the test-class convention added in
1325a44b2f4(AGENTS.md).
CI status (re-verified live): All 4 unit-test job matrix legs (Java 8/11 × ubuntu/windows) in the fork's Build workflow run (goutamadwant/seatunnel run 35046506616) have completed successfully — this is the job that actually executes the new VectorUdfTest/VectorFunctionTest/CalciteSQLEngineTest/SQLVectorFunctionTest cases I analyzed above, so their correctness is CI-confirmed, not just my manual derivation. License header, Code style, Sanity check results, and Dependency licenses also passed. The directly-relevant E2E job, Run / transform-v2-it-part-2 (covers seatunnel-transforms-v2-e2e-part-2, i.e. both modified .conf files), is still in_progress as of this review (queued since 2026-09-16T02:03Z, ~8.5h ago — a large number of unrelated connector-IT matrix legs across the full E2E suite are still queued behind it, which is normal/expected for this repo's CI backlog and not this PR's fault). I could not confirm a final conclusion for that job at review time.
2.3 Docs
docs/en and docs/zh are both updated in lockstep across introduction/concepts/incompatible-changes.md, transforms/calcite.md, and transforms/sql-functions.md, satisfying the repo's "any user-visible change must update both docs/en and docs/zh" rule. Content is accurate against the code (verified against 1.1/1.2 above) and includes concrete migration guidance, not just a changelog bullet.
3. Architectural Soundness
The fix is minimally scoped and touches only the six affected arithmetic call sites, consistent with the repo's "PR Scope Rule" (no unrelated refactors). One structural observation, not introduced by this PR but worth naming: the same widening logic had to be hand-applied twice — once in the CalciteUdf implementations and once in VectorFunction (Zeta native SQL) — because the two SQL engines maintain independent, near-duplicate implementations of these vector functions. That pre-existing duplication is exactly why this single logical bug required a 6-times-2 mechanical fix instead of a 6-times-1 fix. Extracting a shared VectorMath-style helper used by both engines would prevent the next fix in this area from needing the same double-application — but that is a larger, unrelated refactor and correctly out of scope for a Fix PR; I'm flagging it only as a non-blocking follow-up suggestion (see Issue #1 below).
4. Issue Summary
| # | Location | Problem | Risk | Severity | Raised by another reviewer |
|---|---|---|---|---|---|
| 1 | seatunnel-transforms-v2/.../calcite/udf/*.java vs .../sql/zeta/functions/VectorFunction.java |
Vector arithmetic logic (including this widening fix) is duplicated across the Calcite and Zeta native SQL engines instead of sharing one implementation | Future correctness fixes in this area must be remembered and applied twice, as this PR itself had to do; low risk of drift if missed once | Low (non-blocking, suggestion for a separate follow-up PR) | No |
| 2 | VectorFunction.applyProjection / createGaussianProjectionMatrix (RANDOM_PROJECTION, SPARSE_RANDOM_PROJECTION) |
Still accumulates in float precision, same class of overflow/underflow theoretically possible for extreme-magnitude inputs |
Low — explicitly out of this PR's stated scope and explicitly disclosed as unaffected in all three doc files; not a defect in what was shipped | Low (informational only, not blocking) | No |
No correctness, compatibility, or test-coverage blockers were found.
5. Merge Recommendation
No source-code blocking items. The fix is a correct, narrowly-scoped float→double widening correction applied consistently across every relevant hot spot in both SQL engines (verified complete via full-repo grep), preserves all existing output types (no schema/sink compatibility break), is properly disclosed as a documented behavior correction with migration guidance in both docs/en and docs/zh, and is backed by precision-aware unit tests (already passing in CI on all 4 platform legs), SQL-call-chain tests, and E2E scenarios for both engines.
Outstanding, CI-only: the E2E job that directly covers this PR's new scenarios (Run / transform-v2-it-part-2) was still in_progress at review time, and the remainder of the full connector-IT matrix is still queued behind it — this is normal CI backlog on this repo, not evidence of any problem with the change, but it means I cannot certify "all CI green" as of this review. I'd recommend merging once that job (and the rest of the required checks) finish green; no further code changes are needed from my read.
Overall assessment: Approve, pending the in-flight E2E job completing successfully.
Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
|
Synced with dev and resolved the EN/ZH migration-note conflict without dropping either entry. The vector-arithmetic fix is unchanged by the conflict resolution. Parent-content preservation was checked; this is not a new full-reactor test result. Pushed in 78919dc. CI for the new head is pending; the results above are scoped verification, not a green aggregate-build claim. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the update, @goutamadwant. I re-reviewed the new head from scratch. I compared the previously-approved commit against the current head directly rather than trusting the description of the merge, and can confirm your summary is accurate: the vector-arithmetic source, test, and e2e-conf files are byte-for-byte identical to what I already approved, and the incompatible-changes.md merge correctly kept both the existing "SQL and Calcite Vector Arithmetic" entry and the incoming "Redis Authentication" entry (from the unrelated Redis named-user PR that landed on dev in the meantime) with no conflict markers or lost content. No new issue surfaced in this pass, so there is nothing here that should have been caught earlier - this is a genuine no-op-for-the-fix sync, not a carryover miss.
What Problem Does This PR Solve?
- User pain point: the six vector arithmetic UDFs (
VECTOR_NORM,INNER_PRODUCT,COSINE_DISTANCE,L1_DISTANCE,L2_DISTANCE,VECTOR_NORMALIZE), implemented once as Calcite UDFs and once as native Zeta SQL functions, multiplied/subtracted vector elements infloatprecision before widening todouble, so finite-but-large or finite-but-tiny inputs could silently overflow/underflow toInfinity/NaN/0.0instead of producing a correct finite result. - Fix approach: cast one operand to
(double)before each multiplication/subtraction so JLS binary numeric promotion forces the whole expression intodouble, applied consistently at all 6 x 2 call sites in both engines. - One-sentence summary: a precision-widening bug fix for vector arithmetic UDFs, now re-synced with
devwith no change to the fix itself.
1. Code Change Review
1.1 Core Logic Analysis
I diffed the previously-approved commit (f7b92a71c62) against the current head (78919dc7ec5) restricted to the PR's own source/test/e2e-conf paths and got an empty diff - the fix logic is unchanged:
// VectorFunction.java (Zeta native SQL path), unchanged from prior approval
double dotProduct =
IntStream.range(0, vector1.length)
.mapToDouble(i -> (double) vector1[i] * vector2[i])
.sum();
double norm1 = Arrays.stream(vector1).mapToDouble(v -> (double) v * v).sum();Key findings from this pass:
- Re-verified with a fresh
apache/devfetch thatapache/dev...refs/review/pr-12337(three-dot diff) contains exactly the 19 files that belong to this fix: the 6 Calcite UDF files,VectorFunction.java, the two E2E.conffiles, the four new/extended test classes, and thedocs/en+docs/zhdoc pairs forincompatible-changes.md,calcite.md,sql-functions.md. Nothing from unrelated connectors leaked into the real diff oncedevwas current - my first pass against a stale localapache/devref falsely showed Fluss/Redis/Tablestore/MQTT files as part of this PR, which was a local-ref staleness artifact, not a PR problem. - The merge commit (
78919dc7ec5, mergingdevintofix/vector-arithmetic-overflow) is a clean two-parent merge with no leftover conflict markers anywhere in the full diff (checked via a grep for<<<<<<</=======/>>>>>>>). docs/en/introduction/concepts/incompatible-changes.mdand itszhcounterpart both now contain, in order: the vector-arithmetic entry this PR added, then the Redis-authentication entry that landed ondevafter this PR branched, then the pre-existing RabbitMQ entry. Both new entries survived the merge intact - this was the actual conflict the author resolved, and it resolved correctly.- Call-chain reachability (re-confirmed, not assumed from the prior review):
SQLTransform.transformRow()-> Zeta SQL evaluator ->VectorFunction.cosineDistance/...for theSqltransform, andCalciteSQLEngine-> registeredCalciteUdf->CosineDistanceFunction.eval/...for theCalcitetransform.SQLVectorFunctionTest.testFiniteVectorArithmeticThroughSqlandCalciteSQLEngineTest.testFiniteVectorArithmeticexercise these end-to-end viatransform.transformRow(...)/a full SQL query, not the static UDF methods directly, so the fix is proven reachable from real SQL jobs. RANDOM_PROJECTION/SPARSE_RANDOM_PROJECTION(VectorFunction.applyProjection) remain intentionally untouched and this remains correctly disclosed in all three doc files as out of scope.
flowchart LR
A[SQL job: Sql or Calcite transform] --> B{Engine}
B -->|Zeta Sql transform| C[VectorFunction.cosineDistance/innerProduct/...]
B -->|Calcite transform| D[CalciteUdf: CosineDistanceFunction/...eval]
C --> E["(double) v1[i] * v2[i] -- JLS 5.6.2 double promotion"]
D --> E
E --> F[double accumulator: no float overflow/underflow]
1.2 Compatibility Impact
Fully compatible at the type/schema/config level, with an intentionally and correctly documented value-level behavior change. Return types for all 6 functions are unchanged (Double for the five distance/norm/product functions, byte[]/Float[] encoding for VECTOR_NORMALIZE), so there is no schema or sink-compatibility break. Output values can differ in low-order digits for ordinary inputs (not just the overflow/underflow extremes) because the accumulation precision genuinely changed from float to double throughout - this is disclosed with migration guidance in both docs/en and docs/zh, matching repository policy for incompatible changes. No Option, config default, checkpoint/state format, or SPI contract is touched. This is a behavior correction, not a breaking schema/config/state change.
1.3 Performance / Side-Effect Analysis
Unchanged from the prior review: each added (double) cast is a single f2d bytecode instruction per vector element, no allocation, no new boxing, negligible constant-factor cost inside the existing per-element loop.
1.4 Error Handling and Logging
No exceptions, error codes, or log statements were added or modified in this PR. No issues found in this category.
2. Code Quality Assessment
2.1 Coding Standards
Every changed/added method in this PR is either a small, self-explanatory arithmetic expression fix or a test method with a clear body; none of the core Calcite eval(...)/VectorFunction static methods gained new undocumented public surface in this change (they already had class-level or method-level context from before). No wildcard imports, no new dependencies, formatting matches AOSP/Spotless conventions used elsewhere in the module. Nothing to flag here.
2.2 Test Coverage and Test Stability
Unchanged from the prior approval, and re-verified: VectorUdfTest/VectorFunctionTest add a @ParameterizedTest over {Float.MAX_VALUE, 1e20f, 1e-30f, Float.MIN_NORMAL, Float.MIN_VALUE, 3f, 0.1f} with BigDecimal-derived expected values and appropriately calibrated tolerances (tighter for pure-double outputs, looser for VECTOR_NORMALIZE's float-rounded output), plus dedicated large-magnitude-cancellation and NaN/Infinity-propagation regression tests. SQLVectorFunctionTest/CalciteSQLEngineTest exercise the fix through the real SQL call chain. The two E2E .conf files add large/tiny-magnitude scenarios through a full FakeSource -> transform -> Assert pipeline. All new tests extend existing test classes per the repo's test-class convention rather than adding new ones. No flaky-pattern risk found (no timing dependence, no sleeps, deterministic numeric assertions with justified tolerances). Stability rating: Stable.
CI status (re-checked live at review time): the apache-side Build check is a pointer, still queued/pending. The actual work runs on the fork (goutamadwant/seatunnel); its Build workflow run for this exact head SHA (run 35695254986) is also still queued as of this review and has not started executing jobs yet, so I cannot cite a fresh green unit-test/E2E result for this specific head the way the prior review could for the earlier commit. This is CI backlog, not evidence of a problem with the diff itself, given the diff against the fix's own files is empty.
2.3 Documentation Updates
docs/en and docs/zh remain updated in lockstep for incompatible-changes.md, transforms/calcite.md, and transforms/sql-functions.md. The merge conflict in incompatible-changes.md was resolved correctly in both languages, preserving both the pre-existing vector-arithmetic entry and the newly-landed Redis-authentication entry from dev.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix - a minimal, correctly-scoped widening correction applied uniformly to every affected call site in both engines, with no unrelated refactor bundled in.
3.2 Maintainability
Same observation as before, restated because it's still accurate on this head: the same widening fix had to be hand-applied twice (once per SQL engine) because CalciteUdf and VectorFunction maintain independent implementations of the same vector math. Not a defect in this PR, and correctly out of scope for a Fix PR - flagged again below only as a non-blocking follow-up suggestion.
3.3 Extensibility
No impact - no new extension points added or removed.
3.4 Historical-Version Compatibility
No config/state/protocol contract changes; only output-value precision improves. Covered fully under 1.2.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Vector arithmetic logic is duplicated across the Calcite and Zeta native SQL engines instead of sharing one implementation, so future fixes in this area must be applied twice as this one was | seatunnel-transforms-v2/.../calcite/udf/*.java vs .../sql/zeta/functions/VectorFunction.java |
Low (non-blocking follow-up suggestion, raised in prior review, still applies, not new) |
| 2 | RANDOM_PROJECTION/SPARSE_RANDOM_PROJECTION still accumulate in float precision |
VectorFunction.applyProjection/createGaussianProjectionMatrix |
Low (informational, explicitly out of this PR's disclosed scope) |
No correctness, compatibility, or test-coverage blockers were found on this re-review. Both issues above are carried over unchanged from the prior approval, not new findings.
5. Merge Recommendation
Conclusion: Ready to merge after fixes
Correction: there are no code-side fixes needed. The only open item is CI completing on the current head.
- Blockers - must be fixed: none. The fix logic, tests, and docs on this head are identical to what was already approved; the only change since approval is a clean
devsync that correctly preserved both sides of a documentation-only merge conflict. - Recommended fixes - non-blocking: consider a shared
VectorMath-style helper to remove the Calcite/Zeta duplication (Issue #1) as a separate follow-up PR; no action needed on Issue #2 for this PR.
Overall assessment: this re-review confirms the fix itself is unchanged and correct, and the dev sync was handled properly with no lost content. The fork's Build workflow for this exact head SHA is still queued and has not produced fresh results yet, so I'm not able to certify a live green run for 78919dc7ec5 specifically at this moment, even though the underlying diff is identical to a commit whose unit tests already passed on all 4 platform legs. I'd merge as soon as the fork's CI (particularly the transform-v2-it-part-2 E2E job that covers the new scenarios) comes back green for this head; no further code changes are needed from my read.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for keeping this branch current, @goutamadwant. I re-reviewed the current head f7f128b856c1 in full (the whole diff against dev, not just the merges). The commits added since my last review (136bb45795, f7f128b856) are dev sync merges, and I found nothing new, so there is nothing here that should have been caught earlier.
What Problem Does This PR Solve?
- User pain point: the six vector arithmetic functions (
VECTOR_NORM,INNER_PRODUCT,COSINE_DISTANCE,L1_DISTANCE,L2_DISTANCE,VECTOR_NORMALIZE) multiplied or subtractedFloatelements infloatprecision before widening, so finite inputs could overflow or underflow toInfinity,NaNor0.0. - Fix approach: cast one operand to
(double)before each multiplication or subtraction so the whole expression is evaluated indouble, in both the Calcite UDFs and the Zeta SQLVectorFunction. - One-sentence summary: a precision-widening fix for vector arithmetic, now re-synced with
devwith no change to the fix itself.
1. Code Change Review
1.1 Core Logic Analysis
I compared the PR's own added and removed lines at the current head against the version I last approved (78919dc7ec): the six Calcite UDF files, VectorFunction.java, the two e2e .conf files, the docs entries, and the four test classes carry the same changes. The only visible difference is four lines of test imports and a closing brace that no longer appear in this PR's diff, because identical lines were landed on dev by an unrelated change to the same test files (dev now also contains the ByteBuffer.duplicate() change in VectorFunction.convertToFloatArray and its own test cases, which is not part of this PR). I read the production diff again end to end and each changed site is the same (double) widening as before, for example:
double dotProduct =
IntStream.range(0, vector1.length)
.mapToDouble(i -> (double) vector1[i] * vector2[i])
.sum();Runtime path (re-confirmed): Sql transform -> SQLTransform.transformRow() -> VectorFunction.*, and Calcite transform -> CalciteSQLEngine -> CalciteUdf eval(...). Both are the normal paths for any job using these functions. The commit 340363ef27b (GET_JSON_OBJECT) that landed on dev after the last merge only adds a new UDF and docs sections, and does not modify the vector UDFs. The merged incompatible-changes.md (EN and ZH) keeps every entry from both sides, and I found no conflict markers in the touched trees.
1.2 Compatibility Impact
Fully compatible for return types, options and state. Low-order digits of results can change because accumulation is now in double; this is documented with migration guidance in both languages, unchanged.
1.3 Performance / Side-Effect Analysis
Unchanged: one extra float-to-double conversion per element, no allocation.
1.4 Error Handling and Logging
No exceptions or logs were added or modified. No issues.
2. Code Quality Assessment
- Coding standards: unchanged.
- Test coverage and stability: unchanged from my approval (parameterized finite-value cases, cancellation without overflow, special values, and SQL-level tests for both engines). Stability rating: Stable.
- Documentation:
docs/enanddocs/zhremain in lockstep.
3. Architectural Soundness
Precise fix. Fully compatible with historical versions apart from the documented precision improvement. As before, the duplicated vector math in the Calcite and Zeta engines is a non-blocking follow-up idea for a separate PR, and RANDOM_PROJECTION remains explicitly out of scope.
4. Issue Summary
No numbered issues. No blocking issues found.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers - must be fixed: none from the source side.
- CI on the current head (fork run for
f7f128b856):unit-teston Java 8 and 11 for ubuntu and windows,transform-v2-it-part-1/part-2(which run the new vector scenarios),engine-v2-it, and the license/dead-link checks are green. The overall run ended ascancelledbecausejdbc-connectors-it-part-4 (11)was cancelled,google-pubsub-connector-it (8)lost its runner ("The hosted runner lost communication with the server"), and a few other lanes were cancelled. Those are unrelated to vector arithmetic, so this reads as a runner or infrastructure issue (my inference from the job annotations). The lowest-cost next step is to re-run the failed and cancelled jobs for this head; the branch is 46 commits behinddev(GitHub reports no merge conflict), so syncing is optional. - From my side the source-level blocker is cleared and I see no new code-side blocker. Because I am a read-only reviewer, a maintainer with write access will still need to approve once CI is green.
Thanks again for the thorough work on this fix.
Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for syncing this branch with dev again, @goutamadwant, and sorry for the extra notification; our process re-reviews every new head. I re-reviewed the current head c828efd61d0 in full (the whole diff against dev). The only commit added since my last review (f7f128b856) is "Sync vector arithmetic with dev CI updates", and I found nothing new, so there is nothing here that should have been caught earlier.
What Problem Does This PR Solve?
- User pain point: the six vector arithmetic functions (
VECTOR_NORM,INNER_PRODUCT,COSINE_DISTANCE,L1_DISTANCE,L2_DISTANCE,VECTOR_NORMALIZE) multiplied or subtractedFloatelements infloatprecision before widening, so finite inputs could overflow or underflow toInfinity,NaNor0.0. - Fix approach: cast one operand to
(double)before each multiplication or subtraction, in both the Calcite UDFs and the Zeta SQLVectorFunction. - One-sentence summary: a precision-widening fix for vector arithmetic, re-synced with
dev(behind_by=0) with no change to the fix itself.
1. Code Change Review
1.1 Core Logic Analysis
The PR's own added and removed lines at this head match the head I last reviewed (only hunk offsets moved). I re-read the production diff end to end: every changed site is the same (double) widening in the six Calcite UDFs and in VectorFunction, for example:
.mapToDouble(i -> (double) vector1[i] * vector2[i])Runtime path (re-confirmed): Sql transform -> SQLTransform.transformRow() -> VectorFunction.*, and Calcite transform -> CalciteSQLEngine -> CalciteUdf eval(...); both are normal paths for jobs using these functions. Tests (VectorFunctionTest, SQLVectorFunctionTest, VectorUdfTest, CalciteSQLEngineTest) and the two e2e .conf files are unchanged. No conflict markers.
1.2 Compatibility Impact
Fully compatible for options, defaults, protocols and serialization. The only behavior change is the intended one (finite inputs no longer overflow in float), documented in incompatible-changes.md (EN and ZH).
1.3 Performance / Side-Effect Analysis
A float-to-double widening per element; negligible cost, no allocation, concurrency or resource effects.
1.4 Error Handling and Logging
Unchanged from my previous review, no new findings.
2. Code Quality, Tests and Architecture
- Coding standards and comments: unchanged from my previous review, no new findings.
- Tests: no change to the PR's own test files in this head; no new flakiness patterns introduced by this sync (stability rating unchanged: Stable).
- Docs: EN and ZH entries are still consistent with each other and with the code.
4. Issue Summary
No issues found on this head. I have no other reviewers' feedback to reconcile that is still open.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers - must be fixed: none from the source side.
- CI on the current head: the checks on the apache/seatunnel side are only the pointer jobs, and the real
Buildrun in your fork for this head is still in progress (https://github.com/goutamadwant/seatunnel/actions/runs/38092115617). Nothing has failed yet, so I have no CI diagnosis to give; the branch is not behinddev(behind_by=0) and GitHub reports it as mergeable with no conflicts, so no further sync is needed. Please re-run only the failed jobs if any unrelated lane goes red. - From my side the source-level blocker is cleared and I see no new code-side blocker. As a read-only reviewer I cannot change GitHub's review decision, so a maintainer with write access will still need to approve once CI is green.
Thanks again for the thorough work on this fix.
DanielLeens
left a comment
There was a problem hiding this comment.
Review conclusion
Reviewed commit: 4b256c8
No source-level blocking finding found in the complete diff scan. The arithmetic now widens each float operand before multiplication/subtraction, preventing intermediate float overflow in cosine distance, norms, inner product, and L1/L2 distance. The same contract is applied to Calcite UDFs and Zeta SQL functions, with unit and SQL-level coverage for the high-magnitude case and paired documentation/incompatible-change notes.
Compatibility: the deliberate behavior change affects vectors whose float intermediates overflow even though the double result is representable; it is documented.
Best change location: widening at every shared vector function is the correct boundary. Widening only a caller or one SQL engine would leave the other engine semantically divergent.
Validation performed: fetched the current ref; inspected all 19 changed files, vector arithmetic paths, tests, SQL configs, and bilingual documentation. No local build/test was run.
CI gate: Build is currently failing, so final merge remains blocked pending a green run.
Conclusion
No source-level blocking finding. Final merge gate: green CI required.
|
The CI fact cited in my previous review has changed: Build for the current unchanged head is now passing. CI was previously the only remaining blocker; CI is now passing, so my technical conclusion changes to approve. I do not see a new source-side blocker from Daniel's review. This branch is behind the latest dev base, which I have recorded as merge metadata only; because the current head CI is green, that fact alone does not call for an additional source change. I have read-only review controls, so this COMMENT does not change GitHub's displayed review decision; a write-capable maintainer must perform any final approval or dismissal action. |
DanielLeens
left a comment
There was a problem hiding this comment.
Re-checked current head 4b256c8bef9d, which is unchanged since my last review. In that review I found no source-level blocker, and the only remaining item was CI (my review recorded Build as failing). CI was previously the only remaining blocker, and it is now passing: the fork Build run 39008530099 completed with success for exactly this head SHA, and the apache-side Build check reports success as well. So my conclusion changes to approve. Thanks again for the careful vector-overflow fix, @goutamadwant!
Note: my reviewer account is read-only on this repository, so a maintainer with write access still needs to do the final merge. The branch being behind dev is merge metadata only and does not by itself need a source change.
davidzollo
left a comment
There was a problem hiding this comment.
基本信息
- 标题:[Fix][Transform-V2] Widen vector operands before arithmetic
- 中文释义:六个向量函数(Zeta SQL 与 Calcite UDF 两套)在乘法 / 减法前先把 float 提升为 double,避免中间结果溢出或下溢
- 作者:goutamadwant
- 目标分支:dev
- 变更量:+389 / -17,19 个文件
- 状态:OPEN,可合并
- Review 报告时间:2026-10-21 09:20:53 EDT (UTC-04:00)
- 本地分支:pr-12337(head
4b256c8bef9d) - PR 链接:#12337
PR 解决了什么问题(小白示例)
- 用户痛点:向量元素是 float。
COSINE_DISTANCE等函数里vector1[i] * vector2[i]先按 float 相乘,再加到 double 累加器。两个 1e20 的 float 相乘在 float 里已经是 Infinity,再转 double 也救不回来;很小的值相乘则变成 0。结果是有限输入得到 Infinity、NaN 或 0。 - 修复方式:在每个中间乘法 / 减法前加
(double),让运算在 double 中进行;累加器和返回类型保持不变。 - 一句话:向量距离 / 范数 / 归一化不再因为 float 中间溢出而算错。
一、代码变更审查
1.1 核心逻辑分析
变更内容精确描述
生产代码共 7 个文件,每处都是同一种改法:
calcite/udf/CosineDistanceFunction、InnerProductFunction、L1DistanceFunction、L2DistanceFunction、VectorNormFunction、VectorNormalizeFunctionsql/zeta/functions/VectorFunction(cosineDistance、l1Distance、l2Distance、vectorNorm、innerProduct、vectorNormalize)
修改前 / 修改后(以 VectorFunction.cosineDistance 为例):
// before
.mapToDouble(i -> vector1[i] * vector2[i])
// after
.mapToDouble(i -> (double) vector1[i] * vector2[i])(double) v1[i] * v2[i] 中强制转换优先级高于乘法,先把左操作数提升为 double,右操作数随之按二元数值提升为 double,整个乘法在 double 中完成。减法同理 (double) v1[i] - v2[i]。
调用方:ZetaSQLFunction.java:688-703 分发到 VectorFunction 的各方法;Calcite UDF 由 Calcite 引擎按名调用。两套实现本次同步修改。
关键发现
- 正常路径会命中:每个向量函数的每次调用都经过被修改的表达式;对不会溢出的常规向量,结果只在低位数字上可能有差异(double 乘法比 float 乘法更精确),文档已说明。
- 改法最小且正确:只改中间运算的精度,不改累加器、返回类型、null 处理和零向量分支(
norm == 0.0返回 1.0 保留)。 - 两套实现(Zeta SQL 与 Calcite)同步修改,避免了同一函数在不同 engine 下结果不同。
- 精准修复,不是规避。
逻辑正确性深度分析
- 对
Float包装类型,(double) vector1[i]是拆箱后加宽,Java 转换上下文允许;null 元素的 NPE 行为与旧代码一致(旧代码同样拆箱)。 VectorNormalizeFunction中magnitude += (double) value * value在value != null分支内,null 处理不变;归一化输出仍是 float。- 不加入非有限值校验:输入本身含 Infinity/NaN 时结果仍可能非有限,作者文档化并有测试。
1.2 兼容性影响
部分不兼容(行为修正):结果的低位数字可能变化,之前因中间溢出得到的 Infinity/NaN/0 变为正确有限值。无 API、配置、schema、依赖、状态格式变化。EN/ZH incompatible-changes.md、sql-functions.md、calcite.md 已更新。
1.3 性能 / 副作用分析
float 乘法换成 double 乘法,现代 JVM 上开销可忽略;无额外分配。无并发副作用。
1.4 错误处理与日志
维度不匹配仍抛原异常;无日志变化。
1.5 引擎改动专项检查
不适用。
二、代码质量评估
2.1 代码规范
改动极小且一致;无新增注释需求。
2.2 测试覆盖
- 单测:
VectorFunctionTest(+97)、VectorUdfTest(+69)覆盖溢出 / 下溢输入、常规输入、含 Infinity 的混合输入。 - SQL 层:
SQLVectorFunctionTest(+35)、CalciteSQLEngineTest(+36)。 - E2E:
func_vector.conf(+51)与calcite_builtin_functions.conf(+24)增加极值向量。 - 回归:两套引擎都有覆盖,能发现任一套漏改。
本地验证结果
git fetch upstream pull/12337/head:pr-12337:通过;head4b256c8bef9d。git diff --stat upstream/dev...pr-12337:通过;19 个文件,+389 / -17。git diff upstream/dev...pr-12337 -- 'seatunnel-transforms-v2/src/main/**':通过;逐行阅读全部 7 个生产文件。rg -n "VectorFunction\.\w+\(" seatunnel-transforms-v2/src/main:通过;调用方为ZetaSQLFunction.java:688-703。gh pr checks 12337:通过;BuildSUCCESS。- 编译 / 测试:未执行。原因:Review PR 默认不做本地编译;运行验证以当前 head 的 GitHub CI 为准。
2.3 文档更新
EN/ZH 三组文档均已更新,与代码一致。
三、架构合理性
3.1 解决方案的优雅性
最佳改动位置评估
- 当前改动位置:各向量函数的中间运算表达式。
- 根因位置:同一处,float 中间运算。
- 是否为最佳改动:是。把向量统一转成
double[]再计算是另一种写法,但会增加一次数组拷贝且改动面更大;在表达式处加宽是最小且语义等价的修法。 - 全局最佳改动位置:同当前位置。
- 最小安全改动与全局最佳改动:一致。
- Merge 影响:精准修复,不阻塞。
3.2 可维护性
改法统一,后续新增向量函数照此写即可;建议未来在 VectorUtils 提供 double 视图以避免再次遗漏,但不属于本 PR。
3.3 扩展性
不引入新抽象,合理。
3.4 历史版本兼容性
行为修正已记录;无迁移步骤。
四、问题汇总
全量问题穷尽自检
- PR diff / changed files:19 个文件已逐项审查完(7 个生产文件逐行,测试与文档按内容核对)。
- 关键调用链:
ZetaSQLFunction -> VectorFunction.*与 Calcite UDF,已追踪。 - 根因 / 当前改动位置 / 最佳改动位置 / 方案取舍:已判断。
- 兼容性 / 升级路径 / 协议或配置契约:行为修正已文档化。
- 测试分层 / 文档 / 示例 / 默认配置:已核对。
- Whale 协同仓库:不涉及。
- CI / Review / 冲突 gate:
BuildSUCCESS,DanielLeens 已 APPROVE,无冲突。 - 无法审查范围:无。
未发现阻塞性问题。剩余风险:输入本身含非有限值时结果仍可能非有限(既有行为,已文档化)。
五、是否可以 Merge 的结论
结论:可以 merge
阻塞项(必须修复):无。
建议修复(非阻塞):无。
整体评价:最小、一致且语义正确的精度修复,两套引擎同步,四层测试覆盖,文档完整,CI 已绿。
|
Thanks for the additional review. My previous source-level conclusion on the unchanged head remains clear, and the current Build is green. GitHub now reports actual merge conflicts against Status evidence: head |
Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for syncing the latest dev, @goutamadwant. The new head 27727ce63323 merges dev (9ab97e15f33c) into the head I approved last time (4b256c8bef9d), and it resolves the merge conflict I flagged on 2026-10-22. I re-reviewed the full diff against dev. Comparing the PR-owned patch before and after the merge, the only differences are context lines from new upstream entries in incompatible-changes.md. None of the vector functions, tests, E2E configs or docs changed. Both EN and ZH incompatible-changes.md keep all upstream entries (including the Helm REST API v1 note in ZH), your section is added cleanly, and no conflict markers remain.
What Problem Does This PR Solve?
- User pain point: vector elements are
float. Expressions likevector1[i] * vector2[i]were evaluated in float before being added to a double accumulator. So1e20f * 1e20fwas alreadyInfinity, and tiny products underflowed to0, and finite inputs produced Infinity, NaN or 0. - Fix approach: widen the left operand to
doublebefore every intermediate multiplication or subtraction, in both the Zeta SQL functions and the Calcite UDFs. Accumulators and return types stay unchanged. - One-sentence summary: vector norms, distances, inner products and normalization no longer break on float intermediate overflow or underflow.
1. Code Change Review
1.1 Core Logic Analysis
Changed production files (same pattern everywhere):
transform/sql/zeta/functions/VectorFunction.java(cosineDistance 58-61, l1Distance 93, l2Distance 123, vectorNorm 159, innerProduct 185, vectorNormalize 298)transform/calcite/udf/CosineDistanceFunction.java:56-59,InnerProductFunction.java:53,L1DistanceFunction.java:53,L2DistanceFunction.java:56,VectorNormFunction.java:45,VectorNormalizeFunction.java:47
// before
.mapToDouble(i -> vector1[i] * vector2[i])
// after
.mapToDouble(i -> (double) vector1[i] * vector2[i])Runtime path:
Sql transform (ZETA engine)
-> ZetaSQLFunction.executeFunctionExpr (case COSINE_DISTANCE / L1_DISTANCE / ... : 687-703)
-> VectorFunction.<fn> -> widened double intermediates
Sql transform (CALCITE engine)
-> CalciteUdf implementations (COSINE_DISTANCE, ...) -> widened double intermediates
Key findings:
- The cast binds tighter than
*/-, so the whole intermediate expression runs in double. - For
Floatwrappers, the change unboxes and then widens. A null element still raises the same NPE as before, so null handling is unchanged. - Zero-vector handling (
norm == 0.0) and the float output of normalize ((float) (vector[i] / magnitude)) are unchanged. - I checked the remaining float arithmetic in these files. Only the random/sparse projection scale factors stay float, which matches the documented scope.
- Both engines are fixed together, which avoids divergent results between ZETA and CALCITE.
1.2 Compatibility Impact
Partially incompatible (a documented behavior correction). Results can differ in their low-order digits, and results that previously overflowed or underflowed now become correct finite values. There are no option, type, schema, API or state-format changes. EN/ZH incompatible-changes.md, sql-functions.md and calcite.md are updated.
1.3 Performance / Side-Effect Analysis
The change swaps float multiplications for double ones, with no extra allocation. The cost is negligible, and there is no concurrency impact.
1.4 Error Handling and Logging
Dimension-mismatch errors are unchanged, and there are no logging changes. No issue found.
2. Code Quality Assessment
2.1 Coding Standards
The edits are minimal and consistent, and no new non-trivial methods or fields are added. No issue found.
2.2 Test Coverage and Test Stability
VectorFunctionTestandVectorUdfTestadd parameterized finite-arithmetic cases (testFiniteVectorArithmetic), plustestLargeProductsCancelWithoutOverflowandtestVectorArithmeticSpecialValues. Reverting any one widening cast makes the corresponding overflow case fail.- SQL level:
SQLVectorFunctionTest.testFiniteVectorArithmeticThroughSqlandCalciteSQLEngineTest. E2E:func_vector.confandcalcite_builtin_functions.confadd extreme-magnitude vectors. - Stability rating: Stable. The tests are pure and deterministic, with no timing or port dependence.
2.3 Documentation Updates
EN and ZH are both updated and accurate: no non-finite input sanitization, normalize output stays float, and random projection is unaffected.
3. Architectural Soundness
3.1 Elegance
Precise fix at the exact expressions that overflow. Converting whole vectors to double[] first would add an array copy and a larger diff for the same semantics.
3.2 Maintainability
The pattern is uniform. As a possible future follow-up (not for this PR), a shared double-view helper in the vector utilities would stop new functions from repeating the mistake.
3.3 Extensibility
No new abstractions. Appropriate for the scope.
3.4 Historical-Version Compatibility
No checkpoint, serialization or config impact. The behavior correction is documented.
4. Issue Summary
| No. | Issue | Location | Severity |
|---|---|---|---|
| - | No blocking issues found | - | - |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers (must fix): none on the source side. The only remaining gate is CI: fork
Buildrun40063639075for27727ce63323is still queued, so there is no result on this head yet. - Recommended fixes (non-blocking): none.
- Overall assessment: a minimal, consistent and semantically correct precision fix across both SQL engines, with unit, SQL-level and E2E coverage and complete bilingual docs. I will convert this to an approval once CI on this head is green.
- Better alternative? None for this scope.
- Residual risk: inputs that already contain non-finite elements can still produce non-finite results. That is existing behavior, and it is documented.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks again for the contribution. The CI fact in my previous guidance has changed: Build is now SUCCESS on the unchanged head 27727ce633239f72f1fb73f2a28254da8370ea2c. The earlier pending/failed-run guidance is superseded; no extra rerun is needed for this head.
My latest technical assessment had no outstanding source blocker and left CI as the remaining check gate. That CI gate has now cleared, so my technical conclusion is non-blocking. Any suggestions already identified as non-blocking remain optional; this is a CI/review-state update, not a new full source review or a claim of local test execution.
GitHub currently reports BLOCKED / REVIEW_REQUIRED. I have READ repository permission, so I cannot supply the effective write-capable approval/dismissal required by the repository. A maintainer with write access must perform that final step; this COMMENT is not an APPROVED review. Historical requested-changes entries, if still visible, must be read separately from this latest technical conclusion. The branch is diverged against dev (ahead 9, behind 8); that drift is recorded only and is not a reason to sync while CI is green.
|
@nzw921rx can you approve the workflow runs? thanks! |
Done. |
|
Thanks for the fix. I reviewed head Correctness and scopeThe fix addresses the arithmetic at the correct boundary: widening an operand before multiplication or subtraction prevents the intermediate operation from overflowing or underflowing in float precision. All six affected functions are updated consistently in both Zeta SQL and Calcite:
The production changes introduce no mutable shared state or input mutation. Return types, configuration, schemas and checkpoint/state formats remain unchanged. Local validationThe PR was merged locally with dev
The regression cases cover large and tiny finite operands, minimum normal and subnormal values, cancellation of large products, ordinary decimal values, zero/empty vectors, null inputs and non-finite values. They also exercise actual SQL and Calcite query evaluation. Compatibility and CIThis is a numerical behavior correction: ordinary inputs can also produce different low-order digits because intermediate operations retain greater precision. The bilingual documentation describes this change. Normalized output elements remain float, so output rounding and underflow remain possible. The exact-head Build and the relevant Transform E2E jobs passed. The E2E results were verified in CI; container E2E tests were not rerun locally. LGTM. |
Purpose of this pull request
Closes #12336.
Widen float operands before intermediate products and differences in six SQL vector functions and their equivalent Calcite UDFs. The existing double accumulators and return types are retained.
Extend existing function/SQL tests, both E2E fixtures, EN/ZH function documentation and the incompatible-changes pages.
Does this PR introduce any user-facing change?
Yes. Finite vectors no longer produce incorrect infinity, NaN or zero merely because an intermediate float operation overflows or underflows. Results, including low-order digits, can change; review thresholds and previously computed vector metrics before replaying data.
No API, configuration, schema, dependency or state-format changes. NULL and actual zero handling remain in place. Normalized output remains float. No nonfinite validation policy is added, but corrected finite intermediates can affect mixed nonfinite results; the tiny-vector/infinity cosine case is documented and tested. Random projection is unchanged. Reproduced on current dev; released versions were not separately tested.
How was this patch tested?
Check list