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 3b8302e8 [SPARK-61414][CONNECT] Send a limit of one row over an empty 
projection in DataFrame::is_empty of the Rust API, as PySpark does
3b8302e8 is described below

commit 3b8302e8f583766eb09080113d23472e45bbfcd8
Author: Timothy Meehan <[email protected]>
AuthorDate: Thu Nov 12 08:30:26 2026 +0900

    [SPARK-61414][CONNECT] Send a limit of one row over an empty projection in 
DataFrame::is_empty of the Rust API, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61414](https://issues.apache.org/jira/browse/SPARK-61414): send a 
limit of one row over an empty projection in `DataFrame::is_empty` of the Rust 
API, as PySpark does.
    
    `DataFrame::is_empty` of the Rust API, and so `DataFrame.isEmpty` of the 
Python client, now sends `Limit(1)` over a `Project` with no expressions and 
checks whether a row comes back, as PySpark's `isEmpty` (`select().take(1)`) 
does. It sent a `count(1)` aggregate over `Limit(1)`.
    
    ### Why are the changes needed?
    
    The answers were the same, but the plan the server ran and the result it 
returned were not those of PySpark.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No change to the result. The request that `is_empty` and `isEmpty` send is 
now the one PySpark sends.
    
    ### How was this patch tested?
    
    - Rust: an offline test (`tests/is_empty_plan.rs`, an in-process gRPC stub 
that answers Config and ExecutePlan) of the relation of the request; it fails 
on master (an `Aggregate` is sent). A server-gated test (`e2e_dataframe.rs`) of 
the result for a non-empty and an empty DataFrame; it ran against a local OSS 
Spark 4.3.0 Connect server and passed.
    - Python: an offline test of the request relation with `mock_connect`. It 
fails against a build with the old `is_empty` (observed by rebuilding the 
drop-in with the old code) and passes with the fix.
    - Library tests: 599 passed, and the `apache-spark-connect-core` tests 
pass. Integration targets compile with and without `wasm-udf`. `cargo fmt --all 
--check` and `ruff check` pass. Python offline suites: 3115 passed, 8 skipped. 
Live Python suites: 281 passed, 1 skipped.
    - Against a local OSS Spark 4.3.0 Connect server, the plan is the same as 
`pyspark-client 4.3.0` sends.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Sonnet 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #518 from tdcmeehan/SPARK-61414-is-empty-plan.
    
    Authored-by: Timothy Meehan <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 Cargo.lock                                  |   1 +
 crates/spark-connect/Cargo.toml             |   1 +
 crates/spark-connect/src/dataframe.rs       |   3 +-
 crates/spark-connect/tests/e2e_dataframe.rs |  15 +++
 crates/spark-connect/tests/is_empty_plan.rs | 169 ++++++++++++++++++++++++++++
 python/tests/test_dropin_offline.py         |  16 +++
 6 files changed, 204 insertions(+), 1 deletion(-)

diff --git a/Cargo.lock b/Cargo.lock
index 772b1ffc..07a6ef8c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -71,6 +71,7 @@ dependencies = [
  "stacker",
  "thiserror",
  "tokio",
+ "tonic",
  "uuid",
 ]
 
diff --git a/crates/spark-connect/Cargo.toml b/crates/spark-connect/Cargo.toml
index 927540cb..648d04fc 100644
--- a/crates/spark-connect/Cargo.toml
+++ b/crates/spark-connect/Cargo.toml
@@ -38,6 +38,7 @@ polars = { workspace = true, optional = true }
 
 [dev-dependencies]
 base64 = "0.21"
+tonic.workspace = true
 
 [features]
 # Run Rust UDFs on Spark via WebAssembly (the `wasm_udf` module). Off by
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 562823fe..c25394c2 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1337,7 +1337,8 @@ impl DataFrame {
 
     /// Check if the DataFrame is empty.
     pub fn is_empty(&self) -> Result<bool> {
-        self.limit(1).count().map(|c| c == 0)
+        let no_columns: [Column; 0] = [];
+        self.select(no_columns).take(1).map(|rows| rows.is_empty())
     }
 
     /// Get column names.
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs 
b/crates/spark-connect/tests/e2e_dataframe.rs
index dacfc361..82633a96 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -937,3 +937,18 @@ fn repartition_by_range_splits_into_contiguous_ranges() {
         vec![(0, 24, 25), (25, 49, 25), (50, 74, 25), (75, 99, 25)]
     );
 }
+
+#[test]
+fn is_empty_is_true_only_without_rows() {
+    if !should_run() {
+        return;
+    }
+    let s = session();
+    assert!(!s.range(3).unwrap().is_empty().unwrap());
+    assert!(s
+        .range(3)
+        .unwrap()
+        .filter(col("id").gt(lit(5)))
+        .is_empty()
+        .unwrap());
+}
diff --git a/crates/spark-connect/tests/is_empty_plan.rs 
b/crates/spark-connect/tests/is_empty_plan.rs
new file mode 100644
index 00000000..587205c3
--- /dev/null
+++ b/crates/spark-connect/tests/is_empty_plan.rs
@@ -0,0 +1,169 @@
+// 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.
+
+//! The request of `DataFrame::is_empty`, against a loopback gRPC service that 
records the
+//! bytes of every ExecutePlan request; no Spark server required.
+
+use std::convert::Infallible;
+use std::sync::{Arc, Mutex};
+use std::task::{Context, Poll};
+
+use futures::stream;
+use prost::Message;
+use spark_connect::SparkSession;
+use spark_connect_core::bytes_codec::BytesCodec;
+use spark_connect_proto as proto;
+use tokio::net::TcpListener;
+use tonic::body::Body;
+use tonic::codegen::{http, BoxFuture, Service};
+use tonic::server::{NamedService, ServerStreamingService, UnaryService};
+use tonic::{Request, Response, Status};
+
+const SERVICE: &str = "/spark.connect.SparkConnectService/";
+type Requests = Arc<Mutex<Vec<Vec<u8>>>>;
+
+#[derive(Clone)]
+struct TestService(Requests);
+
+impl NamedService for TestService {
+    const NAME: &'static str = "spark.connect.SparkConnectService";
+}
+
+impl Service<http::Request<Body>> for TestService {
+    type Response = http::Response<Body>;
+    type Error = Infallible;
+    type Future = BoxFuture<Self::Response, Self::Error>;
+
+    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), 
Self::Error>> {
+        Poll::Ready(Ok(()))
+    }
+
+    fn call(&mut self, request: http::Request<Body>) -> Self::Future {
+        let method = 
request.uri().path().trim_start_matches(SERVICE).to_string();
+        let requests = self.0.clone();
+        Box::pin(async move {
+            let mut grpc = tonic::server::Grpc::new(BytesCodec);
+            Ok(match method.as_str() {
+                "ExecutePlan" => grpc.server_streaming(Execute(requests), 
request).await,
+                _ => grpc.unary(Config, request).await,
+            })
+        })
+    }
+}
+
+/// ExecutePlan: records the request and answers with an empty, complete 
result.
+struct Execute(Requests);
+
+impl ServerStreamingService<Vec<u8>> for Execute {
+    type Response = Vec<u8>;
+    type ResponseStream = 
futures::stream::Iter<std::vec::IntoIter<Result<Vec<u8>, Status>>>;
+    type Future = BoxFuture<Response<Self::ResponseStream>, Status>;
+
+    fn call(&mut self, request: Request<Vec<u8>>) -> Self::Future {
+        let bytes = request.into_inner();
+        let session_id = proto::ExecutePlanRequest::decode(bytes.as_slice())
+            .unwrap()
+            .session_id;
+        self.0.lock().unwrap().push(bytes);
+        let done = proto::ExecutePlanResponse {
+            session_id,
+            response_id: "complete".into(),
+            response_type: 
Some(proto::execute_plan_response::ResponseType::ResultComplete(
+                proto::execute_plan_response::ResultComplete {},
+            )),
+            ..Default::default()
+        };
+        let frames = stream::iter(vec![Ok(done.encode_to_vec())]);
+        Box::pin(async { Ok(Response::new(frames)) })
+    }
+}
+
+/// Config: answers with no pairs, which leaves plan compression off.
+struct Config;
+
+impl UnaryService<Vec<u8>> for Config {
+    type Response = Vec<u8>;
+    type Future = BoxFuture<Response<Vec<u8>>, Status>;
+
+    fn call(&mut self, request: Request<Vec<u8>>) -> Self::Future {
+        let session_id = 
proto::ConfigRequest::decode(request.into_inner().as_slice())
+            .unwrap()
+            .session_id;
+        let body = proto::ConfigResponse {
+            session_id,
+            ..Default::default()
+        }
+        .encode_to_vec();
+        Box::pin(async { Ok(Response::new(body)) })
+    }
+}
+
+/// Serves on a thread of its own, since a session blocks the thread that 
calls it.
+fn serve() -> (String, Requests) {
+    let requests = Requests::default();
+    let service = TestService(requests.clone());
+    let (sender, receiver) = std::sync::mpsc::channel();
+    std::thread::spawn(move || {
+        let runtime = tokio::runtime::Builder::new_multi_thread()
+            .enable_all()
+            .build()
+            .unwrap();
+        runtime.block_on(async move {
+            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+            sender.send(listener.local_addr().unwrap()).unwrap();
+            let incoming = stream::unfold(listener, |listener| async {
+                Some((listener.accept().await.map(|(socket, _)| socket), 
listener))
+            });
+            tonic::transport::Server::builder()
+                .add_service(service)
+                .serve_with_incoming(incoming)
+                .await
+                .unwrap();
+        });
+    });
+    (format!("sc://{}", receiver.recv().unwrap()), requests)
+}
+
+#[test]
+fn is_empty_sends_a_limit_of_one_row_over_an_empty_projection_as_pyspark() {
+    let (remote, requests) = serve();
+    let session = SparkSession::builder()
+        .remote(&remote)
+        .get_or_create()
+        .unwrap();
+    assert!(session.range(3).unwrap().is_empty().unwrap());
+
+    let requests = requests.lock().unwrap();
+    assert_eq!(requests.len(), 1);
+    let request = 
proto::ExecutePlanRequest::decode(requests[0].as_slice()).unwrap();
+    let Some(proto::plan::OpType::Root(root)) = request.plan.and_then(|p| 
p.op_type) else {
+        panic!("not a root plan");
+    };
+    let Some(proto::relation::RelType::Limit(limit)) = root.rel_type else {
+        panic!("not a limit: {root:?}");
+    };
+    assert_eq!(limit.limit, 1);
+    let input = limit.input.unwrap();
+    let Some(proto::relation::RelType::Project(project)) = input.rel_type else 
{
+        panic!("not a projection: {input:?}");
+    };
+    assert!(project.expressions.is_empty());
+    assert!(matches!(
+        project.input.unwrap().rel_type,
+        Some(proto::relation::RelType::Range(_))
+    ));
+}
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 0f6bd0d6..982e4036 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1396,6 +1396,22 @@ def 
test_repartition_does_not_unpack_a_list_among_its_columns_as_pyspark(mock_co
     df.repartitionByRange(2, "id", F.col("id"))
 
 
+def 
test_is_empty_sends_a_limit_of_one_row_over_an_empty_projection_as_pyspark(mock_connect):
+    # As PySpark's select().take(1): Limit(1) over a Project with no 
expressions.
+    spark, service = mock_connect
+    spark.range(3).isEmpty()
+    # ExecutePlanRequest.plan=3, Plan.root=1; Relation.limit=8, project=3, 
range=15;
+    # Project.expressions=3.
+    plan = 
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+    relation = parse_message(plan)
+    assert 9 not in relation
+    limit = parse_message(relation[8][0])
+    assert limit[2] == [1]
+    project = parse_message(parse_message(limit[1][0])[3][0])
+    assert 3 not in project
+    assert 15 in parse_message(project[1][0])
+
+
 def 
test_session_id_of_any_uuid_version_and_the_user_id_of_the_requests(monkeypatch,
 mock_connect):
     # A session_id is any UUID, as uuid.UUID(session_id, version=4) takes it, 
and is sent as
     # given. The user ID of each request is SPARK_USER, else USER, as PySpark 
sets it.


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

Reply via email to