You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "azhangd (via GitHub)" <gi...@apache.org> on 2026/04/11 07:20:03 UTC
[PR] perf: implement convert_to_state for SparkAvg [datafusion]
azhangd opened a new pull request, #21548:
URL: https://github.com/apache/datafusion/pull/21548
## Which issue does this PR close?
- Part of #17964.
## Rationale for this change
SparkAvg's AvgGroupsAccumulator doesn't implement supports_convert_to_state (defaults to false), which prevents the skip-partial-aggregation optimization from kicking in for queries that use Spark's avg().
I ran into this while benchmarking a Spark Connect engine built on DataFusion. On TPC-H q17 at SF10, the partial aggregate for avg(l_quantity) grouped by l_partkey (~2M groups out of 60M rows) was not triggering skip-aggregation:
| Metric | Without convert_to_state | With convert_to_state |
|--------|-------------------------|-----------------------|
| Partial aggregate memory | 923 MB | 40 MB |
| Partial aggregate elapsed | 4.75s | 109ms |
The skip-aggregation probe (#11627) detects when a partial aggregate isn't reducing cardinality and falls back to passing rows through as state directly. This needs convert_to_state so the accumulator can produce [sum, count] state arrays from raw input. The built-in Avg already has this (#11734), but it wasn't carried over when SparkAvg was migrated from Comet in #17871.
## What changes are included in this PR?
Adds convert_to_state() and supports_convert_to_state() to AvgGroupsAccumulator in datafusion-spark.
Follows the same approach as the built-in Avg, adapted for SparkAvg's differences:
- State order is [sum, count] (vs [count, sum] in the built-in)
- Count type is Int64 (vs UInt64 in the built-in)
- Null handling uses NullBuffer::union directly instead of pulling in datafusion-functions-aggregate-common as a dep
Also cleaned up the fully-qualified arrow::array::BooleanArray references in update_batch / merge_batch since adding BooleanArray to the import block triggered the unused_qualifications lint.
## Are these changes tested?
Yes, unit tests covering basic conversion, null propagation, filter handling, and a roundtrip through merge_batch to verify the converted state produces correct results end-to-end.
## Are there any user-facing changes?
No. Queries using avg() through the Spark function registry will automatically benefit from skip-partial-aggregation on high-cardinality groupings.
--
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] perf: implement convert_to_state for SparkAvg [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #21548:
URL: https://github.com/apache/datafusion/pull/21548
--
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] perf: implement convert_to_state for SparkAvg [datafusion]
Posted by "azhangd (via GitHub)" <gi...@apache.org>.
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: 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] perf: implement convert_to_state for SparkAvg [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #21548:
URL: https://github.com/apache/datafusion/pull/21548#discussion_r3135964158
##########
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:
Could we hold off on enabling `supports_convert_to_state()` here until the merge path is null-aware?
`merge_batch()` above still merges `partial_sums.values()` and `partial_counts.values()` directly, without checking the null bitmap. Since `convert_to_state()` encodes filtered rows and null inputs as null state entries, once skip-partial-aggregation kicks in those rows can still contribute their backing values during merge.
For example, `avg([1.0, NULL, 3.0])` could be merged as if the null row were present, which would produce the wrong average. I think this needs a null-aware merge path, similar to built-in Avg, before this can safely be turned on.
##########
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
Review Comment:
Small suggestion while we are in this area: could this reuse the shared `filtered_null_mask` and `set_nulls` helpers from `datafusion_functions_aggregate_common` instead of open-coding the null-mask construction?
The built-in Avg already uses those utilities, and sharing them here would make the Spark implementation easier to compare against it and less likely to drift again.
--
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] perf: implement convert_to_state for SparkAvg [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #21548:
URL: https://github.com/apache/datafusion/pull/21548#issuecomment-4328771846
Looks great -- thank you @azhangd and @kosiew
--
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] perf: implement convert_to_state for SparkAvg [datafusion]
Posted by "azhangd (via GitHub)" <gi...@apache.org>.
azhangd commented on code in PR #21548:
URL: https://github.com/apache/datafusion/pull/21548#discussion_r3139716240
##########
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
Review Comment:
Thanks @kosiew, done. Swapped to `filtered_null_mask`/`set_nulls` and pulled in `datafusion-functions-aggregate-common`. The `convert_to_state` body matches the built-in 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: 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] perf: implement convert_to_state for SparkAvg [datafusion]
Posted by "azhangd (via GitHub)" <gi...@apache.org>.
azhangd commented on PR #21548:
URL: https://github.com/apache/datafusion/pull/21548#issuecomment-4322196473
@kosiew thanks for the review!
--
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