This is an automated email from the ASF dual-hosted git repository.

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 670e9b05 [SPARK-61243][CONNECT] Aggregate every numeric column in the 
Rust GroupedData sum, avg, min, max and mean without columns, as PySpark does
670e9b05 is described below

commit 670e9b05a4ccd16ac4a616a3c872592d6eb61666
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 20:41:56 2026 +0900

    [SPARK-61243][CONNECT] Aggregate every numeric column in the Rust 
GroupedData sum, avg, min, max and mean without columns, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61243](https://issues.apache.org/jira/browse/SPARK-61243): Route the 
Rust `GroupedData::sum`, `avg`, `min`, `max` and `mean` through the same 
numeric aggregation as the Python drop-in, so they behave as PySpark 4.3.0 for 
no columns, numeric columns and non-numeric columns.
    
    - `sum`, `avg`, `min`, `max` now call `numeric_agg`. Without columns they 
aggregate every numeric column of the DataFrame, in schema order, named as 
PySpark names them (`sum(i)`, `avg(d)`, ...). A given column must be numeric, 
otherwise the call fails with `NOT_NUMERIC_COLUMNS` (`PySparkTypeError` in 
Python) and `invalid_columns` lists the bad names in the given order, as 
`_numeric_agg` does. A missing column is also invalid.
    - `mean` still delegates to `avg`. `count` is unchanged.
    - Public API change: these five methods now return `Result<DataFrame>` 
instead of `DataFrame`, because `numeric_agg` reads the schema (an analysis 
RPC). Callers in the workspace are updated: 
`crates/spark-connect/tests/e2e_coverage.rs` and `e2e_ops_breadth.rs`. No doc 
snippet or example used them.
    - The offline unit test `group_sum_plan` is removed: it built the plan 
without a server, and `sum` now needs the schema. The new e2e test checks the 
same plan shape through the results.
    
    The results were checked against PySpark 4.3.0 (Connect) on a DataFrame 
with a string grouping column `k`, `i int`, `l long`, `d double` (NULL for one 
group), a string `s` and a pivot column `p`: `groupBy("k").sum()` gives `['k', 
'sum(i)', 'sum(l)', 'sum(d)']` with rows `(a, 3, 30, 4.0)`, `(b, 3, 30, None)`; 
`rollup` and `cube` give the same plus a NULL key row `(None, 6, 60, 4.0)`; a 
pivot on `p` with values `p`, `q` gives `p_sum(i)`, ..., `q_sum(d)`; 
`sum("s")`, `min("i", "nope", "s [...]
    
    ### Why are the changes needed?
    
    `GroupedData::sum(vec![])` built an aggregate with no expressions, so the 
result held only the grouping columns, where PySpark returns the sum of every 
numeric column. A non-numeric column was sent to the server as a raw `sum(s)` 
with no check, so the error was the server's and not PySpark's 
`NOT_NUMERIC_COLUMNS`. The Python drop-in already used `numeric_agg` and 
behaved as PySpark, so the two clients differed.
    
    Example: `df.group_by(vec![col("k")]).sum(vec![])` returned only `k` on a 
frame with `i`, `l`, `d`; PySpark returns `k, sum(i), sum(l), sum(d)`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. The Rust `GroupedData::sum`, `avg`, `min`, `max` and `mean` return 
`Result<DataFrame>` (was `DataFrame`). Without columns they aggregate every 
numeric column (was: grouping columns only). A non-numeric or missing column is 
`NOT_NUMERIC_COLUMNS` (was: passed to the server). The Python drop-in is 
unchanged.
    
    ### How was this patch tested?
    
    - `group_numeric_aggregates_follow_pyspark` (new, 
`crates/spark-connect/tests/e2e_dataframe.rs`, before 
`dataframe_metadata_json_semantics`): `sum`, `avg`, `mean`, `min`, `max` with 
no columns and with a given numeric column on groupBy, rollup and pivot; 
grouping sets checked against rollup; a cube checked against rollup; and the 
`NOT_NUMERIC_COLUMNS` errors (kind, condition, `invalid_columns`) for a string 
column, a missing column, a pivot and a rollup. The expected names and values  
[...]
    - `aggregates_execute` (`e2e_ops_breadth.rs`) and 
`agg_na_stat_reshape_surface` (`e2e_coverage.rs`) now unwrap the `Result` and 
pass.
    - The lib tests (521 passed), the build of all tests, the offline Python 
suites (2819 passed, 8 skipped) with the rebuilt extension, the live Rust tests 
`e2e_dataframe` (5 passed), `e2e_ops_breadth` (5 passed) and `e2e_coverage` (25 
passed), and the live drop-in tests `-k group` (6 passed) against a local Spark 
4.3.0 server. Clippy reports no diagnostics in the changed lines.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #421 from HyukjinKwon/SPARK-61243-grouped-numeric-agg.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/group.rs             |  68 ++---------
 crates/spark-connect/tests/e2e_coverage.rs    |   5 +
 crates/spark-connect/tests/e2e_dataframe.rs   | 169 ++++++++++++++++++++++++++
 crates/spark-connect/tests/e2e_ops_breadth.rs |   5 +
 4 files changed, 192 insertions(+), 55 deletions(-)

diff --git a/crates/spark-connect/src/group.rs 
b/crates/spark-connect/src/group.rs
index 4ae98284..72306f72 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -414,52 +414,28 @@ impl GroupedData {
         Ok(self.agg(expressions))
     }
 
-    /// Sum values in each group.
-    pub fn sum(&self, columns: Vec<&str>) -> DataFrame {
-        use crate::functions;
-        let expressions: Vec<_> = columns
-            .iter()
-            .map(|col| 
functions::sum(crate::column::col(col)).expression().clone())
-            .collect();
-
-        self.agg(expressions)
+    /// Sum values in each group, as `GroupedData.sum`: every numeric column 
without `columns`.
+    pub fn sum(&self, columns: Vec<&str>) -> Result<DataFrame> {
+        self.numeric_agg("sum", columns)
     }
 
-    /// Average values in each group.
-    pub fn avg(&self, columns: Vec<&str>) -> DataFrame {
-        use crate::functions;
-        let expressions: Vec<_> = columns
-            .iter()
-            .map(|col| 
functions::avg(crate::column::col(col)).expression().clone())
-            .collect();
-
-        self.agg(expressions)
+    /// Average values in each group, as `GroupedData.avg`: every numeric 
column without `columns`.
+    pub fn avg(&self, columns: Vec<&str>) -> Result<DataFrame> {
+        self.numeric_agg("avg", columns)
     }
 
-    /// Minimum values in each group.
-    pub fn min(&self, columns: Vec<&str>) -> DataFrame {
-        use crate::functions;
-        let expressions: Vec<_> = columns
-            .iter()
-            .map(|col| 
functions::min(crate::column::col(col)).expression().clone())
-            .collect();
-
-        self.agg(expressions)
+    /// Minimum values in each group, as `GroupedData.min`: every numeric 
column without `columns`.
+    pub fn min(&self, columns: Vec<&str>) -> Result<DataFrame> {
+        self.numeric_agg("min", columns)
     }
 
-    /// Maximum values in each group.
-    pub fn max(&self, columns: Vec<&str>) -> DataFrame {
-        use crate::functions;
-        let expressions: Vec<_> = columns
-            .iter()
-            .map(|col| 
functions::max(crate::column::col(col)).expression().clone())
-            .collect();
-
-        self.agg(expressions)
+    /// Maximum values in each group, as `GroupedData.max`: every numeric 
column without `columns`.
+    pub fn max(&self, columns: Vec<&str>) -> Result<DataFrame> {
+        self.numeric_agg("max", columns)
     }
 
     /// Mean (alias for avg).
-    pub fn mean(&self, columns: Vec<&str>) -> DataFrame {
+    pub fn mean(&self, columns: Vec<&str>) -> Result<DataFrame> {
         self.avg(columns)
     }
 }
@@ -983,24 +959,6 @@ mod tests {
         }
     }
 
-    #[test]
-    fn group_sum_plan() {
-        let spark = session();
-        let df = spark.range(10).unwrap();
-        let grouped = df.group_by(vec![crate::column::col("id")]);
-        let result = grouped.sum(vec!["id"]);
-        match result.plan.as_ref() {
-            LogicalPlan::Aggregate {
-                group_type: AggregateGroupType::GroupBy,
-                aggregate_expressions,
-                ..
-            } => {
-                assert!(!aggregate_expressions.is_empty());
-            }
-            _ => panic!("expected Aggregate plan"),
-        }
-    }
-
     #[test]
     fn group_agg_plan() {
         let spark = session();
diff --git a/crates/spark-connect/tests/e2e_coverage.rs 
b/crates/spark-connect/tests/e2e_coverage.rs
index 2b531d4e..7d486346 100644
--- a/crates/spark-connect/tests/e2e_coverage.rs
+++ b/crates/spark-connect/tests/e2e_coverage.rs
@@ -453,26 +453,31 @@ fn agg_na_stat_reshape_surface() {
     let _ = df
         .group_by(vec![col("id")])
         .sum(vec!["val"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
         .group_by(vec![col("id")])
         .avg(vec!["val"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
         .group_by(vec![col("id")])
         .min(vec!["val"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
         .group_by(vec![col("id")])
         .max(vec!["val"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
         .group_by(vec![col("id")])
         .mean(vec!["val"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df.rollup(vec![col("id")]).count().collect().unwrap();
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs 
b/crates/spark-connect/tests/e2e_dataframe.rs
index 46fb12eb..da4c312e 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -83,6 +83,175 @@ fn dataframe_transforms_and_setops() {
     assert_eq!(m.count().unwrap(), 4);
 }
 
+/// The column names of `df`, then its rows as display strings, sorted.
+fn named_rows(df: &DataFrame) -> (Vec<String>, Vec<Vec<String>>) {
+    let columns = df.columns().unwrap();
+    let mut rows: Vec<Vec<String>> = df
+        .collect()
+        .unwrap()
+        .iter()
+        .map(|row| {
+            (0..columns.len())
+                .map(|i| row.get(i).map_or_else(String::new, |v| 
v.to_string()))
+                .collect()
+        })
+        .collect();
+    rows.sort();
+    (columns, rows)
+}
+
+/// `GroupedData.sum`, `avg`, `mean`, `min` and `max` aggregate every numeric 
column without
+/// columns, and reject a given column that is not a numeric one, as PySpark's 
`_numeric_agg`
+/// does, for groupBy, rollup, cube, grouping sets and pivot.
+#[test]
+fn group_numeric_aggregates_follow_pyspark() {
+    use spark_connect::row::Value;
+    use spark_connect::SparkErrorKind;
+    if !should_run() {
+        return;
+    }
+    let s = session();
+    // k: grouping string; i int, l long, d double (NULL in group b), s 
string, p pivot string.
+    let df = s
+        .sql(
+            "SELECT * FROM VALUES ('a', 1, 10L, 1.5D, 'x', 'p'), ('a', 2, 20L, 
2.5D, 'y', 'q'), \
+             ('b', 3, 30L, CAST(NULL AS DOUBLE), 'z', 'p') AS t(k, i, l, d, s, 
p)",
+        )
+        .unwrap();
+    let names = |names: &[&str]| names.iter().map(|n| 
n.to_string()).collect::<Vec<String>>();
+    let rows = |rows: &[&[&str]]| {
+        rows.iter()
+            .map(|r| r.iter().map(|v| v.to_string()).collect::<Vec<String>>())
+            .collect::<Vec<Vec<String>>>()
+    };
+
+    // Every numeric column, in schema order, with PySpark's names (`sum(i)`, 
...).
+    let (cols, got) = 
named_rows(&df.group_by(vec![col("k")]).sum(vec![]).unwrap());
+    assert_eq!(cols, names(&["k", "sum(i)", "sum(l)", "sum(d)"]));
+    assert_eq!(
+        got,
+        rows(&[&["a", "3", "30", "4"], &["b", "3", "30", "NULL"]])
+    );
+    let (cols, got) = 
named_rows(&df.group_by(vec![col("k")]).avg(vec![]).unwrap());
+    assert_eq!(cols, names(&["k", "avg(i)", "avg(l)", "avg(d)"]));
+    assert_eq!(
+        got,
+        rows(&[&["a", "1.5", "15", "2"], &["b", "3", "30", "NULL"]])
+    );
+    let (cols, got) = 
named_rows(&df.group_by(vec![col("k")]).mean(vec![]).unwrap());
+    assert_eq!(cols, names(&["k", "avg(i)", "avg(l)", "avg(d)"]));
+    assert_eq!(
+        got,
+        rows(&[&["a", "1.5", "15", "2"], &["b", "3", "30", "NULL"]])
+    );
+    let (cols, got) = 
named_rows(&df.group_by(vec![col("k")]).min(vec![]).unwrap());
+    assert_eq!(cols, names(&["k", "min(i)", "min(l)", "min(d)"]));
+    assert_eq!(
+        got,
+        rows(&[&["a", "1", "10", "1.5"], &["b", "3", "30", "NULL"]])
+    );
+    let (cols, got) = 
named_rows(&df.group_by(vec![col("k")]).max(vec![]).unwrap());
+    assert_eq!(cols, names(&["k", "max(i)", "max(l)", "max(d)"]));
+    assert_eq!(
+        got,
+        rows(&[&["a", "2", "20", "2.5"], &["b", "3", "30", "NULL"]])
+    );
+
+    // A given numeric column only.
+    let (cols, got) = named_rows(&df.group_by(vec![col("k")]).sum(vec!["d", 
"i"]).unwrap());
+    assert_eq!(cols, names(&["k", "sum(d)", "sum(i)"]));
+    assert_eq!(got, rows(&[&["a", "4", "3"], &["b", "NULL", "3"]]));
+
+    // Rollup, cube and grouping sets (`GROUPING SETS ((k), ())` is 
`ROLLUP(k)`).
+    let (cols, got) = 
named_rows(&df.rollup(vec![col("k")]).sum(vec![]).unwrap());
+    assert_eq!(cols, names(&["k", "sum(i)", "sum(l)", "sum(d)"]));
+    assert_eq!(
+        got,
+        rows(&[
+            &["NULL", "6", "60", "4"],
+            &["a", "3", "30", "4"],
+            &["b", "3", "30", "NULL"]
+        ])
+    );
+    // With one grouping column, a cube is a rollup.
+    assert_eq!(
+        named_rows(&df.cube(vec![col("k")]).sum(vec![]).unwrap()),
+        named_rows(&df.rollup(vec![col("k")]).sum(vec![]).unwrap())
+    );
+    let grouping_sets = df
+        .grouping_sets(vec![vec![col("k")], vec![]])
+        .sum(vec![])
+        .unwrap();
+    assert_eq!(
+        named_rows(&grouping_sets).1,
+        named_rows(&df.rollup(vec![col("k")]).sum(vec![]).unwrap()).1
+    );
+
+    // Pivot: the numeric columns of each pivot value, or the given one.
+    let pivot = |grouped: spark_connect::group::GroupedData| {
+        grouped
+            .pivot(
+                col("p"),
+                Some(vec![Value::String("p".into()), 
Value::String("q".into())]),
+            )
+            .unwrap()
+    };
+    let (cols, got) = 
named_rows(&pivot(df.group_by(vec![col("k")])).sum(vec![]).unwrap());
+    assert_eq!(
+        cols,
+        names(&["k", "p_sum(i)", "p_sum(l)", "p_sum(d)", "q_sum(i)", 
"q_sum(l)", "q_sum(d)"])
+    );
+    assert_eq!(
+        got,
+        rows(&[
+            &["a", "1", "10", "1.5", "2", "20", "2.5"],
+            &["b", "3", "30", "NULL", "NULL", "NULL", "NULL"]
+        ])
+    );
+    let (cols, got) = 
named_rows(&pivot(df.group_by(vec![col("k")])).sum(vec!["i"]).unwrap());
+    assert_eq!(cols, names(&["k", "p", "q"]));
+    assert_eq!(got, rows(&[&["a", "1", "2"], &["b", "3", "NULL"]]));
+
+    // A column that is not numeric, or not in the schema, is 
NOT_NUMERIC_COLUMNS with the
+    // invalid columns in PySpark's order.
+    let check = |err: spark_connect::SparkError, invalid: &str| {
+        assert_eq!(err.kind, SparkErrorKind::TypeError);
+        assert_eq!(err.get_condition().as_deref(), 
Some("NOT_NUMERIC_COLUMNS"));
+        assert_eq!(
+            err.params.get("invalid_columns").map(String::as_str),
+            Some(invalid)
+        );
+    };
+    check(
+        df.group_by(vec![col("k")])
+            .sum(vec!["s"])
+            .err()
+            .expect("a string column"),
+        "['s']",
+    );
+    check(
+        df.group_by(vec![col("k")])
+            .min(vec!["i", "nope", "s"])
+            .err()
+            .expect("a missing and a string column"),
+        "['nope', 's']",
+    );
+    check(
+        pivot(df.group_by(vec![col("k")]))
+            .sum(vec!["s"])
+            .err()
+            .expect("a string column of a pivot"),
+        "['s']",
+    );
+    check(
+        df.rollup(vec![col("k")])
+            .avg(vec!["s"])
+            .err()
+            .expect("a string column of a rollup"),
+        "['s']",
+    );
+}
+
 #[test]
 fn dataframe_metadata_json_semantics() {
     if !should_run() {
diff --git a/crates/spark-connect/tests/e2e_ops_breadth.rs 
b/crates/spark-connect/tests/e2e_ops_breadth.rs
index c66f1241..3af3d618 100644
--- a/crates/spark-connect/tests/e2e_ops_breadth.rs
+++ b/crates/spark-connect/tests/e2e_ops_breadth.rs
@@ -161,26 +161,31 @@ fn aggregates_execute() {
     let _ = df
         .group_by(vec![col("id")])
         .sum(vec!["v"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
         .group_by(vec![col("id")])
         .avg(vec!["v"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
         .group_by(vec![col("id")])
         .min(vec!["v"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
         .group_by(vec![col("id")])
         .max(vec!["v"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
         .group_by(vec![col("id")])
         .mean(vec!["v"])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df.rollup(vec![col("id")]).count().collect().unwrap();


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to