shihchengwei-lab commented on PR #27796:
URL: https://github.com/apache/datafusion/pull/27796#issuecomment-7231358617
**Wrapping the intermediate sum can silently corrupt a representable
`AVG(Duration)`.** At `732f550ec74bc37c004aa571677dbe62ab79fc46`, averaging
106,752 one-day nanosecond durations returns `-86399985702465ns`; the correct
average is `86400000000000ns`. Every input and the correct result fit in
`i64`—only the intermediate sum overflows.
The new overflow test asserts the wrapped intermediate value, so it would
make this wrong query result expected behavior. Could `DurationAvgAccumulator`
retain enough precision until division, or return an overflow error, instead of
successfully returning the wrapped average?
<details>
<summary>Minimal reproduction</summary>
Add this test to `datafusion/functions-aggregate/src/average.rs`:
```rust
#[test]
fn avg_duration_one_day_across_default_sized_batches() -> Result<()> {
const DAY_NS: i64 = 86_400_000_000_000;
const BATCH_SIZE: usize = 8_192;
const ROW_COUNT: usize = 106_752;
let input_type = DataType::Duration(TimeUnit::Nanosecond);
let return_type = DataType::Duration(TimeUnit::Nanosecond);
let mut acc = avg_accumulator(&input_type, &return_type)?;
for _ in 0..(ROW_COUNT / BATCH_SIZE) {
let values: ArrayRef = Arc::new(
arrow::array::DurationNanosecondArray::from_value(
DAY_NS,
BATCH_SIZE,
),
);
acc.update_batch(std::slice::from_ref(&values))?;
}
let values: ArrayRef = Arc::new(
arrow::array::DurationNanosecondArray::from_value(
DAY_NS,
ROW_COUNT % BATCH_SIZE,
),
);
acc.update_batch(std::slice::from_ref(&values))?;
assert_eq!(
acc.evaluate()?,
ScalarValue::DurationNanosecond(Some(DAY_NS))
);
Ok(())
}
```
Run:
```sh
cargo test -p datafusion-functions-aggregate \
average::tests::avg_duration_one_day_across_default_sized_batches \
-- --exact --nocapture
```
With base commit `be0307a4c5e0d91654f15887ab540edd148267af`, the debug build
panics at the running addition with `attempt to add with overflow`. With this
PR, evaluation succeeds and the assertion reports:
```text
left: DurationNanosecond("-86399985702465")
right: DurationNanosecond("86400000000000")
```
I ran both versions on Windows with Rust 1.98.0.
</details>
*Disclosure: AI helped review the code, design the reproduction, and draft
this comment.*
--
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]