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 094f47b6 [SPARK-61285][CONNECT][PYTHON] Partition by range in
DataFrame::repartition_by_range of the Rust API, as PySpark's
repartitionByRange does
094f47b6 is described below
commit 094f47b6d4f06c199a95da2e9ae9c3903430cbc2
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 08:05:18 2026 +0900
[SPARK-61285][CONNECT][PYTHON] Partition by range in
DataFrame::repartition_by_range of the Rust API, as PySpark's
repartitionByRange does
### What changes were proposed in this pull request?
[SPARK-61285](https://issues.apache.org/jira/browse/SPARK-61285):
`DataFrame::repartition_by_range` and `repartition_by_range_opt` sort each
column that is not already a sort order ascending, nulls first, as PySpark's
`repartitionByRange` does.
- `crates/spark-connect/src/dataframe.rs`: `repartition_by_range_opt` wraps
each plain column in `SortOrder::asc_nulls_first` and keeps sort orders as they
are. The server range-partitions only on sort orders, so before this change a
plain column was hash-partitioned.
- `crates/pyspark-rs/src/dataframe.rs`: `repartitionByRange` had the same
wrapping in the Python client. It now relies on the core method, so both
clients share one code path. Its behavior is unchanged.
- Tests: an offline unit test in `plan_construction_tests` checks the
`partition_exprs` of both methods (plain column becomes ascending, nulls first;
descending and ascending-nulls-last sort orders are unchanged). An e2e test in
`tests/e2e_dataframe.rs` checks that `range(100).repartition_by_range(4, id)`
puts 0-24, 25-49, 50-74 and 75-99 in the four partitions.
### Why are the changes needed?
Repro against an OSS Spark 4.3.0 Connect server, the min, max and count of
`id` per `spark_partition_id()`:
| Call | Result before | Result after |
|---|---|---|
| Rust `repartition_by_range(4, id)` | (2, 93, 28), (0, 99, 24), (14, 94,
24), (3, 98, 24) | (0, 24, 25), (25, 49, 25), (50, 74, 25), (75, 99, 25) |
| Python `repartitionByRange(4, "id")` | (0, 24, 25), (25, 49, 25), (50,
74, 25), (75, 99, 25) | unchanged |
| PySpark 4.3.0 `repartitionByRange(4, "id")` | (0, 24, 25), (25, 49, 25),
(50, 74, 25), (75, 99, 25) | same |
The Rust result equals `repartition(4, id)`, so the rows of a partition
were not contiguous. Files written per partition therefore differed, and
`sortWithinPartitions` after the call did not sort globally.
### Does this PR introduce _any_ user-facing change?
Yes. `DataFrame::repartition_by_range` and `repartition_by_range_opt` now
range-partition on plain columns instead of hash-partitioning them. Calls that
pass sort orders (`asc`, `desc`, with nulls first or last) are unchanged.
### How was this patch tested?
- New offline unit test `repartition_by_range_sorts_plain_columns_only`
(both methods). It fails without this change.
- New e2e test `repartition_by_range_splits_into_contiguous_ranges` in
`tests/e2e_dataframe.rs`, run against the local Spark 4.3.0 Connect server. It
fails without this change (it returned the hash split above) and passes with it.
- `cargo test -p apache-spark-connect --release --lib`: 529 passed.
- `cargo test -p apache-spark-connect --release --no-run`, and with
`--features wasm-udf`: build.
- `cargo fmt --all --check`: clean. Clippy reports no diagnostics on the
changed lines.
- Live `e2e_dataframe`, `e2e_ops_breadth`, `coverage_plan_extra`: 8, 5 and
7 passed.
- Python offline suites (`test_dropin_offline.py`, `test_ml_offline.py`,
`test_arrow_handoff.py`): 2927 passed, 8 skipped. Live (`test_arrow_e2e.py`,
`test_dropin_e2e.py`, `test_ml_e2e.py`): 236 passed, 1 skipped.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
This pull request and its description were written by Isaac.
Closes #432 from tdcmeehan/SPARK-61285-repartition-by-range-sort-orders.
Authored-by: Timothy Meehan <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 9 ++---
crates/spark-connect/src/dataframe.rs | 51 +++++++++++++++++++++++++++--
crates/spark-connect/tests/e2e_dataframe.rs | 35 ++++++++++++++++++++
3 files changed, 87 insertions(+), 8 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index d023a04a..6f59fe02 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1146,8 +1146,8 @@ impl PyDataFrame {
numPartitions: Bound<'_, PyAny>,
cols: Vec<Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
- // As PySpark's: a positive partition count and columns, or columns
alone, each sorted
- // ascending unless it is a sort order.
+ // As PySpark's: a positive partition count and columns, or columns
alone. The columns
+ // are sorted ascending unless they are sort orders, by
`repartition_by_range_opt`.
let (num_partitions, cols) = if
numPartitions.is_instance_of::<PyInt>() {
let n = positive_partitions(py, numPartitions.extract()?)?;
if cols.is_empty() {
@@ -1175,10 +1175,7 @@ impl PyDataFrame {
};
let exprs: Vec<_> = to_column_list(cols)?
.into_iter()
- .map(|c| match c.expression().node() {
- spark_connect::expression::ExpressionNode::SortOrder(_) =>
c.expression().clone(),
- _ => c.asc().expression().clone(),
- })
+ .map(|c| c.expression().clone())
.collect();
Ok(PyDataFrame::new(
self.dataframe
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index 6e5fd538..a232bba6 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -10,7 +10,7 @@ use spark_connect_core::runtime::{block_on, get_runtime};
use spark_connect_proto as proto;
use crate::column::Column;
-use crate::expression::{Expression, ExpressionNode};
+use crate::expression::{Expression, ExpressionNode, SortOrder};
use crate::plan::{AggregateGroupType, JoinType, LogicalPlan, RelationOwner,
SetOpType};
use crate::progress::ExecutionStream;
use crate::row::{Row, StructValue, Value};
@@ -1585,10 +1585,22 @@ impl DataFrame {
num_partitions: Option<i32>,
columns: Vec<Expression>,
) -> DataFrame {
+ // The server range-partitions only on sort orders, so a plain column
is sorted
+ // ascending, nulls first, as PySpark's `repartitionByRange` does.
+ let partition_exprs = columns
+ .into_iter()
+ .map(|expr| {
+ if matches!(expr.node(), ExpressionNode::SortOrder(_)) {
+ expr
+ } else {
+
ExpressionNode::SortOrder(Box::new(SortOrder::asc_nulls_first(expr))).into()
+ }
+ })
+ .collect();
let plan = LogicalPlan::RepartitionByRange {
input: Arc::clone(&self.plan),
num_partitions,
- partition_exprs: columns,
+ partition_exprs,
};
self.with_cached_schema(plan)
}
@@ -4882,6 +4894,41 @@ mod plan_construction_tests {
}
}
+ /// Both range repartitions sort a plain column ascending, nulls first,
and keep sort
+ /// orders as they are, as PySpark's `repartitionByRange` does.
+ #[test]
+ fn repartition_by_range_sorts_plain_columns_only() {
+ use crate::functions::col;
+
+ let spark = session();
+ let df = spark.range(5).unwrap();
+ let id = || col("id").expression().clone();
+ let inputs = vec![
+ id(),
+ col("id").desc_nulls_last().expression().clone(),
+ col("id").asc_nulls_last().expression().clone(),
+ ];
+ let expected = vec![
+ col("id").asc_nulls_first().expression().clone(),
+ col("id").desc_nulls_last().expression().clone(),
+ col("id").asc_nulls_last().expression().clone(),
+ ];
+ let outputs = [
+ df.repartition_by_range(3, inputs.clone()),
+ df.repartition_by_range_opt(None, inputs),
+ ];
+ for out in &outputs {
+ match out.plan.as_ref() {
+ LogicalPlan::RepartitionByRange {
+ partition_exprs, ..
+ } => {
+ assert_eq!(partition_exprs, &expected);
+ }
+ _ => panic!("expected RepartitionByRange plan"),
+ }
+ }
+ }
+
/// Exercise every plan-building builder AND its `plan.to_proto()` arm
offline
/// (the gRPC channel connects lazily, so no server is contacted). This
pins the
/// large builder set in dataframe.rs and the matching to_proto arms in
plan.rs.
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs
b/crates/spark-connect/tests/e2e_dataframe.rs
index b94ec112..2e97489a 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -607,3 +607,38 @@ fn subqueries_return_the_rows_of_pyspark() {
vec![(1, 2)]
);
}
+
+/// `repartition_by_range` splits the ids into contiguous ranges, as PySpark's
+/// `repartitionByRange` does; a hash split of the same column would not.
+#[test]
+fn repartition_by_range_splits_into_contiguous_ranges() {
+ if !should_run() {
+ return;
+ }
+ let s = session();
+ let rows = s
+ .range(100)
+ .unwrap()
+ .repartition_by_range(4, vec![col("id").expression().clone()])
+ .with_column("p", f::spark_partition_id())
+ .group_by(vec![col("p")])
+ .agg(vec![
+ f::min(col("id")).alias("lo").expression().clone(),
+ f::max(col("id")).alias("hi").expression().clone(),
+ f::count(col("id")).alias("n").expression().clone(),
+ ])
+ .order_by(vec![col("p").expression().clone()])
+ .collect()
+ .unwrap();
+ let ranges: Vec<(i64, i64, i64)> = rows
+ .iter()
+ .map(|row| {
+ let get = |name: &str| row.get_by_name(name).and_then(|v|
v.as_i64()).unwrap();
+ (get("lo"), get("hi"), get("n"))
+ })
+ .collect();
+ assert_eq!(
+ ranges,
+ vec![(0, 24, 25), (25, 49, 25), (50, 74, 25), (75, 99, 25)]
+ );
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]