-
Notifications
You must be signed in to change notification settings - Fork 214
[BugFix] Detect BIGINT overflow in SUM and fix wrong AVG on the Calcite engine #5612
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ahkcs
wants to merge
9
commits into
opensearch-project:main
Choose a base branch
from
ahkcs:fix/sum-avg-bigint-overflow
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e559663
Detect BIGINT overflow in SUM and fix wrong AVG on the Calcite engine
ahkcs 21c5910
Use checked long accumulator for BIGINT SUM
ahkcs 24eaea6
Fix checked BIGINT SUM CI expectations
ahkcs 8f2a150
Update checked aggregation CI expectations
ahkcs efbc261
Apply checked sum to all integral types
ahkcs 1b981f2
Update integral checked sum unit plans
ahkcs 9fc45d9
Use native sum for checked aggregation pushdown
ahkcs 481819a
Preserve native aggregation pushdown
ahkcs 47145b5
Address aggregation overflow review comments
ahkcs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
core/src/main/java/org/opensearch/sql/calcite/udf/udaf/BigintAvgAggFunction.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| /* | ||
| * Copyright OpenSearch Contributors | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| package org.opensearch.sql.calcite.udf.udaf; | ||
|
|
||
| /** BIGINT average aggregate that accumulates in double to avoid an intermediate long overflow. */ | ||
| public class BigintAvgAggFunction { | ||
|
|
||
| public static Accumulator init() { | ||
| return new Accumulator(); | ||
| } | ||
|
|
||
| public static Accumulator add(Accumulator accumulator, Long value) { | ||
| if (value != null) { | ||
| accumulator.sum += value; | ||
| accumulator.count++; | ||
| } | ||
| return accumulator; | ||
| } | ||
|
|
||
| public static Double result(Accumulator accumulator) { | ||
| return accumulator.count == 0 ? null : accumulator.sum / accumulator.count; | ||
| } | ||
|
|
||
| public static class Accumulator { | ||
| private double sum; | ||
| private long count; | ||
| } | ||
| } |
22 changes: 22 additions & 0 deletions
22
core/src/main/java/org/opensearch/sql/calcite/udf/udaf/CheckedLongSumAggFunction.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| /* | ||
| * Copyright OpenSearch Contributors | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| package org.opensearch.sql.calcite.udf.udaf; | ||
|
|
||
| /** BIGINT sum aggregate that throws when its running long accumulator overflows. */ | ||
| public class CheckedLongSumAggFunction { | ||
|
|
||
| public static long init() { | ||
| return 0L; | ||
| } | ||
|
|
||
| public static long add(long accumulator, long value) { | ||
| return Math.addExact(accumulator, value); | ||
| } | ||
|
|
||
| public static long result(long accumulator) { | ||
| return accumulator; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -283,6 +283,7 @@ | |
| import java.util.Optional; | ||
| import java.util.StringJoiner; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.function.Function; | ||
| import java.util.regex.Pattern; | ||
| import java.util.regex.PatternSyntaxException; | ||
| import java.util.stream.Collectors; | ||
|
|
@@ -1595,23 +1596,45 @@ void register( | |
| } | ||
|
|
||
| void registerOperator(BuiltinFunctionName functionName, SqlAggFunction aggFunction) { | ||
| SqlOperandTypeChecker innerTypeChecker = extractTypeCheckerFromUDF(aggFunction); | ||
| registerOperator(functionName, aggFunction, field -> aggFunction); | ||
| } | ||
|
|
||
| void registerOperator( | ||
| BuiltinFunctionName functionName, | ||
| SqlAggFunction typeCheckerSource, | ||
| Function<RexNode, SqlAggFunction> aggFunctionSelector) { | ||
| SqlOperandTypeChecker innerTypeChecker = extractTypeCheckerFromUDF(typeCheckerSource); | ||
| PPLTypeChecker typeChecker = | ||
| wrapSqlOperandTypeChecker(innerTypeChecker, functionName.name(), true); | ||
| AggHandler handler = | ||
| (distinct, field, argList, ctx) -> { | ||
| List<RexNode> newArgList = | ||
| argList.stream().map(PlanUtils::derefMapCall).collect(Collectors.toList()); | ||
| return UserDefinedFunctionUtils.makeAggregateCall( | ||
| aggFunction, List.of(field), newArgList, ctx.relBuilder); | ||
| aggFunctionSelector.apply(field), List.of(field), newArgList, ctx.relBuilder); | ||
| }; | ||
| register(functionName, handler, typeChecker); | ||
| } | ||
|
|
||
| /** Registers checked integral sums while retaining standard SUM behavior for other types. */ | ||
| void registerSumOperator() { | ||
| registerOperator( | ||
| SUM, | ||
| SqlStdOperatorTable.SUM, | ||
| field -> | ||
| isIntegral(field.getType().getSqlTypeName()) | ||
| ? PPLBuiltinOperators.CHECKED_LONG_SUM | ||
| : SqlStdOperatorTable.SUM); | ||
| } | ||
|
|
||
| private static boolean isIntegral(SqlTypeName typeName) { | ||
| return SqlTypeName.INT_TYPES.contains(typeName); | ||
| } | ||
|
Comment on lines
+1630
to
+1632
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use "SqlTypeName.INT_TYPES.contains(...)"
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Updated |
||
|
|
||
| void populate() { | ||
| registerOperator(MAX, SqlStdOperatorTable.MAX); | ||
| registerOperator(MIN, SqlStdOperatorTable.MIN); | ||
| registerOperator(SUM, SqlStdOperatorTable.SUM); | ||
| registerSumOperator(); | ||
| registerOperator(VARSAMP, PPLBuiltinOperators.VAR_SAMP_NULLABLE); | ||
| registerOperator(VARPOP, PPLBuiltinOperators.VAR_POP_NULLABLE); | ||
| registerOperator(STDDEV_SAMP, PPLBuiltinOperators.STDDEV_SAMP_NULLABLE); | ||
|
|
@@ -1630,7 +1653,14 @@ void populate() { | |
|
|
||
| register( | ||
| AVG, | ||
| (distinct, field, argList, ctx) -> ctx.relBuilder.avg(distinct, null, field), | ||
| (distinct, field, argList, ctx) -> { | ||
| if (field.getType().getSqlTypeName() == SqlTypeName.BIGINT) { | ||
| return ctx.relBuilder | ||
| .aggregateCall(PPLBuiltinOperators.BIGINT_AVG, field) | ||
| .distinct(distinct); | ||
| } | ||
| return ctx.relBuilder.avg(distinct, null, field); | ||
| }, | ||
| wrapSqlOperandTypeChecker( | ||
| SqlStdOperatorTable.AVG.getOperandTypeChecker(), AVG.name(), false)); | ||
|
|
||
|
|
||
44 changes: 44 additions & 0 deletions
44
core/src/test/java/org/opensearch/sql/calcite/udf/udaf/BigintAvgAggFunctionTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| /* | ||
| * Copyright OpenSearch Contributors | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| package org.opensearch.sql.calcite.udf.udaf; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertNull; | ||
|
|
||
| import org.apache.calcite.sql.SqlKind; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.opensearch.sql.expression.function.PPLBuiltinOperators; | ||
|
|
||
| class BigintAvgAggFunctionTest { | ||
|
|
||
| @Test | ||
| void retainsAvgKindForPushdownRules() { | ||
| assertEquals(SqlKind.AVG, PPLBuiltinOperators.BIGINT_AVG.getKind()); | ||
| } | ||
|
|
||
| @Test | ||
| void averagesWithoutLongOverflow() { | ||
| BigintAvgAggFunction.Accumulator accumulator = BigintAvgAggFunction.init(); | ||
| accumulator = BigintAvgAggFunction.add(accumulator, Long.MAX_VALUE); | ||
| accumulator = BigintAvgAggFunction.add(accumulator, Long.MAX_VALUE); | ||
|
|
||
| assertEquals((double) Long.MAX_VALUE, BigintAvgAggFunction.result(accumulator)); | ||
| } | ||
|
|
||
| @Test | ||
| void ignoresNulls() { | ||
| BigintAvgAggFunction.Accumulator accumulator = BigintAvgAggFunction.init(); | ||
| accumulator = BigintAvgAggFunction.add(accumulator, null); | ||
| accumulator = BigintAvgAggFunction.add(accumulator, 10L); | ||
|
|
||
| assertEquals(10D, BigintAvgAggFunction.result(accumulator)); | ||
| } | ||
|
|
||
| @Test | ||
| void returnsNullForEmptyInput() { | ||
| assertNull(BigintAvgAggFunction.result(BigintAvgAggFunction.init())); | ||
| } | ||
| } |
42 changes: 42 additions & 0 deletions
42
core/src/test/java/org/opensearch/sql/calcite/udf/udaf/CheckedLongSumAggFunctionTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| /* | ||
| * Copyright OpenSearch Contributors | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| package org.opensearch.sql.calcite.udf.udaf; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
|
|
||
| import org.apache.calcite.sql.SqlKind; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.opensearch.sql.expression.function.PPLBuiltinOperators; | ||
|
|
||
| class CheckedLongSumAggFunctionTest { | ||
|
|
||
| @Test | ||
| void retainsSumKindForPlannerRules() { | ||
| assertEquals(SqlKind.SUM, PPLBuiltinOperators.CHECKED_LONG_SUM.getKind()); | ||
| } | ||
|
|
||
| @Test | ||
| void sumsExactly() { | ||
| long accumulator = CheckedLongSumAggFunction.init(); | ||
| accumulator = CheckedLongSumAggFunction.add(accumulator, 1L << 62); | ||
| accumulator = CheckedLongSumAggFunction.add(accumulator, 1L); | ||
|
|
||
| assertEquals((1L << 62) + 1L, CheckedLongSumAggFunction.result(accumulator)); | ||
| } | ||
|
|
||
| @Test | ||
| void throwsOnPositiveOverflow() { | ||
| assertThrows( | ||
| ArithmeticException.class, () -> CheckedLongSumAggFunction.add(Long.MAX_VALUE, 1L)); | ||
| } | ||
|
|
||
| @Test | ||
| void throwsOnNegativeOverflow() { | ||
| assertThrows( | ||
| ArithmeticException.class, () -> CheckedLongSumAggFunction.add(Long.MIN_VALUE, -1L)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#5604 use Math.addExact to detect overflow. Why Sum choose another approach?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#5604 and this PR now use the same checked-addition primitive, but at different planner levels.
#5604 handles scalar arithmetic such as
a + b. Calcite exposes it asRexCall(PLUS, a, b), so it can be rewritten toCHECKED_PLUS, which callsMath.addExactonce.SUMis anAggregateCall; its internal additions are not visiblePLUSnodes, so the scalar rewrite cannot intercept them. We now solve that with a customCHECKED_LONG_SUMaggregate:CheckedLongSumAggFunctioncallsMath.addExact(accumulator, value)for every row.checked_long_sumcallsMath.addExactduring shard accumulation and coordinator reduction, and transports exactlongvalues.TINYINT,SMALLINT,INTEGER, andBIGINTinputs all use this checked BIGINT accumulator.This intentionally fails on an intermediate overflow even if later values would bring the final mathematical sum back into range. For example,
Long.MAX_VALUE, 1, -1throws atLong.MAX_VALUE + 1. We consider that fail-fast, order-dependent behavior acceptable and consistent with checked Java/Spark-style accumulation.