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 ae7b003f [SPARK-61292][CONNECT][PYTHON] Ask the server in
DataFrame.isLocal of the Python client, as PySpark does
ae7b003f is described below
commit ae7b003f14e7fafbbf67411f33f860800bcbdbc8
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 11:27:33 2026 +0900
[SPARK-61292][CONNECT][PYTHON] Ask the server in DataFrame.isLocal of the
Python client, as PySpark does
### What changes were proposed in this pull request?
[SPARK-61292](https://issues.apache.org/jira/browse/SPARK-61292):
`DataFrame.isLocal` of the Python client asks the server, as PySpark's does,
instead of answering from the client's own plan.
- `spark-connect` gets `DataFrame::is_local_on_server`, which sends an
`AnalyzePlan` `IsLocal` request of the DataFrame's plan and returns the
server's answer. The answer is cached per DataFrame, as the schema is: exact
clones share it, a derived DataFrame asks the server for its own plan, and a
failed request is not cached. The existing client-side `DataFrame::is_local` is
unchanged.
- `pyspark-rs` binds `isLocal` to `is_local_on_server`, detaching from the
GIL while the request runs, as `isStreaming` does.
- Offline tests in `python/tests/test_dropin_offline.py` use the mock
server, which now answers `IsLocal` from the root relation of the plan (or from
a value a test sets). They cover one request per DataFrame, the server's answer
being returned, and a failure not being cached. The offline checks of
`createDataFrame` local-ness now go through that mock server, since the answer
is no longer computed locally.
- Live tests: `python/tests/test_dropin_e2e.py` checks `isLocal` for
`VALUES`, `SHOW DATABASES`, `SELECT 1`, `createDataFrame` and `range`, and
`crates/spark-connect/tests/e2e_new_methods.rs` checks the server's answer in
Rust.
### Why are the changes needed?
PySpark's `DataFrame.isLocal` sends an `AnalyzePlan` `IsLocal` request, and
the server answers from the plan it analyzes. The drop-in answered from the
plan on the client, so only a local relation built by the client, or a command
result, was local. The two differ where the server resolves another plan into a
local relation: `spark.sql("VALUES (1)").isLocal()` was `False` and PySpark
returns `True`.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client. `DataFrame.isLocal()` now returns the server's
answer, as PySpark does, and sends one request per DataFrame, as PySpark's
cached call does. For example, `spark.sql("VALUES (1)").isLocal()` is now
`True`, where it was `False`. The Rust API gains
`DataFrame::is_local_on_server`; `DataFrame::is_local` is unchanged.
### How was this patch tested?
- `cargo test -p apache-spark-connect --release --lib`: 528 passed.
- `cargo test -p apache-spark-connect --release --no-run` and with
`--features wasm-udf`: compile.
- `cargo fmt --all --check`: passes.
- Offline Python with the mock server: `tests/test_dropin_offline.py` 1644
passed, `tests/test_ml_offline.py` 97 passed, `tests/test_arrow_handoff.py`
1189 passed. The new tests are
`test_is_local_asks_the_server_once_per_dataframe`,
`test_is_local_returns_the_servers_answer` and
`test_is_local_failure_is_not_cached`. The `createDataFrame` local-ness tests
now ask the mock server, and the arrow handoff mock answers `IsLocal`.
- With the extension built from master, the three new offline tests fail;
with this change they pass.
- Live Python against a Spark 4.3.0 Connect server: the drop-in, Arrow and
ML suites pass (241 passed, 1 skipped), including the new
`test_is_local_is_the_servers_answer_as_pyspark` (five cases: `VALUES (1)` and
`SHOW DATABASES` are local, `SELECT 1` and `range(1)` are not,
`createDataFrame` is). The five cases give the same answers with PySpark 4.3.0
on the same server.
- Clippy reports no diagnostics on the changed lines.
- Live Rust
(`crates/spark-connect/tests/e2e_new_methods.rs::is_local_on_server_is_the_servers_answer`)
passes against the same server.
### 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 #447 from tdcmeehan/SPARK-61292-is-local-from-server.
Lead-authored-by: Timothy Meehan <[email protected]>
Co-authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 7 +--
crates/spark-connect/src/dataframe.rs | 38 +++++++++++++
crates/spark-connect/tests/e2e_new_methods.rs | 17 ++++++
python/tests/_mock_connect_server.py | 18 +++++++
python/tests/test_arrow_handoff.py | 10 +++-
python/tests/test_dropin_e2e.py | 16 ++++++
python/tests/test_dropin_offline.py | 77 ++++++++++++++++++++++-----
7 files changed, 164 insertions(+), 19 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index f6017ab3..90ce443e 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1954,10 +1954,11 @@ impl PyDataFrame {
py.detach(|| self.dataframe.input_files()).to_pyerr()
}
- /// Whether collect/take can run without a Spark job (a local relation).
+ /// Whether the server answers that this DataFrame is local (a local
relation).
#[pyo3(name = "isLocal")]
- fn is_local(&self) -> bool {
- self.dataframe.is_local()
+ fn is_local(&self, py: Python<'_>) -> PyResult<bool> {
+ py.detach(|| self.dataframe.is_local_on_server().map_err(Box::new))
+ .to_pyerr()
}
/// Whether this (cached) DataFrame is cached.
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index 121efaba..c536aff7 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -45,6 +45,9 @@ pub struct DataFrame {
// resolved schema, but have their own cache for subsequent analysis.
// The resolved value is immutable, so propagation need not copy wide
schemas.
schema_cache: Arc<Mutex<Option<Arc<DataType>>>>,
+ // The server's answer to `is_local_on_server`, cached like the schema:
exact clones
+ // share it and a derived plan asks the server again.
+ is_local_cache: Arc<Mutex<Option<bool>>>,
// The information of the last execution of this DataFrame, as PySpark's
// `DataFrame._execution_info`: exact clones share it, and a derived
DataFrame, of
// another plan, has its own, which is empty until it executes.
@@ -371,6 +374,7 @@ impl DataFrame {
session,
plan: Arc::new(plan),
schema_cache: Arc::new(Mutex::new(schema)),
+ is_local_cache: Arc::new(Mutex::new(None)),
execution: Arc::new(Mutex::new(None)),
}
}
@@ -2319,6 +2323,40 @@ impl DataFrame {
}
}
+ /// Whether the server answers that this DataFrame is local, mirroring
PySpark's
+ /// `DataFrame.isLocal`, which asks the server about the plan it analyzes.
Unlike
+ /// [`DataFrame::is_local`], this sees the plan as the server resolves it.
+ ///
+ /// The answer is cached for this DataFrame and its exact clones; a failed
request is
+ /// not cached.
+ pub fn is_local_on_server(&self) -> Result<bool> {
+ // As `schema`, hold the lock across the request so concurrent calls
send one.
+ let mut cached = self.is_local_cache.lock().unwrap_or_else(|poisoned| {
+ self.is_local_cache.clear_poison();
+ poisoned.into_inner()
+ });
+ if let Some(is_local) = *cached {
+ return Ok(is_local);
+ }
+ let request =
self.analyze_request(proto::analyze_plan_request::Analyze::IsLocal(
+ proto::analyze_plan_request::IsLocal {
+ plan: Some(proto::Plan {
+ op_type: Some(proto::plan::OpType::Root(self.relation()?)),
+ }),
+ },
+ ));
+ let response = block_on(self.session.client().analyze_plan(request))?;
+ match response.result {
+ Some(proto::analyze_plan_response::Result::IsLocal(r)) => {
+ *cached = Some(r.is_local);
+ Ok(r.is_local)
+ }
+ _ => Err(SparkError::connect_msg(
+ "AnalyzePlan response did not contain an isLocal result",
+ )),
+ }
+ }
+
/// Collect the DataFrame and serialize it to Arrow IPC (file format)
bytes.
///
/// The returned buffer is a self-describing Arrow IPC stream that can be
read
diff --git a/crates/spark-connect/tests/e2e_new_methods.rs
b/crates/spark-connect/tests/e2e_new_methods.rs
index 0bb20b90..4488cc68 100644
--- a/crates/spark-connect/tests/e2e_new_methods.rs
+++ b/crates/spark-connect/tests/e2e_new_methods.rs
@@ -84,6 +84,23 @@ fn checkpoints_and_input_files_local() {
let _ = df.is_cached().expect("is_cached");
}
+#[test]
+fn is_local_on_server_is_the_servers_answer() {
+ if !should_run() {
+ return;
+ }
+ let spark = session();
+ // A VALUES relation is local on the server, whatever the plan the client
built.
+ let values = spark.sql("VALUES (1)").expect("sql");
+ assert!(values.is_local_on_server().expect("isLocal"));
+ assert!(values.is_local_on_server().expect("isLocal again"));
+ assert!(!spark
+ .range(1)
+ .expect("range")
+ .is_local_on_server()
+ .expect("isLocal"));
+}
+
#[test]
fn stat_corr_cov_sample_by() {
if !should_run() {
diff --git a/python/tests/_mock_connect_server.py
b/python/tests/_mock_connect_server.py
index f4cc8da2..607fdee7 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -282,6 +282,9 @@ def serve(connection):
self.block_result_complete = False
self.result_complete_operations = []
self.analyze_requests = []
+ # The isLocal answer of a test, or None for the answer of the
plan, and a failure.
+ self.local = None
+ self.local_failure = False
self.execute_requests = []
self.release_execute_requests = []
self.execute_payload = b""
@@ -356,6 +359,21 @@ def serve(connection):
if 8 in parse_message(request):
streaming = getattr(self, "streaming", False)
return message_field(6, varint_field(1, 1) if streaming else
b"")
+ # base.proto: AnalyzePlanRequest.is_local=7 -> IsLocal.plan=1 ->
Plan.root=1;
+ # AnalyzePlanResponse.is_local=5 -> IsLocal.is_local=1. A local
relation is
+ # Relation.local_relation=11, cached_local_relation=36 or
+ # chunked_cached_local_relation=45.
+ # `local`, which a test may set, overrides the answer derived from
the plan.
+ if 7 in parse_message(request):
+ if getattr(self, "local_failure", False):
+ context.abort(grpc.StatusCode.INVALID_ARGUMENT, "isLocal
unavailable")
+ local = getattr(self, "local", None)
+ if local is None:
+ is_local = parse_message(parse_message(request)[7][0])
+ plan = parse_message(is_local[1][0])
+ relation = parse_message(plan[1][0])
+ local = any(field in relation for field in (11, 36, 45))
+ return message_field(5, varint_field(1, 1) if local else b"")
if blocked and not response_gate.wait(5):
context.abort(
grpc.StatusCode.DEADLINE_EXCEEDED,
diff --git a/python/tests/test_arrow_handoff.py
b/python/tests/test_arrow_handoff.py
index af89b6b6..6d0150c0 100644
--- a/python/tests/test_arrow_handoff.py
+++ b/python/tests/test_arrow_handoff.py
@@ -670,9 +670,15 @@ def _arrow_input_service(
dict(name=name, data_type=ddl_type(kind), nullable=True) for name,
kind in fields]))
def analyze(raw, context):
- # As the server, which parses the DDL schemas that the client sends
(`_parse_ddl`);
- # the tests ask for no other analysis.
+ # As the server, which parses the DDL schemas that the client sends
(`_parse_ddl`) and
+ # answers whether a plan is local: a local relation, cached or
chunked, is local.
request = protocol("AnalyzePlanRequest").FromString(raw)
+ if request.WhichOneof("analyze") == "is_local":
+ local = request.is_local.plan.root.WhichOneof("rel_type") in (
+ "local_relation", "cached_local_relation",
"chunked_cached_local_relation")
+ return protocol("AnalyzePlanResponse",
session_id=request.session_id,
+ server_side_session_id=server_id,
+ is_local=dict(is_local=local)).SerializeToString()
if request.WhichOneof("analyze") != "ddl_parse":
context.abort(grpc.StatusCode.UNIMPLEMENTED, "Method not found!")
state["ddl_strings"].append(request.ddl_parse.ddl_string)
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 15e3e27b..851aaad5 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2863,6 +2863,22 @@ def test_sql_runs_statements_eagerly(session):
assert [tuple(r) for r in query.collect()] == [(1,)]
[email protected](
+ "make, expected",
+ [
+ (lambda s: s.sql("VALUES (1)"), True),
+ (lambda s: s.sql("SHOW DATABASES"), True),
+ (lambda s: s.sql("SELECT 1"), False),
+ (lambda s: s.createDataFrame([(1,)], "a int"), True),
+ (lambda s: s.range(1), False),
+ ],
+)
+def test_is_local_is_the_servers_answer_as_pyspark(session, make, expected):
+ # As PySpark: isLocal asks the server about the plan, so a VALUES is
local, though the
+ # client's own plan of it is not.
+ assert make(session).isLocal() is expected
+
+
def
test_struct_field_from_ddl_parses_as_data_type_from_ddl_as_pyspark(session):
# As PySpark: StructField inherits DataType.fromDDL, so it parses a DDL
string to the type
# that DataType.fromDDL gives, with the same errors, and a StructType
creates a DataFrame.
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 3b71ad58..f7678857 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -6753,6 +6753,48 @@ def
test_is_streaming_asks_the_server_as_pyspark(mock_connect):
assert sum(8 in parse_message(request) for request in
service.analyze_requests) == 2
+def _is_local_requests(service):
+ # base.proto: AnalyzePlanRequest.is_local=7.
+ return sum(7 in parse_message(request) for request in
service.analyze_requests)
+
+
+def test_is_local_asks_the_server_once_per_dataframe(mock_connect):
+ # As PySpark's: isLocal is cached per DataFrame, so a second call sends no
request.
+ spark, service = mock_connect
+ df = spark.createDataFrame([(1,)], "a int")
+ assert df.isLocal() is True
+ assert df.isLocal() is True
+ assert _is_local_requests(service) == 1
+ # A derived DataFrame analyzes its own plan.
+ assert df.select("a").isLocal() is False
+ assert _is_local_requests(service) == 2
+
+
+def test_is_local_returns_the_servers_answer(mock_connect):
+ spark, service = mock_connect
+ df = spark.createDataFrame([(1,)], "a int")
+ service.local = False
+ try:
+ assert df.isLocal() is False
+ finally:
+ service.local = None
+
+
+def test_is_local_failure_is_not_cached(mock_connect):
+ from pyspark.errors.exceptions.connect import SparkConnectGrpcException
+
+ spark, service = mock_connect
+ df = spark.createDataFrame([(1,)], "a int")
+ service.local_failure = True
+ try:
+ with pytest.raises(SparkConnectGrpcException, match="isLocal
unavailable"):
+ df.isLocal()
+ finally:
+ service.local_failure = False
+ assert df.isLocal() is True
+ assert _is_local_requests(service) == 2
+
+
def test_struct_type_field_access():
"""Test accessing StructType fields by index and name."""
st = T.StructType([
@@ -8633,13 +8675,19 @@ def test_timedelta_values_convert_as_pyspark():
_local_create_dataframe([(value,)], "d interval day to second")
-def _local_create_dataframe(*args):
+def _local_create_dataframe(*args, session=None):
# The local relation and its toDF are built without a server; a DDL
schema, which PySpark
# asks the server to parse, is parsed as the server would.
args = list(args)
if len(args) > 1 and isinstance(args[1], str) and ddl_json(args[1]) is not
None:
args[1] = T._parse_datatype_json_string(json.dumps(ddl_json(args[1])))
- return _offline_session().createDataFrame(*args)
+ return (_offline_session() if session is None else
session).createDataFrame(*args)
+
+
+def _is_local_created(mock_connect, *args):
+ # isLocal is the server's answer, which the mock derives from the plan it
receives.
+ spark, _ = mock_connect
+ return _local_create_dataframe(*args, session=spark).isLocal()
@pytest.mark.parametrize("data,schema,expected", [
@@ -8657,8 +8705,8 @@ def _local_create_dataframe(*args):
([1, 2], T.LongType(), True),
([], "a long", True),
])
-def test_create_dataframe_rows_is_local_as_pyspark(data, schema, expected):
- assert _local_create_dataframe(data, schema).isLocal() is expected
+def test_create_dataframe_rows_is_local_as_pyspark(mock_connect, data, schema,
expected):
+ assert _is_local_created(mock_connect, data, schema) is expected
@pytest.mark.parametrize("schema", [None, ["c", "d"], ["c"], "a long, b
string",
@@ -8675,10 +8723,10 @@ def
test_create_dataframe_pandas_is_not_local_as_pyspark(mock_connect, schema):
assert 18 in parse_message(plan[1][0])
-def test_create_dataframe_empty_pandas_is_local_as_pyspark():
+def test_create_dataframe_empty_pandas_is_local_as_pyspark(mock_connect):
pd = pytest.importorskip("pandas")
# Empty input returns the relation of its schema, without toDF.
- assert _local_create_dataframe(pd.DataFrame({"a": [], "b": []}), "a long,
b string").isLocal()
+ assert _is_local_created(mock_connect, pd.DataFrame({"a": [], "b": []}),
"a long, b string")
_Pair = namedtuple("_Pair", ["x", "y"])
@@ -9200,15 +9248,16 @@ def
test_create_dataframe_warns_of_the_arguments_that_connect_ignores():
_local_create_dataframe([(1,)], None, None, True)
-def test_create_dataframe_converts_numpy_scalars_as_pyarrow():
+def test_create_dataframe_converts_numpy_scalars_as_pyarrow(mock_connect):
import re
np = pytest.importorskip("numpy")
# As PySpark, where PyArrow takes a NumPy scalar as the Python value that
it stands for:
# an integer, a float (truncated for an integer type) and a bool (also for
an integer).
- assert _local_create_dataframe(
+ assert _is_local_created(
+ mock_connect,
[(np.int64(1), np.float32(0.5), np.bool_(True), np.float32(1.5),
np.bool_(True))],
- "a bigint, b double, c boolean, d bigint, e bigint").isLocal()
+ "a bigint, b double, c boolean, d bigint, e bigint")
for value, schema, message in [
(np.bool_(True), "a double",
r"Could not convert \S+ with type numpy\.bool_?: tried to convert to
double"),
@@ -17380,12 +17429,12 @@ def
test_catalog_warns_of_the_deprecated_db_name_as_pyspark(mock_connect, call,
@pytest.mark.parametrize("text", [
"", "1.25", "-42", "NaN", "a\x00b", "é雪😀", "e\u0301", "\uffff",
])
-def test_exact_string_converts_as_text(text):
+def test_exact_string_converts_as_text(mock_connect, text):
# A string, even when it reads as a number, is text: with a string or an
integer in
# another row, the column is a string column, as PySpark merges the types
(the live
# suite checks the values).
- assert _local_create_dataframe([Row(value=text), Row(value="y")]).isLocal()
- assert _local_create_dataframe([Row(value=text), Row(value=5)]).isLocal()
+ assert _is_local_created(mock_connect, [Row(value=text), Row(value="y")])
+ assert _is_local_created(mock_connect, [Row(value=text), Row(value=5)])
@pytest.mark.parametrize("text", ["\ud800", "\udfff", "a\ud800b"])
@@ -17395,7 +17444,7 @@ def
test_exact_string_surrogate_error_preserves_generic_fallback(text):
_local_create_dataframe([Row(value=text)])
-def test_exact_string_subclass_uses_generic_conversion():
+def test_exact_string_subclass_uses_generic_conversion(mock_connect):
from pyspark.errors import PySparkTypeError
class IndexString(str):
@@ -17404,7 +17453,7 @@ def
test_exact_string_subclass_uses_generic_conversion():
# As in PySpark, which takes an instance of a subclass by its `__dict__`:
an empty
# struct, which merges with neither an integer nor a string.
- assert _local_create_dataframe([Row(value=IndexString("x"))]).isLocal()
+ assert _is_local_created(mock_connect, [Row(value=IndexString("x"))])
for other, data_type in [(5, "LongType"), ("y", "StringType")]:
with pytest.raises(PySparkTypeError) as error:
_local_create_dataframe([Row(value=IndexString("x")),
Row(value=other)])
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]