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 10a08265 [SPARK-61399][CONNECT][PYTHON] Raise in fit of the native
Pipeline and CrossValidator instead of returning a model that the server cannot
use
10a08265 is described below
commit 10a08265362cdb754e21456e2d3000ce2816096a
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:41:51 2026 +0900
[SPARK-61399][CONNECT][PYTHON] Raise in fit of the native Pipeline and
CrossValidator instead of returning a model that the server cannot use
### What changes were proposed in this pull request?
[SPARK-61399](https://issues.apache.org/jira/browse/SPARK-61399): found in
a review of #446 (SPARK-61324) and #460 (SPARK-61334). `fit` of the native
`Pipeline` and `CrossValidator` (`Pipeline::fit_impl` and
`CrossValidator::fit_impl` in `crates/spark-connect/src/ml.rs`) returns a
`NOT_IMPLEMENTED` error (`Pipeline.fit` or `CrossValidator.fit`), of kind
`NotImplementedError`, before any request, instead of a model. The Python
drop-in raises it as `PySparkNotImplementedError: [NOT_IMPL [...]
### Why are the changes needed?
Both `fit_impl`s ignored the DataFrame and returned a local model without
any server call. So `fit` silently succeeded, and the model's `transform` then
failed on the server:
```python
from pyspark.ml.connect import Pipeline
model = Pipeline(stages=["va"]).fit(df) # no error, and no request
model.transform(df) # UnknownException:
java.lang.AssertionError (MLHandler._transformMLRelation)
```
The same held for `CrossValidator(numFolds=2).fit(df)`. The native
`Pipeline` takes stage names, not stages, and the native `CrossValidator` has
no estimator, evaluator or param grid, so neither can be fitted as it is. #446
also said that "Pipeline fit and transform still fail on the server with the
known AssertionError", where it was the transform alone. Now `fit` raises
`NOT_IMPLEMENTED` at once, as PySpark's `NOT_IMPLEMENTED` errors do.
### Does this PR introduce _any_ user-facing change?
Yes. `fit` of the native `Pipeline` and `CrossValidator` raises
`NOT_IMPLEMENTED` instead of returning a model that fails at transform. In
Rust, `Estimator::fit` of both returns a `NotImplementedError`.
### How was this patch tested?
- Rust unit tests for both fits (the kind, the condition and the message).
- An offline test,
`test_ml_pipeline_and_cross_validator_fit_is_not_implemented`, which checks the
error and that no request but ML deletes is sent, on the constructor and setter
paths.
- The existing tests that fitted these classes now assert the error
(`e2e_coverage`, the ML unit tests, `test_ml_offline.py`, and `test_ml_e2e.py`
against a Spark 4.3.0 server).
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--release --lib`, the `--no-run` builds, `cargo fmt --check`,
`scripts/audit_no_stubs.sh`, and the offline and e2e ML suites.
### 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 #490 from HyukjinKwon/SPARK-61399-native-pipeline-cv-fit.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/ml.rs | 82 ++++++++++++++++++------------
crates/spark-connect/tests/e2e_coverage.rs | 11 ++--
docs/compatibility.md | 15 ++++++
python/tests/test_ml_e2e.py | 14 ++---
python/tests/test_ml_offline.py | 71 +++++++++++++++++++-------
5 files changed, 133 insertions(+), 60 deletions(-)
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index ef76e446..895529ab 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -6,6 +6,7 @@
//! - Base traits: `Estimator`, `Transformer`, `Model`, `Evaluator`
//! - Concrete example: `StandardScaler` estimator + `StandardScalerModel`
+use spark_connect_core::error::{SparkError, SparkErrorKind};
use spark_connect_proto as proto;
use std::collections::HashMap;
use std::sync::Arc;
@@ -1032,6 +1033,16 @@ impl Model for MaxAbsScalerModel {
}
}
+/// The NOT_IMPLEMENTED error of a `fit` that the Connect ML protocol cannot
run, named by
+/// `feature` as PySpark's NOT_IMPLEMENTED names it.
+fn fit_not_implemented(feature: &str) -> SparkError {
+ SparkError::classed(
+ SparkErrorKind::NotImplementedError,
+ "NOT_IMPLEMENTED",
+ &[("feature", feature)],
+ )
+}
+
/// Submit training data and parameters and read the fitted operator metadata.
fn fit_via_command(
operator: &MlOperator,
@@ -2660,17 +2671,10 @@ impl Estimator for Pipeline {
&mut self.params
}
+ // The stages are names that the server cannot fit, and it has no
PipelineModel to
+ // transform. This raises before any request, so no model that fails later
is returned.
fn fit_impl(&mut self, _df: &DataFrame) ->
spark_connect_core::error::Result<Box<dyn Model>> {
- let model = PipelineModel {
- operator: MlOperator::with_uid(
- &self.operator.name,
- &self.operator.uid,
- OperatorType::Model,
- ),
- params: self.params.clone(),
- stages: self.stages(),
- };
- Ok(Box::new(model))
+ Err(fit_not_implemented("Pipeline.fit"))
}
}
@@ -2788,9 +2792,8 @@ impl Evaluator for MulticlassClassificationEvaluator {
///
/// The nested estimator/evaluator/estimatorParamMaps have no scalar-literal
/// encoding, so this carries the numeric tuning params it can faithfully
encode
-/// (numFolds, seed, parallelism); the sub-estimator/evaluator are held for the
-/// server-side fit. fit() produces a CrossValidatorModel the same lazy way the
-/// other estimators do.
+/// (numFolds, seed, parallelism). fit() raises NOT_IMPLEMENTED, as those
nested
+/// params are not held for a server-side fit.
#[derive(Debug, Clone)]
pub struct CrossValidator {
operator: MlOperator,
@@ -2854,16 +2857,10 @@ impl Estimator for CrossValidator {
fn params_mut(&mut self) -> &mut Params {
&mut self.params
}
+ // The estimator, evaluator and param grid are not held, so the server
cannot run the
+ // tuning. This raises before any request, so no model that fails later is
returned.
fn fit_impl(&mut self, _df: &DataFrame) ->
spark_connect_core::error::Result<Box<dyn Model>> {
- let model = CrossValidatorModel {
- operator: MlOperator::with_uid(
- &self.operator.name,
- &self.operator.uid,
- OperatorType::Model,
- ),
- params: self.params.clone(),
- };
- Ok(Box::new(model))
+ Err(fit_not_implemented("CrossValidator.fit"))
}
}
@@ -3365,6 +3362,23 @@ mod tests {
);
}
+ /// Asserts that `result` is the NOT_IMPLEMENTED error of the `fit` named
`feature`, and
+ /// that no model is returned with it.
+ fn assert_fit_not_implemented(
+ result: spark_connect_core::error::Result<Box<dyn Model>>,
+ feature: &str,
+ ) {
+ let error = result
+ .err()
+ .expect("fit raises an error, and returns no model");
+ assert_eq!(error.kind, SparkErrorKind::NotImplementedError);
+ assert_eq!(error.get_condition().as_deref(), Some("NOT_IMPLEMENTED"));
+ assert_eq!(
+ error.message(),
+ format!("[NOT_IMPLEMENTED] {feature} is not implemented.")
+ );
+ }
+
#[test]
fn cross_validator_creation_getters_and_fit() {
let cv = CrossValidator::new()
@@ -3382,14 +3396,22 @@ mod tests {
assert!(cv.params().get_param("seed").is_some());
assert_eq!(CrossValidator::default().num_folds(), 3);
- // fit builds a CrossValidatorModel; its transform yields an
MlTransform plan.
+ // fit is not implemented: it raises NOT_IMPLEMENTED without a
request, and returns no
+ // model that the server could not transform.
let s = offline_session();
let df = s.range(3).unwrap();
let mut cv2 = CrossValidator::new().set_num_folds(2);
- let mut model = cv2.fit(&df).unwrap();
- let out = model.transform(&df).unwrap();
- assert!(matches!(out.plan.as_ref(), LogicalPlan::MlTransform { .. }));
- let _ = model.clone_box();
+ assert_fit_not_implemented(cv2.fit(&df), "CrossValidator.fit");
+ assert_eq!(cv2.num_folds(), 2);
+ }
+
+ #[test]
+ fn pipeline_fit_is_not_implemented() {
+ let s = offline_session();
+ let df = s.range(3).unwrap();
+ let mut pipeline = Pipeline::new().set_stages(vec!["a", "b"]);
+ assert_fit_not_implemented(pipeline.fit(&df), "Pipeline.fit");
+ assert_eq!(pipeline.stages(), ["a", "b"]);
}
#[test]
@@ -3420,12 +3442,6 @@ mod tests {
assert_eq!(transform_model_ref(&out), "indexer-1");
let _ = m.clone_box();
- let mut pipe = Pipeline::new().set_stages(vec!["a", "b"]);
- assert_eq!(pipe.stages().len(), 2);
- let mut m = pipe.fit(&df).unwrap();
- let _ = m.transform(&df).unwrap();
- let _ = m.clone_box();
-
// VectorAssembler transformer.
let mut va = VectorAssembler::new()
.set_input_cols(vec!["a", "b"])
diff --git a/crates/spark-connect/tests/e2e_coverage.rs
b/crates/spark-connect/tests/e2e_coverage.rs
index 0624b6ae..fd89a724 100644
--- a/crates/spark-connect/tests/e2e_coverage.rs
+++ b/crates/spark-connect/tests/e2e_coverage.rs
@@ -1308,11 +1308,14 @@ fn ml_estimators_and_transformers() {
.set_metric_name("areaUnderROC");
assert_eq!(bin_eval.evaluate(&bin_df).unwrap(), 0.75);
- // Pipeline carries stage names as params; this smoke test tolerates
rejection.
+ // Pipeline.fit is not implemented: the stages are names that the server
cannot fit.
+ use spark_connect::SparkErrorKind;
let mut pipeline = Pipeline::new().set_stages(vec!["scaler", "lr"]);
- if let Ok(mut m) = pipeline.fit(&df) {
- let _ = m.transform(&df).and_then(|d| d.count());
- }
+ let error = pipeline
+ .fit(&df)
+ .err()
+ .expect("Pipeline.fit raises an error");
+ assert_eq!(error.kind, SparkErrorKind::NotImplementedError);
}
#[test]
diff --git a/docs/compatibility.md b/docs/compatibility.md
index e60f1bc8..f20463dd 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -253,6 +253,21 @@ The Python model uses the existing `MLModel.transform`
interface. Model inspecti
(coefficients, intercept and summaries), single-vector prediction and model
persistence are not exposed by this addition.
+## Native Pipeline and CrossValidator: fit is not implemented
+
+`spark_connect::ml::Pipeline` and `spark_connect::ml::CrossValidator`, and
their Python
+classes `pyspark.ml.connect.Pipeline` and `pyspark.ml.connect.CrossValidator`,
do not fit.
+Their `fit` raises `NOT_IMPLEMENTED` (`PySparkNotImplementedError` in Python),
naming
+`Pipeline.fit` or `CrossValidator.fit`, before any request is sent, and
returns no model.
+The Connect ML protocol cannot run either one: the native Pipeline holds stage
names, which
+the server cannot fit, and it has no pipeline model to transform; the native
CrossValidator
+holds its numeric params only, without the estimator, evaluator or param grid.
Their
+constructors and setters still set the params, as before.
+
+To fit a pipeline or to tune a model from Python, use the vendored
`pyspark.ml.Pipeline` and
+`pyspark.ml.tuning.CrossValidator`, which take the estimator and transformer
objects, as
+PySpark does. The Rust API has no way to fit a pipeline or to tune a model.
+
## pyspark.ml
The DataFrame-based `pyspark.ml` API (`pyspark.ml.classification`, `feature`,
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index c47b3fff..f6e64077 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -376,7 +376,6 @@ def
test_ml_connect_setters_change_the_next_evaluate_and_fit_as_pyspark(session)
# As PySpark's Params._set: a setter of pyspark.ml.connect sets the param
of the evaluator or
# estimator itself and returns it, so the next evaluate or fit uses the
value of a setter whose
# result is dropped, with the values of PySpark 4.3.0.
- import pyspark.sql.connect.proto as pb2
from pyspark.ml.connect.classification import LogisticRegression
from pyspark.ml.connect.evaluation import (
BinaryClassificationEvaluator,
@@ -418,13 +417,16 @@ def
test_ml_connect_setters_change_the_next_evaluate_and_fit_as_pyspark(session)
predictions =
estimator.fit(labeled).transform(labeled).orderBy("id").collect()
assert [r.prediction for r in predictions] == labels
- # The server transforms no native Pipeline of stage names: the stages of
the setter are
- # those that the transform of its model sends.
+ # The native Pipeline of stage names is not implemented: its fit raises
NOT_IMPLEMENTED, as
+ # the server cannot fit the stages, and the setter still sets them.
+ from pyspark.errors import PySparkNotImplementedError
+
pipeline = Pipeline()
assert pipeline.setStages(["a", "b"]) is pipeline
- relation =
pb2.Relation.FromString(pipeline.fit(labeled).transform(labeled)._relation_bytes())
- stages =
relation.ml_relation.transform.params.params["stages"].array.elements
- assert [stage.string for stage in stages] == ["a", "b"]
+ with pytest.raises(PySparkNotImplementedError) as error:
+ pipeline.fit(labeled)
+ assert error.value.getCondition() == "NOT_IMPLEMENTED"
+ assert error.value.getMessageParameters() == {"feature": "Pipeline.fit"}
def test_ml_statistics_as_pyspark(session):
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index dc2c9e8e..769d1abc 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -109,6 +109,12 @@ def _commands(service):
return [pb2.ExecutePlanRequest.FromString(r).plan.command for r in
service.execute_requests]
+def _requests_but_deletes(service):
+ # The commands that the server received, but the Delete of a model that an
earlier test
+ # released, which can reach the server during a check.
+ return sum(not command.ml_command.HasField("delete") for command in
_commands(service))
+
+
def _relation(df):
# The relation of a DataFrame, as the core sends it: the relation that the
plans of pyspark.ml
# send in place of its placeholder, which the core replaces with it.
@@ -222,12 +228,7 @@ def
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
elif hasattr(obj, "fit"):
service.execute_payload = _operator_info("model-1")
models.append(obj.fit(df))
- if len(service.execute_requests) > sent:
- params = _commands(service)[sent].ml_command.fit.params
- else:
- # Pipeline and CrossValidator fit no object of the server: the
transform of their
- # model sends the params.
- params =
_relation(models[-1].transform(df)).ml_relation.transform.params
+ params = _commands(service)[sent].ml_command.fit.params
else:
params = _relation(obj.transform(df)).ml_relation.transform.params
return {name: value(literal) for name, literal in
params.params.items()}
@@ -272,8 +273,6 @@ def
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
MulticlassClassificationEvaluator,
dict(labelCol="y", predictionCol="p", metricName="accuracy"),
),
- (Pipeline, dict(stages=["a", "b"])),
- (CrossValidator, dict(numFolds=5, parallelism=2, seed=7)),
]:
setters = {"set" + name[0].upper() + name[1:]: name for name in values}
# Every setter of the class is checked.
@@ -287,6 +286,37 @@ def
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
assert params == sent_params(cls(**values)), cls
+def test_ml_pipeline_and_cross_validator_fit_is_not_implemented(ml_mock):
+ # The native Pipeline and CrossValidator keep their params as their
setters set them, and
+ # their fit raises PySpark's NOT_IMPLEMENTED before any request: the
server cannot fit the
+ # stage names, nor the estimator and evaluator that the CrossValidator
does not hold, so no
+ # model is returned.
+ from pyspark.errors import PySparkNotImplementedError
+ from pyspark.ml.connect import CrossValidator, Pipeline
+
+ spark, service = ml_mock
+ df = spark.range(1)
+ pipeline = Pipeline()
+ assert pipeline.setStages(value=["a", "b"]) is pipeline
+ cv = CrossValidator()
+ assert cv.setNumFolds(value=5) is cv
+ assert cv.setParallelism(value=2) is cv
+ assert cv.setSeed(value=7) is cv
+ for estimator, feature in [
+ (pipeline, "Pipeline.fit"),
+ (cv, "CrossValidator.fit"),
+ (Pipeline(stages=["a"]), "Pipeline.fit"),
+ (CrossValidator(numFolds=2, seed=1), "CrossValidator.fit"),
+ ]:
+ sent = _requests_but_deletes(service)
+ with pytest.raises(PySparkNotImplementedError) as error:
+ estimator.fit(df)
+ assert error.value.getCondition() == "NOT_IMPLEMENTED"
+ assert error.value.getMessageParameters() == {"feature": feature}
+ assert str(error.value) == f"[NOT_IMPLEMENTED] {feature} is not
implemented."
+ assert _requests_but_deletes(service) == sent
+
+
# The params of the native pyspark.ml.connect classes, by the TypeConverters
method of each
# param in PySpark. Their constructors take them all but thresholds, which
PySpark's
# RandomForestClassifier takes by its setter only.
@@ -354,10 +384,14 @@ _NATIVE_REJECTED = {
}
+# The native classes whose fit raises NOT_IMPLEMENTED without a request, so
that no request
+# carries their params.
+_NOT_FITTABLE = ("Pipeline", "CrossValidator")
+
+
def _native_request(spark, service, obj, models):
# The MlOperator and the MlParams that the next evaluate, fit or transform
of the native
- # obj sends; Pipeline and CrossValidator fit no object of the server, so
the transform of
- # their model sends them. The models are kept in models, so that none is
released.
+ # obj sends. The models are kept in models, so that none is released.
df = spark.range(1)
sent = len(service.execute_requests)
if hasattr(obj, "evaluate"):
@@ -368,10 +402,8 @@ def _native_request(spark, service, obj, models):
if hasattr(obj, "fit"):
service.execute_payload = _operator_info("model-1")
models.append(obj.fit(df))
- if len(service.execute_requests) > sent:
- fit = _commands(service)[sent].ml_command.fit
- return fit.estimator, fit.params
- obj = models[-1]
+ fit = _commands(service)[sent].ml_command.fit
+ return fit.estimator, fit.params
transform = _relation(obj.transform(df)).ml_relation.transform
return transform.transformer, transform.params
@@ -446,6 +478,8 @@ def
test_ml_connect_params_convert_with_the_type_converters_of_pyspark(ml_mock):
if param != "thresholds":
made.append(cls(**{param: value}))
for obj in made:
+ if name in _NOT_FITTABLE:
+ continue # Their params are sent by no request.
sent = _native_sent(spark, service, obj, models)
assert sent == {param: expected}, (name, param, value)
for value, message in _NATIVE_REJECTED[kind]:
@@ -472,7 +506,8 @@ def
test_ml_connect_constructors_send_only_the_params_they_are_given_as_pyspark(
spark, service = ml_mock
models = []
for name in _NATIVE_PARAMS:
- assert _native_sent(spark, service, getattr(connect, name)(), models)
== {}, name
+ if name not in _NOT_FITTABLE:
+ assert _native_sent(spark, service, getattr(connect, name)(),
models) == {}, name
assert _native_sent(spark, service, connect.KMeans(k=3), models) == {"k":
("integer", 3)}
forest = connect.RandomForestClassifier(numTrees=3, seed=2**33)
assert _native_sent(spark, service, forest, models) == {
@@ -498,7 +533,7 @@ def
test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
connect.RandomForestClassifier().setNumTrees(2**70),
connect.CrossValidator(numFolds=2**70),
]:
- sent = len(service.execute_requests)
+ sent = _requests_but_deletes(service)
with pytest.raises(PySparkValueError) as error:
estimator.fit(spark.range(1))
assert error.value.getCondition() == "VALUE_NOT_BETWEEN"
@@ -506,7 +541,7 @@ def
test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
"[VALUE_NOT_BETWEEN] Value for `value` must be between
-9223372036854775808 and "
"32767."
)
- assert len(service.execute_requests) == sent
+ assert _requests_but_deletes(service) == sent
estimator = connect.KMeans(seed=2**64)
assert estimator.setSeed(5) is estimator
assert _native_sent(spark, service, estimator, models) == {"seed":
("integer", 5)}
@@ -515,6 +550,8 @@ def
test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
assert sent["seed"][0] == "null"
for name, params in _NATIVE_PARAMS.items():
+ if name in _NOT_FITTABLE:
+ continue # Their params and uids are sent by no request.
cls = getattr(connect, name)
for param, kind in params.items():
setter = "set" + param[0].upper() + param[1:]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]