rich7420 commented on code in PR #6180:
URL: https://github.com/apache/datafusion-comet/pull/6180#discussion_r4240323303
##########
spark/src/test/scala/org/apache/comet/exec/CometExecSuite.scala:
##########
@@ -2549,6 +2549,37 @@ class CometExecSuite extends CometTestBase {
}
}
+ test("filter output projection preserves rows, aliases and metrics") {
Review Comment:
Moved the projection result regression to
`spark/src/test/resources/sql-tests/operators/filter_projection.sql` in #6396,
which is now merged. It covers count-only output, aliases/order/duplicates,
full projections, empty results and a rejected row that must not reach an ANSI
cast. The Scala test retains the native output-row metrics checks, which the
SQL fixture cannot assert. These generic projection changes are no longer in
this PR’s diff.
##########
native/core/src/execution/operators/projection.rs:
##########
@@ -57,12 +60,28 @@ impl OperatorBuilder for ProjectionBuilder {
.map(|(idx, expr)| {
planner
.create_expr(expr, child.schema())
- .map(|r| (r, format!("col_{idx}")))
+ .map(|r| ProjectionExpr::new(r, format!("col_{idx}")))
})
.collect();
+ let mut exprs = ProjectionExprs::from(exprs?);
Review Comment:
Split out as #6396 and merged. This branch now takes the projection
implementation from main, so this PR’s diff is limited to AtLeastNNonNulls and
its configuration, tests, benchmarks and documentation. The shared CASE/IF
implementation (#6350) and independent IF tests (#6397) are also merged.
##########
native/spark-expr/src/predicate_funcs/at_least_n_non_nulls.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::fmt::{Display, Formatter};
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanArray, RecordBatch};
+use arrow::buffer::{BooleanBuffer, Buffer};
+use arrow::compute::cast;
+use arrow::datatypes::{DataType, Float32Type, Float64Type, Schema};
+use datafusion::common::{Result, ScalarValue};
+use datafusion::physical_expr::expressions::{Column, Literal};
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::ColumnarValue;
+
+/// Spark's per-row count of non-null, non-NaN children, stopping once `n` is
reached.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct AtLeastNNonNulls {
+ n: i32,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+}
+
+impl AtLeastNNonNulls {
+ pub fn new(n: i32, children: Vec<Arc<dyn PhysicalExpr>>) -> Self {
+ Self { n, children }
+ }
+
+ // Sub-word batches do not amortize the bitmap counter's bookkeeping. Keep
+ // the row counter for these batches, including single-row scalar inputs.
+ fn evaluate_small_batch(&self, batch: &RecordBatch) ->
Result<ColumnarValue> {
+ let mut counts = vec![0; batch.num_rows()];
+ let mut remaining = batch.num_rows();
+ for child in &self.children {
+ if remaining == 0 {
+ break;
+ }
+ // Column/literal reads cannot raise per-row errors or have side
effects. Avoid
+ // filtering the input batch for the common DataFrame.na.drop
attribute inputs.
+ let value =
+ if remaining == batch.num_rows() || child.is::<Column>() ||
child.is::<Literal>() {
+ child.evaluate(batch)?
+ } else {
+ let selection = BooleanArray::new(
+ BooleanBuffer::collect_bool(counts.len(), |i|
counts[i] < self.n),
+ None,
+ );
+ child.evaluate_selection(batch, &selection)?
+ };
+ let scalar = matches!(value, ColumnarValue::Scalar(_));
+ let array = value.into_array(if scalar { 1 } else {
batch.num_rows() })?;
+ let valid = valid_values(&array)?;
+ if scalar {
+ if valid.value(0) {
+ for count in &mut counts {
+ if *count < self.n {
+ *count += 1;
+ remaining -= usize::from(*count == self.n);
+ }
+ }
+ }
+ } else {
+ for row in valid.set_indices() {
+ if counts[row] < self.n {
+ counts[row] += 1;
+ remaining -= usize::from(counts[row] == self.n);
+ }
+ }
+ }
+ }
+ Ok(ColumnarValue::Array(Arc::new(BooleanArray::new(
+ BooleanBuffer::collect_bool(counts.len(), |i| counts[i] >= self.n),
+ None,
+ ))))
+ }
+}
+
+impl Display for AtLeastNNonNulls {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(f, "atleastnnonnulls({}, {:?})", self.n, self.children)
+ }
+}
+
+impl PhysicalExpr for AtLeastNNonNulls {
+ fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ Display::fmt(self, f)
+ }
+
+ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
+ Ok(DataType::Boolean)
+ }
+
+ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+ Ok(false)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ if self.n <= 0 {
+ return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))));
+ }
+ // The standard na.drop("all"/"any") cases reduce to bitmap OR/AND and
do not
+ // need a per-row counter. For AND, still evaluate every child: Spark
does not
+ // skip later expressions just because a row can no longer reach the
threshold.
+ if self.n == 1 || self.n as usize == self.children.len() {
+ let all = self.n != 1;
+ let mut result = if all {
+ BooleanBuffer::new_set(batch.num_rows())
+ } else {
+ BooleanBuffer::new_unset(batch.num_rows())
+ };
+ for child in &self.children {
+ if batch.num_rows() == 0 || (!all && result.count_set_bits()
== batch.num_rows()) {
+ break;
+ }
+ let value = if all || child.is::<Column>() ||
child.is::<Literal>() {
+ child.evaluate(batch)?
+ } else {
+ child.evaluate_selection(batch,
&BooleanArray::new(!&result, None))?
+ };
+ let valid =
valid_values(&value.into_array(batch.num_rows())?)?;
+ result = if all {
+ &result & &valid
+ } else {
+ &result | &valid
+ };
+ }
+ return Ok(ColumnarValue::Array(Arc::new(BooleanArray::new(
+ result, None,
+ ))));
+ }
+ if batch.num_rows() < 64 {
Review Comment:
64 was a one-word starting point for the general counting path: bitmap
counters process 64 rows per word, while small batches may not amortize their
bookkeeping. It is a heuristic, not a required or universal crossover. I made
it configurable as `spark.comet.exec.atLeastNNonNulls.smallBatchThreshold`,
default 64; any positive value is accepted, independently of the bitmap word
size and the `na.drop` threshold. Tests cover both strategies and
non-word-aligned thresholds. Criterion now compares row, bitmap and default
strategies on identical inputs around the boundary. Current-head timings are
still pending, so I am not claiming that 64 is optimal.
--
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]