Fix #5164: Detect integer/long overflow using Calcite's native checked arithmetic#5204
Fix #5164: Detect integer/long overflow using Calcite's native checked arithmetic#5204penghuo wants to merge 1 commit intoopensearch-project:mainfrom
Conversation
PR Reviewer Guide 🔍(Review updated until commit 59578cf)Here are some key observations to aid the review process:
|
PR Code Suggestions ✨Latest suggestions up to 59578cf
Previous suggestionsSuggestions up to commit 8714c88
|
…te's native checked arithmetic Use Calcite's ConvertToChecked visitor to rewrite PLUS/MINUS/TIMES operators to their overflow-safe CHECKED variants. These generate Math.addExact/ subtractExact/multiplyExact calls that throw ArithmeticException on overflow. Add plugins.calcite.checked_arithmetic.enabled setting (default: true) to control this behavior. ArithmeticException is caught at the QueryService level and wrapped in NonFallbackCalciteException to prevent silent fallback to V2 engine. Update PPLAggregateConvertRule and OpenSearchRelOptUtil to also match CHECKED_PLUS/CHECKED_MINUS/CHECKED_TIMES SqlKinds. Signed-off-by: Peng Huo <penghuo@gmail.com>
|
Persistent review updated to latest commit 59578cf |
Description
Use Calcite's built-in
ConvertToCheckedvisitor to rewrite arithmetic operators(
PLUS/MINUS/TIMES) to their overflow-safeCHECKEDvariants. These generateSqlFunctions.checkedPlus(int, int)→Math.addExact()calls that throwArithmeticExceptionon integer/long overflow instead of silently wrapping.Root cause: Standard Calcite operators (
SqlStdOperatorTable.PLUS/MINUS/MULTIPLY)generate plain Java
+/-/*in the Enumerable code path, which silently wrapon overflow (e.g.,
2147483647 + 1returns-2147483648). This is also the defaultbehavior in Calcite itself — confirmed by testing with CsvTest.
Approach: Calcite 1.41.0 provides a native solution via
SqlConformance.checkedArithmetic()and the
ConvertToCheckedRelNode visitor. This PR applies that visitor in thequery execution pipeline, controlled by a new
plugins.calcite.checked_arithmetic.enabledsetting (default:
true).How it works:
ConvertToCheckedrewritesPLUS → CHECKED_PLUS,MINUS → CHECKED_MINUS,TIMES → CHECKED_MULTIPLYin the RelNode treeSqlFunctions.checkedPlus(int, int)callsthat use
Math.addExact()internallyArithmeticExceptionis caught at theQueryServicelevel and wrapped inNonFallbackCalciteExceptionto prevent silent fallback to the V2 engineComparison with custom UDF approach: This replaces the initial approach of creating
custom UDF operators (AddFunction, SubtractFunction, MultiplyFunction). The native
Calcite approach is simpler (46 lines vs 484 lines), avoids boxing overhead, and
also covers division and unary minus overflow.
Related Issues
#5164
Check List
--signoffor-s.By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.