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 22a99691 [SPARK-61417][CONNECT][PYTHON] Fix review findings: Spark's
ML column defaults, the multiclass metric, the depth of a cross-session
transform, empty observe, done-call errors over batch errors, and unencodable
option strings
22a99691 is described below
commit 22a996915c84d427032c359e59492ada9b9d5935
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:15:03 2026 +0900
[SPARK-61417][CONNECT][PYTHON] Fix review findings: Spark's ML column
defaults, the multiclass metric, the depth of a cross-session transform, empty
observe, done-call errors over batch errors, and unencodable option strings
### What changes were proposed in this pull request?
[SPARK-61417](https://issues.apache.org/jira/browse/SPARK-61417): the
findings of an independent review of the newest commits (SPARK-61362, 61363,
61367, 61385, 61386), each checked against PySpark 4.3.0 or Spark v4.3.0. The
other sessions' findings and in-flight fixes are not repeated here.
- **Native ML column getters** (`crates/spark-connect/src/ml.rs`):
`input_col` of `StandardScaler`, `MaxAbsScaler` and `StringIndexer` returns
`Option<&str>`, as Spark's `HasInputCol` has no default. Their `output_col`,
and `VectorAssembler`'s, return a `String`: the set value, else Spark's
`HasOutputCol` default `<uid>__output`, the column that the server writes.
Before, they gave names the server never wrote ("scaled_features",
"maxAbs_scaled", "indexed", "assembled", input "feature [...]
- **Evaluators** (`crates/pyspark-rs/src/ml.rs`): `pyspark.ml.connect`'s
`MulticlassClassificationEvaluator()` evaluates `accuracy` unless given, as
PySpark's constructor sets it; the JVM evaluator, and the Rust API, default to
`f1`. The three evaluators show PySpark's signatures, with their defaults.
- **Cross-session transform** (`crates/pyspark-rs/src/ml.rs`): the
transform of a DataFrame of another session builds its relation over the
DataFrame's placeholder, which the core resolves counting its levels, as the
plans of `pyspark.ml` do. Before, the input was put in whole and counted as one
level, so levels added over it were not bounded, and a deep input could
overflow a small stack when its relation was cloned.
- **`DataFrame::observe_with`** with no expressions raises
`CANNOT_BE_EMPTY`, as PySpark's `observe` does first. The doc of `observe`,
which returns no `Result`, says so.
- **Done-call errors over batch errors** (`progress.rs`, `dataframe.rs`,
`catalog.rs`): when decoding a batch or the schema fails, `collect`,
`collect_record_batches`, the local iterator and catalog operations make the
done call of the progress handlers through the new `ExecutionStream::fail`,
whose error replaces the decoding error, as PySpark's `Progress.__exit__` does.
Before, the done call came on drop, and its error was lost.
- **Unencodable strings** (`crates/pyspark-rs`): the keys and values of
reader, writer, streaming and session options (`crate::str_text`) raise
protobuf's `ValueError` for a str that UTF-8 cannot encode (a lone surrogate).
Before, they were sent with U+FFFD, so a write could go to another path. A fill
value of such a str raises the `UnicodeEncodeError` of its encoding (a
`ValueError`) instead of a `TypeError` "unsupported value type for
createDataFrame: str".
- **Docs**: the empty `agg` of the Rust API (as the Scala client),
`PipelineModel`'s public fields, the year-month interval columns that
`create_dataframe` takes, the getters above and the evaluator's default; a
stale comment.
### Why are the changes needed?
Each was a difference from PySpark or Spark that a review of the newest
commits found:
- **Getters** naming a column that does not exist (UNRESOLVED_COLUMN on
`select`), documented as Spark's defaults.
- **A silently different metric** of a no-argument multiclass evaluator.
- **An unbounded depth**, and a possible stack overflow, through a
cross-session transform.
- **A late server error** for an empty observe.
- **A lost done-call error** when decoding fails.
- **Lossy option strings** and a misleading fill error.
### Does this PR introduce _any_ user-facing change?
Yes, all of the above:
- **Rust signatures:** `input_col() -> Option<&str>` and `output_col() ->
String` on the four classes, and the generic list setters. A migration
paragraph in `docs/compatibility.md` covers them.
- **Python:** `MulticlassClassificationEvaluator()` evaluates `accuracy` by
default.
- **Errors:** `CANNOT_BE_EMPTY`, the done-call errors, and `ValueError` for
unencodable option strings.
### How was this patch tested?
Each new test fails without its change: the Python ones against an
extension built from master.
- Rust unit tests:
- `ml.rs`: `column_getters_give_the_defaults_of_spark`.
- `dataframe.rs`:
`observe_with_no_expressions_is_cannot_be_empty_as_pyspark`.
- The existing scaler and indexer tests now read `Some(...)` inputs.
- Offline Python (`python/tests/test_dropin_offline.py`, placed before
`test_functions_levenshtein`):
-
`test_the_exception_of_a_done_call_replaces_the_error_of_a_batch_as_pyspark`: a
batch that is not Arrow IPC, for collect and an iterator.
-
`test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_as_pyspark`:
read, write, readStream, `SparkSession.builder.config(map=...)` and `fillna`.
- Offline ML (`python/tests/test_ml_offline.py`):
`test_ml_connect_evaluators_take_the_signatures_and_defaults_of_pyspark`.
`test_ml_connect_constructors_send_only_the_params_they_are_given_as_pyspark`
now expects the multiclass metric.
- Live ML (`python/tests/test_ml_e2e.py`, against a local Spark 4.3.0
server):
`test_the_transform_of_a_deep_dataframe_of_another_session_counts_its_levels_as_pyspark`.
700 levels, a cross-session transform, then 100 more levels raise
`RecursionError` before any request. Before, the 800-level plan reached the
server, which failed.
- Updated existing tests:
- The ML offline tests that compare the params a class sends now include
the multiclass evaluator's default metric (`_defaults_sent`).
- `test_string_surrogate_fallback_precedes_importer_configuration`
(`test_arrow_handoff.py`) expects pyarrow's `UnicodeEncodeError`, the error
that PySpark raises for a surrogate in `createDataFrame`, instead of the old
`TypeError`.
- `ml_coverage.rs` and `coverage_ml_extra.rs` read `Some(...)` inputs.
- Checks:
- the lib tests of both crates (777 passed);
- the build of all tests, also with `wasm-udf` and `datafusion,polars`,
without warnings;
- `cargo fmt --all --check`, and clippy with no diagnostics on the
changed lines;
- the offline Python suites, and the live drop-in, Arrow and ML suites
against a local Spark 4.3.0 server (283 passed);
- a full trial on master before the merge.
### 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 #495 from HyukjinKwon/s17-review-followups.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/functions.rs | 5 +-
crates/pyspark-rs/src/lib.rs | 2 +-
crates/pyspark-rs/src/ml.rs | 21 +++--
crates/pyspark-rs/src/options.rs | 15 +++-
crates/pyspark-rs/src/session.rs | 13 +--
crates/spark-connect/src/catalog.rs | 2 +-
crates/spark-connect/src/dataframe.rs | 50 ++++++++++--
crates/spark-connect/src/group.rs | 3 +-
crates/spark-connect/src/ml.rs | 100 +++++++++++++++++-------
crates/spark-connect/src/progress.rs | 8 ++
crates/spark-connect/tests/coverage_ml_extra.rs | 6 +-
crates/spark-connect/tests/ml_coverage.rs | 6 +-
docs/compatibility.md | 15 +++-
python/tests/test_arrow_handoff.py | 3 +-
python/tests/test_dropin_offline.py | 54 +++++++++++++
python/tests/test_ml_e2e.py | 24 ++++++
python/tests/test_ml_offline.py | 57 ++++++++++++--
17 files changed, 313 insertions(+), 71 deletions(-)
diff --git a/crates/pyspark-rs/src/functions.rs
b/crates/pyspark-rs/src/functions.rs
index 95efccf7..41646db7 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -222,7 +222,7 @@ pub(crate) fn value_not_between(py: Python<'_>) -> PyErr {
/// The `ValueError` of protobuf's Python string field for a str that is not
encodable as UTF-8,
/// with its message, which shows at most 1024 characters of the repr of the
value.
-fn not_utf8_string(obj: &Bound<'_, PyAny>) -> PyErr {
+pub(crate) fn not_utf8_string(obj: &Bound<'_, PyAny>) -> PyErr {
let message = pyo3::types::PyString::new(
obj.py(),
"%.1024r isn't a valid unicode string and can't be encoded in UTF-8.",
@@ -813,8 +813,7 @@ fn scalar_literal(obj: &Bound<'_, PyAny>) ->
PyResult<Option<LiteralExpression>>
crate::infer::wall_clock_micros(obj)?,
)));
}
- // Shared with session::py_to_value so lit() and createDataFrame()
agree (a pandas
- // Timestamp's .timestamp() treats a naive value as UTC; normalize
it first).
+ // Shared with session::py_to_value so lit() and createDataFrame()
agree.
let micros = crate::session::datetime_to_micros(obj)?;
return Ok(Some(LiteralExpression::Timestamp(micros)));
}
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index ec7ebfee..5b155550 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -56,7 +56,7 @@ use dataframe::{
};
use datasource::PyDataSourceRegistration;
use group::{PyCoGroupedData, PyGroupedData};
-pub(crate) use options::coerce_option_value;
+pub(crate) use options::{coerce_option_value, str_text};
use readwriter::PyDataFrameReader;
use resource::{
PyExecutorResourceRequests, PyResourceProfile, PyResourceProfileBuilder,
PyTaskResourceRequests,
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index ca59795d..8ec25534 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -299,10 +299,14 @@ impl PyMLModel {
// As PySpark, the transform of a DataFrame of another session
refers to the model
// on the server of that session, which raises
CONNECT_ML.CACHE_INVALID when the
// DataFrame is analyzed or run, as it caches no such model. (The
Rust API rejects
- // the transform itself.)
+ // the transform itself.) Its input is the placeholder of the
DataFrame, as in the
+ // plans of `pyspark.ml`: the core resolves it, counting its
levels for the depth
+ // bound, where an input put in whole would count as one level.
+ let input =
+ DataFrame::from_sent_relation(session.clone(),
df.dataframe.placeholder_relation());
let relation = spark_connect_proto::Relation {
rel_type:
Some(spark_connect_proto::relation::RelType::MlRelation(
-
Box::new(model.build_ml_relation(&df.dataframe).to_pyerr()?),
+ Box::new(model.build_ml_relation(&input).to_pyerr()?),
)),
..Default::default()
};
@@ -1669,7 +1673,7 @@ impl PyRegressionEvaluator {
#[new]
#[pyo3(
signature = (*args, **kwargs),
- text_signature = "(*, labelCol=None, predictionCol=None,
metricName=None)"
+ text_signature = "(*, metricName='rmse', labelCol='label',
predictionCol='prediction')"
)]
fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
let mut this = Self {
@@ -1725,7 +1729,7 @@ impl PyBinaryClassificationEvaluator {
#[new]
#[pyo3(
signature = (*args, **kwargs),
- text_signature = "(*, labelCol=None, rawPredictionCol=None,
metricName=None)"
+ text_signature = "(*, metricName='areaUnderROC', labelCol='label',
rawPredictionCol='rawPrediction')"
)]
fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
let mut this = Self {
@@ -1828,13 +1832,20 @@ impl PyMulticlassClassificationEvaluator {
#[new]
#[pyo3(
signature = (*args, **kwargs),
- text_signature = "(metricName=None, labelCol=None, predictionCol=None)"
+ text_signature = "(metricName='accuracy', labelCol='label',
predictionCol='prediction')"
)]
fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
let mut this = Self {
inner: MulticlassClassificationEvaluator::new(),
unsendable: Vec::new(),
};
+ // As PySpark's, whose constructor sets the metric "accuracy" by
default, where the JVM
+ // evaluator's default (that of the Rust API) is "f1".
+ apply(
+ &mut this,
+ "metricName",
+ Converted::Str("accuracy".to_string()),
+ );
init_params(
&mut this,
"MulticlassClassificationEvaluator",
diff --git a/crates/pyspark-rs/src/options.rs b/crates/pyspark-rs/src/options.rs
index 90028c4a..4a0f027b 100644
--- a/crates/pyspark-rs/src/options.rs
+++ b/crates/pyspark-rs/src/options.rs
@@ -31,7 +31,16 @@ pub(crate) fn coerce_option_value(v: &Bound<'_, PyAny>) ->
PyResult<Option<Strin
if let Ok(b) = v.cast::<PyBool>() {
return Ok(Some(if b.is_true() { "true" } else { "false"
}.to_string()));
}
- Ok(Some(v.str()?.to_string()))
+ Ok(Some(str_text(v)?))
+}
+
+/// The `str()` of `v`, as the reference client sends it in a protobuf string
field, which raises
+/// protobuf's `ValueError` for a str that UTF-8 cannot encode (a lone
surrogate) where a lossy
+/// conversion would send another text, such as another path.
+pub(crate) fn str_text(v: &Bound<'_, PyAny>) -> PyResult<String> {
+ let text = v.str()?;
+ text.extract::<String>()
+ .map_err(|_| crate::functions::not_utf8_string(text.as_any()))
}
/// A reader or writer that takes string options one at a time.
@@ -92,7 +101,7 @@ pub(crate) fn kwargs_skip_none(
if let Some(options) = options {
for (key, value) in options.iter() {
if let Some(value) = coerce_option_value(&value)? {
- map.insert(key.str()?.to_string(), value);
+ map.insert(str_text(&key)?, value);
}
}
}
@@ -120,7 +129,7 @@ pub(crate) fn set_reader_kwargs_unset_none(
) -> PyResult<DataFrameReader> {
if let Some(options) = options {
for (key, value) in options.iter() {
- let key = key.str()?.to_string();
+ let key = str_text(&key)?;
reader = set_reader_option_unset_none(reader, &key, &value)?;
}
}
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 964874e5..97e48f08 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -116,7 +116,7 @@ impl PySparkSessionBuilder {
}
if let Some(m) = map {
for (k, v) in m.iter() {
- let ks = k.str()?.to_string();
+ let ks = crate::str_text(&k)?;
let vs = crate::coerce_option_value(&v)?;
slf.set_option_value(py, &ks, vs)?;
}
@@ -125,8 +125,8 @@ impl PySparkSessionBuilder {
// A SparkConf: apply its (key, value) pairs via getAll().
for pair in c.call_method0("getAll")?.try_iter()? {
let pair = pair?;
- let k: String = pair.get_item(0)?.str()?.to_string();
- let v: String = pair.get_item(1)?.str()?.to_string();
+ let k: String = crate::str_text(&pair.get_item(0)?)?;
+ let v: String = crate::str_text(&pair.get_item(1)?)?;
slf.set_option(py, &k, v)?;
}
}
@@ -3738,8 +3738,11 @@ pub(crate) fn py_to_value(obj: &Bound<'_, PyAny>) ->
PyResult<Value> {
}
// Check for str
- if let Ok(s) = obj.extract::<String>() {
- return Ok(Value::String(s));
+ if obj.is_instance_of::<pyo3::types::PyString>() {
+ // A str that UTF-8 cannot encode (a lone surrogate) raises the
UnicodeEncodeError of its
+ // encoding, a ValueError, as pyarrow's conversion of PySpark does,
rather than the
+ // TypeError of an unsupported type below.
+ return Ok(Value::String(obj.extract::<String>()?));
}
// Check for bytes/bytearray SPECIFICALLY (not `extract::<Vec<u8>>()`,
which also
diff --git a/crates/spark-connect/src/catalog.rs
b/crates/spark-connect/src/catalog.rs
index de52b0b8..96c2ecc9 100644
--- a/crates/spark-connect/src/catalog.rs
+++ b/crates/spark-connect/src/catalog.rs
@@ -1066,7 +1066,7 @@ impl Catalog {
if let
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) =
resp.response_type
{
- rows.extend(decode_arrow_batch(&batch)?);
+ rows.extend(decode_arrow_batch(&batch).map_err(|e|
stream.fail(e))?);
}
}
Ok(rows)
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index c25394c2..9a75e3ea 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -213,13 +213,16 @@ impl LocalRowIterator {
Ok(Some(mut resp)) => {
capture_execution(&mut resp, execution_info, session);
if let Err(e) = keep_schema(&mut resp, &self.schema) {
- return Some(Err(e));
+ return Some(Err(stream.fail(e)));
}
if let
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) =
resp.response_type
{
let schema = self.schema.lock().unwrap_or_else(|p|
p.into_inner());
- return Some(decode_arrow_batch_of(&batch,
schema.as_ref()));
+ return Some(
+ decode_arrow_batch_of(&batch, schema.as_ref())
+ .map_err(|e| stream.fail(e)),
+ );
}
// Metrics/progress response: keep pulling for a batch.
}
@@ -957,7 +960,7 @@ impl DataFrame {
};
capture_execution(&mut resp, &mut info, &self.session);
if let Some(data_type) = resp.schema.take() {
- schema = Some(DataType::from_proto(&data_type)?);
+ schema = Some(DataType::from_proto(&data_type).map_err(|e|
stream.fail(e))?);
}
if let
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) =
resp.response_type
@@ -974,7 +977,7 @@ impl DataFrame {
invalid_utf8 = Some(error);
}
}
- Err(error) => return Err(error),
+ Err(error) => return Err(stream.fail(error)),
}
}
}
@@ -1048,12 +1051,13 @@ impl DataFrame {
};
capture_execution(&mut resp, &mut info, &self.session);
if let Some(data_type) = resp.schema.take() {
- schema = Some(DataType::from_proto(&data_type)?);
+ schema = Some(DataType::from_proto(&data_type).map_err(|e|
stream.fail(e))?);
}
if let
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) =
resp.response_type
{
- let record_batches = decode_arrow_record_batches(&batch)?;
+ let record_batches =
+ decode_arrow_record_batches(&batch).map_err(|e|
stream.fail(e))?;
batches.extend(record_batches);
}
}
@@ -1779,7 +1783,9 @@ impl DataFrame {
}
}
- /// Observe metrics on this DataFrame.
+ /// Observe metrics on this DataFrame. With no `exprs`, the action fails
on the server, where
+ /// PySpark's `observe` raises `CANNOT_BE_EMPTY` at the call, as
+ /// [`DataFrame::observe_with`] does.
pub fn observe(&self, name: &str, exprs: Vec<Expression>) -> DataFrame {
let plan = LogicalPlan::Observe {
input: Arc::clone(&self.plan),
@@ -1801,6 +1807,14 @@ impl DataFrame {
observation: &crate::observation::Observation,
exprs: Vec<Expression>,
) -> Result<DataFrame> {
+ // As PySpark's `observe`, which checks this first.
+ if exprs.is_empty() {
+ return Err(SparkError::classed(
+ SparkErrorKind::ValueError,
+ "CANNOT_BE_EMPTY",
+ &[("item", "exprs")],
+ ));
+ }
let name = observation.name_to_observe()?;
if self.is_streaming()? {
return Err(SparkError::classed(
@@ -1843,7 +1857,9 @@ impl DataFrame {
crate::group::NaFunctions::new(self.clone())
}
- /// Perform aggregation without grouping.
+ /// Perform aggregation without grouping. With no `expressions`, the
result is one row of
+ /// no columns, as of the Scala client's `agg(Map.empty)`, where PySpark's
`agg` raises
+ /// `CANNOT_BE_EMPTY`.
pub fn agg(&self, expressions: Vec<Expression>) -> DataFrame {
let plan = LogicalPlan::Aggregate {
input: Arc::clone(&self.plan),
@@ -5096,6 +5112,24 @@ mod plan_construction_tests {
);
}
+ #[test]
+ fn observe_with_no_expressions_is_cannot_be_empty_as_pyspark() {
+ // As PySpark's `observe`, which checks this first, before any request.
+ let observation = crate::observation::Observation::new("metrics");
+ let Err(error) = session()
+ .range(3)
+ .unwrap()
+ .observe_with(&observation, vec![])
+ else {
+ panic!("no exprs must be rejected");
+ };
+ assert_eq!(error.kind, SparkErrorKind::ValueError);
+ assert_eq!(
+ error.message(),
+ "[CANNOT_BE_EMPTY] At least one exprs must be specified."
+ );
+ }
+
fn session() -> SparkSession {
SparkSession::builder()
.remote("sc://localhost:15002")
diff --git a/crates/spark-connect/src/group.rs
b/crates/spark-connect/src/group.rs
index c288705d..10e11ee2 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -410,7 +410,8 @@ impl GroupedData {
}
}
- /// Perform an aggregation.
+ /// Perform an aggregation. With no `expressions`, the result is the
distinct grouping keys,
+ /// as of the Scala client, where PySpark's `agg` raises an
`AssertionError`.
pub fn agg(&self, expressions: Vec<Expression>) -> DataFrame {
// Convert group columns to expressions
let grouping_expressions = self
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index ffbdbcc1..b94689cd 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -214,6 +214,13 @@ impl Params {
self.string_opt(name).unwrap_or(default)
}
+ /// The `outputCol` parameter, or Spark's default of `HasOutputCol`,
`<uid>__output`, of the
+ /// object of `uid`, the column that the server writes when it is not set.
+ fn output_col_or_default(&self, uid: &str) -> String {
+ self.string_opt("outputCol")
+ .map_or_else(|| format!("{uid}__output"), str::to_string)
+ }
+
/// The string parameter `name`, if it is set.
fn string_opt(&self, name: &str) -> Option<&str> {
match self.literal(name)? {
@@ -589,9 +596,9 @@ impl StandardScaler {
self
}
- /// Get the input column name (default: "features").
- pub fn input_col(&self) -> &str {
- self.params.string_or("inputCol", "features")
+ /// The input column, if set: as in Spark, it has no default.
+ pub fn input_col(&self) -> Option<&str> {
+ self.params.string_opt("inputCol")
}
/// Set the output column name.
@@ -600,9 +607,9 @@ impl StandardScaler {
self
}
- /// Get the output column name (default: "scaled_features").
- pub fn output_col(&self) -> &str {
- self.params.string_or("outputCol", "scaled_features")
+ /// The output column: as in Spark, `<uid>__output` unless set.
+ pub fn output_col(&self) -> String {
+ self.params.output_col_or_default(&self.operator.uid)
}
fn model_from_info(
@@ -715,7 +722,7 @@ impl VectorAssembler {
}
}
- pub fn set_input_cols(mut self, cols: Vec<&str>) -> Self {
+ pub fn set_input_cols(mut self, cols: impl IntoIterator<Item = impl
Into<String>>) -> Self {
self.params = self.params.set_param_string_array("inputCols", cols);
self
}
@@ -730,9 +737,9 @@ impl VectorAssembler {
self
}
- /// The output column (default: "assembled").
- pub fn output_col(&self) -> &str {
- self.params.string_or("outputCol", "assembled")
+ /// The output column: as in Spark, `<uid>__output` unless set.
+ pub fn output_col(&self) -> String {
+ self.params.output_col_or_default(&self.operator.uid)
}
}
@@ -796,9 +803,9 @@ impl StringIndexer {
self
}
- /// The input column (default: empty).
- pub fn input_col(&self) -> &str {
- self.params.string_or("inputCol", "")
+ /// The input column, if set: as in Spark, it has no default.
+ pub fn input_col(&self) -> Option<&str> {
+ self.params.string_opt("inputCol")
}
pub fn set_output_col(mut self, col: &str) -> Self {
@@ -806,9 +813,9 @@ impl StringIndexer {
self
}
- /// The output column (default: "indexed").
- pub fn output_col(&self) -> &str {
- self.params.string_or("outputCol", "indexed")
+ /// The output column: as in Spark, `<uid>__output` unless set.
+ pub fn output_col(&self) -> String {
+ self.params.output_col_or_default(&self.operator.uid)
}
fn model_from_info(
@@ -926,9 +933,9 @@ impl MaxAbsScaler {
self
}
- /// The input column (default: "features").
- pub fn input_col(&self) -> &str {
- self.params.string_or("inputCol", "features")
+ /// The input column, if set: as in Spark, it has no default.
+ pub fn input_col(&self) -> Option<&str> {
+ self.params.string_opt("inputCol")
}
pub fn set_output_col(mut self, col: &str) -> Self {
@@ -936,9 +943,9 @@ impl MaxAbsScaler {
self
}
- /// The output column (default: "maxAbs_scaled").
- pub fn output_col(&self) -> &str {
- self.params.string_or("outputCol", "maxAbs_scaled")
+ /// The output column: as in Spark, `<uid>__output` unless set.
+ pub fn output_col(&self) -> String {
+ self.params.output_col_or_default(&self.operator.uid)
}
fn model_from_info(
@@ -3278,7 +3285,7 @@ impl Pipeline {
}
}
- pub fn set_stages(mut self, stage_names: Vec<&str>) -> Self {
+ pub fn set_stages(mut self, stage_names: impl IntoIterator<Item = impl
Into<String>>) -> Self {
self.params = self.params.set_param_string_array("stages",
stage_names);
self
}
@@ -3616,7 +3623,7 @@ mod tests {
.set_input_col("my_features")
.set_output_col("my_scaled");
- assert_eq!(scaler.input_col(), "my_features");
+ assert_eq!(scaler.input_col(), Some("my_features"));
assert_eq!(scaler.output_col(), "my_scaled");
}
@@ -3652,7 +3659,7 @@ mod tests {
.set_input_col("category")
.set_output_col("category_index");
- assert_eq!(indexer.input_col(), "category");
+ assert_eq!(indexer.input_col(), Some("category"));
assert_eq!(indexer.output_col(), "category_index");
}
@@ -3670,7 +3677,7 @@ mod tests {
.set_input_col("features")
.set_output_col("scaled");
- assert_eq!(scaler.input_col(), "features");
+ assert_eq!(scaler.input_col(), Some("features"));
assert_eq!(scaler.output_col(), "scaled");
}
@@ -4062,7 +4069,7 @@ mod tests {
// The models of the server-fitted estimators transform through their
cached model;
// this exercises the offline model wrappers. The fits are tested
against a server.
let mas = MaxAbsScaler::new().set_input_col("f").set_output_col("o");
- assert_eq!(mas.input_col(), "f");
+ assert_eq!(mas.input_col(), Some("f"));
let mut m = MaxAbsScalerModel {
operator: MlOperator::new("test", OperatorType::Model),
params: mas.params().clone(),
@@ -4792,6 +4799,45 @@ mod tests {
}
}
+ #[test]
+ fn column_getters_give_the_defaults_of_spark() {
+ // As Spark's HasInputCol, which has no default, and HasOutputCol,
whose default is
+ // `<uid>__output`, the column that the server writes when it is not
set.
+ let scaler = StandardScaler::new();
+ assert_eq!(scaler.input_col(), None);
+ assert_eq!(
+ scaler.output_col(),
+ format!("{}__output", scaler.operator.uid)
+ );
+ let scaler = scaler.set_input_col("x").set_output_col("y");
+ assert_eq!(
+ (scaler.input_col(), scaler.output_col()),
+ (Some("x"), "y".to_string())
+ );
+ let max_abs = MaxAbsScaler::new();
+ assert_eq!(max_abs.input_col(), None);
+ assert_eq!(
+ max_abs.output_col(),
+ format!("{}__output", max_abs.operator.uid)
+ );
+ let indexer = StringIndexer::new();
+ assert_eq!(indexer.input_col(), None);
+ assert_eq!(
+ indexer.output_col(),
+ format!("{}__output", indexer.operator.uid)
+ );
+ let assembler = VectorAssembler::new();
+ assert_eq!(
+ assembler.output_col(),
+ format!("{}__output", assembler.operator.uid)
+ );
+ // The list setters take any strings, as `set_param_string_array`.
+ let assembler = assembler.set_input_cols(["a".to_string(),
"b".to_string()]);
+ assert_eq!(assembler.input_cols(), vec!["a", "b"]);
+ let pipeline = Pipeline::new().set_stages(vec!["s1"]);
+ assert_eq!(pipeline.stages(), vec!["s1"]);
+ }
+
#[test]
fn native_estimators_get_their_params_or_the_spark_defaults() {
// Every native estimator has a getter of each param: the value that
is set, else the
diff --git a/crates/spark-connect/src/progress.rs
b/crates/spark-connect/src/progress.rs
index 5adb3f54..c15cc3a6 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -256,6 +256,14 @@ impl ExecutionStream {
}
}
+ /// `error`, of the caller of an execution that ends before its stream
does, such as of the
+ /// decoding of a batch: the handlers get their done call now, whose error
replaces
+ /// `error`, as PySpark's `Progress.__exit__` replaces an error raised in
the `with` of the
+ /// execution.
+ pub(crate) fn fail(&mut self, error: SparkError) -> SparkError {
+ self.progress.finish_after(error)
+ }
+
/// The response of the stream, `response`, after its progress has updated
the handlers and
/// its chunk is joined into its batch.
fn handle(
diff --git a/crates/spark-connect/tests/coverage_ml_extra.rs
b/crates/spark-connect/tests/coverage_ml_extra.rs
index a7a8cb6b..5e732f49 100644
--- a/crates/spark-connect/tests/coverage_ml_extra.rs
+++ b/crates/spark-connect/tests/coverage_ml_extra.rs
@@ -52,7 +52,7 @@ fn params_operator_type_and_ml_operator_conversions() {
fn estimator_builders_and_accessors() {
// StandardScaler
let mut e = StandardScaler::new().set_input_col("f").set_output_col("o");
- assert_eq!(e.input_col(), "f");
+ assert_eq!(e.input_col(), Some("f"));
assert_eq!(e.output_col(), "o");
let _ = e.operator();
let _ = e.operator_mut();
@@ -62,7 +62,7 @@ fn estimator_builders_and_accessors() {
// StringIndexer
let mut e = StringIndexer::new().set_input_col("f").set_output_col("o");
- assert_eq!(e.input_col(), "f");
+ assert_eq!(e.input_col(), Some("f"));
assert_eq!(e.output_col(), "o");
let _ = e.operator();
let _ = e.operator_mut();
@@ -72,7 +72,7 @@ fn estimator_builders_and_accessors() {
// MaxAbsScaler
let mut e = MaxAbsScaler::new().set_input_col("f").set_output_col("o");
- assert_eq!(e.input_col(), "f");
+ assert_eq!(e.input_col(), Some("f"));
assert_eq!(e.output_col(), "o");
let _ = e.operator();
let _ = e.operator_mut();
diff --git a/crates/spark-connect/tests/ml_coverage.rs
b/crates/spark-connect/tests/ml_coverage.rs
index 6ddec8b4..8a46ed8a 100644
--- a/crates/spark-connect/tests/ml_coverage.rs
+++ b/crates/spark-connect/tests/ml_coverage.rs
@@ -7,7 +7,7 @@ use spark_connect::ml::*;
#[test]
fn ml_estimators_setters_getters_proto() {
let ss = StandardScaler::new().set_input_col("f").set_output_col("s");
- assert_eq!(ss.input_col(), "f");
+ assert_eq!(ss.input_col(), Some("f"));
assert_eq!(ss.output_col(), "s");
let va = VectorAssembler::new()
@@ -17,11 +17,11 @@ fn ml_estimators_setters_getters_proto() {
assert_eq!(va.output_col(), "v");
let si = StringIndexer::new().set_input_col("c").set_output_col("i");
- assert_eq!(si.input_col(), "c");
+ assert_eq!(si.input_col(), Some("c"));
assert_eq!(si.output_col(), "i");
let ma = MaxAbsScaler::new().set_input_col("f").set_output_col("s");
- assert_eq!(ma.input_col(), "f");
+ assert_eq!(ma.input_col(), Some("f"));
assert_eq!(ma.output_col(), "s");
let lr = LogisticRegression::new()
diff --git a/docs/compatibility.md b/docs/compatibility.md
index a7d5e00a..7245b72a 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -32,10 +32,15 @@ The native ML classes take a JVM `Int` param as an `i32`:
`LogisticRegression::s
of its params (`KMeans::k`, `RandomForestClassifier::num_trees`, ...), which
reads its
`Params`: the value that is set, else Spark's default (`None` for `seed`,
`weight_col` and
`thresholds`). The fields of `LogisticRegressionModel`, `StringIndexerModel`
and
-`MaxAbsScalerModel` are private, as those of the other fitted models: use
+`MaxAbsScalerModel` are private, as those of the other fitted models but
`PipelineModel`: use
`Transformer::operator` and `Transformer::params`, and
`LogisticRegressionModel::feature_col`,
`label_col` and `prediction_col`. `VectorAssembler::input_cols` and
`Pipeline::stages`
-return a `Vec<String>`.
+return a `Vec<String>`, and `VectorAssembler::set_input_cols` and
`Pipeline::set_stages` take
+`impl IntoIterator<Item = impl Into<String>>`. The `input_col` of
`StandardScaler`,
+`MaxAbsScaler` and `StringIndexer` returns an `Option<&str>`, which is `None`
unless set: as in
+Spark, it has no default. Their `output_col`, and that of `VectorAssembler`,
return a `String`,
+Spark's `<uid>__output` unless set, the column that the server writes. Before,
they gave names
+that the server never wrote, such as `scaled_features`.
`Params::set_param_int32`, `set_param_int_narrow`, `set_param_string_array` and
`set_param_double_array` are public, with the new `Params::clear_param`, and
the evaluators
@@ -118,7 +123,8 @@ of many thousands of levels can overflow a small stack.
months. Collect gives it for a year-month interval, where it gave the text of
the
interval (`Value::String("1-0")`), so that a pivot on collected values names
its
columns as the pivot without values does (`INTERVAL '1-0' YEAR TO MONTH`), and
-`create_dataframe` takes it for a year-month interval column. Downstream
exhaustive
+`create_dataframe` takes it for an `INTERVAL YEAR TO MONTH` column (not for
`INTERVAL YEAR`
+or `INTERVAL MONTH`, which the server cannot narrow the Arrow interval to).
Downstream exhaustive
matches on these enums must handle the new variant. The Python client still
raises
`NOT_IMPLEMENTED` when it collects a year-month interval, as PySpark does.
@@ -170,7 +176,8 @@ The Python classes of the native estimators, transformers
and evaluators of
`pyspark.ml.connect` take their params as PySpark's do. The constructors are
keyword-only, raising PySpark's `TypeError`, except
`MulticlassClassificationEvaluator`,
which takes `metricName`, `labelCol` and `predictionCol` by position as well,
as
-PySpark's does. Each value is converted by the `TypeConverters` of its param in
+PySpark's does; its `metricName` is `accuracy` by default, as in PySpark,
where the JVM
+evaluator and the Rust API default to `f1`. Each value is converted by the
`TypeConverters` of its param in
PySpark (an integral float for an int param, for example), and a value that the
converter rejects raises its `TypeError`. A fit, transform or evaluate sends
only the
params that the constructor or a setter set, so the server applies its
defaults to
diff --git a/python/tests/test_arrow_handoff.py
b/python/tests/test_arrow_handoff.py
index 41daf521..499e4355 100644
--- a/python/tests/test_arrow_handoff.py
+++ b/python/tests/test_arrow_handoff.py
@@ -5744,7 +5744,8 @@ def
test_string_surrogate_fallback_precedes_importer_configuration(protocol, mon
monkeypatch.setattr(pd.DataFrame, "astype", record_rows)
with _arrow_input_service(protocol) as (spark, state):
state["config_error"] = grpc.StatusCode.INVALID_ARGUMENT
- with pytest.raises(TypeError, match="unsupported value type for
createDataFrame: str"):
+ # The UnicodeEncodeError of pyarrow's conversion of PySpark, a
ValueError.
+ with pytest.raises(UnicodeEncodeError, match="surrogates not allowed"):
spark.createDataFrame(frame, schema)
assert calls == ["astype"]
assert state["config_requests"] == []
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 162c6770..d3671cbd 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -6578,6 +6578,60 @@ def test_functions_ascii_and_unicode():
assert type(F.ascii(str_col)).__name__ == "Column"
+def
test_the_exception_of_a_done_call_replaces_the_error_of_a_batch_as_pyspark(mock_connect):
+ # As PySpark's Progress.__exit__, which makes the done call when the
decoding of a batch raises
+ # in the `with` of the execution: the exception of the done call replaces
that error, for
+ # collect as for an iterator, instead of going unreported when the
execution is dropped.
+ spark, service = mock_connect
+ # ExecutePlanResponse.arrow_batch=2: row_count=1, data=2 of bytes that are
not Arrow IPC.
+ service.execute_payload = message_field(2, varint_field(1, 1) +
message_field(2, b"not arrow"))
+ error = ValueError("the done call raises")
+
+ def failing(**kwargs):
+ if kwargs["done"]:
+ raise error
+
+ for action in [lambda: spark.range(3).collect(),
+ lambda: next(spark.range(3).toLocalIterator())]:
+ with pytest.raises(Exception) as decoding:
+ action()
+ assert decoding.value is not error
+ spark.registerProgressHandler(failing)
+ try:
+ with pytest.raises(ValueError) as raised:
+ action()
+ assert raised.value is error
+ finally:
+ spark.clearProgressHandlers()
+
+
+def
test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_as_pyspark(
+ mock_connect,
+):
+ # As PySpark, whose protobuf string fields raise ValueError for a str that
UTF-8 cannot encode
+ # (a lone surrogate): an option is not sent as another text (another
path), and a fill value
+ # raises the ValueError of its encoding rather than a TypeError of its
type.
+ from pyspark.sql import SparkSession
+
+ spark, service = mock_connect
+ bad = "a\ud800b"
+ message = re.escape(f"{bad!r} isn't a valid unicode string and can't be
encoded in UTF-8.")
+ df = spark.range(1)
+ for call in [
+ lambda: spark.read.option("path", bad),
+ lambda: spark.read.options(k=bad),
+ lambda: spark.read.options(**{bad: "v"}),
+ lambda: df.write.option("path", bad),
+ lambda: df.write.options(**{bad: "v"}),
+ lambda: spark.readStream.options(**{bad: "v"}),
+ lambda: SparkSession.builder.config(map={bad: "v"}),
+ ]:
+ with pytest.raises(ValueError, match=message):
+ call()
+ with pytest.raises(ValueError):
+ df.fillna(bad)
+
+
def test_functions_levenshtein():
"""Test levenshtein distance function."""
from pyspark.sql import functions as F
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 020c4c4b..5623d330 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -332,6 +332,30 @@ def
test_native_models_transform_a_dataframe_of_another_session_as_pyspark(sessi
other.stop()
+def
test_the_transform_of_a_deep_dataframe_of_another_session_counts_its_levels_as_pyspark(
+ session,
+):
+ # As PySpark, which serializes the plan of the transform with the plan of
its input in one
+ # recursion: the transform of a DataFrame of another session counts the
levels of that
+ # DataFrame, so that levels over it past the bound raise RecursionError
before any request,
+ # where the input counted as one level.
+ from pyspark.ml.connect import KMeans
+
+ model = KMeans(k=2, seed=1).fit(_native_training(session))
+ other = session.newSession()
+ try:
+ deep = _native_training(other)
+ for _ in range(700):
+ deep = deep.select("*")
+ transformed = model.transform(deep)
+ for _ in range(100):
+ transformed = transformed.select("*")
+ with pytest.raises(RecursionError):
+ transformed.columns
+ finally:
+ other.stop()
+
+
def test_ml_feature_transformers_as_pyspark(session):
from pyspark.ml.feature import IDF, HashingTF, MinMaxScaler, Tokenizer
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index c2fa1ebc..859489ba 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -424,6 +424,14 @@ def _literal_value(literal):
return kind, getattr(literal, kind)
+def _defaults_sent(name):
+ # The params that a native class sends unless it is given them: the metric
of
+ # MulticlassClassificationEvaluator, which PySpark's constructor sets.
+ if name == "MulticlassClassificationEvaluator":
+ return {"metricName": ("string", "accuracy")}
+ return {}
+
+
def _native_sent(spark, service, obj, models):
_, params = _native_request(spark, service, obj, models)
return {name: _literal_value(literal) for name, literal in
params.params.items()}
@@ -490,7 +498,7 @@ def
test_ml_connect_params_convert_with_the_type_converters_of_pyspark(ml_mock):
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)
+ assert sent == {**_defaults_sent(name), param: expected},
(name, param, value)
for value, message in _NATIVE_REJECTED[kind]:
expected = f'Invalid param value given for param "{param}".
{message}'
with pytest.raises(TypeError) as error:
@@ -516,7 +524,8 @@ def
test_ml_connect_constructors_send_only_the_params_they_are_given_as_pyspark(
models = []
for name in _NATIVE_PARAMS:
if name not in _NOT_FITTABLE:
- assert _native_sent(spark, service, getattr(connect, name)(),
models) == {}, name
+ sent = _native_sent(spark, service, getattr(connect, name)(),
models)
+ assert sent == _defaults_sent(name), 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) == {
@@ -525,6 +534,37 @@ def
test_ml_connect_constructors_send_only_the_params_they_are_given_as_pyspark(
}
+def
test_ml_connect_evaluators_take_the_signatures_and_defaults_of_pyspark(ml_mock):
+ # As PySpark's pyspark.ml.connect evaluators: their signatures, and the
metric of
+ # MulticlassClassificationEvaluator, "accuracy" unless given, which its
constructor sets, where
+ # the JVM evaluator's default is "f1".
+ import inspect
+
+ import pyspark.ml.connect as connect
+
+ spark, service = ml_mock
+ signatures = {
+ "RegressionEvaluator": "(*, metricName='rmse', labelCol='label',
predictionCol='prediction')",
+ "BinaryClassificationEvaluator":
+ "(*, metricName='areaUnderROC', labelCol='label',
rawPredictionCol='rawPrediction')",
+ "MulticlassClassificationEvaluator":
+ "(metricName='accuracy', labelCol='label',
predictionCol='prediction')",
+ }
+ for name, signature in signatures.items():
+ assert str(inspect.signature(getattr(connect, name))) == signature,
name
+ models = []
+ evaluator = connect.MulticlassClassificationEvaluator
+ assert _native_sent(spark, service, evaluator(), models) == {
+ "metricName": ("string", "accuracy")
+ }
+ assert _native_sent(spark, service, evaluator(metricName="f1"), models) ==
{
+ "metricName": ("string", "f1")
+ }
+ assert _native_sent(spark, service, evaluator("weightedPrecision"),
models) == {
+ "metricName": ("string", "weightedPrecision")
+ }
+
+
def test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
# As PySpark: an int beyond a long is taken by the constructor and the
setter, and the
# next fit raises the VALUE_NOT_BETWEEN of PySpark's serialization of the
params, before
@@ -568,11 +608,13 @@ def
test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
obj = cls()
assert getattr(obj, setter)(value) is obj
assert getattr(obj, setter)(None) is obj
- assert _native_sent(spark, service, obj, models).keys() ==
{param}, (name, param)
+ sent = _native_sent(spark, service, obj, models)
+ assert sent.keys() == {param} | _defaults_sent(name).keys(),
(name, param)
assert _native_sent(spark, service, obj, models)[param][0] ==
"null", (name, param)
if param != "thresholds":
sent = _native_sent(spark, service, cls(**{param: None}),
models)
- assert sent.keys() == {param} and sent[param][0] == "null",
(name, param)
+ assert sent.keys() == {param} | _defaults_sent(name).keys(),
(name, param)
+ assert sent[param][0] == "null", (name, param)
operator, _ = _native_request(spark, service, cls(), models)
assert re.fullmatch(name + "_[0-9a-f]{12}", operator.uid), operator.uid
@@ -624,8 +666,11 @@ def
test_ml_connect_setters_run_while_a_fit_or_an_evaluate_waits_as_pyspark(ml_m
assert len(outcome) == 1 and not isinstance(outcome[0], Exception),
(name, outcome)
(command,) = _commands(service)
held = command.ml_command.evaluate if hasattr(obj, "evaluate") else
command.ml_command.fit
- assert dict(held.params.params) == {}, name
- assert _native_sent(spark, service, obj, models) == {param: ("string",
"changed")}
+ assert set(held.params.params) == set(_defaults_sent(name)), name
+ assert _native_sent(spark, service, obj, models) == {
+ **_defaults_sent(name),
+ param: ("string", "changed"),
+ }
def
test_native_models_released_while_their_session_stops_send_no_delete(ml_mock):
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]