-
Notifications
You must be signed in to change notification settings - Fork 213
[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
1
commit 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
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
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
78 changes: 78 additions & 0 deletions
78
core/src/main/java/org/opensearch/sql/expression/function/udf/CheckedLongNarrowFunction.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,78 @@ | ||
| /* | ||
| * Copyright OpenSearch Contributors | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|
|
||
| package org.opensearch.sql.expression.function.udf; | ||
|
|
||
| import java.math.BigDecimal; | ||
| import java.util.List; | ||
| import org.apache.calcite.adapter.enumerable.NotNullImplementor; | ||
| import org.apache.calcite.adapter.enumerable.NullPolicy; | ||
| import org.apache.calcite.adapter.enumerable.RexToLixTranslator; | ||
| import org.apache.calcite.linq4j.tree.Expression; | ||
| import org.apache.calcite.linq4j.tree.Expressions; | ||
| import org.apache.calcite.rex.RexCall; | ||
| import org.apache.calcite.sql.type.ReturnTypes; | ||
| import org.apache.calcite.sql.type.SqlReturnTypeInference; | ||
| import org.opensearch.sql.calcite.utils.PPLOperandTypes; | ||
| import org.opensearch.sql.expression.function.ImplementorUDF; | ||
| import org.opensearch.sql.expression.function.UDFOperandMetadata; | ||
|
|
||
| /** | ||
| * Narrows a numeric SUM accumulator (widened to DECIMAL/double so it does not wrap) back to BIGINT, | ||
| * raising an error when the value overflowed the BIGINT range instead of wrapping to a negative | ||
| * value. | ||
| * | ||
| * <p>SUM over a BIGINT column is accumulated as a wider type to avoid the silent {@code long} | ||
| * two's-complement wrap near 2^63. This function restores the declared BIGINT output type. A value | ||
| * whose magnitude clearly exceeds {@code 2^63} is treated as overflow and surfaces as a client | ||
| * error. Because OpenSearch computes pushed-down sums in {@code double}, {@code (double) | ||
| * Long.MAX_VALUE} rounds to exactly {@code 2^63} and cannot be distinguished from a small overflow; | ||
| * to avoid erroring on a legitimate near-{@code Long.MAX_VALUE} sum, only magnitudes strictly | ||
| * beyond {@code 2^63} are rejected, and in-range values saturate on narrowing rather than wrap. | ||
| * This makes the pushdown and in-memory paths behave identically. | ||
| */ | ||
| public class CheckedLongNarrowFunction extends ImplementorUDF { | ||
| public CheckedLongNarrowFunction() { | ||
| super(new CheckedLongNarrowImplementor(), NullPolicy.ANY); | ||
| } | ||
|
|
||
| @Override | ||
| public SqlReturnTypeInference getReturnTypeInference() { | ||
| return ReturnTypes.BIGINT_FORCE_NULLABLE; | ||
| } | ||
|
|
||
| @Override | ||
| public UDFOperandMetadata getOperandMetadata() { | ||
| return PPLOperandTypes.NUMERIC; | ||
| } | ||
|
|
||
| /** {@code 2^63}, the first magnitude beyond the signed BIGINT range. */ | ||
| private static final double TWO_POW_63 = 0x1p63; | ||
|
|
||
| /** Narrow a widened sum value to a long, erroring when it overflowed the BIGINT range. */ | ||
| public static long narrow(Object value) { | ||
| double magnitude = ((Number) value).doubleValue(); | ||
| if (magnitude > TWO_POW_63 || magnitude < -TWO_POW_63) { | ||
| throw new ArithmeticException("BIGINT overflow in SUM"); | ||
| } | ||
| if (value instanceof BigDecimal decimal) { | ||
| // Exact for the in-memory (DECIMAL) path; clamps a value that rounds to exactly 2^63. | ||
| return decimal | ||
| .min(BigDecimal.valueOf(Long.MAX_VALUE)) | ||
| .max(BigDecimal.valueOf(Long.MIN_VALUE)) | ||
| .longValue(); | ||
| } | ||
| // double path (pushed-down sum): saturating narrow (JLS 5.1.3) clamps 2^63 to Long.MAX_VALUE. | ||
| return (long) magnitude; | ||
| } | ||
|
|
||
| public static class CheckedLongNarrowImplementor implements NotNullImplementor { | ||
| @Override | ||
| public Expression implement( | ||
| RexToLixTranslator translator, RexCall call, List<Expression> translatedOperands) { | ||
| return Expressions.call(CheckedLongNarrowFunction.class, "narrow", translatedOperands.get(0)); | ||
| } | ||
| } | ||
| } |
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
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?
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 handles scalar arithmetic such as a + b. Calcite represents that operation as a visible RexCall(PLUS, a, b), so we can replace it with
CHECKED_PLUS, which executes using Math.addExact.SUM is represented as an
AggregateCall; its repeated additions happen internally inside Calcite’s aggregate accumulator, so there are no individualPLUSnodes for #5604’s rewrite to replace. UsingMath.addExactwould require a custom aggregate implementation, would not apply to native OpenSearch pushdown, and could report an order-dependent intermediate overflow even when the final mathematical sum fits.Therefore, the no-pushdown path accumulates BIGINT values in a wider DECIMAL, then checks and narrows the final result back to BIGINT. Keeping the standard SUM operator also preserves the existing pushdown optimizations.