HyukjinKwon opened a new pull request, #754:
URL: https://github.com/apache/spark-connect-rust/pull/754
### What changes were proposed in this pull request?
This PR fixes the gaps that a review of the last 200 commits of master
found, where we do not behave as official PySpark 4.3.0 does. Each finding was
checked on both clients, ours and the official `pyspark-client` 4.3.0, against
a Spark 4.3.0 Connect server. This PR covers the native ML classes, the
DataFrame, the readers, the session builder and the Rust ML API.
**Native ML classes (Python)**
- `BisectingKMeansModel.computeCost` raises PySpark's `FutureWarning`
("Deprecated in 3.0.0. It will be removed in future versions. Use
ClusteringEvaluator instead. ...") before it fetches the cost.
- A pandas DataFrame given to `fit`, `transform` or `evaluate` raises
PySpark's `AttributeError: 'DataFrame' object has no attribute 'sparkSession'`,
not our own `TypeError`. `OneVsRest.fit` already runs PySpark's own
`OneVsRest._fit` for such a dataset (#748), which raises PySpark's `KeyError`.
So the old pandas rejection has no caller left, and is deleted.
- `StopWordsRemover.loadDefaultStopWords` takes a `(value, DataType)` pair,
as PySpark's literal arguments do.
- The native modules have PySpark's names:
- `pyspark.ml.connect.feature` has PySpark's `__all__`.
- `classification`, `clustering` and `regression` list their `__all__` in
PySpark's order.
- `pyspark.ml.connect.pipeline` has no `__all__`, as PySpark's has none.
- The modules export PySpark's own abstract base classes, of which the
native classes are subclasses: `Classifier`, `ClassificationModel`,
`ProbabilisticClassifier`, `ProbabilisticClassificationModel`,
`ClusteringSummary`, `JavaEvaluator`, `Regressor` and `RegressionModel`.
**DataFrame**
- `withColumns` asserts its mapping as PySpark's `WithColumns` plan does. An
empty mapping, a key that is not a str, or a value that is not a Column raises
PySpark's bare `AssertionError` at the call.
- `to(schema)` keeps a schema that is not a `DataType`, or a `StructType`
that has a `StructField` as a type, as PySpark keeps it. `columns`, `dtypes`,
`repr`, `printSchema` and `schema` read it as PySpark's code does.
- `select`, `groupBy`, `orderBy` and the other methods that unpack a list of
columns unpack any `collections.abc.Sequence`, such as a `range`, bytes or a
`UserList`, as PySpark's `_to_cols` does.
- Some arguments fail when the plan is built, not at the call, as on PySpark:
- the counts and seeds of `limit`, `offset`, `repartition`,
`repartitionByRange`, `repartitionById`, `coalesce`, `sample`, `sampleBy` and
`randomSplit`;
- `allowExactMatches`, `direction` and `how` of `_joinAsOf`.
- `copy.copy`, `copy.deepcopy` and pickle keep the instance attributes of a
`DataFrameWriter` and a `DataFrameWriterV2`.
- A copy of a DataFrame requests its schema as PySpark's does, so a stopped
session fails it with `SparkConnectException`.
**Readers and the session builder**
- `read.table`, `readStream.table` and `changes` of a name that is not a
str, or of bytes that are not UTF-8, give a DataFrame whose plan raises
protobuf's `TypeError`, or the decode error, as PySpark's does.
- A reader keeps a format that is not a str, and `_format` returns it.
- Copies and pickles of the readers and of the stream writer keep their
instance attributes.
- `SparkSession.builder.remote` keeps a value that is not a str, and
`create` then raises PySpark's `INVALID_CONNECT_URL`. After `remote(None)`,
`create` and `getOrCreate` raise an `AssertionError`, as PySpark's do.
- `createDataFrame` of empty data sends the JSON of a schema whose
`nullable` is not a bool, as PySpark does, so the server rejects it in the same
way.
**Rust ML API**
- Persistence:
- a Pipeline or a validator that the JVM saved (classes
`org.apache.spark.ml.*`) loads, mapped as PySpark's `DefaultParamsReader` maps
it;
- a compound estimator with duplicate uids fails its save and its load
with PySpark's `RuntimeError`;
- a fitted model given as a plain transformer stage fails at the save,
with a pointer to `PipelineStage::model`;
- the fit of a Pipeline of a `QuantileDiscretizer` gives a `Bucketizer` of
a new uid, as PySpark's does;
- the JSON of params writes floats and non-ASCII strings as Python's
`json.dumps` does;
- messages render params and floats as Python's `repr` does.
- Params:
- the params of a loaded object are serialized again as PySpark infers
them: string arrays with the `UTF8_BINARY` collation, vectors without the
Python class;
- a decimal is sent as PySpark's `DecimalType()`, `(10, 0)`;
- writer option keys are lowercased.
- A malformed cluster-center matrix from the server returns a `ValueError`
instead of panicking.
- The Delete of a released ML object sends `evict_only = false`, as
PySpark's does.
- Docs:
- the default seeds of the tree and clustering estimators are the server's;
- the doc of a struct param says that PySpark's `deserialize_param`
refuses it.
**CI and tooling**
- The feature offline suite fails under CI when protobuf is too old, instead
of skipping silently.
- `scripts/gen_ml_stage_kinds.py` wraps a long param doc of the generated
`param_specs.rs` with Rust's line continuations, so no line passes 100 columns.
The strings are unchanged.
Differences that remain, and their follow-ups:
- `getattr(df, "__deepcopy__")`: PySpark's `__getattr__` answers it by
reading the columns. Documented.
- `builder.remote(url=None)` is accepted, as the classic `remote(url)`
signature has it. Already pinned by
`test_session_builder_remote_takes_the_url_as_pyspark`.
- The private `_options` dict of a reader drops an option of None, where
PySpark keeps `{'k': None}`. No public behavior differs.
### Why are the changes needed?
So that the drop-in behaves as PySpark 4.3.0 does, and the Rust ML API sends
what PySpark sends. Each item is a difference that the review found and that a
probe on both clients confirmed.
### Does this PR introduce _any_ user-facing change?
Yes, the behaviors above, in the Python client and the Rust ML API. For
example:
| Call | Before | After (as PySpark) |
|---|---|---|
| `KMeans().fit(pandas_df)` | `TypeError: fit() requires a Spark DataFrame;
...` | `AttributeError: 'DataFrame' object has no attribute 'sparkSession'` |
| `bkm_model.computeCost(df)` | no warning | `FutureWarning: Deprecated in
3.0.0. ...` |
| `df.limit(2.0)` | an error at the call | a DataFrame, whose action raises
the same error |
| `df.withColumns({})` | the frame unchanged | `AssertionError` |
| `df.select(range(0))` | `NOT_EXPECTED_TYPE` | a DataFrame of no columns |
| `spark.read.table(3)` | `TypeError` at the call | `TypeError` when the
plan is built |
| `SparkSession.builder.remote(None).create()` | a session of
`sc://localhost` | `AssertionError` |
### How was this patch tested?
- Each change was probed on both clients against the official
`pyspark-client` 4.3.0 and a Spark 4.3.0 Connect server, and the outputs were
compared.
- New and updated offline tests, in `test_dropin_offline.py`,
`test_ml_api_offline.py`, `test_ml_offline.py`, `test_ml_features_offline.py`,
`test_evaluators_offline.py`, `test_als_offline.py` and
`test_frequent_patterns_offline.py`.
- New Rust unit tests in `meta.rs`, `validators.rs`, `object.rs`,
`persistence.rs` and `clustering_api.rs`, a new replay test in
`feature_models_replay.rs`, and an `evict_only` check in `ml_golden_replay.rs`.
- New live tests in `e2e_ml_meta.rs`: a JVM-named validator's load and fit,
duplicate uids, and a Pipeline of a QuantileDiscretizer. Also a new case of the
clustering API golden, `computeCost_future_warnings`, recaptured on official
PySpark.
- Locally, on the combined tree:
- the whole offline list of the coverage job: 5704 passed, 76 skipped.
After the rebase onto the latest master, the ML and drop-in offline files pass
again: 3495 passed;
- the Rust tests of the `rust` job (`cargo test -p apache-spark-connect -p
apache-spark-connect-core --release`): 1565 passed, 0 failed;
- `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt
--check`, `ruff check` and `ruff format --check`: clean.
### 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.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]