Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions datafusion/core/tests/sql/aggregates/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,162 @@ use datafusion_catalog::MemTable;
use datafusion_common::ScalarValue;
use insta::assert_snapshot;

#[tokio::test]
async fn aggregate_scalar_filter() -> Result<()> {
use arrow::array::BooleanArray;
use datafusion::logical_expr::{ColumnarValue, Volatility, create_udf};
use datafusion_common::assert_batches_eq;
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion_physical_plan::collect;

let schema = Arc::new(Schema::new(vec![
Field::new("key", DataType::Int32, false),
Field::new("value", DataType::Int32, true),
Field::new("keep", DataType::Boolean, true),
]));
let mut offset = 0;
let batches = [
(Some(true), 3),
(Some(false), 2),
(None, 1),
(Some(true), 4),
]
.into_iter()
.map(|(keep, len)| {
let keys = Int32Array::from_iter_values(offset..offset + len);
offset += len;
RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(keys),
Arc::new(Int32Array::from_iter((0..len).map(|row| {
if keep == Some(true) {
(row != 0).then_some(2)
} else {
Some(0)
}
}))),
Arc::new(BooleanArray::from(vec![keep; len as usize])),
],
)
})
.collect::<Result<Vec<_>, _>>()?;

for partitions in [1, 2] {
for skip in [false, true] {
let config = SessionConfig::new()
.with_target_partitions(partitions)
.with_coalesce_batches(false)
.set_usize(
"datafusion.execution.skip_partial_aggregation_probe_rows_threshold",
if skip { 0 } else { usize::MAX },
)
.set(
"datafusion.execution.skip_partial_aggregation_probe_ratio_threshold",
&ScalarValue::Float64(Some(if skip { 0.0 } else { 1.0 })),
);
let ctx = SessionContext::new_with_config(config);
// A runtime scalar can change between batches. Volatility prevents
// the optimizer from folding away the FILTER before execution.
ctx.register_udf(create_udf(
"batch_filter",
vec![DataType::Boolean],
DataType::Boolean,
Volatility::Volatile,
Arc::new(|args| match &args[0] {
ColumnarValue::Array(array) => Ok(ColumnarValue::Scalar(
ScalarValue::try_from_array(array, 0)?,
)),
scalar => Ok(scalar.clone()),
}),
));
ctx.register_table(
"scalar_filters",
Arc::new(MemTable::try_new(
Arc::clone(&schema),
vec![batches.clone(), batches.clone()],
)?),
)?;
for grouped in [false, true] {
let aggs = "count(*) FILTER (WHERE batch_filter(keep)) AS c,
sum(10 / value) FILTER (WHERE batch_filter(keep)) AS s,
sum(7) FILTER (WHERE batch_filter(keep)) AS l,
count(value) FILTER (WHERE batch_filter(keep)) AS v";
let sql = if grouped {
format!(
"SELECT count(*) AS g, sum(c) AS c, sum(s) AS s, sum(l) AS l, sum(v) AS v
FROM (SELECT {aggs} FROM scalar_filters GROUP BY key)"
)
} else {
format!("SELECT count(DISTINCT key) AS g, {aggs} FROM scalar_filters")
};
let plan = ctx.sql(&sql).await?.create_physical_plan().await?;
let output = collect(Arc::clone(&plan), ctx.task_ctx()).await?;
assert_batches_eq!(
[
"+----+----+----+----+----+",
"| g | c | s | l | v |",
"+----+----+----+----+----+",
"| 10 | 14 | 50 | 98 | 10 |",
"+----+----+----+----+----+"
],
&output
);
if grouped && partitions == 2 && skip {
let mut skipped_rows = 0;
plan.apply(|node| {
skipped_rows += node
.metrics()
.and_then(|m| m.sum_by_name("skipped_aggregation_rows"))
.map_or(0, |m| m.as_usize());
Ok(TreeNodeRecursion::Continue)
})?;
assert!(skipped_rows > 0);
}
}
// `array_agg` keeps null arguments, so a group whose rows are all
// rejected is NULL only if the rejected rows are filtered out, also
// during skip-partial conversion.
let result = ctx
.sql(
"SELECT count(*) AS g, count(a) AS a FROM (
SELECT array_agg(value) FILTER (WHERE batch_filter(keep)) AS a
FROM scalar_filters GROUP BY key)",
)
.await?
.collect()
.await?;
assert_batches_eq!(
[
"+----+---+",
"| g | a |",
"+----+---+",
"| 10 | 7 |",
"+----+---+"
],
&result
);
for predicate in ["false", "CAST(NULL AS BOOLEAN)"] {
let result = ctx.sql(&format!("SELECT
count(*) FILTER (WHERE batch_filter({predicate})) AS c,
sum(10 / (value - value)) FILTER (WHERE batch_filter({predicate})) AS s
FROM scalar_filters")).await?.collect().await?;
assert_batches_eq!(
[
"+---+---+",
"| c | s |",
"+---+---+",
"| 0 | |",
"+---+---+"
],
&result
);
}
}
}
Ok(())
}

#[tokio::test]
async fn csv_query_array_agg_distinct() -> Result<()> {
let ctx = SessionContext::new();
Expand Down
133 changes: 126 additions & 7 deletions datafusion/physical-plan/src/aggregates/aggregate_argument.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

//! Evaluation of aggregate function arguments against input batches.

use std::borrow::Cow;
use std::sync::Arc;

use crate::PhysicalExpr;
Expand All @@ -13,6 +14,7 @@ use arrow::datatypes::{DataType, Field, Fields, Schema, SchemaRef};
use arrow::record_batch::{RecordBatch, RecordBatchOptions};
use datafusion_common::cast::as_boolean_array;
use datafusion_common::{Result, ScalarValue, internal_err};
use datafusion_expr::ColumnarValue;
use datafusion_physical_expr::expressions::Literal;
use datafusion_physical_expr::utils::collect_columns;
use datafusion_physical_expr_common::utils::scatter;
Expand Down Expand Up @@ -151,6 +153,20 @@ pub(in crate::aggregates) struct AggregateFilter {
selected_schema: Option<(SchemaRef, SchemaRef)>,
}

/// The rows of a batch that an [`AggregateFilter`] selects.
///
/// A filter often selects every row of a batch or none of them, for example
/// when its predicate is a literal or returns a scalar. Then neither a
/// [`BooleanArray`] nor a copy of the selected rows is needed.
pub(in crate::aggregates) enum AggregateSelection {
/// Every row is selected.
All,
/// No row is selected.
Empty,
/// The rows where the array is true: at least one row, but not all.
Rows(BooleanArray),
}

impl AggregateFilter {
pub(in crate::aggregates) fn new(
predicate: Arc<dyn PhysicalExpr>,
Expand All @@ -174,16 +190,53 @@ impl AggregateFilter {
&self.predicate
}

/// Evaluates the filter predicate for every row of `batch`.
/// Evaluates the filter predicate for `batch` and returns the rows it
/// selects. A null rejects its row, like `false`.
///
/// The predicate is evaluated for every batch, even if it returns a
/// scalar: a runtime scalar, such as the result of a UDF, can change
/// between batches.
pub(in crate::aggregates) fn evaluate(
&self,
batch: &RecordBatch,
) -> Result<BooleanArray> {
let selection = self
.predicate
.evaluate(batch)?
.into_array(batch.num_rows())?;
Ok(as_boolean_array(&selection)?.clone())
) -> Result<AggregateSelection> {
let selection = match self.predicate.evaluate(batch)? {
ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))) => {
return Ok(AggregateSelection::All);
}
ColumnarValue::Scalar(ScalarValue::Boolean(_)) => {
return Ok(AggregateSelection::Empty);
}
value => value.into_array(batch.num_rows())?,
};
let selection = as_boolean_array(&selection)?;
// Nulls are counted neither by `has_true` nor by `has_false`.
Ok(if !selection.has_true() {
AggregateSelection::Empty
} else if selection.null_count() == 0 && !selection.has_false() {
AggregateSelection::All
} else {
AggregateSelection::Rows(selection.clone())
})
}

/// Returns the rows of `batch` that `selection` selects, for evaluating
/// the arguments of the aggregate, or `None` if no row is selected.
///
/// If every row is selected, `batch` itself is returned. Otherwise the
/// rows are copied by [`Self::select`].
pub(in crate::aggregates) fn selected_batch<'a>(
&mut self,
batch: &'a RecordBatch,
selection: &AggregateSelection,
) -> Result<Option<Cow<'a, RecordBatch>>> {
Ok(match selection {
AggregateSelection::All => Some(Cow::Borrowed(batch)),
AggregateSelection::Empty => None,
AggregateSelection::Rows(selection) => {
Some(Cow::Owned(self.select(batch, selection)?))
}
})
}

/// Returns the rows of `batch` where `selection` is true, for evaluating
Expand Down Expand Up @@ -376,6 +429,72 @@ mod tests {
Ok(())
}

#[test]
fn filter_selection_is_normalized() -> Result<()> {
let schema =
Arc::new(Schema::new(vec![Field::new("p", DataType::Boolean, true)]));
let batch = |values: Vec<Option<bool>>| {
RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(BooleanArray::from(values))],
)
};
let argument = AggregateArgument::try_new(col("p", &schema)?, &schema)?;
let filter =
|predicate| AggregateFilter::new(predicate, std::slice::from_ref(&argument));
let kind = |selection: &AggregateSelection| match selection {
AggregateSelection::All => "all",
AggregateSelection::Empty => "empty",
AggregateSelection::Rows(_) => "rows",
};

let null = lit(ScalarValue::Boolean(None));
let column = col("p", &schema)?;
let cases = [
// A scalar selects or rejects every row; a null rejects.
(lit(true), vec![Some(false), None], "all"),
(lit(false), vec![Some(true)], "empty"),
(null, vec![Some(true)], "empty"),
// So does an array that is all true, or has no true value.
(Arc::clone(&column), vec![Some(true), Some(true)], "all"),
(Arc::clone(&column), vec![Some(false), None], "empty"),
(Arc::clone(&column), vec![], "empty"),
// A null rejects its row.
(Arc::clone(&column), vec![Some(true), None], "rows"),
(Arc::clone(&column), vec![Some(false), Some(true)], "rows"),
];
for (predicate, values, expected) in cases {
let selection = filter(predicate).evaluate(&batch(values.clone())?)?;
assert_eq!(kind(&selection), expected, "{values:?}");
}

let batch = batch(vec![Some(true), None, Some(false)])?;
let mut filter = filter(column);
let selection = filter.evaluate(&batch)?;
let AggregateSelection::Rows(rows) = &selection else {
panic!("expected rows");
};
assert_eq!(
rows,
&BooleanArray::from(vec![Some(true), None, Some(false)])
);
let Some(Cow::Owned(selected)) = filter.selected_batch(&batch, &selection)?
else {
panic!("expected a copy of the selected rows");
};
assert_eq!(selected.num_rows(), 1);
assert!(matches!(
filter.selected_batch(&batch, &AggregateSelection::All)?,
Some(Cow::Borrowed(all)) if std::ptr::eq(all, &raw const batch)
));
assert!(
filter
.selected_batch(&batch, &AggregateSelection::Empty)?
.is_none()
);
Ok(())
}

#[test]
fn filter_selects_only_argument_columns() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Expand Down
Loading