azhangd commented on code in PR #21548:
URL: https://github.com/apache/datafusion/pull/21548#discussion_r3139701565


##########
datafusion/spark/src/function/aggregate/avg.rs:
##########
@@ -343,7 +345,141 @@ where
         ])
     }
 
+    fn convert_to_state(
+        &self,
+        values: &[ArrayRef],
+        opt_filter: Option<&BooleanArray>,
+    ) -> Result<Vec<ArrayRef>> {
+        let sums = values[0]
+            .as_primitive::<T>()
+            .clone()
+            .with_data_type(self.return_data_type.clone());
+
+        let counts = Int64Array::from_value(1, sums.len());
+
+        // null out filtered / null input rows
+        let filter_nulls = opt_filter.map(|f| {
+            let (bools, nulls) = f.clone().into_parts();
+            NullBuffer::union(Some(&NullBuffer::from(bools)), nulls.as_ref())
+                .expect("at least one input is Some")
+        });
+        let nulls =
+            NullBuffer::union(filter_nulls.as_ref(), 
sums.logical_nulls().as_ref());
+
+        let (dt, buf, _) = sums.into_parts();
+        let sums = PrimitiveArray::<T>::new(buf, 
nulls.clone()).with_data_type(dt);
+        let (_, buf, _) = counts.into_parts();
+        let counts = Int64Array::new(buf, nulls);
+
+        // [sum, count] - must match state() and merge_batch()
+        Ok(vec![
+            Arc::new(sums) as ArrayRef,
+            Arc::new(counts) as ArrayRef,
+        ])
+    }
+
+    fn supports_convert_to_state(&self) -> bool {

Review Comment:
   Thanks @kosiew, you're right. `merge_batch` was reading `.values()` straight 
off the buffer, so the null rows from `convert_to_state` were still getting 
summed in once skip-partial-aggregation kicked in.
   
   Pushed a fix. `merge_batch` now iterates with an index and skips rows where 
`partial_counts` or `partial_sums` is null.
   
   Added a regression test (`convert_to_state_null_merge_matches_direct`) for 
the `avg([1.0, NULL, 3.0])` case. Returns 2.0 now.



-- 
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]

Reply via email to