You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "kosiew (via GitHub)" <gi...@apache.org> on 2026/05/30 06:35:32 UTC

[PR] Unify AVG group state conversion and filter handling across Spark and built-in accumulators [datafusion]

kosiew opened a new pull request, #22639:
URL: https://github.com/apache/datafusion/pull/22639

   
   
   ## Which issue does this PR close?
   
   * Closes #22638.
   
   ## Rationale for this change
   
   Spark AVG and the built-in AVG implementations maintained separate logic for converting input values into group-accumulator state, including null and filter handling. This duplication increased the risk of behavioral divergence and made maintenance more difficult.
   
   This change introduces a shared helper for AVG state conversion and aligns null/filter semantics across both implementations. It also ensures that Spark AVG applies filters consistently during state merges, reducing the chance of discrepancies between the two implementations.
   
   ## What changes are included in this PR?
   
   * Added a shared AVG state conversion helper in `functions-aggregate-common`:
   
     * `groups_accumulator::avg::convert_to_avg_state`
   * Refactored the built-in AVG implementation to use the shared helper instead of maintaining local null-mask and state-conversion logic.
   * Refactored the Spark AVG implementation to use the same shared helper for `convert_to_state`.
   * Updated Spark AVG `merge_batch` to skip rows that are:
   
     * null in the partial count state,
     * null in the partial sum state,
     * filtered out by a merge filter (including `NULL` filter values).
   * Preserved implementation-specific state ordering:
   
     * Built-in AVG: `[count, sum]`
     * Spark AVG: `[sum, count]`
   * Added regression tests covering:
   
     * propagation of input nulls into AVG state,
     * propagation of filter nulls into AVG state,
     * preservation of sum data types,
     * state ordering expectations,
     * Spark AVG merge behavior with filters.
   
   ## Are these changes tested?
   
   Yes.
   
   New unit tests were added for the shared helper and both AVG implementations:
   
   ### `functions-aggregate-common`
   
   * `convert_to_avg_state_applies_input_nulls_to_sum_and_count`
   * `convert_to_avg_state_applies_filter_nulls_to_sum_and_count`
   * `convert_to_avg_state_preserves_sum_data_type`
   
   ### Built-in AVG (`functions-aggregate`)
   
   * `float64_convert_to_state_uses_count_sum_order_and_null_filter`
   * `decimal_convert_to_state_preserves_sum_type_and_nulls`
   * `duration_convert_to_state_preserves_sum_type_and_applies_filter`
   
   ### Spark AVG
   
   * `convert_to_state_with_null_filter`
   * `merge_batch_applies_filter`
   
   Existing AVG tests continue to validate state round-tripping and related behavior. 
   
   ## Are there any user-facing changes?
   
   No user-facing changes are intended. This PR refactors and aligns internal AVG group-accumulator state handling and adds regression coverage for null and filter semantics.
   
   ## LLM-generated code disclosure
   
   This PR includes LLM-generated code and comments. All LLM-generated content has been manually reviewed and tested.
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Unify AVG group state conversion and filter handling across Spark and built-in accumulators [datafusion]

Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew closed pull request #22639: Unify AVG group state conversion and filter handling across Spark and built-in accumulators
URL: https://github.com/apache/datafusion/pull/22639


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Unify AVG group state conversion and filter handling across Spark and built-in accumulators [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #22639:
URL: https://github.com/apache/datafusion/pull/22639#issuecomment-4697538560

   i'm not sure about pulling a niche case like this into the `common` crate (especially as that would widen our API surface); maybe we're better off trying to see if we can combine the spark version into the datafusion code 🤔


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Unify AVG group state conversion and filter handling across Spark and built-in accumulators [datafusion]

Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on PR #22639:
URL: https://github.com/apache/datafusion/pull/22639#issuecomment-4707010768

   @Jefffrey 
   Thanks for the feedback. I've updated the approach accordingly:
   
   * Removed the new `functions-aggregate-common::aggregate::groups_accumulator::avg` module and kept the implementation within the existing AVG codepath.
   * Folded Spark grouped AVG into a built-in AVG grouped accumulator implementation
   * Preserved the existing state contracts:
   
     * Spark AVG: `[sum, count]` with `Int64` counts
     * Built-in AVG: `[count, sum]` with `UInt64` counts
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Unify AVG group state conversion and filter handling across Spark and built-in accumulators [datafusion]

Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #22639:
URL: https://github.com/apache/datafusion/pull/22639#discussion_r3432922097


##########
datafusion/functions-aggregate/src/average.rs:
##########
@@ -955,22 +1058,149 @@ where
             .as_primitive::<T>()
             .clone()
             .with_data_type(self.sum_data_type.clone());
-        let counts = UInt64Array::from_value(1, sums.len());
+        let counts = PrimitiveArray::<CountType>::from_value(
+            CountType::Native::usize_as(1),
+            sums.len(),
+        );
 
         let nulls = filtered_null_mask(opt_filter, &sums);
-
-        // set nulls on the arrays
         let counts = set_nulls(counts, nulls.clone());
         let sums = set_nulls(sums, nulls);
 
-        Ok(vec![Arc::new(counts) as ArrayRef, Arc::new(sums)])
+        Ok(Layout::state_arrays(sums, counts))
     }
 
     fn supports_convert_to_state(&self) -> bool {
         true
     }
 
     fn size(&self) -> usize {
-        self.counts.capacity() * size_of::<u64>() + self.sums.capacity() * size_of::<T>()
+        self.counts.capacity() * size_of::<CountType::Native>()
+            + self.sums.capacity() * size_of::<T::Native>()
+            + self.null_state.size()
+    }
+}
+
+/// Creates the Spark AVG grouped accumulator using the built-in AVG state
+/// handling implementation while preserving Spark's `[sum, count]` state order
+/// and signed count type.
+#[doc(hidden)]
+pub fn spark_avg_groups_accumulator(

Review Comment:
   I moved to a neutral shared abstraction that both built-in AVG and Spark AVG use.
   
   Changes:
   - `datafusion/functions-aggregate/src/average.rs`
     - Removed Spark-specific names/API from the built-in aggregate crate.
     - Replaced `SparkAvgLayout`, `SparkAvgGroupsAccumulator`, and `spark_avg_groups_accumulator(...)` with neutral shared pieces:
       - `AvgStateLayout`
       - `CountSumAvgStateLayout`
       - `SumCountAvgStateLayout`
       - `create_avg_groups_accumulator(...)`
   - `datafusion/spark/src/function/aggregate/avg.rs`
     - Spark now selects the neutral shared constructor with `Float64Type`, `Int64Type`, and `SumCountAvgStateLayout`.
     - Spark still owns its `[sum, count]` + signed-count contract at the call site.
   
   Result: shared AVG state/null/merge logic remains unified, but `functions-aggregate` no longer exposes Spark-named concepts.
   



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Unify AVG group state conversion and filter handling across Spark and built-in accumulators [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #22639:
URL: https://github.com/apache/datafusion/pull/22639#discussion_r3425516398


##########
datafusion/functions-aggregate/src/average.rs:
##########
@@ -788,14 +786,99 @@ where
 
     /// Function that computes the final average (value / count)
     avg_fn: F,
+
+    /// AVG state layout marker.
+    layout: PhantomData<Layout>,
+}
+
+#[derive(Debug)]
+struct BuiltInAvgLayout;

Review Comment:
   I don't know if the layout of state fields differing between the implementations is actually significant 🤔 



##########
datafusion/functions-aggregate/src/average.rs:
##########
@@ -955,22 +1058,149 @@ where
             .as_primitive::<T>()
             .clone()
             .with_data_type(self.sum_data_type.clone());
-        let counts = UInt64Array::from_value(1, sums.len());
+        let counts = PrimitiveArray::<CountType>::from_value(
+            CountType::Native::usize_as(1),
+            sums.len(),
+        );
 
         let nulls = filtered_null_mask(opt_filter, &sums);
-
-        // set nulls on the arrays
         let counts = set_nulls(counts, nulls.clone());
         let sums = set_nulls(sums, nulls);
 
-        Ok(vec![Arc::new(counts) as ArrayRef, Arc::new(sums)])
+        Ok(Layout::state_arrays(sums, counts))
     }
 
     fn supports_convert_to_state(&self) -> bool {
         true
     }
 
     fn size(&self) -> usize {
-        self.counts.capacity() * size_of::<u64>() + self.sums.capacity() * size_of::<T>()
+        self.counts.capacity() * size_of::<CountType::Native>()
+            + self.sums.capacity() * size_of::<T::Native>()
+            + self.null_state.size()
+    }
+}
+
+/// Creates the Spark AVG grouped accumulator using the built-in AVG state
+/// handling implementation while preserving Spark's `[sum, count]` state order
+/// and signed count type.
+#[doc(hidden)]
+pub fn spark_avg_groups_accumulator(

Review Comment:
   I'm personally not sure about pulling in Spark specific code to functions-aggregate 🤔 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org