morrySnow opened a new pull request, #67740:
URL: https://github.com/apache/doris/pull/67740
## Problem
When multiple DISTINCT aggregates trigger the AVG decomposition rewrite,
`AVG(DISTINCT BIGINT)` can return an incorrect value. For example, averaging
`9223372036854775807` and `9223372036854775806` produced `-1.5`; a predicate
such as `avg_value > 0` could therefore discard a row that should match.
## Root cause
The rewrite decomposed `AVG(DISTINCT BIGINT)` into
`SUM(DISTINCT BIGINT) / COUNT(DISTINCT BIGINT)`. Native AVG uses a LARGEINT
accumulator for BIGINT input, while SUM keeps a BIGINT accumulator. The SUM
overflowed before the division result was converted to AVG's return type.
## Reproduction
```sql
SELECT AVG(DISTINCT x)
FROM (
SELECT CAST(9223372036854775807 AS BIGINT) AS x
UNION ALL
SELECT CAST(9223372036854775806 AS BIGINT) AS x
) t;
```
With the multi-distinct rewrite enabled, the result was `-1.5` instead of
approximately `9.223372036854776e18`.
## Fix
Losslessly widen a BIGINT AVG argument to LARGEINT before constructing the
replacement SUM and COUNT. The same widened expression is reused by both
aggregates, preserving the shared DISTINCT argument required by the
multi-distinct rewrite while matching AVG's original accumulator width.
## Tests
- Added a focused rewrite unit test that verifies the SUM uses LARGEINT and
the generated COUNT shares the same widened argument.
- Added a regression case using the two BIGINT boundary values above together
with another DISTINCT aggregate and an outer positive-value filter.
- The focused FE unit test passed: 1 test, 0 failures.
- The regression suite passed: 1 suite, 0 failed suites.
- Sandbox verification changed the result from `-1.5`/0 matching rows to
`9.223372036854776e18`/1 matching row.
Issue Number: None
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]