From adc2f1c5b34a02f02b51d696badc64fb04837f4d Mon Sep 17 00:00:00 2001 From: Harshil Valecha Date: Sat, 5 Dec 2026 13:00:43 +0530 Subject: [PATCH] [#39751] Stop rounding Beam SQL AVG to 10 significant digits AVG divided every sum with MathContext(10), so an average over one row did not equal that row and a BIGINT average near Long.MAX_VALUE came back with the opposite sign. Divide integer sums exactly to an integral result, truncating toward zero as integer division does, and DECIMAL sums with 34 significant digits. --- .../transform/BeamBuiltinAggregations.java | 31 +++++-- .../BeamBuiltinAggregationsTest.java | 85 +++++++++++++++++++ 2 files changed, 110 insertions(+), 6 deletions(-) create mode 100644 sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/impl/transform/BeamBuiltinAggregationsTest.java diff --git a/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/transform/BeamBuiltinAggregations.java b/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/transform/BeamBuiltinAggregations.java index f79527e4da63..147ac5cda2b7 100644 --- a/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/transform/BeamBuiltinAggregations.java +++ b/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/transform/BeamBuiltinAggregations.java @@ -90,7 +90,12 @@ public class BeamBuiltinAggregations { .put("COUNTIF", typeName -> CountIf.combineFn()) .build(); - private static MathContext mc = new MathContext(10, RoundingMode.HALF_UP); + /** + * The precision of a DECIMAL average, the 34 digits of IEEE 754 decimal128. Integer averages are + * divided exactly instead, see {@link Avg#prepareIntegralOutput}. + */ + private static final MathContext DECIMAL_AVG_CONTEXT = + new MathContext(MathContext.DECIMAL128.getPrecision(), RoundingMode.HALF_UP); public static CombineFn create(String functionName, Schema.FieldType fieldType) { @@ -466,7 +471,19 @@ public Coder> getAccumulatorCoder( } protected BigDecimal prepareOutput(KV accumulator) { - return accumulator.getValue().divide(new BigDecimal(accumulator.getKey()), mc); + return accumulator + .getValue() + .divide(new BigDecimal(accumulator.getKey()), DECIMAL_AVG_CONTEXT); + } + + /** + * Divides the exact sum of integer inputs to an integral average, truncating toward zero as + * integer division does, so the average of any values of an integer type fits that type. + */ + protected BigDecimal prepareIntegralOutput(KV accumulator) { + return accumulator + .getValue() + .divide(new BigDecimal(accumulator.getKey()), 0, RoundingMode.DOWN); } @Override @@ -478,7 +495,7 @@ protected BigDecimal prepareOutput(KV accumulator) { static class IntegerAvg extends Avg { @Override public @Nullable Integer extractOutput(KV accumulator) { - return accumulator.getKey() == 0 ? null : prepareOutput(accumulator).intValue(); + return accumulator.getKey() == 0 ? null : prepareIntegralOutput(accumulator).intValueExact(); } @Override @@ -490,7 +507,7 @@ public BigDecimal toBigDecimal(Integer record) { static class LongAvg extends Avg { @Override public @Nullable Long extractOutput(KV accumulator) { - return accumulator.getKey() == 0 ? null : prepareOutput(accumulator).longValue(); + return accumulator.getKey() == 0 ? null : prepareIntegralOutput(accumulator).longValueExact(); } @Override @@ -502,7 +519,9 @@ public BigDecimal toBigDecimal(Long record) { static class ShortAvg extends Avg { @Override public @Nullable Short extractOutput(KV accumulator) { - return accumulator.getKey() == 0 ? null : prepareOutput(accumulator).shortValue(); + return accumulator.getKey() == 0 + ? null + : prepareIntegralOutput(accumulator).shortValueExact(); } @Override @@ -514,7 +533,7 @@ public BigDecimal toBigDecimal(Short record) { static class ByteAvg extends Avg { @Override public @Nullable Byte extractOutput(KV accumulator) { - return accumulator.getKey() == 0 ? null : prepareOutput(accumulator).byteValue(); + return accumulator.getKey() == 0 ? null : prepareIntegralOutput(accumulator).byteValueExact(); } @Override diff --git a/sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/impl/transform/BeamBuiltinAggregationsTest.java b/sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/impl/transform/BeamBuiltinAggregationsTest.java new file mode 100644 index 000000000000..c919d7c63c4d --- /dev/null +++ b/sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/impl/transform/BeamBuiltinAggregationsTest.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.beam.sdk.extensions.sql.impl.transform; + +import static org.junit.Assert.assertEquals; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.transforms.Combine.CombineFn; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for the {@code AVG} aggregations in {@link BeamBuiltinAggregations}. */ +@RunWith(JUnit4.class) +public class BeamBuiltinAggregationsTest { + + @SuppressWarnings("unchecked") + private static T avg(FieldType type, List inputs) { + CombineFn fn = + (CombineFn) BeamBuiltinAggregations.create("AVG", type); + Object accumulator = fn.createAccumulator(); + for (T input : inputs) { + accumulator = fn.addInput(accumulator, input); + } + return fn.extractOutput(accumulator); + } + + /** An average of a single row is that row, with no rounding to 10 significant digits (#39751). */ + @Test + public void testAverageOfOneRowIsThatRow() { + for (long value : new long[] {Long.MAX_VALUE, Long.MIN_VALUE, 1786500000123L}) { + assertEquals(Long.valueOf(value), avg(FieldType.INT64, Arrays.asList(value))); + } + assertEquals( + Integer.valueOf(Integer.MIN_VALUE), avg(FieldType.INT32, Arrays.asList(Integer.MIN_VALUE))); + assertEquals( + new BigDecimal("123456789.99"), + avg(FieldType.DECIMAL, Arrays.asList(new BigDecimal("123456789.99")))); + } + + @Test + public void testIntegerAverageTruncatesTowardZero() { + assertEquals(Integer.valueOf(1), avg(FieldType.INT32, Arrays.asList(1, 2))); + assertEquals(Integer.valueOf(-1), avg(FieldType.INT32, Arrays.asList(-1, -2))); + assertEquals( + Short.valueOf((short) 2), avg(FieldType.INT16, Arrays.asList((short) 2, (short) 3))); + assertEquals(Byte.valueOf((byte) -2), avg(FieldType.BYTE, Arrays.asList((byte) -2, (byte) -3))); + // The sum overflows a long, the average does not. + assertEquals( + Long.valueOf(Long.MAX_VALUE - 1), + avg(FieldType.INT64, Arrays.asList(Long.MAX_VALUE, Long.MAX_VALUE - 1))); + } + + @Test + public void testDecimalAverageKeepsPrecision() { + assertEquals( + new BigDecimal("1234567890123.5"), + avg( + FieldType.DECIMAL, + Arrays.asList(new BigDecimal("1234567890123"), new BigDecimal("1234567890124")))); + } + + @Test + public void testAverageOfNoRowsIsNull() { + assertEquals(null, avg(FieldType.INT64, Arrays.asList())); + } +}