)]}'
{
  "log": [
    {
      "commit": "876c1b6c89a42c999582b786092c5721790d2b28",
      "tree": "457ce871a4de9b49e64139811f64492d33ec618a",
      "parents": [
        "407442389aea3fc2a3d1ed4e41a7aae5ae10df2b"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Dec 03 15:17:26 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Dec 03 15:17:26 2026 +0800"
      },
      "message": "[SPARK-62624][CONNECT][ML] Add array_to_vector and vector_to_array to the Rust API\n\n### What changes were proposed in this pull request?\n\nExpose three column expressions in `spark_connect::ml`.\n\n- `array_to_vector(column)` turns a numeric array into a dense ML vector.\n- `vector_to_array(column)` converts a dense or sparse vector to an array of doubles, matching the default in `pyspark.ml.functions`.\n- `vector_to_array_with_dtype(column, dtype)` accepts `\"float32\"` or `\"float64\"`. Spark validates the dtype when it analyzes the expression.\n\nEach helper accepts a column name or a `Column`. Use the helpers in the native `OneVsRestModel` transform and in the feature and GBT regressor integration tests. Add usage to the columns and functions guide.\n\n### Why are the changes needed?\n\nRust users currently have to name a Spark function and build its argument expressions by hand to prepare vector features or inspect a model\u0027s probability vector. The named helpers build the same expressions as standard PySpark over Connect.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. Rust callers can now write `df.with_column(\"features\", array_to_vector(\"measurements\"))` or `df.select([vector_to_array(\"probability\")])`.\n\n### How was this patch tested?\n\nRan the Rust ML feature and GBT regressor suites against a Spark 4.3.0 Connect server, plus the OneVsRest golden transform test. The new test covers dense and sparse vectors, default and explicit double precision, single precision, and the server error for an unsupported dtype.\n\nAll 864 Rust library tests passed. Spark 4.3.0\u0027s official ML functions and classification suites passed 31 tests in each of the drop-in and transport modes. Upstream skips its single-worker prediction-cache test on a remote server.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nYes.\n\nThis pull request and its description were written by Isaac.\n\nCloses #1037 from zhengruifeng/ml/vector-array-functions.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "407442389aea3fc2a3d1ed4e41a7aae5ae10df2b",
      "tree": "525203f26d51db652d3245571de66fa6b6c7a393",
      "parents": [
        "86c467ca9aa4d5230f055cfe2fad74a033331b0c"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Dec 03 12:39:26 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Dec 03 12:39:26 2026 +0800"
      },
      "message": "[SPARK-62611][CONNECT][EXAMPLES] Add a runnable Rust LogisticRegression example\n\n### What changes were proposed in this pull request?\n\nAdd a runnable `logistic_regression` binary to the `examples` package. It uses `VectorAssembler` to combine study hours and practice-test counts into features, fits a binary `LogisticRegression` model on six labeled rows, and calls `transform` on two new rows.\n\nDocument the run command and expected predictions in the examples guide. The example connects to `sc://localhost:15002` by default and accepts a different endpoint through `SPARK_REMOTE`.\n\n### Why are the changes needed?\n\nThe native Rust ML API has integration tests, but the examples package has no program that shows readers how to go from numeric DataFrame columns to a fitted model and predictions. Inline data lets readers run the whole example from a checkout with a Spark Connect server.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. From the repository root, run `cargo run -p examples --bin logistic_regression`.\n\n### How was this patch tested?\n\nRan the documented Cargo command against a local Spark Connect 4.3.0 server and verified both output rows. The model predicted `0.0` for one study hour and one practice test and `1.0` for seven hours and four tests.\n\nThe strict documentation build and all 864 Rust library tests passed. Spark’s official classification and feature suites also passed all 68 tests in both drop-in and transport modes.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nYes.\n\nThis pull request and its description were written by Isaac.\n\nCloses #1036 from zhengruifeng/examples/ml-logistic-regression.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "86c467ca9aa4d5230f055cfe2fad74a033331b0c",
      "tree": "7f251ef38318756cce7601d005aaa7778a2d31ae",
      "parents": [
        "0720193768ff884182ae08cd60580103d88fa089"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Dec 03 09:23:08 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Dec 03 09:23:08 2026 +0800"
      },
      "message": "[SPARK-62610][CONNECT][DOCS] Correct ML parity notes for fitted models and parameter coverage\n\n### What changes were proposed in this pull request?\n\nCorrect the Spark 4.3.0 module audit to describe typed results from standard `pyspark.ml` fits. For example, `LogisticRegression.fit` returns `LogisticRegressionModel`. Clarify that the compatibility guide’s Python-plan pickling example exercises the retained upstream model class.\n\nRename the parameter coverage test’s `no_rust_type` module to `without_params`. Its 21 summaries, the abstract `Evaluator`, and `ParamGridBuilder` all have empty parameter lists in the PySpark fixture. The exclusion reasons now explain that fact.\n\n### Why are the changes needed?\n\nThe previous notes described a shared `MLModel` fit result and labeled summaries such as `KMeansSummary` as missing Rust types. Both descriptions could lead contributors to reimplement existing functionality. [SPARK-62610](https://issues.apache.org/jira/browse/SPARK-62610)\n\n### Does this PR introduce _any_ user-facing change?\n\nNo.\n\n### How was this patch tested?\n\n- Verified that the same 23 classes are excluded and that each has an empty `params` array in the official 4.3.0 fixture. Both `ml_params_table` tests and all 864 Rust library tests passed.\n- Ran the existing upstream-model pickling test and the official classification, clustering and feature suites against Spark Connect 4.3.0. All 76 parity cases passed in each of the two modes, the Rust-backed Python client and official PySpark over Rust transport.\n\nThe live LogisticRegression fit, transform, model fetch, and persistence test also passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1035 from zhengruifeng/docs/ml-parity-notes.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "0720193768ff884182ae08cd60580103d88fa089",
      "tree": "e49f2ca75d8b264de1cdd9bcd59f3850cbe0629c",
      "parents": [
        "b21969f4fb23a7a03b0e8e4e028832b29d81dd11"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Dec 03 08:24:03 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Dec 03 08:24:03 2026 +0800"
      },
      "message": "[SPARK-62583][CONNECT][PYTHON] Test cached ML model lifetimes through DataFrame unions\n\n### What changes were proposed in this pull request?\n\nAdd a parameterized mock-server test for four DataFrames from standard `pyspark.ml`. Three come from LogisticRegression (`transform`, training-summary predictions, and evaluation-summary predictions), and one comes from `GaussianMixtureModel.gaussiansDF`.\n\nEach case drops the model, sends the derived plan to the server with `explain()`, and builds a `unionByName`. After dropping the original DataFrame, the test checks that the union still sends the same ML relation and that the server has received no `Delete` for the fitted model. After dropping the union, it checks for a single `Delete` naming that model.\n\n### Why are the changes needed?\n\nA lazy DataFrame can outlive the Python model that produced it. A premature deletion leaves the plan pointing to an expired server-side model. The four corresponding upstream Pipeline tests are skipped because they can occasionally hang. The mock server covers the client’s ownership and release behavior in the existing offline ML suite. [Upstream Pipeline tests](https://github.com/apache/spark/blob/v4.3.0/python/pyspark/ml/tests/test_pipeline.py#L177) · [SPARK-62583](https://issues.apache.org/jira/browse/SPARK-62583)\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. This change adds tests.\n\n### How was this patch tested?\n\n- `python -m pytest -q python/tests/test_ml_offline.py` passed all 453 tests. The four new cases also passed with official PySpark 4.3.0.\n- In a local negative control, reconstructing the union from its serialized plan dropped the model reference. All four cases detected the premature `Delete`.\n- Ran the four original upstream test bodies against Spark Connect 4.3.0 in fresh processes with a 90-second deadline per case. Three repetitions each with the Rust-backed Python client, official PySpark over Rust transport, and official PySpark over gRPC passed all 36 runs.\n- The official Pipeline, classification and clustering parity suites passed in both drop-in and Rust-transport modes (31 passed per mode, with the four upstream skips in each).\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1034 from zhengruifeng/test/ml-derived-frame-lifetime.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "b21969f4fb23a7a03b0e8e4e028832b29d81dd11",
      "tree": "2f52f7c4b2489cef04d4528d01cba1655364b520",
      "parents": [
        "328d288d6101b14186f233d122a8f29d22463400"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 23:00:38 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 23:00:38 2026 +0800"
      },
      "message": "[SPARK-62579][CONNECT] Group PyO3 ML reader and writer bindings in the persistence module\n\n### What changes were proposed in this pull request?\n\nMove the native Python ML reader and writer (`PyMLReader` and `PyMLWriter`) from `crates/pyspark-rs/src/ml/object.rs` to `ml/persistence.rs`. Their save/load callbacks, path and option handling, and pickle factories move with them. The persistence module registers both classes and both factories under their existing Python names.\n\nUpdate the binding macros and the handwritten ML stages to use the new location. Model code still builds the write target from its model reference and parameters.\n\n### Why are the changes needed?\n\nAfter #1032, following a save or load still required switching between the large object module and the persistence module that resolves classes and loads metadata. Grouping the two bindings with those helpers gives persistence code a single entry point and removes about 500 lines from `ml/object.rs`.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. The Python import paths, reader/writer methods, pickle protocol, and Spark ML artifact formats are preserved.\n\n### How was this patch tested?\n\n- Compared the public reader/writer methods and signatures with master. In fresh Python processes, loaded configured readers and writers pickled by the other build in both directions at protocols 0 through 5. Checked the reader\u0027s estimator class, writer options, overwrite flag, estimator UID and parameter values.\n- Exchanged saved estimators and fitted models in both directions with official PySpark 4.3.0. Cases included a direct Word2Vec save/load, a pipeline with nested stages, and both tuning validators with persisted sub-models.\n- Ran the repository\u0027s Python ML suites (1,705 passed and 68 skipped offline, 102 passed live). Compared the public API of 173 standard Python ML classes with master.\n- Ran 11 official ML parity suites through the drop-in and official-PySpark-over-Rust modes. Each mode had 126 passes and 4 upstream Pipeline skips.\n- Ran 864 Rust unit tests, 9 live Rust ML integration tests and 2 parameter-table tests. Compiled all Rust integration targets with and without `wasm-udf` and checked formatting, workspace Clippy, strict Rustdoc and the binary license inventory.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1033 from zhengruifeng/refactor/ml-reader-writer-layout.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "328d288d6101b14186f233d122a8f29d22463400",
      "tree": "3bd22c443a1dab42aa4e08aac25bea89c6a9a9e3",
      "parents": [
        "d15677ff2ee7ff27b5b809e1d48388a5121cc604"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 21:19:14 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 21:19:14 2026 +0800"
      },
      "message": "[SPARK-62577][CONNECT] Split the shared Rust ML module roots by responsibility\n\n### What changes were proposed in this pull request?\n\nReplace `crates/spark-connect/src/ml.rs` and `crates/pyspark-rs/src/ml.rs` with small `ml/mod.rs` files that declare the modules and preserve the existing exports.\n\n| Responsibility | Rust client | PyO3 bindings |\n| --- | --- | --- |\n| Stage execution | `base.rs` holds the stage traits. `operator.rs` builds and executes Connect ML requests. | `base.rs` handles dataset arguments, fit dispatch and Python subclass hooks. |\n| Parameters and values | `params.rs` holds parameter storage and accessors. `linalg.rs` encodes and decodes vectors and matrices. | `param_conversion.rs` applies PySpark\u0027s type converters. `native.rs` binds parameters and snapshots the native stage for execution. |\n| Fitted models | `model_ref.rs` owns the session reference, release and transform logic for cached objects. | `model.rs` holds the generic Python `MLModel` wrapper. |\n\nThe first commit moves the two files. The second extracts the implementations and moves the shared Rust module tests to `ml/tests.rs`.\n\n### Why are the changes needed?\n\nThe family refactors in #1026 through #1031 grouped each algorithm with its model. The shared implementations still occupied 2,580 lines in the Rust module root and 841 lines in the binding root. For example, following a model reference from creation to release required switching between `ml.rs` and `ml/object.rs`. Both parts now live in `ml/model_ref.rs`.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. Rust callers continue to import from `spark_connect::ml`, and the native Python classes keep their existing names and import paths.\n\n### How was this patch tested?\n\n- Compared the documented public Rust declarations across all 221 ML exports and the public members and signatures of 173 standard Python ML classes with master. Both comparisons matched.\n- Loaded 66 configured estimators, transformers and models pickled on master across classification, regression, clustering, feature, pipeline and tuning. Checked their types, UIDs and configured values.\n- Ran the official PySpark ML parity suites for classification, regression, clustering, evaluation, feature, ALS, FPM, statistics, OneVsRest, pipeline and tuning. The drop-in and official-PySpark-over-Rust modes each had 126 passes and four Pipeline skips.\n- Ran the repository\u0027s Python ML suites (1,705 passed and 68 skipped offline, 47 passed live) and Rust tests (864 unit, 26 live ML integration and 47 ML golden or coverage tests).\n- Compiled all Rust integration targets with and without `wasm-udf`. Checked formatting, workspace Clippy, the binary license inventory and the CI Rustdoc command with warnings denied.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1032 from zhengruifeng/refactor/ml-module-roots.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "d15677ff2ee7ff27b5b809e1d48388a5121cc604",
      "tree": "52a3dd08b8e82d10de2001ad50d39372ba626501",
      "parents": [
        "31e21a3576fcb9b26577f27c8c11002bb111f562"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 20:56:26 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 20:56:26 2026 +0800"
      },
      "message": "[SPARK-62575][CONNECT] Group Rust ML tuning implementations by validator\n\n### What changes were proposed in this pull request?\n\nGroup `CrossValidator` and `TrainValidationSplit` under `src/ml/tuning/` in both `spark-connect` and `pyspark-rs`. Each validator shares a file with its fitted model. Both crates have a `persistence.rs` for common validator metadata and stage I/O. The Rust client also groups its dataset split functions and `ParamGridBuilder` here.\n\nThe first commit moves the existing files and updates module references. The second splits their contents by validator and moves the associated tests.\n\n### Why are the changes needed?\n\nAfter the Pipeline reorganization in #1030, following a validator across the Python binding and the Rust client still required searching two files of over 2,000 lines each. The matching filenames put each validator’s fit, model and persistence entry points in one place per crate.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. The public Rust exports, Python import paths, parameter handling and PySpark artifact format stay the same.\n\n### How was this patch tested?\n\n- Compared the public Python members and signatures of both estimators, both models and `ParamGridBuilder` against master. Loaded pickles created on master for all four validator classes and checked UIDs, parameter grids, metrics and sub-models.\n- Saved both estimators and their fitted models with sub-models, then loaded them with official PySpark 4.3.0. Repeated with official PySpark as the writer. Both clients reproduced the saved results.\n- Ran the official tuning, Pipeline and OneVsRest parity suites against a live Spark Connect server through the Python drop-in and through Rust transport. Each mode had 16 passes and 4 skips. All seven upstream tuning tests passed in each mode.\n- Ran the repository’s Python ML tests (1,705 passed, 68 skipped offline, 82 passed live), 864 Rust unit tests, all 9 live `e2e_ml_meta` tests and both `ml_params_table` tests.\n- Compiled all Rust integration targets with and without `wasm-udf`. Checked formatting, workspace Clippy with warnings denied, binary license inventory and the seven public tuning paths in the generated Rust docs.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1031 from zhengruifeng/refactor/ml-tuning-layout.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "31e21a3576fcb9b26577f27c8c11002bb111f562",
      "tree": "90d94fe7a711440b3b761cd22da920a3bcb0a09d",
      "parents": [
        "dac611d8fd04bf3b996a24400177b1c65b624bde"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 20:30:28 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 20:30:28 2026 +0800"
      },
      "message": "[SPARK-62572][CONNECT] Group Rust ML pipeline implementations by responsibility\n\n### What changes were proposed in this pull request?\n\nGroup the standard ML pipeline implementation under `src/ml/pipeline/` in both `spark-connect` and `pyspark-rs`. Each crate now has `mod.rs` for `Pipeline` and `PipelineModel`, `stage.rs` for stage handling, and `persistence.rs` for saving and loading pipelines. Six existing Rust unit tests move alongside the behavior they cover.\n\nThe first commit renames the PyO3 pipeline module. The second extracts the Rust pipeline implementation from `meta.rs` and gives the Python binding\u0027s shared metadata and parameter-copy helpers homes that tuning and OneVsRest can also use.\n\n### Why are the changes needed?\n\nTracing a pipeline fit or load previously required looking in the Rust `meta.rs` and the PyO3 `pipeline_api.rs`. The matching filenames make it easier to find the implementation on either side of the binding, following #1026 through #1029.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. The Rust exports, standard Python import paths, stage execution order, and saved pipeline format are preserved.\n\n### How was this patch tested?\n\n- Compared the public Python members, signatures and native class names for `Pipeline` and `PipelineModel` with master. Loaded pickles made on master for both classes and checked their stage UIDs and parameters.\n- Exchanged saved pipelines and fitted models in both directions with official PySpark 4.3.0. The pipeline included a Python-defined estimator and nested stages. Each client loaded the other\u0027s artifacts, transformed data, refitted the saved estimator, and matched the recorded stage UIDs and output.\n- Passed 1,705 offline Python ML tests (68 skipped) and 76 live Python tests. Ran the official pipeline, tuning and OneVsRest parity suites against the drop-in package (16 passed, 4 skipped) and official PySpark over Rust transport (16 passed, 4 skipped).\n- Passed 864 Rust library tests, 9 live composite-estimator tests and 2 parameter-table tests. Compiled all Rust integrations with and without `wasm-udf`, ran rustfmt and workspace Clippy, and verified the six public Rust pipeline types and function paths in rustdoc.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1030 from zhengruifeng/refactor/ml-pipeline-layout.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "dac611d8fd04bf3b996a24400177b1c65b624bde",
      "tree": "2bf0b53827fa682d05486aec1ae0a3e41f68fa36",
      "parents": [
        "bb564f7e48c699d278d1a06780d8c0d59f119619"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 20:06:53 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 20:06:53 2026 +0800"
      },
      "message": "[SPARK-62571][CONNECT] Group Rust ML feature implementations by algorithm\n\n### What changes were proposed in this pull request?\n\nOrganize the 38 standard feature estimators and transformers by algorithm family under `src/ml/feature/` in both `spark-connect` and `pyspark-rs`. Each fitted model lives with its estimator, including the vocabulary and label factories on `CountVectorizerModel` and `StringIndexerModel`. `QuantileDiscretizer` and `Bucketizer` share a module because the public Python fit returns a `Bucketizer`.\n\nThe first commit moves the existing files. The second splits their contents across matching modules and moves the four remaining Rust feature stages and their tests out of the shared `ml.rs`. The PyO3 registration still publishes all 57 classes and preserves the order of `_ml_feature_names`.\n\n### Why are the changes needed?\n\nFollowing `StandardScaler.fit` previously required looking across the shared Rust ML file, the Rust feature module, and separate PyO3 estimator and model files. The matching module paths follow the layout introduced for classification, regression and clustering in #1026, #1027 and #1028.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. The standard Python classes remain in `pyspark.ml.feature`, and the Rust types remain in `spark_connect::ml`.\n\n### How was this patch tested?\n\n- Compared public members, signatures, native class names, and the ordered registration list for all 57 standard Python feature classes with master. Loaded pickles created on master for all 38 stages and verified their UIDs and configured parameters.\n- Passed 2,429 offline Python ML tests (68 skipped) and 240 live Python tests against Spark Connect 4.3.0. Ran the official PySpark feature parity suite through both the drop-in package (51 passed) and official PySpark over Rust transport (51 passed).\n- Passed 864 Rust library tests, 14 feature, golden and parameter-table tests, and 9 live meta-algorithm tests. Compiled all Rust integration targets with and without `wasm-udf`, ran rustfmt and workspace Clippy, and verified rustdoc links for all 58 public Rust feature types.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1029 from zhengruifeng/refactor/ml-feature-layout.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "bb564f7e48c699d278d1a06780d8c0d59f119619",
      "tree": "ac0d7c4aa4ff1f1958de79b35a74f3a585d3bd45",
      "parents": [
        "2ff221fa190924e77b146a3f59cdc1c5fdc7a8de"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 19:45:04 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 19:45:04 2026 +0800"
      },
      "message": "[SPARK-62570][CONNECT] Group Rust ML clustering implementations by algorithm\n\n### What changes were proposed in this pull request?\n\nGroup the five clustering algorithms in matching `src/ml/clustering/` modules in `spark-connect` and `pyspark-rs`. KMeans, BisectingKMeans and GaussianMixture each share a file with their fitted model and training summary. The LDA module contains both the local and distributed model classes. The PowerIterationClustering module contains graph assignment and persistence.\n\nThe first commit renames the existing modules. The second moves the implementations and six algorithm-specific Rust tests. The two k-means models still share the same cluster-center decoder, and the three summary types still implement the common `ClusteringSummary` trait.\n\n### Why are the changes needed?\n\nFollowing a clustering operation from its Python binding to the Rust client required looking across two shared `ml.rs` files and separate model and summary files. The matching filenames follow the classification and regression layout introduced in #1026 and #1027.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. The standard `pyspark.ml.clustering` classes keep their import paths, signatures and pickle compatibility, and the Rust API remains available through `spark_connect::ml`.\n\n### How was this patch tested?\n\n- Compared public members, signatures and native class names on all 14 standard Python clustering classes with master. Loaded pickles created on master for all five algorithms and verified their UIDs and configured cluster counts.\n- Passed 1,705 offline Python ML tests (68 skipped) and 57 live Python tests against Spark Connect 4.3.0. All eight official PySpark clustering tests passed in each mode, using the drop-in package and official PySpark over Rust transport.\n- Passed 864 Rust library tests, 39 clustering integration and golden tests, and 9 live meta-algorithm tests. Compiled all Rust integration targets with and without `wasm-udf`, ran rustfmt and workspace Clippy, and verified rustdoc links for 14 public clustering types and two traits.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1028 from zhengruifeng/refactor/ml-clustering-layout.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "2ff221fa190924e77b146a3f59cdc1c5fdc7a8de",
      "tree": "05a564d98d92478f6b55c078d9ffaf1312879896",
      "parents": [
        "e08a2545ed5b059d4280f71b094ff9cf00273d34"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 19:27:10 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 19:27:10 2026 +0800"
      },
      "message": "[SPARK-62567][CONNECT] Group Rust ML regression implementations by algorithm\n\n### What changes were proposed in this pull request?\n\nGroup the eight regression estimators with their fitted models and summaries under `src/ml/regression/` in both `spark-connect` and `pyspark-rs`. The two crates now have matching files for linear regression, generalized linear regression, AFT survival regression, isotonic regression, factorization machines, and the three tree regressors. The PyO3 family module registers all 20 regression classes.\n\nThe first commit renames the existing modules. The second moves the implementations and eight algorithm-specific Rust tests. The shared ML garbage-collection test still exercises a regression model alongside clustering and meta-models.\n\n### Why are the changes needed?\n\nAs with classification in #1026, tracing a regression estimator from its Python binding to its Rust implementation meant looking across the shared `ml.rs` files and separate model modules. The matching filenames put the estimator, model, and summary code for each algorithm in one place per crate.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. The Rust types remain available under `spark_connect::ml`, and the standard Python classes retain their import paths, method signatures, and pickle compatibility.\n\n### How was this patch tested?\n\n- Compared the public members, signatures and native class names of all 20 standard Python regression classes with master. Loaded estimator pickles created on master for all eight regressors and verified their UIDs and configured prediction columns.\n- Passed 1,705 offline Python ML tests (68 skipped) and 69 live Python tests against Spark Connect 4.3.0. The official PySpark regression and classification parity suites passed all 27 tests in each mode, using the drop-in Python package and official PySpark over Rust transport.\n- Passed 864 Rust library tests, 55 regression integration and golden tests, and nine live meta-algorithm tests. Compiled all Rust integration tests both with and without `wasm-udf`, ran rustfmt and workspace Clippy, and verified the published rustdoc paths of the 20 regression types and two summary traits.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1027 from zhengruifeng/refactor/ml-regression-layout.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "e08a2545ed5b059d4280f71b094ff9cf00273d34",
      "tree": "a404191b639ffbefed92f89fda351bf155b36516",
      "parents": [
        "6686d8a64a1d2223d5536b72923da8f4797d14a8"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 18:15:56 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 18:15:56 2026 +0800"
      },
      "message": "[SPARK-62566][CONNECT] Group Rust ML classification implementations by algorithm\n\n### What changes were proposed in this pull request?\n\nGroup the nine standard classification estimators with their fitted models and summaries under `src/ml/classification/` in both `spark-connect` and `pyspark-rs`. Both crates use the same algorithm filenames, with the three tree classifiers together in `tree.rs`. The core re-exports the public types through `spark_connect::ml`, and each binding module registers its family with PyO3.\n\nThe first commit renames the existing modules to `classification/mod.rs` and moves their children. The second commit moves the estimator definitions, implementations, and classifier-specific Rust unit tests out of the two `ml.rs` files. The validator test that inspects a nested OneVsRest model now constructs it through the public API.\n\n### Why are the changes needed?\n\nFollowing LogisticRegression from Python to Rust previously required looking in the top-level `ml.rs` and a classification file in each crate. Now the estimator, its fit path, and its typed model are in `classification/logistic.rs` on both sides of the binding. [SPARK-62566](https://issues.apache.org/jira/browse/SPARK-62566)\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. Rust callers keep their `spark_connect::ml` imports. Python callers keep the same classes, signatures, and pickle paths.\n\n### How was this patch tested?\n\n- Compared the 32 registered standard Python classification classes before and after the move, including public member signatures and binding names. Loaded pickles made on master for all nine estimators and checked their UIDs and configured prediction columns.\n- Passed 1,705 local offline Python ML tests (68 skipped) and 66 live Python tests on Spark Connect 4.3.0. The official classification and OneVsRest suites passed all 20 tests in each mode, against the drop-in package and official PySpark over Rust transport.\n- Passed 864 Rust library tests, nine live meta-algorithm tests, and 75 Rust classification, golden, and related integration tests. One existing OneVsRest/forest persistence test is marked ignored. Compiled all Rust integration targets with and without WASM UDFs. Checked rustfmt, Clippy, and rustdoc, including the existing public import paths for all nine classifiers.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1026 from zhengruifeng/refactor/ml-classification-layout.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "6686d8a64a1d2223d5536b72923da8f4797d14a8",
      "tree": "0cf314c47d8b70ee3b3baf8946d4eec5fa95e015",
      "parents": [
        "474db5c691e57903a2d1121e7406a284821054be"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 17:05:12 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 17:05:12 2026 +0800"
      },
      "message": "[SPARK-62564][CONNECT][PYTHON] Delegate standard TrainValidationSplit operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute standard `pyspark.ml.tuning.TrainValidationSplit` and `TrainValidationSplitModel` through the existing Rust bindings for fit, transform, save, and load. Both Python import paths now expose the same classes.\n\nRust builds the seeded training and validation splits. The binding runs PySpark’s per-parameter-map fit and evaluation tasks, orders the results by parameter map, and refits the winner on the full dataset. Python subclasses can still override `_fit` and `_copyValues`. Fitted models store `bestModel`, `validationMetrics`, and `subModels` as ordinary Python instance attributes.\n\n### Why are the changes needed?\n\nStandard PySpark ran a second train-validation loop in Python. Sharing the native implementation lets upstream PySpark tests exercise the Rust-backed split and model persistence paths. This completes the standard tuning validator migration started with CrossValidator in #1024. [SPARK-62564](https://issues.apache.org/jira/browse/SPARK-62564)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe compatibility classes now report `pyspark.ml.tuning` as their module. Their parameters synchronize eagerly with Rust. The public members and signatures of both standard classes match PySpark 4.3.0. Existing model pickles from both import paths load with the new classes.\n\n### How was this patch tested?\n\n- Ran the official Spark 4.3.0 tuning and pipeline suites against the Rust-backed Python package and against official PySpark over Rust transport. Each mode passed 13 tests and skipped four upstream-disabled pipeline tests.\n- Ran 35 live Python tests. The new regression checks a seeded holdout, two parallel parameter maps, metric and submodel order, the full-data refit, subclass dispatch, and model persistence with and without submodels.\n- Exchanged saved validators and fitted models with official PySpark in both directions. Independent fits produced identical validation metrics and predictions for the best model and both submodels. The Rust-backed process ran with optional Python dependencies, including protobuf and gRPC, blocked.\n- Passed 2,433 offline Python ML and type-stub tests (68 skipped), 864 Rust library tests, and nine live Rust meta-algorithm tests. Compiled the Rust integration tests with and without WASM UDFs and checked Clippy, formatting, generated stubs, and vendored-file drift.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1025 from zhengruifeng/feature/standard-train-validation-split-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "474db5c691e57903a2d1121e7406a284821054be",
      "tree": "0eeda4e6f7c013f8e50d6e024d29e0754f61d8c2",
      "parents": [
        "6493f7b0f8343ee62bd4011636fffdb70e9c00f9"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 16:45:32 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 16:45:32 2026 +0800"
      },
      "message": "[SPARK-62563][CONNECT][PYTHON] Delegate standard CrossValidator operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute standard `pyspark.ml.tuning.CrossValidator` and `CrossValidatorModel` through the existing Rust bindings for fit, transform, and persistence. Both import paths now expose the same classes.\n\nThe default fold splitter uses the Rust core. The fit loop calls `self._kFold` and `self._copyValues` so Python subclasses can customize fold assignment and the fitted model. PySpark still supplies the Python worker tasks for each parameter map and the metric aggregation. The model keeps `bestModel`, `avgMetrics`, `stdMetrics`, and `subModels` as ordinary Python instance attributes.\n\n### Why are the changes needed?\n\nStandard PySpark previously ran a separate cross-validation loop in Python. Sharing the native implementation lets the upstream tuning tests exercise the same fold and persistence code used by this client\u0027s native binding. [SPARK-62563](https://issues.apache.org/jira/browse/SPARK-62563)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe compatibility imports for these two classes now report `pyspark.ml.tuning` as their module. The standard public members and signatures match PySpark 4.3.0. Existing saved estimators and models remain readable.\n\n### How was this patch tested?\n\n- Ran the official Spark 4.3.0 tuning and pipeline suites against the Rust-backed Python package and against official PySpark over Rust transport. Each mode passed 13 tests. Upstream skips four Pipeline garbage-collection tests.\n- Tested reversed custom folds with two parallel parameter maps. Compared each metric against its collected submodels, checked the winning parameter, and compared predictions after saving and loading.\n- Exchanged estimators and fitted models with official PySpark in both directions, using a pipeline as the tuned estimator and persisting submodels. Compared UIDs, grids, metrics, and predictions. The Rust-backed process ran with optional Python transport and ML dependencies blocked.\n- Passed 2,433 local offline ML and type-stub tests (68 skipped) and 24 live tests. Also passed 864 Rust library tests, nine live Rust meta-algorithm tests, integration-test compilation with and without WASM UDFs, Clippy, formatting, and generated-file and vendor checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1024 from zhengruifeng/feature/standard-cross-validator-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "6493f7b0f8343ee62bd4011636fffdb70e9c00f9",
      "tree": "810079661dd5471924fe3d32774b06d821d861a4",
      "parents": [
        "9aabd9e217e25f562edd21bf48e8ae161711be00"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 14:50:55 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 14:50:55 2026 +0800"
      },
      "message": "[SPARK-62562][CONNECT][PYTHON] Delegate standard Pipeline and PipelineModel operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute `pyspark.ml.Pipeline.fit` and `PipelineModel.transform` through the existing PyO3 stage loops. The binding calls each stage\u0027s Python `fit` or `transform`, including overrides on user-defined stages. Saving and loading use the existing native pipeline reader and writer.\n\nKeep `stages` as a normal Python instance attribute on the fitted model. The binding reads it at transform time, so replacing or deleting the list and overriding it in a subclass work as in PySpark. Both public import paths now resolve to the same classes. The Spark 4.3.0 definitions retained for signatures, Params and persistence helpers are covered by the vendor drift check.\n\n### Why are the changes needed?\n\nThe standard import previously ran a second implementation of the pipeline stage loop in Python. Sharing the binding lets the upstream PySpark pipeline tests exercise native orchestration, including pipelines that mix Python and Rust-backed stages. [SPARK-62562](https://issues.apache.org/jira/browse/SPARK-62562)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe compatibility imports now alias the standard classes and report `pyspark.ml.pipeline` as their module. The standard constructors, public method signatures, stage ordering, copy semantics and saved format match PySpark 4.3.0.\n\n### How was this patch tested?\n\n- Ran the Spark 4.3.0 Pipeline and tuning parity suites against the Rust-backed Python package and against official PySpark over Rust transport. Each mode passed 13 tests. Upstream disables four Pipeline GC tests.\n- Exchanged saved nested pipelines and fitted models in both directions with official PySpark, comparing stage classes, UIDs and transformed rows. The Rust-backed process ran with the optional Python transport and ML dependencies blocked.\n- Ran the local offline ML and type-stub suites and live tests for ML persistence, pipelines, validators and Python subclasses. Compared both Pipeline classes\u0027 public members and signatures against official PySpark.\n- Ran the Rust library tests, live Rust meta-algorithm tests, integration-test builds with and without WASM UDFs, Clippy, formatting, and generated-file and vendor checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1023 from zhengruifeng/feature/standard-pipeline-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "9aabd9e217e25f562edd21bf48e8ae161711be00",
      "tree": "9544a69d0a879b8a5632590b2c184bda8117b706",
      "parents": [
        "6e566d0cdd411e17db17a683519ade22478db00b"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 13:04:53 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 13:04:53 2026 +0800"
      },
      "message": "[SPARK-62559][CONNECT][PYTHON] Delegate standard Word2Vec operations to Rust\n\n### What changes were proposed in this pull request?\n\nExpose the existing Rust-backed `Word2Vec` and `Word2VecModel` through `pyspark.ml.feature`. The standard classes use the native bindings for fit, transform, persistence, and the model requests behind `getVectors`, `findSynonyms`, and `findSynonymsArray`. Update the compatibility type aliases and exercise both import paths. [SPARK-62559](https://issues.apache.org/jira/browse/SPARK-62559)\n\n### Why are the changes needed?\n\nWord2Vec was the last standard feature estimator still using Python ML request construction. Routing it through the Rust client lets the official PySpark feature suite exercise the implementation used by Rust applications. Spark still trains the model and computes embeddings and neighbors on the server.\n\n### Does this PR introduce _any_ user-facing change?\n\nPython setters update the native stage immediately, and a parameter map supplied to fit or transform applies to that call. The public signatures, return types, and Spark ML persistence format are preserved.\n\n### How was this patch tested?\n\n- Ran the new live test with Python ML request builders disabled. It checks vocabulary pruning, sentence averages, empty and out-of-vocabulary inputs, and cosine similarity for word and vector queries after reloading the model.\n- Ran the official Spark 4.3.0 feature and pipeline suites against the Rust-backed package and with official PySpark over Rust transport. Each mode passed 57 tests and skipped four pipeline tests.\n- Exchanged saved estimators, fitted models, pipelines, and fitted pipelines between the two clients. Verified UIDs, parameters, vocabulary vectors, synonyms, and transformed rows in both directions.\n- Compared public class members, signatures, and parameters with official PySpark. The standard feature inventory now matches all 20 estimators, 19 fitted model classes, and 18 other transformers.\n- Ran 335 live ML tests and 2,368 offline tests (68 skipped), including type-stub checks. The Rust library and feature tests, integration-test builds with and without WASM UDFs, Clippy, formatting, and generated-file checks also passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1022 from zhengruifeng/feature/standard-word2vec-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "6e566d0cdd411e17db17a683519ade22478db00b",
      "tree": "2587ab8abd6da0a4ab5cd7c4da7d2ced4f129ccd",
      "parents": [
        "4cddacf0ddab00555b0bfd76682cf2fe35f2f288"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 12:17:17 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 12:17:17 2026 +0800"
      },
      "message": "[SPARK-62556][CONNECT][PYTHON] Delegate standard SQLTransformer operations to Rust\n\n### What changes were proposed in this pull request?\n\nExpose the Rust-backed `SQLTransformer` through `pyspark.ml.feature`. Transforming a DataFrame and saving or loading the stage now use the native ML bindings. Update the type alias and compatibility docs. The docstring golden samples `PipelineModel` because the `SQLTransformer` stub now imports the public class. [SPARK-62556](https://issues.apache.org/jira/browse/SPARK-62556)\n\n### Why are the changes needed?\n\nThe standard Python class built a transformer relation through the Python ML helpers. Using the existing Rust stage also exercises the Rust implementation when running the upstream SQLTransformer tests.\n\n### Does this PR introduce _any_ user-facing change?\n\nSetting the SQL statement updates the native stage immediately. A statement passed to `transform` overrides the stored statement for that call. Public signatures, `__THIS__` resolution, and the Spark ML persistence format are preserved.\n\n### How was this patch tested?\n\n- Ran 236 live tests across the standard ML and feature API suites, plus 1,084 offline ML and type-stub tests. The new test disables Python ML request builders and runs an aggregate and a per-call filter against a reloaded transformer, including a quoted column name and null values.\n- Ran the official Spark 4.3.0 feature and pipeline suites against the Rust-backed Python package and with official PySpark over Rust transport. Each mode passed 57 tests and skipped four pipeline tests.\n- Exchanged saved transformers, pipelines, and fitted pipelines in both directions with official PySpark. Verified stage types, UIDs, statements, and transformed rows. Compared the public API to official PySpark.\n- Ran the Rust library and feature tests, integration-test compilation with and without WASM UDFs, Clippy, formatting, and generated-file checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1021 from zhengruifeng/feature/standard-sql-transformer-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "4cddacf0ddab00555b0bfd76682cf2fe35f2f288",
      "tree": "39bbd8243e331087b881d216be45ff4f99ee3f54",
      "parents": [
        "2464c1f9935defaec6a5aec090c21b36f7094099"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 11:14:11 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 11:14:11 2026 +0800"
      },
      "message": "[SPARK-62557][CONNECT][PYTHON] Delegate standard RFormula operations to Rust\n\n### What changes were proposed in this pull request?\n\nExpose the existing Rust-backed `RFormula` and `RFormulaModel` through `pyspark.ml.feature`. Fitting, transformation, saving, loading, and retrieving the fitted model’s resolved formula now use the native ML bindings. Update the generated type aliases and the compatibility documentation. [SPARK-62557](https://issues.apache.org/jira/browse/SPARK-62557)\n\n### Why are the changes needed?\n\nStandard Python imports still constructed formula requests through the Python ML helpers. Delegating to Rust lets the upstream PySpark tests exercise the same implementation as the Rust client.\n\n### Does this PR introduce _any_ user-facing change?\n\nThe Python setters synchronize parameters with the native stage immediately. A parameter map passed to `fit` applies only to that fit. Public signatures, formula and model descriptions, and the Spark ML persistence format are preserved.\n\n### How was this patch tested?\n\n- Ran 236 live ML tests and 1,085 offline ML and type-stub tests. The new live test disables Python ML request builders and checks categorical encoding, a numeric interaction, forced label indexing, unseen-category handling, feature metadata, and the resolved formula after reloading.\n- Ran the official Spark 4.3.0 feature and pipeline suites against the Rust-backed Python package and with official PySpark over Rust transport. Each mode passed 57 tests and skipped four pipeline tests.\n- Loaded each client’s saved stages, fitted models, pipelines, and fitted pipelines in the other client and compared their UIDs, parameters, descriptions and results. Compared the public API to official PySpark.\n- Ran the Rust library and feature tests, integration-test compilation with and without WASM UDFs, Clippy, formatting, and generated-file checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1020 from zhengruifeng/feature/standard-rformula-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "2464c1f9935defaec6a5aec090c21b36f7094099",
      "tree": "f92ccdbe7cceb85cdae39345db74cfee23dd3ab9",
      "parents": [
        "5b681c33ec3c352522a5077e6f536bd60d8b6d48"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 10:48:49 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 10:48:49 2026 +0800"
      },
      "message": "[SPARK-62555][CONNECT][PYTHON] Delegate standard Imputer and PCA operations to Rust\n\n### What changes were proposed in this pull request?\n\nPublish the existing Rust-backed `Imputer`, `ImputerModel`, `PCA`, and `PCAModel` under `pyspark.ml.feature`. Their fits, transforms, persistence, and fitted model properties now go through the Rust ML bindings. Update the type aliases and compatibility documentation. [SPARK-62555](https://issues.apache.org/jira/browse/SPARK-62555)\n\n### Why are the changes needed?\n\nThe standard Python imports still constructed their own ML requests. Using the existing bindings lets the upstream PySpark feature tests exercise the same implementation that Rust applications use.\n\n### Does this PR introduce _any_ user-facing change?\n\nSetting a Python parameter updates the native stage immediately. Parameters supplied to an individual fit or transform apply to that call. Public signatures, the types returned by `surrogateDF`, `pc`, and `explainedVariance`, and the Spark ML persistence format are preserved.\n\n### How was this patch tested?\n\n- Ran 235 live standard ML and feature API tests against Spark Connect 4.3.0. The new tests disable the Python ML request builders and verify median imputation for nulls and NaNs, learned surrogate values, PCA projections of sparse inputs, and explained variance.\n- Ran the official feature and pipeline suites in both modes, against the Rust-backed Python package and through Rust transport with official PySpark. Each run passed 57 tests and skipped four pipeline tests.\n- Loaded estimators, fitted models, pipelines, and fitted pipelines saved by each client in the other client. Verified stage types, UIDs, learned values, and transformed rows.\n- Compared public members, signatures, and properties for all four classes against official PySpark 4.3.0. Ran 1,083 offline ML and type-stub tests, 864 Rust library tests, the Rust feature tests, integration-test compilation with and without WASM UDFs, Clippy, formatting, and generated-file checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1019 from zhengruifeng/feature/standard-imputer-pca-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "5b681c33ec3c352522a5077e6f536bd60d8b6d48",
      "tree": "ba059423d774e01f4b091288223864bff2b9d43e",
      "parents": [
        "342f97175edf5a6e8323d7cdf997e0e8f633c7ac"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 09:28:15 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 09:28:15 2026 +0800"
      },
      "message": "[SPARK-62553][CONNECT][PYTHON] Delegate standard target encoding, vector indexing and feature hashing to Rust\n\n### What changes were proposed in this pull request?\n\nExpose `TargetEncoder`, `TargetEncoderModel`, `VectorIndexer`, `VectorIndexerModel`, and `FeatureHasher` through the existing Rust ML bindings under `pyspark.ml.feature`. The standard imports now delegate fitting, transformation, persistence, and the fitted vector indexer\u0027s `categoryMaps` and `numFeatures` to those bindings. Update the compatibility docs and generated type aliases. [SPARK-62553](https://issues.apache.org/jira/browse/SPARK-62553)\n\n### Why are the changes needed?\n\nThese standard Python classes still used upstream Python helpers to build ML requests. Sharing the existing Rust implementations lets the upstream feature tests exercise the same operations used by the Rust client.\n\n### Does this PR introduce _any_ user-facing change?\n\nSetting a Python parameter immediately updates the native stage. Parameters supplied to an individual `fit` or `transform` apply to that call. Public signatures and the Spark ML persistence format remain compatible with official PySpark.\n\n### How was this patch tested?\n\n- Ran 120 standard ML live tests and 97 feature API tests against a local Spark Connect 4.3.0 server. With Python ML request builders disabled, the new tests cover smoothing, unseen and null categories, learned index maps, sparse vectors, and collisions between numeric, boolean, and string features.\n- Ran the official feature and pipeline suites with the Rust-backed package and with official PySpark over Rust transport. Each run passed 57 tests and skipped four pipeline tests.\n- Exchanged the individual stages, fitted models, a `Pipeline`, and a `PipelineModel` in both directions with official PySpark. The stage types, UIDs, explicit parameters, learned indices, schema metadata, and output values matched. Also compared single-column continuous target encoding with smoothing.\n- Compared public members, signatures, and properties of all five classes with the official `pyspark-client` distribution. Ran the offline ML and type-stub suites, the Rust library and feature tests, the integration-test builds with and without `wasm-udf`, and the formatting, Clippy, and vendor checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1018 from zhengruifeng/feature/standard-categorical-features-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "342f97175edf5a6e8323d7cdf997e0e8f633c7ac",
      "tree": "b1f1ff066b8c0a6c353199a09630632255a3d2ea",
      "parents": [
        "4e70e11ed2ef73398c7c4193452d1becf7fcda55"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 08:47:00 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 08:47:00 2026 +0800"
      },
      "message": "[SPARK-62524][CONNECT][PYTHON] Delegate standard locality-sensitive hashing stages to Rust\n\n### What changes were proposed in this pull request?\n\nExpose `BucketedRandomProjectionLSH`, `MinHashLSH`, and their fitted models through the existing Rust bindings in `pyspark.ml.feature`. The two models build their `approxNearestNeighbors` and `approxSimilarityJoin` relations in Rust. Update the compatibility documentation and generated type stubs. [SPARK-62524](https://issues.apache.org/jira/browse/SPARK-62524)\n\nA loaded LSH model can outlive the Python module that published it. Its native finalizer previously imported that module during interpreter shutdown to update the Python reference count, which could raise an unraisable `ModuleNotFoundError`. The finalizer now captures the callback when the class is published and passes it to the Rust binding. Rust continues to manage the server-side model and its pending queries.\n\n### Why are the changes needed?\n\nThe standard imports still built LSH requests through upstream Python helpers. Using the Rust implementation lets the Python and Rust clients share those operations and lets upstream PySpark feature tests exercise the native bindings.\n\n### Does this PR introduce _any_ user-facing change?\n\nPublic signatures and persistence formats stay the same. Python parameter updates take effect on the native stage immediately. A fit or transform parameter override applies only to that call.\n\n### How was this patch tested?\n\n- Ran the official PySpark 4.3.0 feature and pipeline suites against the drop-in and transport configurations. Each passed 57 tests and skipped four pipeline tests.\n- Tested seeded hashes, prehashed input, sparse query keys, and default and custom distance columns. With Python ML request builders disabled, the two models returned the expected Euclidean and Jaccard distances. The lazy queries remained usable after model finalization.\n- Exchanged each estimator, fitted model, `Pipeline`, and `PipelineModel` in both directions with official PySpark. Compared UIDs, parameters, hashes, neighbor and join results, and schemas. Checked class signatures, parameter defaults, and subclass seeds against the reference.\n- Reproduced the shutdown error before the fix and reran the same case afterward. All 282 live standard ML, feature API, model-lifetime, and subclass tests passed. Also passed 368 standard offline tests, 42 PyO3 unit tests, 864 Rust library tests, 12 Rust feature tests, the type-stub checks, integration builds, formatting, Clippy, and vendor and license checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1017 from zhengruifeng/feature/standard-lsh-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "4e70e11ed2ef73398c7c4193452d1becf7fcda55",
      "tree": "945134025db14bffc350c909407ee3e28ad56195",
      "parents": [
        "142c627d522febb6750029542cb417fc55524223"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 00:39:45 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Wed Dec 02 00:39:45 2026 +0800"
      },
      "message": "[SPARK-62516][CONNECT][PYTHON] Delegate standard feature selectors to Rust\n\n### What changes were proposed in this pull request?\n\nPublish `ChiSqSelector`, `UnivariateFeatureSelector`, `VarianceThresholdSelector`, and their three fitted models through the existing Rust bindings in `pyspark.ml.feature`. The standard imports now use Rust for fit, transform, reading `selectedFeatures`, and persistence. Update the compatibility docs and generated type stubs. [SPARK-62516](https://issues.apache.org/jira/browse/SPARK-62516)\n\n### Why are the changes needed?\n\nThe Rust API already implements all three selectors. Using it from the standard Python imports lets the Rust and Python clients share the request logic and lets upstream PySpark feature tests exercise those bindings.\n\n### Does this PR introduce _any_ user-facing change?\n\nThe selectors keep their PySpark signatures and Spark persistence format. Setters update native parameter state immediately. A parameter map passed to `fit` or `transform` applies only to that call.\n\n### How was this patch tested?\n\n- Ran the official PySpark 4.3.0 feature and pipeline tests in both the drop-in and transport configurations. Each passed 57 tests and skipped four pipeline tests.\n- Ran the standard ML and feature API integration suites against a local Spark Connect server. The new cases disable Python ML request builders while fitting and projecting unlabeled dense and sparse vectors. They check the indices and attribute names, fit and transform overrides, persistence, and a custom fitted model that selects zero features.\n- Saved and loaded each selector, its fitted model, a `Pipeline`, and a `PipelineModel` in both directions between official PySpark and the Rust-backed package. The UIDs, explicit parameters, learned indices, output metadata, and vector types and values matched.\n- Compared the six public classes\u0027 signatures and properties with official PySpark. Ran the standard and broader ML offline suites, type checks, stub generator checks, and vendor drift checks.\n- Ran the Rust library and feature tests, compiled the integration suites with and without `wasm-udf`, and checked formatting, Clippy, and licenses.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1016 from zhengruifeng/feature/standard-feature-selectors-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "142c627d522febb6750029542cb417fc55524223",
      "tree": "6515605a722bef99613e792d8bd74cc1912cb251",
      "parents": [
        "0c7fefa78e967b326e1c5594da4e6933d7ec2bd9"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 21:59:38 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 21:59:38 2026 +0800"
      },
      "message": "[SPARK-62513][CONNECT][PYTHON] Delegate standard vector math feature transformers to Rust\n\n### What changes were proposed in this pull request?\n\nExpose the existing Rust-backed `DCT`, `ElementwiseProduct`, `Interaction`, and `PolynomialExpansion` through `pyspark.ml.feature`. The four transformers reuse the standard feature bindings for parameter updates, transformation, and persistence. Update the compatibility documentation and generated type stubs. [SPARK-62513](https://issues.apache.org/jira/browse/SPARK-62513)\n\n### Why are the changes needed?\n\nThese four standard Python imports still used upstream Python helpers to build ML requests. Routing them through the PyO3 bindings lets the Rust and Python clients share the transformer implementation and lets upstream PySpark feature tests exercise it.\n\n### Does this PR introduce _any_ user-facing change?\n\nThe public imports, signatures, and Spark persistence format stay the same. Setting a parameter updates the Rust-backed stage immediately. Passing a parameter map to `transform` applies the override to that call only.\n\n### How was this patch tested?\n\n- Ran the official PySpark 4.3.0 feature and pipeline suites against a live Spark Connect server in both the drop-in and transport configurations. Each run passed 57 tests and skipped four pipeline tests.\n- Ran the standard ML and feature API integration suites (111 and 97 tests). The new cases disable Python ML request construction and cover inverse DCT, sparse scaling vectors, interaction attribute names, polynomial feature order, and per-call overrides.\n- Exchanged each transformer, a `Pipeline`, and a `PipelineModel` between official PySpark and the Rust-backed package in both directions. Checked UIDs, explicit parameters, schemas and metadata, and dense and sparse results with two- and three-dimensional input vectors.\n- Compared the four public classes\u0027 signatures against official PySpark. Ran 358 standard ML offline tests, the broader ML offline suites, and the stub and generator checks.\n- Ran 864 Rust library tests and 12 feature tests, compiled all integration tests with and without `wasm-udf`, and checked formatting, Clippy, vendored sources, and licenses.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1015 from zhengruifeng/feature/standard-vector-math-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "0c7fefa78e967b326e1c5594da4e6933d7ec2bd9",
      "tree": "d3b18137b629568103f56e6df790eef5d18aa246",
      "parents": [
        "f69fad3a9991b6116a8f8f631c07564405c06993"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 21:41:10 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 21:41:10 2026 +0800"
      },
      "message": "[SPARK-62510][CONNECT][PYTHON] Delegate standard numeric discretization stages to Rust\n\n### What changes were proposed in this pull request?\n\nRoute standard `pyspark.ml.feature.Binarizer`, `Bucketizer`, and `QuantileDiscretizer` through their existing Rust implementations. Python setters update native parameters immediately.\n\n`QuantileDiscretizer.fit` now uses the typed Rust fit and reads the learned splits. The default Python model is a fresh `Bucketizer` with its own UID, the estimator\u0027s input/output columns, and its invalid-value policy. The binding calls the Python getters, honors a subclass\u0027s `_create_model`, and returns the result of `_copyValues`. A custom factory receives the fitted server reference.\n\n### Why are the changes needed?\n\nStandard Python imports previously built the requests for these stages in Python. Sharing the Rust operations lets upstream PySpark feature and pipeline tests cover the same discretization code used by Rust clients. [SPARK-62510](https://issues.apache.org/jira/browse/SPARK-62510)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe compatibility and standard imports now expose the same classes. Public members and signatures match official PySpark 4.3.0. A fitted discretizer can be saved and loaded as a `Bucketizer` independently of its estimator.\n\n### How was this patch tested?\n\n- Ran the official PySpark 4.3.0 feature and pipeline parity suites on a live Spark Connect server. They passed 57 tests and skipped four pipeline cases.\n- Saved and loaded estimators, single- and multi-column learned bucketizers, and fitted and unfitted pipelines in both directions between official PySpark and the Rust-backed client. Compared saved UIDs, explicit parameters, learned splits, output schemas, and bucket assignments at boundaries, at infinity and for NaN. The Rust-backed process ran with Python protobuf, gRPC and Py4J imports blocked.\n- Added live tests with Python ML request builders disabled for per-fit parameter overrides, `keep` and `skip`, fresh bucketizer UIDs, overridden getters, a custom model factory and a custom `_copyValues` result. Checked a subclass that calls its superclass\u0027s factory with both clients. Verified official PySpark\u0027s missing-column error when a mock accepts an unconfigured estimator.\n- Passed all 109 live standard ML tests, 97 live feature API cases, 354 standard offline ML tests and 2,058 broader offline tests (68 skipped, four existing model-finalizer warnings). Passed 864 Rust library tests, 12 Rust feature tests and the mypy/Pyright checks. Compiled all Rust integration tests with and without `wasm-udf`, and checked formatting, Clippy, Ruff, stubs and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1014 from zhengruifeng/feature/standard-discretization-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "f69fad3a9991b6116a8f8f631c07564405c06993",
      "tree": "539ef3edffeac7f73a7c94a72b11429ec1b4aa2a",
      "parents": [
        "50c4f57ba54fb6002b1c8027e4087ba1812ec5da"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 21:11:58 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 21:11:58 2026 +0800"
      },
      "message": "[SPARK-62509][CONNECT][PYTHON] Delegate standard feature scaling stages to Rust\n\n### What changes were proposed in this pull request?\n\nRoute the standard `pyspark.ml.feature` imports for `MaxAbsScaler`, `MinMaxScaler`, `RobustScaler`, `StandardScaler`, their four fitted models, and `Normalizer` through the existing Rust bindings. Python setters update native parameters immediately. Rust handles fitting, transformation, persistence, and reads of learned vectors such as `mean`, `std`, `median` and `range`.\n\n### Why are the changes needed?\n\nThese standard classes previously built ML requests in Python. Sharing the existing Rust operations lets the official PySpark feature and pipeline tests exercise the same scaling implementation that Rust applications use. [SPARK-62509](https://issues.apache.org/jira/browse/SPARK-62509)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe standard and compatibility imports now expose the same classes. Public members and signatures match official PySpark 4.3.0. The compatibility type stubs re-export the standard types, so both imports work interchangeably in annotated code.\n\n### How was this patch tested?\n\n- Ran the official PySpark 4.3.0 feature and pipeline parity suites against the Rust-backed package on a live Connect server. They passed 57 tests and skipped four pipeline cases.\n- Saved and loaded all nine stages and models, as well as fitted and unfitted pipelines, in both directions between official PySpark and the Rust-backed client. Checked UIDs, explicit parameters, learned vectors, output schemas, and dense and sparse vector representations. Also exchanged a saved `Normalizer` with an infinite p-norm. Python protobuf, gRPC and Py4J imports were blocked in the Rust-backed process.\n- Added five live tests with Python ML request builders disabled. They cover learned scaler statistics, constant and all-zero features, per-call overrides, L1 and infinity norms, and sparse zero vectors. Added offline checks for eager parameters, copying, pickling, import order, and mypy/Pyright aliases.\n- Passed all 107 live standard ML tests, all 97 live feature API cases, 351 standard offline ML tests, and 2,058 broader offline tests (68 skipped, four existing model-finalizer warnings). Passed 864 Rust library tests and the Rust feature suites. Compiled all Rust integration tests with and without `wasm-udf`. Checked formatting, Clippy, Ruff, generated stubs and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1013 from zhengruifeng/feature/standard-feature-scaling-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "50c4f57ba54fb6002b1c8027e4087ba1812ec5da",
      "tree": "c831ec9e8c025946fdeb8ee1953aa634ce687cd1",
      "parents": [
        "a826583494d8c4736d60c3859a8b2e966228755d"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 20:59:28 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 20:59:28 2026 +0800"
      },
      "message": "[SPARK-62508][CONNECT][PYTHON] Delegate standard categorical encoding feature stages to Rust\n\n### What changes were proposed in this pull request?\n\nDelegate standard `pyspark.ml.feature.StringIndexer`, `StringIndexerModel`, `OneHotEncoder`, `OneHotEncoderModel`, and `IndexToString` to the existing Rust ML bindings. Rust handles fitting, transformation, persistence and reads of `labels`, `labelsArray` and `categorySizes`. Python parameter setters update the native stage immediately.\n\nThe Rust and Python paths for `StringIndexerModel.from_labels` and `from_arrays_of_labels` now share the requests that create the server-side model. They use the model\u0027s UID and explicitly typed string arrays, which preserve empty label lists for individual input columns.\n\n### Why are the changes needed?\n\nThese standard imports previously built ML requests in Python. Routing them through Rust lets upstream PySpark tests cover the same categorical encoding operations that Rust applications use. [SPARK-62508](https://issues.apache.org/jira/browse/SPARK-62508)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe standard and compatibility imports now expose the same classes. Public members and signatures match the official PySpark 4.3.0 client. The indexer\u0027s output retains the label metadata used by downstream one-hot encoding and index-to-string decoding.\n\n### How was this patch tested?\n\n- Ran the official PySpark 4.3.0 feature and pipeline parity suites against a live Spark Connect server using the Rust-backed package. They passed 57 tests and skipped four pipeline cases.\n- Saved and loaded estimators, fitted models, models constructed from explicit labels, and fitted and unfitted pipelines in both directions between official PySpark and the Rust-backed client. Compared UIDs, parameters, label order, category sizes, sparse vectors, decoded rows, and full output schemas. The Rust-backed process ran with Python protobuf, gRPC and Py4J imports blocked.\n- Added live tests with Python ML request builders disabled for multi-column fitting, unseen and null categories, `dropLast` overrides, metadata-based decoding, empty label arrays and invalid label types. Verified both factories return a standard model when invoked on a Python subclass. Exercised eager parameter updates, copying, pickling and type aliases.\n- Passed 102 live standard ML tests, all 97 live feature API cases, 342 standard ML offline tests, and 2,058 broader offline tests (68 skipped and four existing model-finalizer warnings). Passed 864 Rust library tests, the Rust feature suites, and mypy and Pyright checks. Compiled all Rust integration tests with and without `wasm-udf` and checked formatting, Clippy, Ruff, generated stubs and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1012 from zhengruifeng/feature/standard-categorical-encoding-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "a826583494d8c4736d60c3859a8b2e966228755d",
      "tree": "a4af991ec54e0a4cce608e4f96ddafa61fb8d02f",
      "parents": [
        "2e2e7abf3866a0fe5464e55cec54dc4541d84f9e"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 20:46:22 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 20:46:22 2026 +0800"
      },
      "message": "[SPARK-62507][CONNECT][PYTHON] Delegate standard term frequency and IDF feature stages to Rust\n\n### What changes were proposed in this pull request?\n\nRoute standard `pyspark.ml.feature.HashingTF`, `CountVectorizer`, `CountVectorizerModel`, `IDF` and `IDFModel` through the existing Rust ML bindings. Python setters update the native parameters immediately. Rust handles fitting, transformation, model properties, and persistence. Both client APIs now use the same Spark Connect helper to create a model from a supplied vocabulary.\n\nThe native feature estimator fit path honors Python subclasses\u0027 `_create_model` and `_copyValues` hooks. A fit or estimator write uses the JVM operator class selected by the Python wrapper. The shared writer also handles PySpark’s special case for `PowerIterationClustering`, which Spark persists through `PowerIterationClusteringWrapper`.\n\n### Why are the changes needed?\n\nThese standard Python imports previously constructed ML requests in Python. Reusing the Rust implementation lets the upstream PySpark feature and pipeline suites exercise the same operations used by Rust applications. [SPARK-62507](https://issues.apache.org/jira/browse/SPARK-62507)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe standard and compatibility imports now expose the same classes. Public members and signatures match the official PySpark 4.3.0 client. `HashingTF.indexOf` still requires classic PySpark. This also restores `PowerIterationClustering.save`, which failed on master because Spark rejects its unwrapped JVM class name.\n\n### How was this patch tested?\n\n- Ran the official PySpark 4.3.0 feature and pipeline parity suites against a live Connect server using this package (57 passed, four skipped).\n- Saved and loaded individual stages, fitted models, an explicit vocabulary, a pipeline, and a fitted pipeline in both directions between official PySpark and this package. Checked UIDs, explicit parameters, vocabulary ordering, document frequencies, IDF weights, sparse vector indices and values, and full output schemas. Python protobuf, gRPC and Py4J imports were blocked in the Rust-backed process.\n- Added live tests with the Python ML request builders disabled, including a subclass that selects a different JVM estimator and supplies its own model factory. Checked eager parameter updates, copying, pickling, both import paths, and mypy/Pyright compatibility.\n- Ran all 100 live standard ML tests, all 97 live feature API cases, 337 standard ML offline tests and 2,058 broader offline tests (68 skipped, four existing model-finalizer warnings). All 864 Rust library tests and 12 Rust feature tests passed. Compiled all Rust integration tests with and without `wasm-udf` and checked Clippy, formatting, Ruff, generated stubs and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1011 from zhengruifeng/feature/standard-term-weighting-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "2e2e7abf3866a0fe5464e55cec54dc4541d84f9e",
      "tree": "11b81cf452c4ea8684acf248d518cbf4887f49fa",
      "parents": [
        "d901360b95770f06c3d58cf7161d288e0511bc89"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 19:34:00 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 19:34:00 2026 +0800"
      },
      "message": "[SPARK-62506][CONNECT][PYTHON] Delegate standard text feature transformers to Rust\n\n### What changes were proposed in this pull request?\n\nDelegate `Tokenizer`, `RegexTokenizer`, `StopWordsRemover` and `NGram` from standard `pyspark.ml.feature` to the existing Rust transformers for `transform`, `save` and `load`. Python setters update the native parameters immediately. The standard and compatibility imports expose the same classes.\n\n`StopWordsRemover` keeps PySpark’s constructor. It fetches the server’s default locale and English stop words through Rust, once each, in the same order as PySpark. Copies and pickle round trips reuse those defaults. Language-specific lookups share the Rust implementation, including when Python supplies a typed Spark SQL literal.\n\n### Why are the changes needed?\n\nStandard Python imports previously built the transform relations and stop-word helper requests in Python. Routing these operations through Rust lets the upstream Python feature tests exercise the implementation used by the Rust client. [SPARK-62506](https://issues.apache.org/jira/browse/SPARK-62506)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe standard Python API, saved-stage format and dependencies are preserved. Rust adds `StopWordsRemover::default_locale` for the server locale and `load_default_stop_words_literal` for callers that already have a Spark SQL literal.\n\n### How was this patch tested?\n\n- Ran the official Spark 4.3.0 standard feature and pipeline suites against the drop-in client. All 51 feature tests passed. Six pipeline tests passed and four were skipped.\n- Disabled Python ML request construction while tokenizing, applying a regex, removing stop words from two columns, constructing n-grams, and saving and loading each stage. Checked the exact constructor and load requests with a mock server.\n- Exchanged all four saved stages, a `Pipeline` and a `PipelineModel` in both directions with official PySpark. Verified class, UID, explicit parameters, server defaults, array contents and full schemas, including Unicode and empty input. The Rust-backed process ran with Python protobuf, gRPC, Py4J and optional ML packages blocked.\n- Compared public Python members and signatures with official PySpark. Ran 332 standard offline ML tests and 2,058 broader offline ML tests. The broader suites had 68 skips and four existing model-finalizer warnings. Also ran 864 Rust library tests, 10 feature integration tests and the mypy and Pyright probes. Compiled all Rust integration tests with and without `wasm-udf` and checked formatting, Clippy, Ruff, generated stubs and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1010 from zhengruifeng/feature/standard-text-transformers-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "d901360b95770f06c3d58cf7161d288e0511bc89",
      "tree": "b98ae59c9f563b9664e7e5e72007924754492075",
      "parents": [
        "a9af42a9b5174cbc2cb4ee24e4f84218ad33c346"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 19:13:59 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 19:13:59 2026 +0800"
      },
      "message": "[SPARK-62505][CONNECT][PYTHON] Delegate standard vector feature transformers to Rust\n\n### What changes were proposed in this pull request?\n\nDelegate `VectorSizeHint`, `VectorAssembler` and `VectorSlicer` from `pyspark.ml.feature` to the existing Rust transformers for `transform`, `save` and `load`. These stages are often used together to set vector dimensions, assemble a feature vector and select attributes by name or index.\n\nPython setters update the Rust parameters immediately. The standard `Transformer.transform(dataset, params)` method still applies per-call overrides to a copy and invokes its `_transform` hook. The native transform and writer honor the JVM class selected by a Python subclass.\n\nThe standard module loads the original PySpark 4.3.0 definitions from `_upstream/feature.py`. The existing compatibility imports and type stubs re-export the same three classes.\n\n### Why are the changes needed?\n\nStandard Python imports previously constructed the transform relation in Python, even though the Rust client already implemented these stages. The standard Python and Rust APIs now exercise the same transformation code. [SPARK-62505](https://issues.apache.org/jira/browse/SPARK-62505)\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. The public Python signatures, Spark vector metadata, persistence format and Python dependencies are preserved.\n\n### How was this patch tested?\n\n- Ran the official PySpark 4.3.0 standard feature and pipeline suites against the drop-in client. All 51 feature tests passed. Six pipeline tests passed and four were skipped.\n- Exchanged saved stages, a `Pipeline` and a `PipelineModel` in both directions with official PySpark. The loaded stages preserved class, UID and explicit parameters. Dense and sparse inputs produced identical rows and full schemas, including vector sizes and attribute names. The Rust-backed process ran with Python protobuf, gRPC, Py4J and optional ML packages blocked.\n- Disabled Python ML request builders during transform, save and load. Checked per-call overrides, filtering a vector of the wrong size, and writing the JVM class selected by a Python subclass. Compared public members and signatures for all three classes with official PySpark.\n- Ran 329 standard offline ML tests and 2,057 broader offline ML tests. The broader suites had 68 skips and four existing model-finalizer warnings. Ran 864 Rust library tests and 10 feature integration tests, including live Spark. Compiled all Rust integrations with and without `wasm-udf`. Checked Clippy, Ruff, generated stubs, mypy, Pyright and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1009 from zhengruifeng/feature/standard-vector-transformers-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "a9af42a9b5174cbc2cb4ee24e4f84218ad33c346",
      "tree": "1e35ed670f3abbd5a0bf2d36b2f50fb49d572c9a",
      "parents": [
        "9949dbdcf936ec2670a24d9e2589b3a91f8c34a2"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 18:51:02 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 18:51:02 2026 +0800"
      },
      "message": "[SPARK-62504][CONNECT][PYTHON] Delegate standard ML evaluator operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute all six concrete classes in `pyspark.ml.evaluation` through the existing Rust evaluators for evaluation and persistence. This covers `BinaryClassificationEvaluator`, `MulticlassClassificationEvaluator`, `MultilabelClassificationEvaluator`, `RegressionEvaluator`, `ClusteringEvaluator` and `RankingEvaluator`.\n\nPython setters update native parameters immediately. The public `Evaluator.evaluate(dataset, params)` still applies a nonempty parameter map to a copy and calls its `_evaluate` method. Python subclasses can override that method or select a different JVM evaluator. Both evaluation and saving use the selected JVM class.\n\nThe standard module loads the original PySpark 4.3.0 definitions from `_upstream/evaluation.py`. The existing compatibility imports refer to the same classes.\n\n### Why are the changes needed?\n\nStandard PySpark callers previously built evaluation requests in Python. The standard Python and Rust APIs can now share the same request implementation, and the upstream Python evaluator tests exercise the Rust implementation. [SPARK-62504](https://issues.apache.org/jira/browse/SPARK-62504)\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. The public Python signatures, metric direction, saved-evaluator format and dependencies are preserved.\n\n### How was this patch tested?\n\n- Ran the official PySpark evaluation, tuning, pipeline and ALS suites against the drop-in client. 26 tests passed and four pipeline tests were skipped. All nine upstream evaluator tests passed.\n- Ran 128 live Python tests, including all 83 metric configurations, input validation, per-call parameter overrides and saved validators. Six tests disabled Python request construction while evaluating, saving and loading.\n- Exchanged all six saved evaluators in both directions with official PySpark 4.3.0. The loaded evaluators preserved UIDs, explicit parameters, metric directions and scores. The Rust-backed process ran with Python protobuf, gRPC, Py4J and optional ML dependencies blocked.\n- Compared public members and signatures with official PySpark. Verified custom JVM-class dispatch and writes against both clients. The offline ML suites had 2,452 passes, 68 skips and four warnings from existing model finalizers.\n- Ran 864 Rust library tests and 10 integration tests covering evaluator fixtures, request replay and live Spark. Compiled all integration tests with and without `wasm-udf`. Checked formatting, Clippy, Ruff, generated stubs, type annotations and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1008 from zhengruifeng/feature/standard-evaluators-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "9949dbdcf936ec2670a24d9e2589b3a91f8c34a2",
      "tree": "a2fdf41ac00061dba9f1326d7e130b0956f5e8a0",
      "parents": [
        "3dcd9f61aee58bfcd9c2c9a661005568b28a0392"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 17:59:50 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 17:59:50 2026 +0800"
      },
      "message": "[SPARK-62503][CONNECT][PYTHON] Delegate standard ALS operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake `from pyspark.ml.recommendation import ALS, ALSModel` use the Rust client for fit, transform, rank, factor tables, recommendations and persistence. Python setters update the native parameters immediately, including both block counts set by `setNumBlocks`. The compatibility import aliases the same classes.\n\nThe Rust APIs and PyO3 now share the relation builder for factor tables and all four recommendation methods. A lazy result retains both the fitted model and any models used by its subset DataFrame. Python subclasses can still override `_fit`, `_create_model` and `_copyValues`. ALS and FPGrowth share the code that hands a fitted model reference to a custom factory.\n\nThe standard module loads its PySpark definitions from the byte-identical Spark 4.3.0 file at `python/pyspark/ml/_upstream/recommendation.py`.\n\n### Why are the changes needed?\n\nALS was already available in Rust, but standard Python callers still used upstream Python code to build the requests. Routing the standard import through Rust lets the upstream PySpark ALS tests exercise the implementation used by Rust callers. [SPARK-62503](https://issues.apache.org/jira/browse/SPARK-62503)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe public Python signatures, import paths and saved-model format are preserved. This change adds no Python dependency.\n\n### How was this patch tested?\n\n- Ran the official PySpark ALS, FPM, model offloading, cache, pipeline and tuning suites against the drop-in client. 31 tests passed and four were skipped.\n- Ran 31 local live Python tests, including recommendation arguments, model lifetime, custom factories and persistence. The routing test disabled the Python request builders while fitting, saving, loading and collecting predictions, factor tables and recommendations.\n- Exchanged saved estimators and models in both directions with official PySpark 4.3.0 for explicit and implicit feedback. For each loaded model, predictions, both factor tables and all four recommendation outputs matched in rows and exact schemas. The Rust-backed process ran with Python protobuf, gRPC, Py4J and optional ML packages blocked.\n- Compared public members and signatures for `ALS` (75) and `ALSModel` (40). Ran the standard and broader offline ML suites, Rust library and live ALS tests, and type checks. Compiled all Rust integration tests with and without `wasm-udf`. Checked formatting, Clippy, Ruff, generated stubs and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1007 from zhengruifeng/feature/standard-als-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "3dcd9f61aee58bfcd9c2c9a661005568b28a0392",
      "tree": "66ed0aa120ae2d7305ab3b0130376ea54e7324b8",
      "parents": [
        "0ce4c624db10e5207c675d6ff5c4267eaa5eb6b0"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 17:45:21 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 17:45:21 2026 +0800"
      },
      "message": "[SPARK-62502][CONNECT][PYTHON] Delegate standard PrefixSpan operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute standard `pyspark.ml.fpm.PrefixSpan.findFrequentSequentialPatterns` through the Rust helper used by `ml::PrefixSpan`. Both clients build the same lazy Connect relation and retain its input DataFrame. The compatibility import exposes the same Python class.\n\nThe four Python parameters update native state eagerly. When building the relation, the binding calls the Python getters in PySpark order, so subclasses can override them. Copies and pickle round trips preserve custom defaults.\n\n### Why are the changes needed?\n\nStandard PySpark, the native Python binding and the Rust API previously built the PrefixSpan request separately. Sharing the Rust implementation means the upstream PySpark test exercises the relation that Rust callers use. This completes the standard frequent-pattern API migration following #1005. [SPARK-62502](https://issues.apache.org/jira/browse/SPARK-62502)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe existing Python import paths and signatures are preserved. `findFrequentSequentialPatterns` continues to return a lazy DataFrame with `sequence` and `freq` columns. This change adds no Python dependency.\n\n### How was this patch tested?\n\n- Ran all 14 tests from the upstream PySpark FPM, model offloading and cache modules against the drop-in client.\n- Ran 22 live Python checks, including a subclass overriding a getter with the Python helper disabled. A separate comparison against official PySpark 4.3.0 matched rows and exact schemas for integer sequences with a null row, string sequences, and an input with no qualifying patterns.\n- Compared the constructor and all 27 public PrefixSpan members with official PySpark. Ran the 308 standard ML offline tests, the broader ML offline suite (2,032 passed, 68 skipped), and the type-stub checks.\n- All 864 Rust library tests and eight focused mining, golden and replay tests passed. Compiled all integration tests with and without `wasm-udf`. Checked Rust formatting, Clippy, Ruff, generated stubs and vendored-source drift.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1006 from zhengruifeng/feature/standard-prefixspan-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "0ce4c624db10e5207c675d6ff5c4267eaa5eb6b0",
      "tree": "e8f34cb8e3db7064a55e412f8e1f990f308fa525",
      "parents": [
        "71a48531d4ba99bda1e6a46f7dd59ca11f16347a"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 17:02:40 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 17:02:40 2026 +0800"
      },
      "message": "[SPARK-62501][CONNECT][PYTHON] Delegate standard FPGrowth operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute `pyspark.ml.fpm.FPGrowth` and `FPGrowthModel` through the existing Rust ML implementation. Python setters update native parameters eagerly. Rust fits the model, builds the transform and the lazy `freqItemsets` and `associationRules` DataFrames, and handles estimator and model persistence.\n\nA Python subclass can still override `_fit`, `_create_model`, or `_copyValues`. When a subclass supplies its own model factory, Rust fits the estimator and passes the resulting `RemoteModelRef` to that factory. The custom model then owns the reference and uses the usual PySpark cleanup.\n\nThe public module loads Spark 4.3.0’s definitions from the byte-identical `_upstream/fpm.py` and publishes the two Rust-backed classes. The compatibility import aliases the same classes. Standard `PrefixSpan` continues to use its upstream implementation.\n\n### Why are the changes needed?\n\nThe standard Python API and the Rust client each constructed FPGrowth requests. Sharing the Rust implementation lets upstream PySpark FPGrowth tests exercise the same fit, transform and persistence operations that Rust callers use. [SPARK-62501](https://issues.apache.org/jira/browse/SPARK-62501)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe import paths, public method signatures, and saved model format are preserved. This change adds no Python dependency.\n\n### How was this patch tested?\n\n- Ran the new live FPGrowth tests against Spark Connect with Python ML request builders disabled and unraisable warnings treated as errors. Both passed, including collecting lazy results after dropping the model. Another 21 live frequent-pattern checks passed.\n- Ran five upstream PySpark test modules against the drop-in client, covering FPM, model offloading, cache handling, pipelines and tuning. 27 tests passed and four were skipped.\n- Saved and loaded models in both directions between official PySpark 4.3.0 and the Rust-backed client. Itemsets, association rules, predictions and loaded schemas matched on string baskets, integer baskets, and a case with no qualifying rules.\n- 1,348 offline Python checks passed (68 skipped). All 864 Rust library tests and eight focused Rust frequent-pattern, golden, and replay tests passed. All Rust integration tests compiled with and without `wasm-udf`. Checked formatting, Clippy, public signatures, generated stubs and vendored source.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1005 from zhengruifeng/feature/standard-fpgrowth-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "71a48531d4ba99bda1e6a46f7dd59ca11f16347a",
      "tree": "87ec4110fb29b995b962691ff6ff9154948286e4",
      "parents": [
        "9d1a2cc49defbab9e0b4eaa8e589d8cd26ef6aa7"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 15:59:20 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 15:59:20 2026 +0800"
      },
      "message": "[SPARK-62499][CONNECT][PYTHON] Delegate standard PowerIterationClustering operations to Rust\n\n### What changes were proposed in this pull request?\n\nDelegate `pyspark.ml.clustering.PowerIterationClustering.assignClusters` and persistence to the Rust ML implementation. The compatibility import re-exports the standard class. Parameter setters update the native object immediately.\n\nThe Python binding calls the public parameter getters when building the assignment, including subclass overrides and custom defaults. It then passes the input and the resolved arguments to the same Rust relation builder as `PowerIterationClustering::assign_clusters`. The returned DataFrame captures the graph and parameter values at the time of the call.\n\n### Why are the changes needed?\n\nPower iteration clustering is the last of the five standard clustering algorithms whose Python entry point still built its own Spark Connect requests. Sharing the assignment relation lets the official PySpark clustering tests exercise the protocol used by Rust callers. [SPARK-62499](https://issues.apache.org/jira/browse/SPARK-62499)\n\n### Does this PR introduce _any_ user-facing change?\n\nExisting callers continue to use `assignClusters(dataset)`, which returns a DataFrame with `id` and `cluster`. The standard and compatibility imports now refer to the same class. Its constructor and all 37 public members match PySpark 4.3.0. This change adds no Python dependencies.\n\n### How was this patch tested?\n\n- Ran the standard API against a local Spark 4.3.0 Connect server with the Python ML request builders disabled. The same six-vertex graph produces one group without weights and two groups with weights. The test checks vertex membership, the result schema, lazy parameter capture and persistence.\n- Saved weighted and unweighted algorithms with official PySpark, loaded them with the Rust-backed client and compared their UIDs and assignments. Repeated in the other direction with the same results.\n- Compared the lazy helper requests with official protobuf fixtures. Covered custom defaults, a subclass overriding `getK`, an omitted or explicit null weight column, and deferred overflow errors.\n- Ran the upstream clustering, model offloading, cache, pipeline and tuning suites in drop-in mode (31 passed, 4 skipped), the offline ML and type-stub suites, the Rust library and clustering tests, full integration-test compilation with and without `wasm-udf`, Clippy, Ruff, formatting, and the generated-file and vendor checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1004 from zhengruifeng/feature/standard-power-iteration-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "9d1a2cc49defbab9e0b4eaa8e589d8cd26ef6aa7",
      "tree": "f09a90f666bcb846c645e19ca997a3d05f958242",
      "parents": [
        "d39af83cb23307113c598237672214adfac97577"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 14:45:41 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 14:45:41 2026 +0800"
      },
      "message": "[SPARK-62498][CONNECT][PYTHON] Delegate standard LDA operations to Rust\n\n### What changes were proposed in this pull request?\n\nDelegate standard `pyspark.ml.clustering.LDA` to the existing Rust ML API. Python setters synchronize parameters eagerly. The standard and compatibility imports expose the same estimator and model classes.\n\nThe online optimizer returns a `LocalLDAModel`. EM returns a `DistributedLDAModel`, whose `toLocal()` caches the converted model. Both concrete classes now accept a PySpark `RemoteModelRef` through the shared model constructor. When Rust receives a model from the server, it binds the reference after the Python constructor finishes. This preserves the reference across copies and lazy transforms.\n\n### Why are the changes needed?\n\nThe standard estimator previously built fit, transform and persistence requests in Python. Delegating these operations lets standard PySpark LDA tests exercise the implementation used by Rust callers and follows the other migrated clustering estimators. [SPARK-62498](https://issues.apache.org/jira/browse/SPARK-62498)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe public imports, class hierarchy and method signatures match PySpark 4.3.0. Existing LDA estimators and models saved by either client can be loaded by the other. The change adds no Python dependencies.\n\n### How was this patch tested?\n\n- Ran both optimizers on a local Spark 4.3.0 Connect server with the Python ML request builders disabled. Covered topic matrices, topic distributions (including an empty document), likelihood, cached `toLocal()`, save/load and a lazy transform collected after releasing the model.\n- Saved estimators and models with official PySpark and loaded them with the Rust-backed client, then repeated in the other direction. Compared topic matrices and per-document probabilities. Reloading an EM model introduces small variations in Spark\u0027s inference step, also observed between official PySpark loads.\n- Ran seven upstream ML suites in drop-in mode (clustering, classification, regression, model offloading, model cache, pipelines and tuning). 58 tests passed and 4 were skipped. All public signatures and member kinds matched PySpark 4.3.0 for the estimator and three model classes.\n- Ran the offline ML tests (1,577 passed), type-stub tests (21 passed), 864 Rust library tests, and the live and golden Rust clustering suites. Compiled all Rust integration tests with and without `wasm-udf` and ran formatting, Clippy, Ruff, generated-stub and vendor-drift checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1003 from zhengruifeng/feature/standard-lda-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "d39af83cb23307113c598237672214adfac97577",
      "tree": "a650fde71f00d9329aa83d728b261992afa0567e",
      "parents": [
        "67e89cc50667186e0e7ac037e2d899cc8bc9ce2d"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 13:29:57 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 13:29:57 2026 +0800"
      },
      "message": "[SPARK-62496][CONNECT][PYTHON] Delegate standard GaussianMixture operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute `pyspark.ml.clustering.GaussianMixture` fit, transform, prediction, component and training summary access, and persistence through the existing Rust implementation. Python setters update the native estimator and model parameters immediately. The standard and compatibility imports share `GaussianMixture`, `GaussianMixtureModel`, and `GaussianMixtureSummary`.\n\n### Why are the changes needed?\n\nThe standard estimator previously built ML requests in Python. Delegating these operations lets Spark’s existing PySpark GaussianMixture tests exercise the implementation Rust callers use, following KMeans and BisectingKMeans. [SPARK-62496](https://issues.apache.org/jira/browse/SPARK-62496)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe compatibility classes now report `pyspark.ml.clustering` as their public module. Standard method signatures, probability vectors, Gaussian component types and persistence formats match PySpark 4.3.0.\n\n### How was this patch tested?\n\n- Ran Spark 4.3.0’s official clustering, cache, pipeline and tuning tests against a live Spark Connect server and the built drop-in package. All eight clustering tests passed. Across the four suites, 25 tests passed and four pipeline tests were skipped upstream.\n- Added a weighted two-component fit with the Python ML request builders disabled. It checks the fitted mixture weights, means and covariances, point and DataFrame probability predictions, training log likelihood, and a lazy transform collected after the loaded model is released.\n- Verified that official PySpark and the Rust-backed client can read one another’s saved estimator and model, with optional Python transport and ML dependencies blocked in the Rust-backed process. Compared all public member kinds and signatures of the estimator, model and summary against official PySpark.\n- Ran the standard ML and native binding offline tests, mypy and Pyright stub tests, Rust library and live GaussianMixture tests, release integration-test compilation with and without `wasm-udf`, Clippy, rustfmt, Ruff and the generated-file checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1002 from zhengruifeng/feature/standard-gaussian-mixture-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "67e89cc50667186e0e7ac037e2d899cc8bc9ce2d",
      "tree": "68cd0a640a510717e4a101452c31fbbf8e0f9a33",
      "parents": [
        "f2174a12b815755f8edb408a6beb7c27a4cbbe68"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 13:15:35 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 13:15:35 2026 +0800"
      },
      "message": "[SPARK-62493][CONNECT][PYTHON] Delegate standard BisectingKMeans operations to Rust\n\n### What changes were proposed in this pull request?\n\nDelegate `pyspark.ml.clustering.BisectingKMeans` fit, transform, prediction, cost, training summaries and persistence to the existing Rust implementation. Python keeps its setters, parameter maps, copying and subclass hooks. Changes to estimator and model parameters reach Rust as soon as the setter returns.\n\nThe standard and compatibility imports share the estimator, model and summary classes. The native `computeCost` method uses the original PySpark warning location so filters for `pyspark.ml.clustering` and the warn-once behavior still work.\n\n### Why are the changes needed?\n\nThe standard Python estimator previously built its own ML requests. This lets Spark’s existing BisectingKMeans tests exercise the same implementation as Rust callers and continues the clustering migration started with KMeans. [SPARK-62493](https://issues.apache.org/jira/browse/SPARK-62493) · [KMeans PR #1000](https://github.com/apache/spark-connect-rust/pull/1000)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe three compatibility classes now report `pyspark.ml.clustering` as their public module. The standard signatures and persistence format match PySpark 4.3.0.\n\n### How was this patch tested?\n\n- Ran Spark 4.3.0’s official clustering, cache, pipeline and tuning suites against the Rust-backed package and a live Spark Connect server. All eight clustering tests passed. The four suites had 25 passes and four upstream pipeline skips.\n- Extended the weighted clustering test with Python ML request builders disabled. With four clusters requested and a minimum divisible cluster size of 75%, it verifies two fitted centers, summary sizes of `[2, 2, 0, 0]`, weighted training cost of `15.0` and `computeCost` of `12.5`. It also exercises prediction, save/load and a lazy transform after releasing the loaded model.\n- Verified both clients could load one another’s saved estimator and model and produce identical predictions, with optional Python transport dependencies blocked in the Rust-backed process. Compared public member signatures and kinds for the estimator, model and summary against official PySpark.\n- Ran the standard ML and native binding offline suites, mypy and Pyright stub tests, Rust library and live BisectingKMeans tests, release integration-test compilation with and without `wasm-udf`, Clippy, rustfmt, Ruff, and the vendoring, generated stub and binary license checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1001 from zhengruifeng/feature/standard-bisecting-kmeans-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "f2174a12b815755f8edb408a6beb7c27a4cbbe68",
      "tree": "a283d276d72fc30525e8ba140d3f81064950d696",
      "parents": [
        "66454a89c1fae85b8625eddb0c6e188e08f7af46"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 11:46:03 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 11:46:03 2026 +0800"
      },
      "message": "[SPARK-62488][CONNECT][PYTHON] Delegate standard KMeans operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute `pyspark.ml.clustering.KMeans.fit`, model transformation and prediction, training summary access, and estimator/model persistence through the existing Rust KMeans implementation. Python keeps its parameter setters, copying, and subclass hooks. Setter calls update the native parameter state immediately.\n\nThe standard and compatibility imports share `KMeans`, `KMeansModel`, and `KMeansSummary`. The clustering adapter loads the Spark 4.3.0 source from `ml/_upstream/clustering.py`. The vendor check verifies that copy against the Spark tag.\n\n### Why are the changes needed?\n\nThe standard Python estimator previously assembled ML requests in Python, so running Spark’s upstream KMeans tests against this package did not exercise the Rust KMeans implementation. This extends the standard ML delegation used for classification and regression to the first clustering estimator. [SPARK-62488](https://issues.apache.org/jira/browse/SPARK-62488)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe three compatibility imports now identify their public module as `pyspark.ml.clustering`. Their standard Python signatures, fitted results and persisted formats match PySpark 4.3.0.\n\n### How was this patch tested?\n\n- Ran the official Spark 4.3.0 clustering, cache, pipeline and tuning parity modules against the built drop-in and a live Spark Connect server. All 8 clustering tests passed. Across the four modules, 25 tests passed and 4 pipeline tests were skipped upstream.\n- Added a weighted two-cluster test with the Python ML request builders disabled. It checks centers, point predictions, summary cost and sizes, persistence, and a lazy transform collected after releasing the loaded model. Also verified that official PySpark and the Rust-backed client can read each other’s estimators and models, with optional Python transport dependencies blocked in the Rust-backed process.\n- Compared the public signatures and member kinds of all three classes against official PySpark 4.3.0. Ran the standard ML offline suite (237 passed), ML API and binding offline suites (1,277 passed, 68 skipped), and type-stub suite with mypy and Pyright (21 passed).\n- Ran the Rust KMeans live and golden tests, Rust library tests (864 passed), release integration-test compilation with and without `wasm-udf`, Clippy, rustfmt, Ruff, and the vendor, generated stub and binary license checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #1000 from zhengruifeng/feature/standard-kmeans-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "66454a89c1fae85b8625eddb0c6e188e08f7af46",
      "tree": "02f93767be92fb7c1315bb9f6e2209b002a7db9e",
      "parents": [
        "4460f48ace2ba43c0d6b439188b4dcb2110522df"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 10:14:03 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 10:14:03 2026 +0800"
      },
      "message": "[SPARK-62486][CONNECT][PYTHON] Delegate standard OneVsRest operations to Rust\n\n### What changes were proposed in this pull request?\n\nPublish `OneVsRest` and `OneVsRestModel` through `pyspark.ml.classification` and re-export the same classes from the compatibility module. Python parameter mutations update their native state immediately.\n\nA fit with a built-in binary classifier uses the Rust implementation to fit one model per class. A Python subclass, a custom classifier, or a classifier with an instance-level fit override uses PySpark\u0027s fit loop so its hook sees each binary dataset. The public model composes the transforms of its current `models` list. Replacing or reordering those models changes its predictions.\n\n### Why are the changes needed?\n\nAfter #998, OneVsRest was the remaining classifier whose standard and compatibility imports selected different implementations. The standard path can share native class fits and persistence while continuing to support Python-defined classifiers.\n\n### Does this PR introduce _any_ user-facing change?\n\nThe import paths now resolve to the same estimator and model. The original public signatures are preserved. On the model, `models` remains a mutable instance attribute and is also visible as a descriptor when inspecting the class.\n\nThe native fit respects default-only classifier and column parameters and carries the base classifier\u0027s defaults into the binary submodels. The estimator and model readers restore saved defaults using the standard PySpark metadata rules.\n\n### How was this patch tested?\n\n- Added live tests that disable the Python fit loop for a built-in classifier, verify the binary labels passed to subclass and instance-level fit hooks, and reverse the loaded submodels to check that predictions follow their order.\n- Ran the official Spark 4.3.0 classification, regression, model-cache and OneVsRest parity suites against this package. All 34 tests passed. All 33 selected OneVsRest interaction and error cases also passed on official PySpark.\n- Loaded estimators and models saved by each client with the other and compared predictions, raw scores, UIDs and parameter defaults. The Rust-backed process ran with Python protobuf, gRPC, Py4J and SciPy imports blocked. Python pickles of estimators and unbound model wrappers also round-tripped across clients.\n- The offline ML and typing suites passed 2,614 tests (68 skipped), including mypy and Pyright. All 131 live integration tests passed. The generated-stub and vendored-source checks and Ruff passed.\n- All 864 Rust library tests passed. Compiled all integration tests with default features and with `wasm-udf`. Rust formatting, workspace Clippy and the binary license check passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #999 from zhengruifeng/feature/standard-one-vs-rest-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "4460f48ace2ba43c0d6b439188b4dcb2110522df",
      "tree": "cb7ef72355a76afab81fe1466373062463b26a48",
      "parents": [
        "a55d4e13550a91040b2e6a3613cfb794f669b594"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 09:01:05 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 09:01:05 2026 +0800"
      },
      "message": "[SPARK-62485][CONNECT][PYTHON] Delegate standard FMClassifier operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute the standard `pyspark.ml.classification.FMClassifier` and its model and two summary classes through the existing Rust ML implementation. The compatibility module re-exports those same classes. Parameter setters update Rust immediately, including the generic `set` for `weightCol`. The estimator preserves custom defaults on copy and participates in Python garbage collection.\n\n### Why are the changes needed?\n\nThe standard import previously built its fit, transform and model requests in Python. Both Python import paths and the Rust client can now exercise the same FM implementation. This continues the work in #997 for the factorization machine classifier.\n\n### Does this PR introduce _any_ user-facing change?\n\nThe standard and compatibility imports now resolve to the same classes. The public names, signatures and member kinds of all four match PySpark 4.3.0. A fitted model returns a training summary, and a loaded model can evaluate a new DataFrame.\n\n### How was this patch tested?\n\n- Ran 128 live tests against Spark Connect 4.3.0. The new test disables Python ML request builders, checks the factor interaction against the raw score and probability, verifies weighted accuracy, and collects a lazy transform after releasing the loaded model. Nine existing FM cases also passed on official PySpark.\n- Ran the official classification, regression, model-cache and OneVsRest parity suites against the drop-in package. All 34 tests passed.\n- Saved and loaded estimators and models in both directions between official PySpark and the Rust-backed client. Compared the learned factors, coefficients, raw predictions and objective history. The Rust-backed process ran with Python protobuf, gRPC, Py4J and SciPy imports blocked.\n- The offline ML and typing suites passed 2,613 tests (68 skipped), including mypy and Pyright. Verified the generated stubs and docstrings against the Spark 4.3.0 sources and official client package.\n- All 864 Rust library tests passed. Compiled all integration tests with default features and with `wasm-udf`. Rust formatting, workspace Clippy, Ruff, the vendored-source check and the binary license check passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #998 from zhengruifeng/feature/standard-fm-classifier-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "a55d4e13550a91040b2e6a3613cfb794f669b594",
      "tree": "ab8acbb6d64cb9f029249a915b64aa60820226bf",
      "parents": [
        "d68f8425551f32fc384cfb577bc2e43101950be1"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 08:36:55 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Tue Dec 01 08:36:55 2026 +0800"
      },
      "message": "[SPARK-62452][CONNECT][PYTHON] Delegate standard MultilayerPerceptronClassifier operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute the standard `pyspark.ml.classification.MultilayerPerceptronClassifier`, its fitted model and its two summary classes through the existing Rust ML API. Fit, transform, point prediction, weight access, evaluation and persistence now share that implementation. Python setters update native parameters immediately, including network layers and initial weights. The PyO3 estimator preserves custom defaults across copies and exposes them to Python garbage collection.\n\n### Why are the changes needed?\n\nThe standard Python classifier built requests for operations the Rust client already implements. Sharing the implementation lets upstream PySpark tests exercise the Rust perceptron through the standard import. [SPARK-62452](https://issues.apache.org/jira/browse/SPARK-62452)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe standard and compatibility imports now resolve to the same four classes. Their public names, signatures and member kinds match PySpark 4.3.0. As in PySpark, a fitted model exposes a training summary, and a loaded model can evaluate new data.\n\n### How was this patch tested?\n\nA live test disables Python ML request construction and starts from a sparse initial weight vector. It compares the learned weights, raw scores, probabilities and objective history after two gradient descent iterations with official PySpark. It checks the distinct training and evaluation summary classes, restores the estimator and model, and collects a lazy transform after releasing the loaded model.\n\n- All 154 live ML integration tests passed against Spark 4.3.0. The eight perceptron-related cases in the remaining-classifiers suite also passed on official PySpark.\n- All 34 official classification, regression, cache and OneVsRest tests passed against the drop-in package.\n- Both clients loaded and used estimators and models saved by the other. The Rust-backed process fit and evaluated the model with Python protobuf, gRPC, Py4J and SciPy imports blocked.\n- The offline ML and typing suites passed 2,289 tests (68 skipped), including mypy and Pyright. Introspection found zero public API differences across all four classes. Generated stubs, the pinned vendored sources, Ruff and the generator tests passed.\n- All 864 Rust library tests passed. All integration tests compiled with default features and with `wasm-udf`. Rust formatting, workspace Clippy and the binary license checks passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #997 from zhengruifeng/feature/standard-mlp-classifier-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "d68f8425551f32fc384cfb577bc2e43101950be1",
      "tree": "b6307a0e86c3f2f7252be2c6736ce913c91728f8",
      "parents": [
        "b3475b6d8cf0485ac9425997562b1520856daecf"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 21:02:24 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 21:02:24 2026 +0800"
      },
      "message": "[SPARK-62451][CONNECT][PYTHON] Delegate standard NaiveBayes operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute standard `pyspark.ml.classification.NaiveBayes` and `NaiveBayesModel` through the existing Rust ML API for fit, transform, model access, point prediction and persistence. The compatibility imports re-export the same classes. Python setters update native parameters immediately. The PyO3 estimator retains custom defaults across copies and exposes them to Python garbage collection.\n\n### Why are the changes needed?\n\nThe standard Python estimator built ML requests for operations the Rust client already implements. Sharing the implementation lets the official PySpark NaiveBayes tests exercise the Rust ML API through the standard import. [SPARK-62451](https://issues.apache.org/jira/browse/SPARK-62451)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe standard and compatibility imports now resolve to the same estimator and model classes. Their public names, signatures and member kinds match PySpark 4.3.0. All four model types use the same native implementation as their Rust counterparts.\n\n### How was this patch tested?\n\nThe new live test disables Python ML request construction. It compares the priors, means, variances, raw scores and probabilities of a weighted Gaussian model with official PySpark. It also checks a fit-time parameter override and collects predictions from a saved-and-loaded model with custom thresholds after releasing the Python model object.\n\n- All 125 live ML integration tests passed against Spark 4.3.0. The 20 dedicated NaiveBayes cases cover multinomial, Bernoulli, complement and Gaussian models and also passed with official PySpark.\n- All 34 official classification, regression, cache and OneVsRest tests passed against the drop-in package.\n- Each client loaded and used an estimator and model saved by the other. The Rust-backed process completed this round trip with Python protobuf, gRPC, Py4J and SciPy imports blocked.\n- The offline ML and typing suites passed 2,269 tests (68 skipped), including mypy and Pyright. Public API introspection found zero differences for the estimator and model. Generated stubs, the pinned vendor checks, Ruff, and the generator and exclusion tests passed.\n- All 864 Rust library tests passed. All integration tests compiled with default features and with `wasm-udf`. Rust formatting, workspace Clippy and binary license checks passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #996 from zhengruifeng/feature/standard-naive-bayes-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "b3475b6d8cf0485ac9425997562b1520856daecf",
      "tree": "abeb9765ed460d687d3f9bda02c68006da5b717e",
      "parents": [
        "3539ee597658ac035d0fcc2cd58ebb772047eee2"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 20:14:04 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 20:14:04 2026 +0800"
      },
      "message": "[SPARK-62448][CONNECT][PYTHON] Delegate standard GBTClassifier operations to Rust\n\n### What changes were proposed in this pull request?\n\nRoute standard `pyspark.ml.classification.GBTClassifier` and `GBTClassificationModel` through the existing Rust ML API for fit, transform, tree access, per-iteration loss and persistence. The compatibility imports re-export the same classes. Python setters synchronize parameters eagerly. The PyO3 estimator retains custom defaults across copies and exposes those defaults to Python garbage collection.\n\n### Why are the changes needed?\n\nThe standard Python classifier built its own ML requests for operations already implemented in Rust. Sharing the implementation lets upstream PySpark tests exercise the Rust classifier. The fitted ensemble returns standard `DecisionTreeRegressionModel` children because GBT fits regression trees to the gradients. [SPARK-62448](https://issues.apache.org/jira/browse/SPARK-62448)\n\n### Does this PR introduce _any_ user-facing change?\n\nBoth import paths now resolve to the same estimator and model classes. Their public names, signatures and member kinds match PySpark 4.3.0.\n\n### How was this patch tested?\n\nThe live test disables Python ML request construction. It checks weighted training and validation losses against official PySpark, including a fit that stops after one tree. It also covers raw margins, probabilities, threshold overrides, child trees, persistence and collecting a lazy transform after releasing the loaded model.\n\n- 110 live ML integration tests passed against Spark 4.3.0, including the seven dedicated GBTClassifier cases. Those seven cases also passed with official PySpark. All 34 official classification, regression, cache and OneVsRest tests passed against the drop-in package.\n- Verified that each client can load and use both the estimator and model saved by the other client.\n- 2,263 offline ML and typing tests passed (68 skipped), including mypy and Pyright. The Python API comparison found zero differences for the two classes. Generated stubs, vendored sources, Ruff, and the 22 generator and exclusion tests passed.\n- 864 Rust library tests passed. All integration tests compiled with default features and with `wasm-udf`. Rust formatting, workspace Clippy and binary license checks passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #995 from zhengruifeng/feature/standard-gbt-classifier-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "3539ee597658ac035d0fcc2cd58ebb772047eee2",
      "tree": "374f36bffe45e34adeb9dcc913b6e4c78c8c557e",
      "parents": [
        "7913ba4f13f6f4540d17b38bd5e0e11812a11ec0"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 19:18:24 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 19:18:24 2026 +0800"
      },
      "message": "[SPARK-62447][CONNECT][PYTHON] Delegate standard RandomForestClassifier operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake standard `pyspark.ml.classification.RandomForestClassifier` use the Rust ML API for fit, transform, evaluation, tree access and persistence. The model and all four binary and multiclass summary classes use the same bindings. Python setters synchronize parameters eagerly, and the PyO3 estimator preserves custom defaults across copies and participates in Python garbage collection.\n\n### Why are the changes needed?\n\nThe Rust client already implements these operations. Routing the standard Python classifier through that implementation lets the upstream PySpark classification tests also exercise it. This follows the decision tree migration in [#993](https://github.com/apache/spark-connect-rust/pull/993). [SPARK-62447](https://issues.apache.org/jira/browse/SPARK-62447)\n\n### Does this PR introduce _any_ user-facing change?\n\nBoth Python import paths now return the same classes. The estimator, model and four summaries match the public names, member kinds and signatures in PySpark 4.3.0. Fitted forests return standard decision tree models. Loaded forests can evaluate new data and have no stored training summary, as in PySpark.\n\n### How was this patch tested?\n\n- Compared weighted binary and multiclass fits against official PySpark 4.3.0. The live routing tests disable the Python ML request builders and check raw scores, probabilities, leaf indices, summary types, weighted accuracy and binary area under ROC. They also exercise model copying, threshold overrides, persistence, and lazy transforms after releasing the loaded model.\n- All 101 standard ML, tree and classifier integration tests passed, along with six dedicated forest tests. All 34 official classification, regression, cache and OneVsRest tests passed against the drop-in package.\n- All 2,256 executed offline ML and typing tests passed (68 skipped). The member probe now covers ML classes re-exported from the standard modules. Both mypy and Pyright passed, as did stub regeneration, the pinned vendor comparison, Ruff and the 22 generator and exclusion tests.\n- All 864 Rust library tests passed. Integration tests compiled with default features and with `wasm-udf`. Workspace Clippy, Rust formatting and native binary license checks passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #994 from zhengruifeng/feature/standard-random-forest-classifier-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "7913ba4f13f6f4540d17b38bd5e0e11812a11ec0",
      "tree": "644a950487e7b0ef7627a3378dd4b2c37501ac30",
      "parents": [
        "ee33559a718ade10f55acf87230f01ef9eda8dc9"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 18:37:31 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 18:37:31 2026 +0800"
      },
      "message": "[SPARK-62445][CONNECT][PYTHON] Delegate standard DecisionTreeClassifier operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake `pyspark.ml.classification.DecisionTreeClassifier` and `DecisionTreeClassificationModel` use the existing Rust ML operations for fit, transform, tree access, and persistence. The compatibility imports re-export the same classes. Python setters synchronize parameter changes eagerly, including class thresholds and `pruneTree`. The PyO3 estimator holds custom defaults across copies and exposes them to Python garbage collection.\n\n### Why are the changes needed?\n\nThe standard classifier built its ML requests in Python even though the Rust client already supports the tree operations. Sharing the implementation also lets upstream Python classification tests exercise the Rust ML code. Random forest classifiers return the standard model class for each child tree. [SPARK-62445](https://issues.apache.org/jira/browse/SPARK-62445)\n\n### Does this PR introduce _any_ user-facing change?\n\nThe standard and compatibility imports now resolve to the same classes. Both classes match the public API of Spark 4.3.0 in the introspection check.\n\n### How was this patch tested?\n\nThe live routing test disables the Python ML request builders. It fits a weighted three-class tree, checks the predictions, raw counts, probabilities and leaf IDs against official PySpark, and applies a threshold override during transform. It also checks estimator and model persistence and collects a lazy transform after releasing the model. A second test uses a child tree after releasing its random forest. The shared tree tests cover eager defaults, partial parameter conversion failures, copying and pickling, import order, subclass dispatch, and optional-dependency isolation.\n\nThe local run passed 2,244 offline ML and typing tests (73 skipped), 98 standard ML, tree and composition integration tests, and five dedicated classifier integration tests. All 34 official Spark 4.3.0 classification, regression, cache, and OneVsRest tests passed against the drop-in package. The public API comparison found zero differences across the two migrated classes.\n\nAll 864 Rust library tests passed. Generated stubs, pinned vendor comparisons, Ruff lint and format, and 22 generator and exclusion tests with three subtests passed.\n\nAll integration tests compiled with the default features and with `wasm-udf`. Workspace Clippy with warnings denied and native binary license checks passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #993 from zhengruifeng/feature/standard-decision-tree-classifier-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "ee33559a718ade10f55acf87230f01ef9eda8dc9",
      "tree": "016bbdcefe8ea1d71d8d1f1768a917dfd17bffe9",
      "parents": [
        "c7275c84f983fa0e345196d983009a6746ed16cf"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 18:13:03 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 18:13:03 2026 +0800"
      },
      "message": "[SPARK-62444][CONNECT][PYTHON] Delegate standard GBTRegressor operations to Rust\n\n### What changes were proposed in this pull request?\n\nAfter #991, GBTRegressor and GBTRegressionModel were the last classes published by the regression compatibility module. Publish them under `pyspark.ml.regression` using the existing PyO3 and Rust ML implementations for fit, transform, tree access, per-iteration evaluation, and persistence. Python setters update the native parameter maps eagerly. The native estimator holds Python default values across copies and participates in garbage collection.\n\nThe compatibility module now re-exports the standard regression classes. Its generated type stub uses the same aliases.\n\n### Why are the changes needed?\n\nThis lets standard PySpark applications and upstream ML parity tests exercise the Rust GBT implementation. For example, `model.evaluateEachIteration(df, \"absolute\")` now uses the same model reference and operation as a native call. [SPARK-62444](https://issues.apache.org/jira/browse/SPARK-62444)\n\n### Does this PR introduce _any_ user-facing change?\n\nStandard and compatibility imports now resolve to the same estimator and model classes. Their public signatures and numerical behavior match the Spark 4.3.0 reference in the cases tested.\n\n### How was this patch tested?\n\nOn a weighted dataset, the official PySpark client fits three trees and reports a decreasing loss for each iteration. With a validation set whose labels equal the first tree\u0027s predictions, it selects one tree. The live tests check those predictions, leaf IDs, squared and absolute loss sequences, and stopping behavior through the standard import while blocking Python ML request builders. They also exercise loaded models, pipeline tuning, cache lifetime, and dependency isolation.\n\nThe local run passed 2,237 offline ML and typing tests (73 skipped) and 114 live integration tests. The official Spark 4.3.0 regression, classification, cache, and OneVsRest suites passed all 34 tests against the drop-in package. Public API introspection found zero differences across both migrated classes.\n\nAll 864 Rust library tests passed. All Rust integration tests compiled with default features and with `wasm-udf`. Workspace Clippy with warnings denied and the native binary license check passed. The generator and exclusion suites passed 22 tests and 3 subtests. Ruff lint and format, generated-stub checks, and pinned vendor comparisons passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #992 from zhengruifeng/feature/standard-gbt-regressor-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "c7275c84f983fa0e345196d983009a6746ed16cf",
      "tree": "5770bf20b82492d45659867a63f59c7c0201300c",
      "parents": [
        "eb5f9dc5010d358c7c5529eb844f9b4fae5fe55c"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 17:22:24 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 17:22:24 2026 +0800"
      },
      "message": "[SPARK-62442][CONNECT][PYTHON] Delegate standard RandomForestRegressor operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake standard `pyspark.ml.regression.RandomForestRegressor` and `RandomForestRegressionModel` delegate to the existing Rust ML implementation, following #990. The compatibility imports in `pyspark.ml.connect.regression` become aliases of the standard classes.\n\nKeep upstream signatures, Python Params conversions, copying/pickling, subclass dispatch, and persistence APIs. Synchronize parameter mutations eagerly, retain operation-time synchronization for direct parameter-map writes, and expose native estimator defaults to Python garbage collection. Reuse the existing native ensemble and child-tree handling. No vendored upstream sources or dependencies change.\n\n### Why are the changes needed?\n\nThe standard forest classes still construct ML operations through Python helpers while the native implementation already supports them. Sharing the Rust implementation lets standard PySpark calls and upstream parity tests exercise the same ML core as the Rust API.\n\nTracks [SPARK-62442](https://issues.apache.org/jira/browse/SPARK-62442).\n\n### Does this PR introduce _any_ user-facing change?\n\nNo new public API or intended numerical behavior changes. Standard forest operations now use Rust, parameter mutations synchronize eagerly, and standard and compatibility imports refer to the same classes.\n\n### How was this patch tested?\n\n- Offline ML/API/type checks: **2,230 passed, 73 skipped**; generator/exclusion tests: **22 passed plus 3 subtests**.\n- Live standard/regression tests against Spark 4.3.0: **109 passed**. Official PySpark independently confirmed the weighted forest predictions, leaf vectors, tree metadata, and cached-tree sharing.\n- Official Spark 4.3.0 drop-in suites (`test_parity_regression`, `test_parity_classification`, `test_connect_cache`, `test_parity_ovr`): **34 passed, no skips**.\n- Public names, member kinds, and signatures: **zero differences** for both migrated classes.\n- Rust library tests: **864 passed**; all integration tests compiled with and without `wasm-udf`. Rustfmt, Ruff 0.14.8 lint/format, generated stubs, and pinned vendor drift checks passed.\n- Workspace Clippy with warnings denied and native binary license checks passed.\n\nExtend the shared tree tests to cover forest import order, copying/pickling, unfitted-model copy semantics, eager defaults, partial conversion failures, subclass dispatch, garbage collection, cache release, and pipeline tuning. Add forest-specific tests for bootstrap/feature-subsampling parameters, weighted predictions, vector leaf IDs, feature importances, shared cached trees, persistence, and lazy forest/child-tree plans after model deletion. Live routing guards reject Python ML request builders, and dependency-isolation tests exercise the standard API without optional protobuf/gRPC dependencies.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #991 from zhengruifeng/feature/standard-random-forest-regressor-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "eb5f9dc5010d358c7c5529eb844f9b4fae5fe55c",
      "tree": "bf14c93f44aca5a554d0241a10932fd370e0bffe",
      "parents": [
        "d1087e8104e66fac799fea2dfd9f9c5cb0655940"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 15:47:58 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 15:47:58 2026 +0800"
      },
      "message": "[SPARK-62440][CONNECT][PYTHON] Delegate standard DecisionTreeRegressor operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake standard `pyspark.ml.regression.DecisionTreeRegressor` and `DecisionTreeRegressionModel` delegate to the existing Rust ML implementation, following the IsotonicRegression migration in #989. Keep the `pyspark.ml.connect.regression` imports as aliases of these classes.\n\nPreserve upstream signatures, Python Params conversion, copying, pickling, and subclass dispatch. Synchronize parameter setters eagerly, retain operation-time synchronization for direct parameter-map edits, and make native estimator defaults visible to Python garbage collection. No vendored upstream sources are modified and no Python dependencies are added.\n\nNative ensemble child-model construction now reads the completed Python constructor attributes before binding the server reference. Eager synchronization can otherwise observe `_java_obj` before Python assigns it and break RandomForest/GBT fits when their child trees are materialized.\n\n### Why are the changes needed?\n\nThe standard classes currently construct ML operations through Python helpers while the native implementation already handles those operations. Sharing the Rust ML implementation lets standard PySpark calls and upstream parity tests exercise that implementation through PyO3.\n\nTracks [SPARK-62440](https://issues.apache.org/jira/browse/SPARK-62440).\n\n### Does this PR introduce _any_ user-facing change?\n\nNo new public API or intended numerical behavior changes. Standard DecisionTreeRegressor operations now use Rust, parameter mutations synchronize eagerly, and standard and compatibility imports refer to the same classes.\n\n### How was this patch tested?\n\n- Offline ML/API/type checks: **2,223 passed, 73 skipped**; tooling checks: **35 passed plus 9 subtests**.\n- Live standard/regression tests against Spark 4.3.0: **104 passed**. Weighted predictions, variance, feature importances, tree structure, and leaf IDs were also checked with official PySpark.\n- Official Spark 4.3.0 drop-in suites (`test_parity_regression`, `test_parity_classification`, `test_connect_cache`, `test_parity_ovr`): **34 passed, no skips**.\n- Public API names, member kinds, and signatures: **zero differences** for the two migrated classes.\n- Rust library tests: **864 passed**; all integration tests compiled with and without `wasm-udf`. Rustfmt, workspace Clippy with warnings denied, Ruff 0.14.8 lint/format, generated stubs, pinned vendor drift, and native license checks passed.\n\nAdded coverage for eager parameter/default synchronization, partial conversion failures, copying/pickling, import order and dependency isolation, garbage collection, weighted predictions and variance, leaf IDs and output columns, feature importances, persistence, pipelines, tuning, subclass dispatch, and ensemble child-tree lifetime. The live routing guard rejects Python ML request builders during standard fit/transform/persistence checks.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #990 from zhengruifeng/feature/standard-decision-tree-regressor-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "d1087e8104e66fac799fea2dfd9f9c5cb0655940",
      "tree": "9f4b75b82c7ceaef6c3ad7af65da361ec33ce0b4",
      "parents": [
        "2ac9f6eb4d740c431df50599d220512ba9942d6e"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 11:26:39 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 11:26:39 2026 +0800"
      },
      "message": "[SPARK-62438][CONNECT][PYTHON] Delegate standard IsotonicRegression operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake standard `pyspark.ml.regression.IsotonicRegression` and `IsotonicRegressionModel` delegate fitting, transformation, prediction, model access, and persistence to the existing Rust ML implementation, following #988.\n\n- Reuse the shared native regression adapter and synchronize parameters and defaults eagerly.\n- Preserve Python Params, signatures, copying, pickling, and subclass hooks; expose native defaults to Python garbage collection.\n- Make compatibility imports aliases of the standard classes and regenerate their type stubs.\n- Keep the shared metadata parity tests comparing migrated classes with their retained upstream bases when standard and compatibility imports become aliases.\n- Extend standard API tests for weighted increasing/decreasing fits, interpolation, scalar/vector inputs, feature-index changes, persistence, model lifetime, pipelines/tuning, and optional dependency isolation. Run existing isotonic regression cases through the standard import.\n\n### Why are the changes needed?\n\n[SPARK-62438](https://issues.apache.org/jira/browse/SPARK-62438)\n\nThe standard classes currently construct ML requests through retained upstream Python helpers. Delegating operations to Rust shares the implementation with the Rust API and lets standard and upstream Python tests exercise it.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo intended change to the standard public API or results. Standard and compatibility imports now resolve to the same classes. No new Python dependencies are required.\n\n### How was this patch tested?\n\n- 2,217 offline/type cases passed across the suite and targeted reruns; 73 skipped. All 40 subclass/parity tests passed with migrated classes included in the reference comparisons.\n- 97 live cases passed across the suite and targeted reruns against Spark 4.3.0 Connect, including native request routing, weighted increasing/decreasing fits, interpolation, scalar/vector inputs, persistence, model lifetime, pipelines/tuning, and dependency isolation.\n- 34 upstream standard ML tests passed with no skips: regression, classification, cache, and OneVsRest.\n- Public API comparison: zero differences across the two migrated classes. Weighted curve and interpolation expectations were also checked directly against official PySpark.\n- 864 Rust library tests passed; all release integration tests compile with and without `wasm-udf`. PyO3 release build, formatting, and workspace/all-target Clippy with warnings denied passed.\n- 35 tooling tests and nine subtests passed. Generated-stub, upstream vendor drift, Ruff, whitespace, and native-license asset checks passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #989 from zhengruifeng/feature/standard-isotonic-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "2ac9f6eb4d740c431df50599d220512ba9942d6e",
      "tree": "230c4a2082fa2974cf5284084746198f389eca54",
      "parents": [
        "9046860150db4f71d4e290b88d5974e55c1548f1"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 08:27:54 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Mon Nov 30 08:27:54 2026 +0800"
      },
      "message": "[SPARK-62415][CONNECT][PYTHON] Delegate standard FMRegressor operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake standard `pyspark.ml.regression.FMRegressor` and `FMRegressionModel` delegate fitting, transformation, scalar prediction, model access, and persistence to the existing Rust ML implementation, following #987.\n\n- Reuse the shared native regression adapter and synchronize parameters and defaults eagerly, including seeds.\n- Retain Python Params, signatures, copying, pickling, and subclass hooks; expose native defaults to Python garbage collection.\n- Make the repository\u0027s compatibility imports aliases of the standard classes and regenerate their type stubs.\n- Extend shared offline/type coverage and add live tests for factorization predictions, non-square factor matrices, persistence, model lifetime, pipelines/tuning, and optional dependency isolation. Run existing FM regression cases through the standard import.\n\n### Why are the changes needed?\n\n[SPARK-62415](https://issues.apache.org/jira/browse/SPARK-62415)\n\nThe standard FM classes currently construct ML requests through retained upstream Python helpers. Delegating operations to Rust shares the implementation with the Rust API and lets standard and upstream Python tests exercise that implementation.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo intended change to the standard public API or results. Standard and compatibility imports now resolve to the same classes. The estimator and model match the official public names, member kinds, and signatures. No new Python dependencies are required.\n\n### How was this patch tested?\n\n- 2,211 offline/type cases passed across the suite and targeted runs; 73 skipped.\n- 91 live tests passed against Spark 4.3.0 Connect, including native request routing, dense/sparse predictions, non-square factor matrices, weighted fitting, persistence, model lifetime, pipelines/tuning, and dependency isolation.\n- 34 upstream standard ML tests passed with no skips: regression, classification, cache, and OneVsRest.\n- Public API comparison: zero differences across the two migrated classes. Upstream vendor drift and generated-stub checks passed.\n- 864 Rust library tests passed; all release integration tests compile with and without `wasm-udf`. PyO3 release build, formatting, and workspace/all-target Clippy with warnings denied passed.\n- 35 tooling tests and nine subtests passed. Ruff, whitespace, and native-license asset checks passed.\n\nSeed coverage checks default-only and explicitly set seeds and preserves official PySpark Connect\u0027s existing no-op `clear()` behavior, verified against the official client.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #988 from zhengruifeng/feature/standard-fm-regressor-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "9046860150db4f71d4e290b88d5974e55c1548f1",
      "tree": "792ccab35d26666a163ffe4ab071d6d2cc7ac18f",
      "parents": [
        "084437d2c4c134088f084c41d983cb18a4c0babf"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Fri Nov 27 20:28:10 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Fri Nov 27 20:28:10 2026 +0800"
      },
      "message": "[SPARK-62410][CONNECT][PYTHON] Delegate standard AFTSurvivalRegression operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake standard `pyspark.ml.regression.AFTSurvivalRegression` and `AFTSurvivalRegressionModel` delegate fit, transform, model access, quantile prediction, and persistence to the existing Rust ML implementation, following #986.\n\n- Reuse the shared native regression adapter and synchronize parameters and defaults eagerly.\n- Retain Python Params, signatures, copying, pickling, and subclass hooks; expose native defaults to Python garbage collection.\n- Make the repository\u0027s compatibility imports aliases of the standard classes and regenerate their type stubs.\n- Extend shared offline coverage and add live tests for censored survival data, quantiles, persistence, model lifetime, pipelines/tuning, and optional dependency isolation. Run existing AFT regression cases through the standard import.\n\n### Why are the changes needed?\n\n[SPARK-62410](https://issues.apache.org/jira/browse/SPARK-62410)\n\nSharing ML operation logic with the Rust API lets standard and upstream Python tests exercise that implementation. The current standard AFT classes still construct requests through retained upstream Python helpers.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo intended change to the standard API or results. Standard and compatibility imports now resolve to the same classes. The estimator and model match the official public names, member kinds, and signatures. No new Python dependencies are required.\n\n### How was this patch tested?\n\n- 2,191 offline and typing tests passed; 73 skipped.\n- 86 live cases passed across the suite and targeted runs against Spark 4.3.0 Connect, including native request routing, censored data, quantiles, persistence, model lifetime, pipelines/tuning, and dependency isolation.\n- 34 upstream standard ML tests passed with no skips: regression, classification, cache, and OneVsRest.\n- Public API comparison: zero differences across the two migrated classes. Upstream vendor drift and generated-stub checks passed.\n- 864 Rust library tests passed; all release integration tests compile with and without `wasm-udf`. PyO3 release build, formatting, and workspace/all-target Clippy with warnings denied passed.\n- 35 tooling tests and nine subtests passed. Ruff, whitespace, and native-license asset checks passed.\n\nThe quantile tests also verify existing PySpark Connect semantics against the official client: `transform` and save/load apply current client parameters, while direct `predictQuantiles` calls read the fitted remote model.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #987 from zhengruifeng/feature/standard-aft-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "084437d2c4c134088f084c41d983cb18a4c0babf",
      "tree": "78a06df2788eeda2d2a9053c3fd7ad50844e62b7",
      "parents": [
        "97af6bd8dba79abe3623d6c8f5c6bf464cec79b2"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Fri Nov 27 20:07:49 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Fri Nov 27 20:07:49 2026 +0800"
      },
      "message": "[SPARK-62407][CONNECT][PYTHON] Delegate standard GeneralizedLinearRegression operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake standard `pyspark.ml.regression.GeneralizedLinearRegression` and its model and two summary classes delegate their operations to the existing Rust ML implementation, following the LinearRegression migration in #985.\n\n- Reuse the shared regression adapter for fit, transform, evaluation, model and summary access, and persistence.\n- Synchronize parameters and defaults eagerly, including copied and unpickled estimators, and make the native defaults visible to Python garbage collection.\n- Make the repository\u0027s `pyspark.ml.connect.regression` compatibility imports aliases of the standard classes, with matching generated stubs.\n- Extend shared migration tests and run the existing GLR family, link, weight, and offset cases through the standard import.\n\n### Why are the changes needed?\n\n[SPARK-62407](https://issues.apache.org/jira/browse/SPARK-62407)\n\nThe standard Python class currently builds ML requests through retained upstream helpers. Delegating operations to Rust shares the implementation with the Rust API and lets upstream Python ML tests exercise that implementation. Python continues to provide Params, setters, signatures, copying, and subclass hooks.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo intended change to the standard public API or results. The standard and compatibility imports now resolve to the same classes. The four migrated classes match the official public member names, member kinds, and signatures. This adds no required Python dependencies.\n\n### How was this patch tested?\n\n- 2,099 offline and typing tests passed; 73 skipped, including five requiring unavailable pyright. Mypy used the CI-pinned version.\n- 118 live tests passed against a local Spark 4.3.0 Connect server, covering shared migration behavior, GLR families and links, weights and offsets, summaries, persistence, and lifecycle cleanup.\n- 34 upstream standard ML drop-in tests passed with no skips: regression, classification, cache, and OneVsRest.\n- Public API comparison: zero differences across the four migrated GLR classes. Vendored upstream code is unchanged and its drift check passed.\n- 23 tooling tests and three subtests passed; generated-stub check, Ruff, and whitespace checks passed.\n- 864 Rust library tests passed; all release integration tests compile with and without `wasm-udf`. The PyO3 release build, `cargo fmt --all --check`, and workspace/all-target Clippy with warnings denied passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #986 from zhengruifeng/feature/standard-glr-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "97af6bd8dba79abe3623d6c8f5c6bf464cec79b2",
      "tree": "ad542f885540515e0ad7fdcad29af5fc13c0c93a",
      "parents": [
        "a17534cecc80a7ef40f87c1b1ff7f47c814e273b"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Fri Nov 27 16:46:24 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Fri Nov 27 16:46:24 2026 +0800"
      },
      "message": "[SPARK-62403][CONNECT][PYTHON] Delegate standard LinearRegression operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake `from pyspark.ml.regression import LinearRegression` use the existing Rust ML implementation for fit, transform, model access, summaries, evaluation, and persistence, following the LogisticRegression and LinearSVC migrations.\n\n- Publish `LinearRegression`, `LinearRegressionModel`, `LinearRegressionSummary`, and `LinearRegressionTrainingSummary` under their standard module, with eager parameter synchronization for the estimator and model. Keep the compatibility imports as aliases of those same classes.\n- Retain Python-overridden defaults in the native estimator, including copying and garbage-collection support. Setters update local native state without server calls.\n- Preserve the unchanged upstream regression definitions under `ml/_upstream`, with the pinned vendor drift check. Keep Python signatures, documentation, subclass hooks, and parameter behavior.\n- Extend the shared migration tests to regression, wire them into CI, and regenerate the affected type aliases and documentation fingerprint. Keep the test of remaining Python-built model plans on an unmigrated regressor.\n\n### Why are the changes needed?\n\nStandard LinearRegression currently constructs requests through Python helpers even though the Rust client already implements these operations. Delegating them shares the operation implementation between Rust and Python callers and lets upstream standard regression tests exercise the native ML path.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. Standard LinearRegression operations execute through Rust, and ordinary parameter changes immediately update native state. The public signatures are unchanged. No Python runtime dependencies are added.\n\n### How was this patch tested?\n\nValidation used Python 3.11, a rebuilt native extension, and a local Spark 4.3.0 Connect server.\n\n- ML offline and type-stub suites: **2,079 passed, 73 skipped**, including five pyright checks because pyright is unavailable locally. Mypy uses CI\u0027s pinned version, 2.4.1.\n- Live migrated-estimator and broader ML API/lifecycle tests: **88 passed**. Coverage includes disabled Python request builders, eager setters and defaults, summaries, persistence, subclass dispatch, pipelines/tuning, blocked optional dependencies, copies, cyclic garbage collection, and lazy model references.\n- Official standard ML drop-in suites: **34 passed, no skips** across regression, classification, cache, and OneVsRest. Deprecated upstream `pyspark.ml.connect` algorithms remain excluded.\n- Public API comparison: **zero differences** in public names, member kinds, and signatures across the four migrated regression classes.\n- Rust: **864 library tests passed**; all integration tests compiled with and without `wasm-udf`; formatting and workspace Clippy with warnings denied passed.\n- Tooling: **23 tests and three subtests passed**; generated stubs, pinned vendor drift, Ruff, and whitespace checks passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nThis pull request and its description were written by Isaac.\n\nCloses #985 from zhengruifeng/feature/standard-linear-regression-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "a17534cecc80a7ef40f87c1b1ff7f47c814e273b",
      "tree": "04a60d2f54a1a88c4df22548cbdfddf09fa11576",
      "parents": [
        "7bf002bc762eceadc0f6c2957a3016e2a6896fc4"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Fri Nov 27 14:40:58 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Fri Nov 27 14:40:58 2026 +0800"
      },
      "message": "[SPARK-62385][CONNECT][PYTHON] Delegate standard LinearSVC operations to Rust\n\n### What changes were proposed in this pull request?\n\nMake standard `pyspark.ml.classification.LinearSVC` use the existing Rust ML implementation, following #888. This covers LinearSVC, LinearSVCModel, LinearSVCSummary, and LinearSVCTrainingSummary.\n\n- Publish the native classes through the existing classification adapter and retain identical classes at the fork-native import paths.\n- Synchronize estimator/model parameter mutations immediately, including defaults, clearing, copies, UID changes, and unpickling. Keep Python Params authoritative and retain synchronization before native operations for direct dictionary edits.\n- Retain overridden estimator defaults in the native wrapper with garbage-collection support.\n- Share standard-import and live routing tests with LogisticRegression, and update generated type aliases and documentation checks.\n\nThe upstream classification source stays byte-identical to Spark 4.3.0. No runtime dependencies are added. The deprecated upstream `pyspark.ml.connect` algorithms are outside the scope.\n\n- Preserve Python reference counts and immediate ML cache cleanup when native models, copies, and summaries are deleted, including shallow copies that share a reference without incrementing it. Rust continues to retain models needed by lazy plans; Python finalizers wait for deletion outside the GIL.\n- Teach the native ML stub coverage check to validate migrated class re-exports as well as class declarations.\n\n### Why are the changes needed?\n\nStandard LinearSVC still constructs ML requests through upstream Python orchestration even though the Rust API and bindings already implement its operations. Delegating these operations shares the implementation between Rust and Python callers and lets upstream standard ML tests exercise the Rust ML core.\n\nTracks [SPARK-62385](https://issues.apache.org/jira/browse/SPARK-62385). [Design and acceptance criteria](https://github.com/zhengruifeng/spark-connect-rust/blob/feature/standard-linearsvc-rust/specs/features/standard-linearsvc-rust.md).\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. Standard LinearSVC operations use Rust, and ordinary parameter setters immediately update native state without server calls. Public signatures, Python subclass dispatch, copying, pickling, and the `LinearSVCModel.summary()` method remain compatible with PySpark.\n\n### How was this patch tested?\n\nValidation used a rebuilt native extension and Python 3.11, matching CI, with a local Spark 4.3.0 Connect server for live tests.\n\n- ML offline and type-stub suites: **2,060 passed, 73 skipped**. Five skips are pyright checks because pyright is unavailable locally; mypy uses CI\u0027s pinned version, 2.4.1.\n- Live standard-classification and broader ML lifecycle tests: **80 passed**, including native request routing, eager parameter updates, summaries, persistence, subclass dispatch, pipelines/tuning, optional-dependency isolation, ordinary/shallow copies, cyclic garbage collection, and lazy model references.\n- Upstream standard ML drop-in tests: **24 passed, no skips** across `test_connect_cache`, `test_parity_classification`, and `test_parity_ovr`. These tests exercise standard `pyspark.ml` over Connect; deprecated `pyspark.ml.connect` algorithms remain excluded.\n- Public API comparison against official PySpark 4.3.0: **zero differences** in public names, member kinds, and signatures across all 10 migrated LogisticRegression and LinearSVC classes.\n- Rust: **864 library tests passed**; all integration tests compiled with and without `wasm-udf`; `cargo fmt --all --check` and `cargo clippy --workspace --all-targets -- -D warnings` passed.\n- Ruff and `git diff --check` passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #984 from zhengruifeng/feature/standard-linearsvc-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "7bf002bc762eceadc0f6c2957a3016e2a6896fc4",
      "tree": "901ec6ed57a5025a9c54d1c811f705b6a2621e9b",
      "parents": [
        "515037bc6560d5cfdfe5858c8cb8528e6f4b641a"
      ],
      "author": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Nov 26 18:49:52 2026 +0800"
      },
      "committer": {
        "name": "Ruifeng Zheng",
        "email": "ruifengz@apache.org",
        "time": "Thu Nov 26 18:49:52 2026 +0800"
      },
      "message": "[SPARK-62315][CONNECT][PYTHON] Delegate standard LogisticRegression operations to Rust\n\n### What changes were proposed in this pull request?\n\nTracks [SPARK-62315](https://issues.apache.org/jira/browse/SPARK-62315).\n\nMake `from pyspark.ml.classification import LogisticRegression` use the existing Rust ML implementation for fit, transform, model access, evaluation, and persistence. Standard Python ML currently constructs these requests through upstream Python helpers; this change delegates the operations through the PyO3 bindings and Rust ML classes.\n\nThe scope is LogisticRegression, LogisticRegressionModel, and their four summary classes:\n\n- Keep Python Params, setters, signatures, copying, pickling, and subclass hooks. For the estimator and model, synchronize ordinary parameter mutations immediately into native state, including defaults, clearing, UID changes, copies, and unpickling. For example, `lr.setMaxIter(20)` updates both Python and native state before any fit call.\n- Keep Python parameter maps authoritative and synchronize again before native operations to handle direct dictionary edits and subclass overrides that bypass the mutation methods. Eager synchronization makes no server calls and requires no session. Other algorithms retain their existing synchronization behavior.\n- Store overridden LogisticRegression defaults in the native wrapper and traverse their Python references for garbage collection.\n- Preserve Rust model-reference and session handling, including lazy transforms after the Python model wrapper is deleted.\n- Preserve upstream classification source byte-for-byte under `_upstream/classification.py`. The public module loads those definitions and publishes the six native classes; existing fork-native imports alias the same classes.\n- Add no Python runtime dependencies. Fresh-process tests block Python protobuf, gRPC, Py4J, zstandard, scipy, scikit-learn, and torch imports.\n\n[Design and acceptance criteria](https://github.com/zhengruifeng/spark-connect-rust/blob/prototype/standard-logistic-rust/specs/features/standard-logistic-rust.md).\n\n### Why are the changes needed?\n\nSharing Rust ML operations reduces duplicate request construction between the Rust and Python APIs. Upstream standard `pyspark.ml` tests running against this package exercise the same Rust ML core used by Rust callers. Rust API tests remain necessary for Rust-specific behavior.\n\nThis change starts with LogisticRegression while preserving Python parameter and subclass semantics. The deprecated upstream `pyspark.ml.connect` algorithms are outside the scope.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. Standard LogisticRegression operations execute through the native Rust ML API, and parameter setters update native state immediately. The public import path, Python signatures and conversion errors, copying, and expected results remain compatible with PySpark. Package runtime and optional dependency declarations are unchanged.\n\n### How was this patch tested?\n\nBuilt the matching native extension locally and tested it with Python 3.13 and Spark 4.3.0:\n\n- Offline ML API, subclass, and standard-import tests: **896 passed, 68 skipped**. New tests inspect native state directly after mutations, including partial conversion errors, defaults, copies, UID changes, pickle restoration, subclass hooks, and reference-cycle collection. They also verify that other algorithms keep their existing behavior and that operation-time synchronization handles bypasses.\n- Live standard LogisticRegression and native golden tests: **6 passed**, covering fitted-model eager updates, fit/transform/evaluation, persistence, lazy model lifetime, Pipeline/CrossValidator, and optional-dependency isolation. Routing tests disable Python ML request builders so they must use the native ML implementation.\n- `scripts/run_official_tests.py --dropin` with Spark 4.3.0\u0027s complete standard classification parity file: **17 passed, no skips or failures**. These tests import our package, without transport injection. The LogisticRegression-focused selection also passed all 7 tests.\n- Affected typing/runtime-import/docstring checks: **3 passed, 1 skipped** because pyright is unavailable. Ruff, generated type-stub drift, and whitespace checks passed. Fresh introspection found no missing public names on either LogisticRegression class.\n- Preserved upstream classification source matches Spark 4.3.0 byte-for-byte; dependency declarations and the lockfile are unchanged.\n- Rust library tests: **864 passed**. All integration-test targets compiled with both default features and `wasm-udf`. `cargo fmt --all --check` and `cargo clippy --workspace --all-targets -- -D warnings` passed.\n\nAll 18 CI checks passed on the preceding head `4bfeb76f`. The updated commit requires a fresh CI run, including the complete project-wide official suites and coverage. Historical validation is recorded separately in the design spec.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Codex (GPT-6)\n\nThis pull request and its description were written by Isaac.\n\nCloses #888 from zhengruifeng/prototype/standard-logistic-rust.\n\nAuthored-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\nSigned-off-by: Ruifeng Zheng \u003cruifengz@apache.org\u003e\n"
    },
    {
      "commit": "515037bc6560d5cfdfe5858c8cb8528e6f4b641a",
      "tree": "9bf25f8bd58c26fd761ec47e88f77749b12b4e9b",
      "parents": [
        "23804322d254a46e1efcacf5546412d4c51ca0c8"
      ],
      "author": {
        "name": "DB Tsai",
        "email": "dbtsai@dbtsai.com",
        "time": "Tue Nov 24 21:26:56 2026 -1000"
      },
      "committer": {
        "name": "DB Tsai",
        "email": "dbtsai@dbtsai.com",
        "time": "Tue Nov 24 21:26:56 2026 -1000"
      },
      "message": "[SPARK-62192][CONNECT] Isolate cleanup of native JVM query and session owners\n\nJIRA: [SPARK-62192](https://issues.apache.org/jira/browse/SPARK-62192)\n\n### What changes were proposed in this pull request?\n\nA stalled Java query or session close blocks later closes of the same type through a process-wide JNI cleanup queue. Those unrelated owners retain handles and admission permits while waiting.\n\nGive each query and session its own cleanup thread, using the existing attachment, detach and shutdown accounting. Retry failures to start or dispatch to a cleanup thread automatically with bounded backoff on the existing runtime, including during shutdown drain. Server close waits for dispatch retries within its existing shutdown deadline. Retain executed JNI cleanup failures for explicit server-close retry. Task cancellation and task frees keep their shared worker.\n\nEach query/session close now pays for a thread spawn and normally a JNI attach/detach instead of shared-worker burst reuse. Blocked owners that hold admission remain limited to 64 queries and 64 sessions per engine. Threads and attachments finishing completed closes can overlap later admission; these admission limits are not a strict thread bound.\n\nFollow-up to #474.\n\n### Why are the changes needed?\n\nPrevent a blocked close from delaying unrelated queries and sessions, and allow serving-time capacity to recover after a transient cleanup-thread dispatch failure.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. Unrelated query/session cleanup can reclaim admission while a peer close remains blocked. Dispatch failures recover automatically without new admission or an explicit server close. Cleanup diagnostics now say “thread”, distinguish pending dispatch from an executed cleanup failure, and report when dispatch recovers.\n\n### How was this patch tested?\n\nLocal validation on macOS ARM64 with JDK 21 and the pinned Spark 4.2.0-SNAPSHOT runtime: JNI and frontend Rust tests, release client unit tests, full integration-test compilation with and without WASM, workspace Clippy, formatting, license freshness, acceptance-runner guard tests and packaging checks, Java loader tests, C ownership checks with ASan/UBSan, release native build, and real JNI smoke under `-Xcheck:jni`.\n\nThe merged tree with `master` at `dd756c29` also passed the JNI suite, release native build, real JNI smoke and isolation check.\n\nThe new real-JNI isolation regression blocks query and session closes inside Java, completes 70 peers per scenario, verifies retained shutdown ownership, and then releases the gate and retries shutdown. Rust regressions use injected dispatch failures to cover automatic recovery of all 64 query/session admission permits, bounded retry backoff, separation of dispatch and executed-cleanup failures, attachment warning deduplication, and owner-thread exit. Real-host tests verify retries before listener startup, after listener shutdown while native resources drain, and while server close waits for pending dispatch.\n\nCI runs the attached blocked-owner isolation check alongside the existing real JNI smoke, with a 15-minute step budget for both checks.\n\nA disposable fault-injection build retained 64 real query/task owners, reproduced admission exhaustion, then recovered after injection stopped before any new RPC or server close. A second phase keeps dispatch failure active through the ten-second shutdown deadline, verifies retained ownership and its error message, then recovers after injection stops while the listener remains stopped. The fault-injection probe also verifies one dispatch-recovery diagnostic per recovery phase. The committed isolation test also fails with admission exhaustion against the old shared-lane implementation.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: OpenAI Codex (GPT-6)\n\nThis pull request and its description were written by OpenAI Codex.\n\nCloses #902 from dbtsai/codex/native-connect-isolated-owner-cleanup.\n\nAuthored-by: DB Tsai \u003cdbtsai@dbtsai.com\u003e\nSigned-off-by: DB Tsai \u003cdbtsai@dbtsai.com\u003e\n"
    },
    {
      "commit": "23804322d254a46e1efcacf5546412d4c51ca0c8",
      "tree": "39211fca6d0de319deb0f338e4c765410f442deb",
      "parents": [
        "01725993b520960d9acae3955e80bab6e160ace6"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 13:27:23 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 13:27:26 2026 +0000"
      },
      "message": "[SPARK-62325][CONNECT][PYTHON] Move the unread part of a parse out of its slabs for the children kept of released or cleared messages and of merged maps, of no walk of what was read whole, and keep one record of each class of a type\n\n### What changes were proposed in this pull request?\n\nA parse holds the messages that Python has not read in slabs of up to 64 messages (SPARK-62312), and a message that a container or a map releases while Python keeps it moves the part of the parse that it holds unread out of the slabs, so that it keeps none of them alive for the messages released (SPARK-62318). The review of SPARK-62318 and SPARK-62313 found no undefined behaviour, no panic that Python can reach and no value that differs from upb\u0027s, but six fixable things in that release and unpinning, which this PR fixes:\n\n- **A message of a map that a merge replaces is unpinned** (`containers::release_replaced`). The `MergeFrom` and `MergeFromString` of the message that holds a map, which replace the message of an entry (`MapContainer::merge_entries`, the parse of a map entry into an object, `codec::merge_map_entry`), and the copies of `update` and of a new entry, dropped the message replaced as it was. They now release it as `del` of the map does: a message that Python keeps of the entry moves its part of the parse out of the slabs. Of an `MlParams` of 300 entries, the value kept of the key that `p.MergeFrom(...)` replaced held 3 messages of the slabs of the parse after the release of `p`; it holds none.\n- **A child of a message that Python keeps is unpinned once the message no longer holds it** (`message::unpin_held`). Of a message field, a repeated field or a map, of the release of the message (the `Drop` of `PyMessage`), of `ClearField`, `Clear`, `CopyFrom`, and of the member of a oneof that another replaces (`clear_oneof_siblings`). Only the messages of a container or a map released were unpinned. Of a parse read a level at a time (`_proto_whole_limit(0)`), `x \u003d r.join.left.project; del r` kept 14 messages of the slabs, as did a `ClearField` and a oneof switch, and a grandchild of a message of a container 28; none now. The default whole-value limit read those values whole, of no native value; a join of two relations of 184 messages each, which is read a level at a time, held 368 messages of the slabs, now none.\n- **The walk of the unpinning passes by what was read whole** (`PyMessage::clean`, `CLEAN_EPOCH`). A message records the epoch at which it was made holding no native value below it: made empty, of a value read whole (as the read of a value of up to 256 messages makes its objects, of all its levels), or by Python. A native value set in the message unmarks it, and a merge into a message (`merge_native`, and a parse into a message that holds fields), or a copy that shares the native values of a message (`native::copy_parts`), begins another epoch, which unmarks every message made before it: the native values that they set below a message, the marks of the messages above it would not see. A parse into an empty message begins none: what it sets is a parse of its own, all below the message. The walk, one loop of one stack now rather than a recursion of a vector of each level, passes marked messages by, so the `pop` of a message of 1,022 messages read whole, kept by a list, visits the 10 of its messages of the levels read one at a time (each of more than 256 messages below it), not its 1,022: 2.6 µs, of 79.5 µs (upb\u0027s 0.17 µs), and of a message that Python built 0.35 µs, of 15.9 µs (upb\u0027s 0.26 µs). The release of a parse of 400 such messages, kept by a list, takes 1.1 ms, of 30.8 ms (upb\u0027s 0.85 µs, which releases nothing).\n- **`remove` releases the reference of its comparison first** (`RepeatedComposite::remove`), so a message that no other reference holds is released of no walk: its count of references was always above 1 at its release.\n- **A type keeps one record of each of its classes** (`Registry::kept`, `keep_class`). A read of a type after a registration that gave it another class kept a new record of the class, never released, of 48.9 bytes of each registration that alternated two classes and a read (the review\u0027s `p6_registry.py`). The registry now keeps the records of each type under its lock, one of each class: a class that the type had before is kept again of its record, whose generation (`KeptClass::at`, atomic now) the read sets to the later one. `kept_class` reads the generation of the record before the change of the class, so that a record kept again of a later generation, of a read of the registry after the registrations up to it, is never taken for the class of a generation before a change. Of 50,000 registrations that alternate two classes, each followed by a parse, malloc holds 21.1 bytes more of each (53.1 before): the history of the classes that the registrations replaced, which `MessageClass::at` reads for the copies of earlier generations, 20.3 bytes of each with no parse too, as before.\n- **The hash of the addresses of the classes** (`AddressHasher`) shifts out the 4 bits that the alignment of objects makes 0 before its multiplication, so that the low bits of the hash, which pick the bucket, take all their values; its doc said \"the high bits of its product\" and now says what it does.\n\n**Hardening.** The drop of a container of messages and of a map released its messages as `Bound`s of `Python::assume_attached()`, sound only while no container with messages is dropped by a thread that is not attached. It now releases them so only of a thread that CPython\u0027s `PyGILState_Check` finds attached, and leaves them to PyO3 otherwise, which defers their release until a thread attaches, as the `Vec\u003cPy\u003e` of before SPARK-62318 did (`message::if_attached`). `Python::try_attach` takes the lock of PyO3\u0027s pool of deferred references at each call (`AttachGuard::assume`), which made the release of a parse read whole 18% slower (69 ms of the parse of 400 messages of 1,022, 58 ms): CPython\u0027s check takes no lock. On Windows, whose extensions of the limited API link against no `PyGILState_Check`, of `Python::try_attach`. The `Drop` of a message releases nothing as a `Bound`; it reads the count of references of the objects of its fields, which it holds only as an object (its fields are set of the methods of the object), so of the deallocation of the object, of the thread attached, as a debug assertion checks.\n\nThe object of a message stays of 144 bytes: the parent of an unset child is a weak reference and the index of its field of 32 bits (`parent`, `parent_field`), beside the mark of 32 bits, in the room of the parent before (`Parent`, of a field index of 64 bits). New test hooks: `_proto_unpin_counts` (the walks of the unpinning and the objects that they visited) and `_proto_kept_classes` (the records of the classes of a type).\n\n**The cost.** The `Drop` of a message reads its mark, and walks its objects only of a message not marked. A `Drop` of its own makes the drop of a message call the drop of its fields apart rather than inline it, about 4 ns of each message released: the release of a parse of 400 messages of 1,022, read whole, takes 57 ms, 53 ms before (upb\u0027s 0.08 ms, which defers the release to the last of its messages and frees the arena at once). The parses, the reads and the releases of SPARK-62322\u0027s benchmarks take as long as before, within what a build of master with one function that nothing calls moves them (the tables below). `dev/parity/known-differences.md` has a new entry, \"The release of a message that Python keeps of a parse\", and `docs/compatibility.md` says what this PR unpins.\n\n### Why are the changes needed?\n\nThe review of SPARK-62318 and SPARK-62313 (#978, #979): two leaks of slabs of a parse that a kept message held (a map value replaced by a merge; a singular child of a message released, cleared or replaced), the walk of the unpinning of up to 1,024 objects of a message that held nothing to unpin (32 ms to pop 400 messages read whole, upb\u0027s 0.1 ms), the needless unpinning of every message that `remove` removed, a record of a class kept of each registration that changed a class (48 bytes of each), and the hash of the addresses of the classes, whose low 4 bits were always 0.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo change of behaviour: what Python reads, compares and serializes is as before, and upb\u0027s. Memory: a message kept of a map merged into, or of a message released, cleared or replaced, keeps no slab of its parse alive, and registrations that alternate classes keep no record of a class each. Performance: the `pop`, `remove` and release of messages kept of a parse read whole or built by Python take a fraction of the time (2.6 µs to pop a message of 1,022 messages read whole, of 79.5 µs), and the release of a parse read whole takes 3% to 8% longer.\n\n### How was this patch tested?\n\n- `python/tests/test_proto_rust_offline.py`, new tests, of either whole-value limit (the runtime\u0027s and 0) where they read a parse, unless they say otherwise:\n  - `test_map_values_replaced_by_a_merge_keep_no_slab_of_their_parse`: a value of a map of 300 entries kept, which `MergeFrom` and `MergeFromString` of the message replace and `map.MergeFrom` merges into, holds no message of the slabs once the message is released, and reads as before.\n  - `test_children_kept_of_released_or_cleared_messages_keep_no_slab_of_their_parse`: a child kept of a join of two relations of 184 messages each, of the release of its message, `ClearField`, a oneof switch, `Clear` and `CopyFrom`, and a grandchild kept of a message of a container released, hold no message of the slabs and equal the child of another parse.\n  - `test_messages_kept_of_a_read_are_released_of_no_walk_of_what_was_read_whole`: the `pop` of 20 messages of 1,022 messages read whole, of the whole-value limit of the runtime, visits 10 objects each (`_proto_unpin_counts`), and those of a message that Python built none; the messages popped hold no message of the slabs and equal those of another parse.\n  - `test_a_message_removed_of_a_container_is_walked_only_if_python_holds_it`: `remove` of an equal message walks nothing, and of a message that Python keeps walks it once, which then holds no message of the slabs.\n  - `test_a_type_keeps_one_record_of_each_of_its_classes`: of 2,000 registrations that alternate two classes of `Relation`, each followed by a parse, every read is of the class registered then, and the type keeps 2 records (`_proto_kept_classes`).\n  On master (`01725993`), the first two fail (a value kept of `MergeFrom`, and the child kept of a released message at the whole-value limit of the runtime, hold messages of the slabs); the other three need the new hooks.\n- `pbmsg::message::tests::the_hashes_of_addresses_of_objects_differ_in_their_low_bits`, a new unit test: the low 8 bits of the hashes of 256 addresses 16 bytes apart take more than 128 values, and their low 4 bits are not all 0.\n- The review\u0027s probes (`p9_map.py`, `p10_singular.py`, `p1b.py`, `p12_perf.py`, `p11.py`, not in the tree): every value is upb\u0027s, before and after. The messages of the slabs that a kept message holds, master and this PR: of `p9_map.py`, `msg.MergeFrom` 3 and 0, `msg.MergeFromString` 3 and 0 (of either limit; the others 0 and 0); of `p10_singular.py` at the limit 0, the parent released, `ClearField` and a oneof switch 14 and 0 each (at 256, 0 and 0); of `p1b.py` at 0, the grandchild 28 and 0, the great-grandchild 12 and 0 (the rest as before: 29 before the release and 0 after it of a message of a container, and 18,000 of a relation that holds its 600 expressions, more than 256 messages, which stays of the slabs, as before). Of `p12_perf.py`, the pop of 400 messages read whole 33.1 ms and 1.3 ms (upb\u0027s 0.1 ms), and the release of their container with them kept 47 ms and 1.25 ms (upb\u0027s 0.00 ms). Of the registrations of `p6_registry.py`, of the bytes that malloc holds rather than of RSS: 53.1 and 21.1 bytes of each registration with a parse, 20.3 and 20.3 with none.\n- The tests of the runtime (`tests/test_proto_rust_offline.py`, 194) at the whole-value limit of the runtime, at 0 and at 3, under `ulimit -v 4000000`: 194 passed at each. Without `protobuf`: 52 passed and 142 skipped.\n- The lockstep tests of messages, of constructor copies and of parses: 600 seeds each, at the whole-value limits 0 and 256: no failure.\n- The review\u0027s fuzzer of SPARK-62264 (`fuzz_copies.py --aliasing`; 600 seeds of 1,000 steps), at the whole-value limit of the runtime and at 0: the digests of the drop-in\u0027s observations are those of master `afc6be24` for every seed, of either limit, and the same 14 seeds mismatch upb, as before this PR.\n- The gates: `cargo fmt`, clippy 1.100.0, `cargo doc`, the binding\u0027s lib tests (42), ruff, the stub and dispatch generators, the no-stub audit, the guards and the stub test pass. The offline suite of `coverage.yml`: 7970 passed, 121 skipped, 1 xfailed (under `ulimit -v 16000000`). `tests/test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n\nThe benchmarks (µs per call, the best of interleaved rounds of fresh interpreters, each the best of its runs; master is `f30e373b`, whose code `01725993` keeps, adding tests only; a release is timed apart, of the messages made before it):\n\n  The releases of the messages that Python keeps (the review\u0027s `p12_perf.py`; functions of 8 levels of two arguments each, 1,022 messages each; of 6 levels, 254):\n\n  | Case | Master | This PR | upb |\n  |---|---|---|---|\n  | 400 functions read whole: `pop` of each, kept by a list | 79.47 | 2.64 | 0.17 |\n  | 400 functions read whole: release of the parse, the functions kept by a list | 30,800 | 1,135 | 0.85 |\n  | 400 functions read whole: release of the parse | 52,963 | 57,008 | 76.96 |\n  | 100 functions that Python built: `pop` of each, kept by a list | 15.92 | 0.35 | 0.26 |\n  | 100 functions that Python built: release of the message, the functions kept | 1,615 | 12.72 | 0.97 |\n  | 400 functions read whole: `remove` of a function that no other reference holds | 260.34 | 223.83 | 102.74 |\n  | whole-value limit 0: `pop` of each, kept by a list | 76.38 | 72.64 | 0.17 |\n  | whole-value limit 0: `remove` of a function that no other reference holds | 260.40 | 225.71 | 102.74 |\n  | `ClearField` of the parent of a child that Python holds | 0.62 | 0.73 | 0.24 |\n\n  (The `remove` compares the two messages of 1,022 messages each first, most of its time. At the whole-value limit 0 no value is read whole, so the walk visits every object, as before.)\n\n  The releases of SPARK-62322, with two controls of the layout of the code: master with one function that nothing calls (`ctlFn`), and master with an empty `Drop` of `PyMessage` (`ctlDrop`):\n\n  | Case | Master | ctlFn | ctlDrop | This PR |\n  |---|---|---|---|---|\n  | plan 20x10: release of a parse | 66.53 | 70.02 | 73.17 | 71.44 |\n  | plan 20x10: FromString and its release | 277.92 | 280.79 | 281.47 | 280.79 |\n  | plan 3x2: release of a parse | 3.42 | 3.56 | 3.58 | 3.46 |\n  | array 1000: release of a parse | 10.17 | 10.53 | 11.75 | 10.48 |\n  | array 1000: FromString and its release | 61.42 | 62.61 | 61.29 | 61.35 |\n  | array 1000: release of a copy | 20.87 | 24.44 | 23.67 | 23.04 |\n  | array 1000: release of a parse read at its first message | 12.04 | 12.77 | 13.23 | 12.88 |\n  | array 100000: release of a parse | 951.06 | 1,021 | 910.80 | 985.12 |\n  | array 100000: FromString and its release | 6,286 | 6,380 | 6,317 | 6,266 |\n  | array 100000: release of a copy | 3,278 | 3,167 | 3,333 | 2,617 |\n  | array 100000: release of a parse read at its first message | 945.48 | 922.96 | 958.85 | 975.92 |\n  | array 1000000: release of a parse | 13,081 | 13,239 | 13,232 | 13,246 |\n  | array 1000000: FromString and its release | 83,232 | 84,445 | 84,083 | 84,470 |\n  | array 1000000: release of a copy | 32,594 | 32,808 | 32,467 | 32,466 |\n  | array 1000000: release of a parse read at its first message | 13,216 | 13,378 | 13,063 | 13,033 |\n\n  Plans and an array of 1,000 strings, parsed and read whole, with the same controls:\n\n  | Case | Master | ctlFn | ctlDrop | This PR |\n  |---|---|---|---|---|\n  | array 1000: parse | 61.31 | 62.13 | 60.94 | 61.15 |\n  | array 1000: parse, read all | 336.14 | 344.00 | 339.13 | 340.12 |\n  | array 1000: parse, ListFields all | 757.97 | 787.58 | 792.66 | 792.61 |\n  | plan 3x2: parse | 10.42 | 10.38 | 10.49 | 10.60 |\n  | plan 3x2: parse, read all | 95.35 | 94.05 | 96.65 | 95.11 |\n  | plan 5x2: parse | 16.25 | 16.27 | 16.41 | 16.39 |\n  | plan 5x2: parse, read all | 149.69 | 147.97 | 151.77 | 149.80 |\n  | plan 20x10: parse | 276.03 | 278.98 | 275.69 | 274.71 |\n  | plan 20x10: parse, read all | 2,903 | 2,883 | 2,997 | 2,902 |\n  | plan 50x20: parse | 1,400 | 1,412 | 1,425 | 1,395 |\n  | plan 50x20: parse, read all | 14,753 | 14,715 | 15,136 | 14,789 |\n\n  The cases of SPARK-62313:\n\n  | Case | Master | This PR |\n  |---|---|---|\n  | to_plan col | 1.30 | 1.24 |\n  | to_plan v \u003e 0 | 2.21 | 2.13 |\n  | to_plan when/when/otherwise | 4.97 | 4.91 |\n  | Plan.FromString small plan | 10.51 | 10.56 |\n  | Plan.FromString large plan | 277.15 | 275.79 |\n  | ParseFromString large plan | 276.36 | 275.62 |\n  | FromString large plan, a path of 3 | 286.12 | 288.23 |\n  | FromString small plan, read all | 96.43 | 94.37 |\n  | FromString large plan, read all | 2,952 | 2,910 |\n  | FromString large plan, SerializeToString | 467.37 | 464.72 |\n\n  Flat arrays of N strings, parsed and read whole:\n\n  | Case | Master | This PR |\n  |---|---|---|\n  | array 100: parse | 7.06 | 7.00 |\n  | array 100: parse, read all | 36.51 | 36.71 |\n  | array 100: parse, ListFields all | 80.00 | 73.71 |\n  | array 1000: parse | 60.43 | 60.67 |\n  | array 1000: parse, read all | 333.98 | 335.99 |\n  | array 1000: parse, ListFields all | 765.76 | 711.35 |\n  | array 10000: parse | 607.23 | 606.26 |\n  | array 10000: parse, read all | 3,370 | 3,393 |\n  | array 10000: parse, ListFields all | 7,689 | 7,165 |\n  | array 100000: parse | 6,202 | 6,238 |\n  | array 100000: parse, read all | 39,386 | 38,437 |\n  | array 100000: parse, ListFields all | 82,295 | 78,759 |\n  | array 1000000: parse | 83,724 | 83,357 |\n  | array 1000000: parse, read all | 420,013 | 422,907 |\n  | array 1000000: parse, ListFields all | 857,640 | 806,780 |\n\n  The `ListFields` of the arrays, which this PR does not change, moves about 10% between builds of the same code, as SPARK-62322 found of a build of master with one function added; so do the releases of a parse of the plan of 2,835 messages above (66.53 µs of master, 70.02 µs of `ctlFn`).\n\n  The memory of a kept message (SPARK-62318\u0027s probe of 20,000 kept messages, of the bytes that malloc holds): 0.59 KiB of each build; of the reviewer\u0027s `probe7.py` (of RSS), 0.67 KiB of master and 0.56 KiB of this PR, which moves as RSS does.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #983 from HyukjinKwon/SPARK-62325-unpin-fixes.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "01725993b520960d9acae3955e80bab6e160ace6",
      "tree": "e74937d1d64f3e33ad4cf02199038aee0e5f6368",
      "parents": [
        "efc0a7df1f39113440efc6ec32af5752e0749934"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 12:54:58 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 12:55:02 2026 +0000"
      },
      "message": "[SPARK-62329][CONNECT][PYTHON] Make the tests of a collection during the first read of a container take their turn at a collection that each read starts, of no scheduling of the threads\n\n### What changes were proposed in this pull request?\n\nTest only, the follow-up of SPARK-62328 for the other cross-thread test of SPARK-62272: `test_another_thread_during_the_first_read_of_a_container_finds_the_message` (`python/tests/test_proto_rust_offline.py`).\n\n**What the test is for.** The first read of a container makes the container and the weak reference of its owner. SPARK-62272 made it do so with no borrow of the message held, because their allocations may start a collection whose Python code reads the message, or gives the GIL to a thread that does. In the test, the callback of such a collection gives the GIL to another thread, which reads the message (`ListFields()`) while the first read is in progress. Each read must be whole. There are 40 first reads of each of a repeated message field, a map and a repeated scalar field.\n\n**Why it could pass without testing anything.**\n- The callback slept 0.2 ms for the reader to take its turn.\n- The test asserted only that no read raised, not that any read happened.\n- At a threshold of 1, about every other first read started a collection: 17 to 20 of 40.\n- Under 32 busy processes on 32 cores (load average 32 to 39), the reader read none of the 40 first reads of a kind in 4 of 5 runs: the map\u0027s or the repeated scalar\u0027s, or both. Those runs passed having tested nothing.\n\n**What changes:**\n- **Every first read starts a collection within the read**, primed as the tests of the text format are (SPARK-62328): before each read, a collection of the young generation, then one `_GcPrimer`. A probe checks this: in all 40 reads of each kind, with and without protobuf, the collection\u0027s callback saw the frame of the read.\n- **A handshake gives the reader its turn.** The callback hands the reader the message and waits for its read, so every message is read within the first read of its container, with no dependence on how the threads are scheduled.\n- **The test fails loudly if its premise is gone.** It fails, and names the reads, if any first read started no collection. It asserts `{\u0027missed\u0027: [], \u0027ok\u0027: 40, \u0027errors\u0027: {}}` for each kind, and as before, that the container is one object.\n- **The same-thread form** (`test_a_collection_during_the_first_read_of_a_container_finds_the_message`) is primed the same way, and its callback reads only during the read. Before, it relied on whatever the code before the read had left counted, such as the tuple of `gc.get_threshold()`, which a free list may give without counting.\n- **Python 3.12 and later skip both**, as they skip the tests of the text format: they collect after a native call. CI runs Python 3.11.\n- **Shared names.** The note on the primer, and the timeout of the turn (renamed `_COLLECTION_TURN_TIMEOUT` from `_TEXT_FORMAT_TURN_TIMEOUT`), now cover both kinds of tests. The note also says that the primer is deleted after each call, before the next one: otherwise binding the next primer frees the previous one and gives its count back, and no read would collect.\n\n### Why are the changes needed?\n\nThe test could pass under load without reading anything during a first read. It is item 98 of the SPARK-62207 follow-ups. No code of the drop-in changes.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. Only tests change.\n\n### How was this patch tested?\n\n- **Under load,** each run a pytest process of its own of the two tests, under `ulimit -v 4000000`, beside 32 busy processes on 32 cores (load average 32 to 39):\n  - 50 of 50 without protobuf;\n  - 50 of 50 with protobuf.\n- **The tests still catch the bug they are for.** A variant was built whose first read makes the container and the weak reference while it holds the message\u0027s mutable borrow, as before SPARK-62272. On it, both tests fail in every run, with and without protobuf, for each kind:\n  - the cross-thread one with `{\u0027missed\u0027: [], \u0027ok\u0027: 0, \u0027errors\u0027: {\u0027PanicException: Already mutably borrowed: PyBorrowError\u0027: 40}}`;\n  - the same-thread one with that `PanicException`.\n- The four tests of the two families pass, with and without protobuf.\n- **The gates** (at dd1434c4):\n  - ruff 0.14.0, the no-stub audit, the stub and dispatch generators, the license checks, the guards and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`, under `ulimit -v 16000000`: 7965 passed, 121 skipped, 1 xfailed (master\u0027s PyO3 subclass-cycle test);\n  - `test_proto_rust_offline.py` without protobuf, as the step of Connect parity runs it: 47 passed, 142 skipped.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #982 from HyukjinKwon/SPARK-62329-container-first-read-thread-test.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "efc0a7df1f39113440efc6ec32af5752e0749934",
      "tree": "4a6a823bca3ef3ea207257323174fd77ad39692f",
      "parents": [
        "f30e373bab98efa705f9db9bdfd869e2d68614ee"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 12:23:36 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 12:23:39 2026 +0000"
      },
      "message": "[SPARK-62328][CONNECT][PYTHON] Make the tests of a first read during the text format take their turn at a collection that each format starts, of no scheduling of the threads\n\n### What changes were proposed in this pull request?\n\nTest only. `test_a_first_read_of_another_thread_during_the_text_format_finds_the_message` (`python/tests/test_proto_rust_offline.py`, of SPARK-62272) failed in master f30e373b\u0027s Connect parity run 45372919906, in the step \"Drop-in live-server tests ... without protobuf\":\n\n```\nAssertionError: {\u0027ok\u0027: 0, \u0027errors\u0027: {}}\n```\n\n**What the test is for.** Python code runs during the drop-in\u0027s text format (`_proto_message_to_string`): here, the callback of a collection. Through it, another thread reads a plan\u0027s native field for the first time while the writer writes the plan. Each read must be whole, without an error or a `PanicException`, and the field must give one object afterwards. SPARK-62272 made the writer write a native copy, so it holds no borrow of the message while Python code may run.\n\n**Why it failed.** The test assumed the writer\u0027s collections happen often enough for the reader to get a turn. They don\u0027t:\n- The callback slept 0.2 ms for the reader to read meanwhile.\n- But of the 100 formats, only one started a collection: 10 of 10 runs, with and without protobuf, and only in the first format.\n- The writer\u0027s expansion of the `Any` allocates one object of the garbage collector, the message it parses. Since SPARK-62266 the parse makes no other.\n- At a threshold of 1, that allocation starts a collection only if an object that counts was allocated before the call. Only the code before the first format leaves one.\n- So the reader had one window of 0.2 ms, and a loaded machine misses it. Under 32 busy processes on 32 cores (load average 36 to 45), the old test\u0027s logic read nothing in 20 of 30 runs, where it would fail.\n\n**What changes:**\n- **Each format starts a collection within the call.**\n  - Before each format: a collection of the young generation, then one `_GcPrimer`, an object of a class with no free list. A list or a tuple may come from a free list, which doesn\u0027t count.\n  - The message\u0027s allocation then exceeds the threshold, and Python 3.11, like the versions before it, collects right there, within the native call.\n  - A probe checks this: in all 100 formats, with and without protobuf, the collection\u0027s callback saw the loop\u0027s frame at the line of the call.\n- **A handshake gives the reader its turn.** The callback hands the reader the plan and waits for its read, so every plan is read during its own format, with no dependence on how the threads are scheduled. This is the same approach as the probe of SPARK-62309.\n  - The wait has a timeout of 60 s. Only a failure of the reader, such as a crash of its thread, makes it wait that long. A timeout is recorded as an error.\n- **The test fails loudly if its premise is gone.**\n  - If any format started no collection, it fails and names those formats (\"the text formats of the plans [...] started no collection\"). So it cannot pass without testing anything.\n  - It asserts that all 100 reads are whole (`{\u0027ok\u0027: 100, \u0027errors\u0027: {}}`), and as before, that the field gives one object and that each plan serializes to the same bytes.\n- **The same-thread form** (`test_a_first_read_of_a_collection_of_the_text_format_finds_the_message`) relied on the same premise.\n  - Its collection came from the tuple of `gc.get_threshold()`, which a free list may give without counting.\n  - It now primes the young generation the same way, and its callback reads only during the write.\n- **Python 3.12 and later skip both.** They run a collection that an allocation starts at the interpreter\u0027s next instruction, after the native call, so no Python code runs within the format. CI runs Python 3.11.\n\n### Why are the changes needed?\n\nThe test failed CI under load. It is item 97 of the SPARK-62207 follow-ups, of the same kind as SPARK-62309. No code of the drop-in changes.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. Only tests change.\n\n### How was this patch tested?\n\n- **Under load,** each run a pytest process of its own of the two tests, under `ulimit -v 4000000`:\n  - 50 of 50 without protobuf, under 32 busy processes on 32 cores (load average 36 to 45);\n  - 50 of 50 with protobuf, under the same load;\n  - 50 of 50 with protobuf, beside a release build of the extension.\n- **The tests still catch the bug they are for.** A variant was built whose writer writes the message as it is, holding its borrow, as before SPARK-62272. On it, both tests fail in every run, with and without protobuf:\n  - the cross-thread one with `{\u0027ok\u0027: 0, \u0027errors\u0027: {\u0027RuntimeError: Already borrowed\u0027: 100}}`;\n  - the same-thread one with `RuntimeError: Already borrowed`.\n- **The gates** (at 5c95a041):\n  - ruff 0.14.0, the no-stub audit, the stub and dispatch generators, the license checks, the guards and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`, under `ulimit -v 16000000`: 7965 passed, 121 skipped, 1 xfailed (master\u0027s PyO3 subclass-cycle test);\n  - `test_proto_rust_offline.py` without protobuf, as the step of Connect parity runs it: 47 passed, 142 skipped.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #981 from HyukjinKwon/SPARK-62328-text-format-thread-test.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "f30e373bab98efa705f9db9bdfd869e2d68614ee",
      "tree": "8ed4ccba53c04a908379e0f1fce74a6d7daa4f3d",
      "parents": [
        "e65557a0b5bedc7dd709f4f2950391262c8ee27c"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 10:14:40 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 10:14:41 2026 +0000"
      },
      "message": "[SPARK-62322][CONNECT][PYTHON] Release the messages of a list of a parse of each slab at once, and leave the release of a tree as it is, which a walk of its own made slower\n\n### What changes were proposed in this pull request?\n\nA parse holds its messages in slabs of up to 64 (SPARK-62312), and the release of each message decrements the count of its slab, an atomic operation for each message (`arena::release_many`, 7% of the `Plan.FromString` of the plan of 2,835 messages of SPARK-62266\u0027s benchmarks and its release). SPARK-62313 named batching those decrements as the one fixable part of the release left, about 6% of that.\n\n**The change.**\n- **A list of messages of a parse releases those of each slab at once** (`Drop` of `NativeMessages`, `native::release_list`, `NRef::release_with`). A list of 8 messages or more of a parse, of messages of at most one level below them, releases its messages one after another, of one release of the nodes of each slab that it releases in a row (`arena::Releases`), as a parse makes the messages of a flat array in a row; so does a container that holds the messages of a list natively (`Drop` of `RepeatedComposite`, of the messages that it has made no object of yet). A shorter list, a list of messages of more levels (whose nodes are apart in their slabs, between those of the messages below each) and a list of a copy (whose messages are allocations of their own) release their messages as before, of no more than the check of them. Each message keeps its count of references: one that another reference holds is not released (SPARK-62318\u0027s kept messages, and the unpinning at the release of a container, are as before).\n\n**What does not pay: the release of a whole tree.** Three walks of the tree of a parse of their own, which released the nodes of each slab of the tree at once, all made the release of the plan of 2,835 messages slower, of more than the atomic operations that they saved (µs, one parse at a time, the best of 3,000; master `e65557a0` releases it in 53 µs):\n\n| Walk | Release of the plan | Release of a parse of a million strings (ms) |\n|---|---|---|\n| master | 53 | 15.1 |\n| a recursion of the levels, the children of each message before it | 79 to 81 | |\n| a recursion of the levels, each message before its children (the order of the parse) | 81 to 83 | 12.3 |\n| a loop of a stack of the values left | 77 to 78 | 16.3 |\n| this PR (the lists only) | 54 | 11.3 |\n\n`perf` of the walks: taking the native values out of the slots of each message, the `Arc::try_unwrap` of each list (a compare-and-swap and the decrement of its weak count) and the calls or the stack operations of each message took more time than the uncontended atomic operation that the walk saves, which the drop of the messages of the compiler\u0027s drop glue takes as it is. So the tree\u0027s nodes are released as before, of one atomic operation each, and `dev/parity/known-differences.md` (\"The time of a parse\") says so.\n\n### Why are the changes needed?\n\nSPARK-62313 left the batching of the decrements of the slabs as the one fixable part of the release; this PR does it where it pays, and shows where it does not.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo change of behaviour. Performance only: the release of a parse of a flat array takes about a fifth less time (13 ms of a million strings, of 17 ms), and its `FromString` with its release 6% to 9% less; the release of a plan and the reads take as long as before.\n\n### How was this patch tested?\n\n- `crates/pyspark-rs/src/pbmsg/arena.rs`, a new unit test, `a_list_of_a_parse_releases_its_messages_of_each_slab_at_once`: a list of 200 messages of a parse releases them of each slab at once, and a message that another reference holds stays, of its slab, and reads as it did; a short list and a list of a copy release their messages as they are, as before.\n- The tests of the runtime (`tests/test_proto_rust_offline.py`, 189) at the whole-value limit of the runtime, at 0 and at 3, under `ulimit -v 4000000`: 189 passed at each. Without `protobuf`: 47 passed and 142 skipped.\n- The lockstep tests of messages, of constructor copies and of parses: 600 seeds each, at the whole-value limits 0 and 256: no failure.\n- The review\u0027s fuzzer of SPARK-62264 (`fuzz_copies.py --aliasing`; 600 seeds of 1,000 steps), at the whole-value limit of the runtime and at 0: the digests of the drop-in\u0027s observations are those of master `afc6be24` for every seed, of either limit, and the same 14 seeds mismatch upb, as before this PR.\n- The gates: `cargo fmt`, clippy 1.100.0, `cargo doc`, the binding\u0027s lib tests (41), ruff, the stub and dispatch generators, the guards and the stub test pass. The offline suite of `coverage.yml`: 7965 passed, 121 skipped, 1 xfailed (under `ulimit -v 16000000`). `tests/test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n\nThe benchmarks (µs per call, the best of interleaved rounds of fresh interpreters, each the best of its runs; master is `e65557a0`; a release is timed apart, of the messages made before it):\n\n  Releases (and a `FromString` with its release):\n\n  | Case | Master | This PR | vs master |\n  |---|---|---|---|\n  | plan 20x10: release of a parse | 77.20 | 75.73 | -1.9% |\n  | plan 20x10: FromString and its release | 276.49 | 278.79 | +0.8% |\n  | plan 3x2: release of a parse | 3.81 | 3.88 | +2.0% |\n  | array 1000: release of a parse | 15.46 | 12.62 | -18.4% |\n  | array 1000: FromString and its release | 66.97 | 61.12 | -8.7% |\n  | array 1000: release of a copy | 29.92 | 17.19 | -42.5% |\n  | array 1000: release of a parse read at its first message | 17.63 | 14.16 | -19.7% |\n  | array 100000: release of a parse | 1,494 | 1,158 | -22.5% |\n  | array 100000: FromString and its release | 6,896 | 6,411 | -7.0% |\n  | array 100000: release of a copy | 3,506 | 3,593 | +2.5% |\n  | array 100000: release of a parse read at its first message | 1,478 | 1,096 | -25.8% |\n  | array 1000000: release of a parse | 16,769 | 13,131 | -21.7% |\n  | array 1000000: FromString and its release | 88,253 | 83,313 | -5.6% |\n  | array 1000000: release of a copy | 32,460 | 32,667 | +0.6% |\n  | array 1000000: release of a parse read at its first message | 16,814 | 13,026 | -22.5% |\n\n  The cases of SPARK-62313:\n\n  | Case | Master | This PR |\n  |---|---|---|\n  | to_plan col | 1.24 | 1.25 |\n  | to_plan v \u003e 0 | 2.22 | 2.22 |\n  | to_plan when/when/otherwise | 4.96 | 4.95 |\n  | Plan.FromString small plan | 10.46 | 10.44 |\n  | Plan.FromString large plan | 274.26 | 276.11 |\n  | ParseFromString large plan | 273.53 | 276.71 |\n  | FromString large plan, a path of 3 | 283.43 | 285.70 |\n  | FromString small plan, read all | 94.51 | 94.26 |\n  | FromString large plan, read all | 2,916 | 2,908 |\n  | FromString large plan, SerializeToString | 460.35 | 462.04 |\n\n  Flat arrays of N strings, parsed and read whole:\n\n  | Array of | Parse: master | This PR | Read all: master | This PR | ListFields all: master | This PR |\n  |---|---|---|---|---|---|---|\n  | 100 | 7.51 | 7.01 | 36.39 | 36.41 | 72.86 | 79.43 |\n  | 1,000 | 66.05 | 60.32 | 333.67 | 334.03 | 693.82 | 759.64 |\n  | 10,000 | 659.08 | 604.32 | 3,361 | 3,355 | 6,959 | 7,644 |\n  | 100,000 | 6,839 | 6,186 | 39,058 | 39,181 | 75,834 | 82,442 |\n  | 1,000,000 | 86,860 | 83,321 | 415,568 | 415,982 | 778,289 | 849,453 |\n\n  Plans (`ListFields` of every message):\n\n  | Plan | Parse: master | This PR | Read all: master | This PR |\n  |---|---|---|---|---|\n  | 3x2 | 10.58 | 10.50 | 94.82 | 94.67 |\n  | 5x2 | 16.27 | 16.31 | 148.77 | 149.81 |\n  | 20x10 | 274.86 | 275.97 | 2,929 | 2,899 |\n  | 50x20 | 1,398 | 1,415 | 14,846 | 14,725 |\n\n  The release of a copy of 1,000 messages, which this PR leaves as it is, is of the heap of the process of the rounds; of three more runs each, both release it in 14 µs (14.1 to 14.7 of master, 14.3 to 14.5 of this PR). The `ListFields` of the arrays, which this PR does not change, moves about 10% between runs of either build; of three more runs each of a walk of 1,000 strings, master took 781 to 803 µs, a control build of master with one function added that nothing calls 766 to 777 µs, and this PR 773 to 793 µs.\n\n  The memory of a kept message (SPARK-62318\u0027s probe of 20,000 kept messages, of the bytes that malloc holds): 0.59 KiB of each build; of the reviewer\u0027s `probe7.py` (of RSS), 0.47 to 0.49 KiB of master and 0.52 to 0.65 KiB of this PR, which moves as RSS does.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #980 from HyukjinKwon/SPARK-62322-batched-release.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "e65557a0b5bedc7dd709f4f2950391262c8ee27c",
      "tree": "36af20be2f07ff951339e377e2c0a46acb7fe1b3",
      "parents": [
        "9b6996e1ec5aaaec4f3214fe0f4e6778e02c7a65"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 08:52:16 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 08:52:16 2026 +0000"
      },
      "message": "[SPARK-62313][CONNECT][PYTHON] Parse of fewer allocations (short strings and the first two messages of a repeated field in place) and of a table of the small field numbers, and the rest of the gap to upb as inherent\n\n### What changes were proposed in this pull request?\n\nThe native parse of the drop-in\u0027s protobuf runtime (`crates/pyspark-rs/src/pbmsg`, SPARK-62266 and SPARK-62312) took several times as long as upb\u0027s: of the plan of 2,835 messages of SPARK-62266\u0027s benchmarks (20 projections of 10 expressions, 9,913 bytes), `Plan.FromString` took 373 µs, upb\u0027s 49 µs; `ParseFromString`, 372 µs and 98 µs; a path of 3 of it, 383 µs and 50 µs; the `to_plan` of `F.col(\"s.v\")`, 1.50 µs and 0.78 µs.\n\n**The breakdown** (of `perf` of a build of frame pointers and line tables, of the allocations of a preloaded counter of `malloc` and `free`, and of the parse and its release timed apart):\n\n| Part of `Plan.FromString` of the 2,835 messages | Master | This PR | upb |\n|---|---|---|---|\n| total (µs) | 373 | 275 | 49 |\n| the parse, one at a time (µs) | 278 | 215 | 48 |\n| its release (µs) | 77 | 53 | 0.4 |\n| allocations for each message (`malloc`, `free`) | 1.02, 1.00 | 0.53, 0.51 | 0, 0 |\n| a string: an allocation, a copy and its UTF-8 check | yes | the check and a copy in place, of up to 22 bytes | the check, a view of the arena |\n| the list of a repeated field: the `Arc` of it, the vector of its messages | 2 allocations | 1, of up to two messages | 0 |\n| the lookup of a field of its number | a binary search | a table of numbers below 64 | a table |\n| the slots of a message of two fields or more | a vector | a vector | the message struct |\n| each message: a node of 112 bytes, its count of references, its slab\u0027s count | yes | yes | its struct in the arena |\n\nOf this PR\u0027s 275 µs (`perf`, self time): the loop of the parse (the tags, the lengths, the values, the dispatch of the fields and the writes of the nodes and their slots) 46%, the slots and the lists (`Slots::set`, the counts of levels of each message, `MessageClass::now` of each list) 18%, `malloc` and `free` 8%, the release of the nodes 14% (of which the atomic decrement of the count of a slab for each message 7.5%), the lookups of the fields 1%, the boundary of Python less than 1%.\n\n**The change.**\n- **A string of up to 22 bytes is held in place** (`scalar::Str`, of the size of a `String`): the parse and a set of a string field from Python make no allocation of it, and its release frees none. The strings of the messages of Spark Connect are most often a few bytes (names, identifiers, the names of functions): 801 of the plan above, of 1,001 bytes.\n- **The first two messages of the list of a repeated field are held in place** (`native::Items`, of a vector from the third): the arguments of a function, most often one or two, take no allocation of their own (600 of the plan above).\n- **A table of the field numbers below 64** (`MessageDesc::small_numbers`): the parse looks a field up of its number of no search (the binary search took about a tenth of the time of the parse); a larger number is of the binary search, as before.\n- **The messages of a repeated field are parsed in their nodes** (`NativeParse::field`), of no move of each into its slab once it is read, and **the first slot of a message is set in place** (`Slots::set`, inlined; `Slots::set_more` of the others, which appends a field of a number after those set of no search).\n- **The release of a message of no other reference makes no atomic write** of its count (`Drop` of `NRef`: an `NRef` has no weak references, so its only reference has no other to race with).\n- `to_plan` reads the class `Expression` of the module of an interned name (`proto_attr`), and the registry of the classes looks the type of a class up of a hash of its address of a multiplication (`AddressHasher`), rather than of SipHash.\n\n**What is inherent** (`dev/parity/known-differences.md`, \"The time of a parse\"): a message of the runtime is a native value of its own, a node of 112 bytes in a slab of the parse, of a count of its references, so that a read of Python can take its fields into an object, a copy can share it and a message kept of a parse can outlive the rest of it (SPARK-62266, SPARK-62312, SPARK-62318). So the parse writes a node, its slots and its counts of levels for each message, and keeps the vector of the slots of a message of two fields or more and the list of each repeated field, with the reference of its class (0.53 allocations a message); the release drops each node and frees what it holds, of an atomic decrement of the count of its slab for each message (53 µs of the 275), where upb frees the arena of the parse at once (0.4 µs). Parsing in upb\u0027s time would take one block of memory of the parse, freed at once, of which the objects of a read, the copies that share a parse and the messages kept of it could not each hold a part. The `to_plan` of a Column builds the expression in Rust, encodes it and parses it, where PySpark builds the message in Python, of no parse: 1.24 µs, PySpark\u0027s 0.78 µs (1.6 times).\n\n### Why are the changes needed?\n\nThe parse of a response, of a plan or of the expression of a Column took several times as long as PySpark\u0027s; SPARK-62313 asked for its gap to upb broken down, what is fixable fixed toward about twice upb\u0027s time, and what is inherent of the design shown so.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo change of behaviour. Performance only (see the tables below): the parse takes a quarter less time (a third less of messages of short strings), the release of a parse a third to a half less, and the reads of what a parse holds 2% to 10% less.\n\n### How was this patch tested?\n\n- `python/tests/test_proto_rust_offline.py`, a new test, `test_strings_and_short_repeated_fields_of_parses_are_upbs`: strings of 0 to 64 bytes about the 22 that are held in place (of one-, two- and four-byte UTF-8), parsed, read, set, copied and serialized, and repeated message fields of 0 to 4 messages, parsed, read, copied, appended to, extended, popped, compared, serialized and printed, compared with upb\u0027s, at the whole-value limit of the runtime and at 0.\n- New unit tests: `scalar::tests::strings_read_as_their_str_of_either_place` (in place and not, `Cow`, `\u003d\u003d`, order, the hash of the `str`, `Display`, `Debug`); `native::tests::the_messages_of_a_repeated_field_keep_their_order_of_each_size` (0 to 5 messages of a push, a collection and a vector, read by reference, mutably, by value and as a vector); `pool::tests::the_fields_of_small_numbers_are_of_a_table` (numbers 1, 63, 64 and 1,000).\n- The tests of the runtime (`tests/test_proto_rust_offline.py`, 189) at the whole-value limit of the runtime, at 0 and at 3, under `ulimit -v 4000000`: 189 passed at each. Without `protobuf`: 47 passed and 142 skipped.\n- The lockstep tests of messages, of constructor copies and of parses: 600 seeds each, at the whole-value limits 0 and 256: no failure.\n- The review\u0027s fuzzer of SPARK-62264 (`fuzz_copies.py --aliasing`; 600 seeds of 1,000 steps), at the whole-value limit of the runtime and at 0: the digests of the drop-in\u0027s observations are those of master `afc6be24` for every seed, of either limit, and the same 14 seeds mismatch upb, as before this PR.\n- The gates: `cargo fmt`, clippy 1.100.0, `cargo doc`, the binding\u0027s lib tests (40), ruff, the stub and dispatch generators, the guards and the stub test pass. The offline suite of `coverage.yml`: 7965 passed, 121 skipped, 1 xfailed (under `ulimit -v 16000000`). `tests/test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n\nThe benchmarks (µs per call, the best of interleaved rounds of fresh interpreters, each the best of its `timeit` runs; master is `9b6996e1`):\n\n  The cases of SPARK-62313 (the plan of 20x10 of 2,835 messages, and the small one of 3x2):\n\n  | Case | Master | This PR | vs master | PySpark (upb) | vs upb |\n  |---|---|---|---|---|---|\n  | to_plan col | 1.50 | 1.24 | -17.8% | 0.78 | 1.59x |\n  | to_plan v \u003e 0 | 2.50 | 2.18 | -12.6% | 4.24 | 0.51x |\n  | to_plan when/when/otherwise | 5.63 | 4.92 | -12.6% | 17.59 | 0.28x |\n  | Plan.FromString small plan | 13.41 | 10.38 | -22.6% | 2.14 | 4.86x |\n  | Plan.FromString large plan | 372.51 | 274.75 | -26.2% | 49.24 | 5.58x |\n  | ParseFromString large plan | 372.42 | 274.49 | -26.3% | 98.17 | 2.80x |\n  | FromString large plan, a path of 3 | 382.83 | 283.28 | -26.0% | 49.78 | 5.69x |\n  | FromString small plan, read all | 95.61 | 92.61 | -3.1% | 67.92 | 1.36x |\n  | FromString large plan, read all | 2,958 | 2,888 | -2.4% | 2,070 | 1.39x |\n  | FromString large plan, SerializeToString | 561.46 | 462.96 | -17.5% | 132.79 | 3.49x |\n\n  Flat arrays of N strings (`Literal.array.elements`):\n\n  | Array of | Parse: master | This PR | Read all: master | This PR | ListFields all: master | This PR |\n  |---|---|---|---|---|---|---|\n  | 100 | 10.98 | 7.43 (-32.3%) | 39.11 | 36.52 (-6.6%) | 83.78 | 79.60 (-5.0%) |\n  | 1,000 | 100.06 | 65.50 (-34.5%) | 362.08 | 330.51 (-8.7%) | 804.15 | 765.11 (-4.9%) |\n  | 10,000 | 1,002 | 654.93 (-34.6%) | 3,638 | 3,345 (-8.0%) | 8,024 | 7,303 (-9.0%) |\n  | 100,000 | 10,348 | 6,692 (-35.3%) | 41,828 | 38,234 (-8.6%) | 86,659 | 77,685 (-10.4%) |\n  | 1,000,000 | 135,890 | 85,880 (-36.8%) | 464,712 | 416,598 (-10.4%) | 909,056 | 806,773 (-11.3%) |\n\n  Plans (`ListFields` of every message):\n\n  | Plan | Parse: master | This PR | Read all: master | This PR |\n  |---|---|---|---|---|\n  | 3x2 | 13.46 | 10.46 (-22.3%) | 96.29 | 94.12 (-2.3%) |\n  | 5x2 | 20.99 | 16.14 (-23.1%) | 152.75 | 147.97 (-3.1%) |\n  | 20x10 | 371.37 | 274.13 (-26.2%) | 2,964 | 2,895 (-2.3%) |\n  | 50x20 | 1,933 | 1,389 (-28.2%) | 15,050 | 14,768 (-1.9%) |\n\n  The ML client\u0027s `deserialize_param` of the parse of a param of N values:\n\n  | N | strings | arrays of strings | DenseVector | SparseVector |\n  |---|---|---|---|---|\n  | 100 | 385.26 → 382.20 (-0.8%) | 420.24 → 429.57 (+2.2%) | 14.30 → 14.15 (-1.0%) | 44.95 → 44.11 (-1.9%) |\n  | 1,000 | 3,653 → 3,557 (-2.6%) | 3,730 → 3,783 (+1.4%) | 17.63 → 17.37 (-1.5%) | 193.24 → 186.59 (-3.4%) |\n  | 10,000 | 36,428 → 35,254 (-3.2%) | 36,480 → 36,110 (-1.0%) | 47.28 → 46.42 (-1.8%) | 1,728 → 1,672 (-3.2%) |\n  | 100,000 | 376,247 → 361,482 (-3.9%) | 371,883 → 349,206 (-6.1%) | 564.21 → 563.63 (-0.1%) | 16,363 → 15,754 (-3.7%) |\n  | 1,000,000 | 3,742,721 → 3,617,765 (-3.3%) | 3,742,437 → 3,557,182 (-5.0%) | 8,546 → 8,980 (+5.1%) | 172,478 → 166,213 (-3.6%) |\n\n  Of a message of a million messages (a `Literal` array of a million strings; CPU s, best of 3):\n\n  | Operation | Master | This PR | PySpark |\n  |---|---|---|---|\n  | parse | 0.129 | 0.083 | 0.048 |\n  | parse, then a read of every message | 0.462 | 0.412 | 0.176 |\n  | `CopyFrom`, `deepcopy`, `MergeFrom` of a message that Python read | 0.217, 0.229, 0.228 | 0.173, 0.173, 0.172 | 0.095, 0.099, 0.090 |\n  | `MergeFrom` into a message that has the repeated field | 0.222 | 0.205 | 0.091 |\n  | `SerializeToString` of a parse read whole, of a copy | 0.071, 0.058 | 0.068, 0.051 | 0.035, 0.039 |\n  | release of a parse not read, of a copy | 0.038, 0.073 | 0.017, 0.033 | 0.002, 0.003 |\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #979 from HyukjinKwon/SPARK-62313-parse-gap.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "9b6996e1ec5aaaec4f3214fe0f4e6778e02c7a65",
      "tree": "e02c440c9e11928c7307cdddd19e48a768b87e93",
      "parents": [
        "bcaf4031e169537d6d1d9bc0d15eeecf4a1dfb2b"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 07:49:39 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 07:49:39 2026 +0000"
      },
      "message": "[SPARK-62318][CONNECT][PYTHON] Move the unread part of a parse that a kept message holds out of the slabs of the parse, and read the class of a generation under the registry\u0027s lock\n\n### What changes were proposed in this pull request?\n\nFour follow-ups of the review of SPARK-62266 and SPARK-62312 (#973, #976) of the drop-in\u0027s protobuf runtime (`crates/pyspark-rs/src/pbmsg`), and the parse of the packed fields of a fixed width, whose speed SPARK-62312 had of how the compiler happened to compile its loop.\n\n**1. A message kept of a large parse kept a slab of 64 messages alive (SPARK-62312).** A parse holds the messages that Python has not read in slabs of up to 64 messages (`arena`), each released with the last of its messages. A message read of a large parse, which holds the part of the parse below it unread, kept the slabs of that part alive once the rest of the parse was released: of 3,000 parses of a `Relation` of 1,000 expressions, each of which kept `r.project.expressions[7]` with its `unresolved_function` unread, 3.62 KiB stayed allocated for each kept message, where SPARK-62266 kept 0.67 KiB.\n\nNow a message that outlives the container or the map that held it moves the part of the parse that it holds unread out of the slabs (`PyMessage::unpin`, `Value::unpin`, `NRef::rebox`), each message of an allocation of its own: when the container or the map is released while another holds the message (`Drop` of `RepeatedComposite` and of `MapContainer`), and when the container no longer holds it (`pop`, `remove`, `del`, `clear` of a container; `del`, `clear` of a map, and so `pop` and `popitem`). It moves up to 256 messages of a native value, of up to 1,024 objects and native messages below the message: a larger part holds most of the nodes of its slabs itself. A message that no other holds is released with its container as before, of no move, so the reads and the parses take as long as before (see below). 0.67 KiB stay allocated for each kept message now, as of SPARK-62266.\n\n**2. The class of a generation is read under the registry\u0027s lock.** `MessageClass::at` compared the generation of the classes with the one asked for, and then read the registry, so that a registration of another thread in between (of a build of no GIL, `Py_GIL_DISABLED`, which the extension supports) gave the class of the new generation for a message of the old one. It reads the generation under the lock of the registry now, which a registration holds while it changes the classes and begins the next generation, and the class of the generation under the same lock (`MessageClass::of_locked`, `class_now`).\n\n**3. A type keeps the class of the first read after a registration that changed it.** A message type kept the class of its first read (`MessageDesc::class`, a `OnceLock`) for the objects of its messages, made of no lookup of the registry (SPARK-62266); after a registration that gave the type another class, every object of the type took the registry\u0027s lock and a lookup of the name of the type again. The type keeps a record of the class and its generation now (`KeptClass`, of an `AtomicPtr`), which the first read of the registry after such a registration replaces (`keep_class`); a record replaced is never released, as the registry keeps the classes that a registration replaced. The plan of 20x10 read whole after a registration that gave `Expression`, `Literal` and `Relation` other classes and one that gave them theirs back takes as long as before the registrations (2,911 µs, of 2,902 µs before the registrations; master\u0027s 2,979 µs after them, of 2,892 µs before).\n\n**The packed fields of a fixed width** (`codec::fixed_values`, with 1 to 3): a native parse reads the values of a packed field of doubles, floats or fixed integers of the slice of its bytes, a loop of each kind, rather than each byte of each value of a check of the end of the data (but of a field that the patch buffer of upb ends, as before). The `DenseVector` of 1,000 doubles of a model parses in 5.3 µs, master\u0027s 14.7 µs. The parse of a message is inlined into the parse of its children again (`NativeParse::message`), which the compiler stopped doing of the code that this PR adds.\n\n**4. What another thread and a signal handler see of a message during its parse** (docs/compatibility.md): of `FromString`, `ParseFromString` (which clears the message first) and a `MergeFromString` of a message that holds no field, the message empty until the parse ends, as the parse reads the bytes into native values of its own, which the message takes at the end (merged with what another thread set meanwhile, `PyMessage::take_parsed`); of a `MergeFromString` of a message that holds fields, the message as the merge has set it so far, a field at a time; a parse that the exception of a signal handler interrupts leaves the message with what it read until then, as a parse that fails does.\n\nA hook of the tests, `_pyspark._proto_slab_messages(message)`, counts the native messages of slabs that a message holds, of all its levels.\n\n### Why are the changes needed?\n\nA program that keeps a small part of each of many large parses, as a cache of the expressions of plans or of the params of models, kept a slab of 64 messages for each, five times the memory of SPARK-62266. The class of a message of a build of no GIL could be of the wrong generation, and the reads after a registration that changed a class took a lock for each object.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo change of behaviour. Memory and performance only: a message kept of a large parse holds 0.67 KiB rather than 3.62 KiB (of the parse above), and the reads after a registration that changed a class take no lock for each object.\n\n### How was this patch tested?\n\n- `python/tests/test_proto_rust_offline.py`, new tests:\n  - `test_messages_kept_of_released_containers_keep_no_slab_of_their_parse`: an element of a repeated field of 600 messages of a parse, kept while the container is released, popped, removed, deleted or cleared, and a value of a map of 300 entries, kept while the map is released, deleted or cleared, holds no message of a slab once the container or the map is gone (and held some while it was there), and reads as it did; at the whole-value limit of the runtime and at 0.\n  - `test_parses_are_of_the_classes_registered_when_they_were_read`: the objects of parses made before a registration that gave `Relation` another class are of the class before, those of parses made after it of the new class, of reads of a value at once and of a level at a time, three times each, and of the class before again after a registration back.\n- `crates/pyspark-rs/src/pbmsg/arena.rs`, a new unit test: a message of a slab that no other reference holds moves out of it (`NRef::rebox`), released from the slab, and reads as it did; of another reference, it stays.\n- The reviewer\u0027s probe (`probe7.py`, of RSS): 0.58 KiB for each kept message, SPARK-62312\u0027s 3.61 KiB, SPARK-62266\u0027s 0.78 KiB. Of the bytes that malloc holds (`mallinfo`, 20,000 kept messages): 0.67 KiB, 3.62 KiB and 0.67 KiB.\n- The tests of the runtime (`tests/test_proto_rust_offline.py`, 188) at the whole-value limit of the runtime, at 0 and at 3, under `ulimit -v 4000000`: 188 passed at each. Without `protobuf`: 47 passed and 141 skipped.\n- The lockstep tests of messages, of constructor copies and of parses: 600 seeds each, at the whole-value limits 0 and 256: no failure.\n- The review\u0027s fuzzer of SPARK-62264 (`fuzz_copies.py --aliasing`; 600 seeds of 1,000 steps), at the whole-value limit of the runtime and at 0: the digests of the drop-in\u0027s observations are those of master `afc6be24` for every seed, of either limit, and the same 14 seeds mismatch upb, as before this PR.\n- The gates: `cargo fmt`, clippy 1.100.0, `cargo doc`, the binding\u0027s lib tests (37), ruff, the stub and dispatch generators, the guards and the stub test pass. The offline suite of `coverage.yml`: 7961 passed, 121 skipped, 1 xfailed (under `ulimit -v 16000000`). `tests/test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n- The benchmarks (µs per call, the best of interleaved rounds of fresh interpreters, each the best of its `timeit` runs; master is `623ca9b0`):\n\n  `probe` is master with one function added that nothing calls (`_layout_probe`, of the module of the runtime): of the same code otherwise, its numbers are the spread of the layout of the code of the extension, which moves each time the extension changes (`HasField`, which this PR does not change, takes 295 ns of master, 302 ns to 307 ns of `probe` and 303 ns to 308 ns of this PR, of three interleaved runs each). The reads of `ListFields` (of arrays) and of `HasField` (the ML client\u0027s `deserialize_param` of strings), which this PR does not change, move with it.\n\n  | Array of N strings | Parse: master | probe | This PR | Read all: master | probe | This PR | vs master | ListFields all: master | probe | This PR |\n  |---|---|---|---|---|---|---|---|---|---|---|\n  | 100 | 10.95 | 10.96 | 10.98 | 39.03 | 39.35 | 39.18 | +0.4% | 75.37 | 82.16 | 82.83 |\n  | 1,000 | 100.57 | 100.75 | 99.31 | 362.52 | 366.28 | 361.85 | -0.2% | 726.87 | 793.63 | 797.49 |\n  | 10,000 | 1,011 | 998.60 | 992.51 | 3,663 | 3,678 | 3,648 | -0.4% | 7,345 | 7,962 | 8,011 |\n  | 100,000 | 10,403 | 10,343 | 10,194 | 42,145 | 42,337 | 41,701 | -1.1% | 79,509 | 85,751 | 86,383 |\n  | 1,000,000 | 136,347 | 136,362 | 135,283 | 468,307 | 469,943 | 465,256 | -0.7% | 839,513 | 907,248 | 907,327 |\n\n  | Plan | Parse: master | probe | This PR | Read all: master | probe | This PR | vs master |\n  |---|---|---|---|---|---|---|---|\n  | 3x2 | 12.99 | 13.00 | 13.29 | 93.54 | 94.20 | 96.26 | +2.9% |\n  | 5x2 | 20.43 | 20.53 | 20.86 | 148.39 | 149.58 | 152.16 | +2.5% |\n  | 20x10 | 363.81 | 364.07 | 369.54 | 2,886 | 2,901 | 2,956 | +2.4% |\n  | 50x20 | 1,907 | 1,918 | 1,930 | 14,782 | 14,727 | 15,002 | +1.5% |\n\n  | ML case (`deserialize_param` of the parse) | N | master | probe | This PR | vs master |\n  |---|---|---|---|---|---|\n  | strings | 100 | 363.27 | 375.01 | 364.23 | +0.3% |\n  | strings | 1,000 | 3,507 | 3,599 | 3,588 | +2.3% |\n  | strings | 10,000 | 35,003 | 35,819 | 35,811 | +2.3% |\n  | strings | 100,000 | 353,718 | 363,814 | 368,757 | +4.3% |\n  | strings | 1,000,000 | 3,549,848 | 3,673,660 | 3,710,811 | +4.5% |\n  | arrays of strings | 100 | 400.25 | 410.73 | 409.62 | +2.3% |\n  | arrays of strings | 1,000 | 3,510 | 3,615 | 3,625 | +3.3% |\n  | arrays of strings | 10,000 | 34,961 | 35,898 | 36,093 | +3.2% |\n  | arrays of strings | 100,000 | 354,772 | 367,192 | 361,752 | +2.0% |\n  | arrays of strings | 1,000,000 | 3,561,172 | 3,706,800 | 3,669,109 | +3.0% |\n  | DenseVector | 100 | 14.97 | 15.29 | 14.36 | -4.1% |\n  | DenseVector | 1,000 | 26.90 | 27.46 | 17.83 | -33.7% |\n  | DenseVector | 10,000 | 137.97 | 142.58 | 47.24 | -65.8% |\n  | DenseVector | 100,000 | 1,460 | 1,461 | 557.32 | -61.8% |\n  | DenseVector | 1,000,000 | 17,942 | 17,871 | 8,951 | -50.1% |\n  | SparseVector | 100 | 44.13 | 45.42 | 45.23 | +2.5% |\n  | SparseVector | 1,000 | 197.28 | 197.58 | 193.28 | -2.0% |\n  | SparseVector | 10,000 | 1,755 | 1,773 | 1,713 | -2.4% |\n  | SparseVector | 100,000 | 16,760 | 16,548 | 16,315 | -2.7% |\n  | SparseVector | 1,000,000 | 176,089 | 176,377 | 172,374 | -2.1% |\n\n  | Case | master | probe | This PR |\n  |---|---|---|---|\n  | to_plan col | 1.44 | 1.53 | 1.48 |\n  | to_plan v \u003e 0 | 2.46 | 2.49 | 2.50 |\n  | to_plan concat(a, lit, upper(b)) | 3.51 | 3.60 | 3.60 |\n  | to_plan when/when/otherwise | 5.48 | 5.51 | 5.55 |\n  | to_plan 40 additions | 67.36 | 65.56 | 66.20 |\n  | to_plan v \u003e 0, read all | 8.01 | 8.04 | 8.36 |\n  | to_plan 40 additions, read all | 209.20 | 208.02 | 215.00 |\n  | to_plan v \u003e 0, SerializeToString | 3.42 | 3.48 | 3.47 |\n  | Plan.FromString small plan | 12.94 | 13.04 | 13.41 |\n  | Plan.FromString large plan | 364.11 | 363.40 | 369.88 |\n  | ParseFromString large plan | 362.53 | 363.12 | 369.35 |\n  | FromString small plan, read all | 94.72 | 94.82 | 99.76 |\n  | FromString large plan, read all | 2,905 | 2,903 | 3,023 |\n  | FromString large plan, SerializeToString | 554.79 | 554.58 | 562.32 |\n  | FromString large plan, a path of 3 | 370.93 | 370.53 | 383.17 |\n\n  | Parse read whole | master | probe | This PR |\n  |---|---|---|---|\n  | array 1000, parse, read all (no registration) | 369.05 | 368.23 | 365.59 |\n  | plan 20x10, parse, read all (no registration) | 2,892 | 2,927 | 2,902 |\n  | array 1000, parse, read all (after a registration and back) | 368.43 | 369.31 | 365.37 |\n  | plan 20x10, parse, read all (after a registration and back) | 2,979 | 3,034 | 2,911 |\n\n  So the parse and the reads take as long as on master, but for the spread of the layout of the code: the reads of a plan whole take 1.5% to 2.9% longer, of which the release of each container checks the messages that it held for another holder (`release_held`, about 1%, of a build without it). The `DenseVector` of 1,000 doubles of a model parses in 5.3 µs, master\u0027s 14.7 µs.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #978 from HyukjinKwon/SPARK-62318-slab-pin.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "bcaf4031e169537d6d1d9bc0d15eeecf4a1dfb2b",
      "tree": "7448333eb26b21ca9df43bf6dc639ca1faf8f74c",
      "parents": [
        "623ca9b077404399d61ee64b74d225f815f4da86"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 06:29:31 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 06:29:31 2026 +0000"
      },
      "message": "[SPARK-62317][CONNECT][PYTHON] Keep the RecursionError of an override of needConversion, the depth of the StructType constructor and the os global of pyspark.sql.types as in PySpark\n\n### What changes were proposed in this pull request?\n\nA post-merge review of SPARK-62310 (#974) found three differences from PySpark 4.3.0:\n- **The RecursionError of a child\u0027s `needConversion`.** The drop-in replaced any `RecursionError` with the text `maximum recursion depth exceeded while calling a Python object` by a new plain one. That included subclasses and errors that a Python override raises, so their class, traceback, cause and context were lost. It now changes the text only of an exact `RecursionError` that CPython\u0027s check of a call of a native method raised, and does so on the same object. Everything else reaches the caller as in PySpark.\n- **The depth of the `StructType` constructor and `add`.** Before Python 3.12, the drop-in now enters the levels of PySpark\u0027s frames that its native methods lack: `__init__` and its list comprehension, the slot wrapper of `super().__init__`, and the comprehension of `add`. So it raises at PySpark\u0027s depth, 991 rather than 993 at limit 1000 on 3.11. From 3.12, CPython counts Python frames apart, in a depth that the stable ABI can\u0027t enter or read; `dev/parity/known-differences.md` documents it.\n- **The `os` global of `pyspark.sql.types`.** The module now binds `os`, as PySpark\u0027s does, and `YearMonthIntervalType.needConversion` reads it from the module at each call. So `mock.patch.dict(\"pyspark.sql.types.os.environ\", ...)` and `mock.patch.object(types, \"os\", ...)` both work.\n\n### Why are the changes needed?\n\nTo match PySpark 4.3.0.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, the three behaviors above now match PySpark.\n\n### How was this patch tested?\n\n- **New tests in `test_dropin_offline.py`:** three tests, each of which fails without the change and passes on PySpark 4.3.0 too.\n- **Probes against pyspark-client 4.3.0:**\n  - the subclass and override errors are the same on Python 3.9-3.13;\n  - the constructor and `add` depths are the same on 3.10 and 3.11, and differed on 12 of 45 cases before;\n  - the `os` patches are the same on 3.10-3.13.\n- **The usual checks:** clippy, rustdoc, rustfmt, ruff, the vendored check, the stubs, the pyspark-rs lib tests (36), the offline suite (7955 passed), and the offline suite under coverage (93.798%).\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Code\n\nThis pull request and its description were written by Isaac.\n\nCloses #977 from HyukjinKwon/SPARK-62317.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "623ca9b077404399d61ee64b74d225f815f4da86",
      "tree": "c278d7d955ae6045047891969d9310f3c705c194",
      "parents": [
        "6b4b5a63614b19f8f4ebaabdb8eccbf350cde10b"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 04:54:43 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 04:54:43 2026 +0000"
      },
      "message": "[SPARK-62312][CONNECT][PYTHON] Hold the native messages of a parse in slabs, and make the objects of a large repeated message field as they are read, so that a parse read whole takes as long as before the native parse\n\n### What changes were proposed in this pull request?\n\nSPARK-62266 (#973) parses into native values, of no Python object for each message, and makes the objects of a value when Python first reads it. Its parse takes about half the time it took, but a parse read whole took 4% to 34% longer than on `d90a730e`, the master before it: an array of 100,000 strings read whole took 32% longer, a plan of 2,835 messages 11%, and the ML client\u0027s `deserialize_param` of the vocabulary of a model 4% to 5%. Three costs made that:\n\n- Each native message was an `Arc\u003cNative\u003e` of an allocation of its own, which the read released again once its object had taken its fields, and #973\u0027s reads copied one level of each message rather than move it (`native::object_parts`), as the values moved left the memory of each message as a small hole between the values that stayed (a million such holes slowed every later allocation of the process down by up to 3.5 times).\n- The read of a repeated message field of more than 256 messages made the objects of all its messages in a pass of their own, and the program then read them in another, over memory that no longer fits the caches.\n- Each message of a parse and of a read took and released a reference of its type (`Arc\u003cMessageDesc\u003e`), two atomic operations of a shared cache line.\n\n**The change.**\n- **The messages of a parse are held in slabs** (`pbmsg::arena`: `NRef`, `Arena`). A native message of a value is an `NRef`: a count of its references as an `Arc` keeps it (`clone`, `drop`, `get_mut`, `try_unwrap`, and `into_parts`, which takes the fields of a message that no other value holds out of its node, of no copy of the message). The messages of a parse are the nodes of slabs of 64 (of 4, 8, 16 and 32 first, so that a parse of few messages holds no more than as many nodes again as its messages): one allocation for each slab rather than for each message, and a slab is released once none of its messages is held, of one free. A message that a copy makes is an allocation of its own, of the size of the `Arc` before. The slabs of 64 released are kept for the parses that follow, up to 64 MiB: glibc gives the memory released at the top of its heap back to the system, so each parse of a large message faulted its slabs in again (2,684 more faults for a parse of 100,000 messages read whole, 8% of its time).\n- **The objects take the fields of the messages, moved** (`native::own_parts`, `Made::fill`, `Whole::fill`), where no other value holds them, as the objects of copies did before #973, so a read no longer copies one level of each message. The nodes whose messages a read takes in a row are released of one atomic operation for each slab (`arena::Releases`). The memory that a read gives back is that of whole slabs, of 7 KiB each, which the allocator reuses as it reuses any large free: of a parse of a million messages read and held, the `CopyFrom` of it after three more parses takes as long as on `d90a730e` but for glibc\u0027s trim of the heap (see below), where it took 0.72 s with the small holes.\n- **The container of a repeated message field of a large value makes the objects of its messages as they are read** (`RepeatedComposite::of_native`, `make`, `make_all`). The container of a repeated message field of a value of more than 256 messages (which a read makes a level at a time) holds the messages natively, and a read of a message by its index, or of an iteration, makes the objects of the messages up to it, at least 64 at a time: a read of each message takes its object as it is made, while its memory is in the caches, and a read of the first messages makes theirs only. The objects are made with no borrow of the container held, as making them may run Python code (a collection, a checkpoint of the budget, at which another thread may take the GIL), and are set only if the container is as it was, else made again. Every other operation of the container (but `len()`) makes the rest first; the operations of its message read the rest natively, as they read a value that Python has not read: its bytes (`codec::measure_composite`, `write_composite`), its text, `\u003d\u003d` (`MessageRef::Native`), its copies (`copy_parts`), `DiscardUnknownFields` and `ListFields`.\n- **A message type is a `\u0026\u0027static MessageDesc`** (`Fields::desc`, `FieldDesc::message_type`, `MapDesc::value_message`, `Pool::message`): the types of the pool are never released, so a message no longer takes and releases a reference of its type.\n- A hook of the tests, `_pyspark._proto_whole_limit(limit)`, sets the number of messages up to which a read makes the objects of a value at once (256): at 0, every value is read a level at a time, and every repeated message field of a parse or a copy makes its objects as they are read, so the tests run each way.\n\n**Behaviour.** What Python reads is upb\u0027s, as before: the values, the identities of the objects that a field gives (the same object for each read of a message, of an index, a slice or an iteration), the bytes, the text, `\u003d\u003d`, presence, the errors and their order, and the state that each operation leaves, of a field read in part or not at all. `len()` of a repeated message field no longer makes the objects of its messages, so the first read of a message of it does: the two tests of a signal during the first read of a large repeated field now read its last message (`elements[-1]`) rather than its length.\n\n### Why are the changes needed?\n\nA program that reads what it parses whole, as the ML client reads the params of a model (`JavaWrapper._call_java` → `_parse_response` → `deserialize_param`, which reads every element of `literal.array.elements`), took longer than before #973, of more than the parse saved.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo change of behaviour. Performance only (see the tables below): a parse read whole takes about as long as on `d90a730e` (from 4.7% less to 2.9% more, at 100 to a million messages), and the parse alone takes less time than of #973.\n\n### How was this patch tested?\n\n- `python/tests/test_proto_rust_offline.py`, new tests:\n  - `test_large_repeated_fields_of_parses_and_copies_are_upbs`: 70 scenarios, compared with upb\u0027s. A repeated message field of 600 messages of a parse and of a copy, of which the first and the eleventh were read, then each read and change of the container (an index past the end, the last of a negative index, slices, iterations of the same objects, `in`, `\u003d\u003d`, `repr`, `append`, `add`, `extend`, `insert`, `pop`, `remove`, `del` of an index and of a slice, `sort`, `reverse`, `clear`, `MergeFrom`, a constructor of its messages) and of its message (`str`, `ByteSize`, `CopyFrom`, `copy.deepcopy`, `MergeFrom` of itself, `MergeFromString` of its own bytes, `ListFields`, `DiscardUnknownFields`, `ClearField`), with the identities of the messages read before and the bytes after; and `DiscardUnknownFields` of messages that each hold an unknown field, of which only the first 64 have objects.\n  - `test_reads_of_any_size_are_upbs_of_either_way`: those 70 and the 19 scenarios of the parses of SPARK-62266 at a whole-value limit of 0 (`_proto_whole_limit(0)`), so that every value is read a level at a time and every repeated message field makes its objects as they are read.\n  - `test_a_large_repeated_field_extends_itself_as_a_list`: `extend` of the field of itself, of a parse and of a copy, at both limits, takes the messages that it had first, as a list\u0027s and as the drop-in\u0027s before (upb\u0027s `extend` of itself appends the messages that it appends too, up to 2^26 messages, which then fail to serialize, so this one is not compared with upb\u0027s).\n  - `test_a_collection_during_the_reads_of_a_large_repeated_field_finds_it_whole`: a collection at each allocation while an iteration makes the objects of 1,000 messages, whose callback reads the container (its length, a message, an iteration) and serializes its message, finds it free and whole, and the iteration gives one object for each message.\n  - `test_threads_that_read_the_same_large_repeated_field_see_it_whole`: four threads index and iterate the same container of 5,000 messages at a switch interval of a microsecond, five times; each sees every message, of one object each.\n- `crates/pyspark-rs/src/pbmsg/arena.rs`, new unit tests: the counts of the slabs of an arena of 200 messages (slabs of 4, 8, 16, 32, 64, 64 and 64) through clones released by another thread, `try_unwrap`, `into_parts` (of a shared message and of the only reference), `get_mut`, and releases before and after the arena; a message of its own; the releases of a read in a row (`Releases`); and a slab of 64 released, which the next arena takes again.\n- `test_a_signal_during_the_first_read_of_a_copy_leaves_it_whole` and `test_a_signal_during_the_first_read_of_a_parse_leaves_it_whole` read the last message of the field (`elements[-1]`), as `len()` makes no object now.\n- The tests of the runtime (`tests/test_proto_rust_offline.py`, 186) at the whole-value limit of the runtime (256), at 0 and at 3, under `ulimit -v 4000000`: 186 passed at each. Without `protobuf`: 45 passed and 141 skipped.\n- The lockstep tests of messages, of constructor copies and of parses: 600 seeds each, at the whole-value limits 0 and 256: no failure.\n- The review\u0027s fuzzer of SPARK-62264 (`fuzz_copies.py --aliasing`; 600 seeds of 1,000 steps), at the whole-value limit of the runtime and at 0: the digests of the drop-in\u0027s observations are those of master `afc6be24` for every seed, of either limit, and the same 14 seeds mismatch upb, as before this PR (a pickle of `Any`, and upb\u0027s unset children that its `Clear` and `SyncSubobjs` skip).\n- The gates: `cargo fmt`, clippy 1.100.0, `cargo doc`, the binding\u0027s lib tests (36), ruff, the stub and dispatch generators, the guards and the stub test pass. The offline suite of `coverage.yml`: 7959 passed, 121 skipped, 1 xfailed (under `ulimit -v 16000000`). `tests/test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n- The benchmarks below (µs per call, the best of interleaved rounds of fresh interpreters, each the best of its `timeit` runs; `d90a730e` is the master before SPARK-62266, #973 is `606e700a`; \"read all\" reads `e.string` of every element, \"ListFields all\" is `ListFields` of every message, to the bottom):\n\n  Flat arrays of N strings (`Literal.array.elements`):\n\n  | Array of | Parse: d90a730e | #973 | This PR | Read all: d90a730e | #973 | This PR | vs d90a730e | ListFields all: d90a730e | #973 | This PR | vs d90a730e |\n  |---|---|---|---|---|---|---|---|---|---|---|---|\n  | 100 | 20.22 | 11.76 | 10.98 | 38.34 | 45.51 | 39.17 | +2.2% | 75.71 | 85.88 | 75.83 | +0.2% |\n  | 1,000 | 202.31 | 128.60 | 101.07 | 383.13 | 454.35 | 365.77 | -4.5% | 769.25 | 845.48 | 735.69 | -4.4% |\n  | 10,000 | 2,037 | 1,302 | 1,008 | 3,845 | 4,542 | 3,665 | -4.7% | 7,627 | 8,188 | 7,298 | -4.3% |\n  | 100,000 | 24,774 | 16,461 | 10,354 | 42,958 | 56,613 | 42,598 | -0.8% | 79,462 | 92,210 | 79,513 | +0.1% |\n  | 1,000,000 | 276,598 | 204,797 | 136,371 | 458,241 | 615,081 | 469,612 | +2.5% | 818,381 | 976,912 | 841,174 | +2.8% |\n\n  So a parse read whole takes about as long as on `d90a730e`: from 4.7% less to 2.8% more, where #973\u0027s took 7% to 34% longer. Its parse alone takes about half the time, a third less than #973\u0027s at 100,000 messages and more.\n\n  Plans of `depth` projections of `width` expressions each (`ListFields` of every message):\n\n  | Plan | Parse: d90a730e | #973 | This PR | Read all: d90a730e | #973 | This PR | vs d90a730e |\n  |---|---|---|---|---|---|---|---|\n  | 3x2 | 32.25 | 16.79 | 13.01 | 98.17 | 102.05 | 94.41 | -3.8% |\n  | 5x2 | 50.50 | 26.13 | 20.68 | 153.78 | 161.69 | 149.09 | -3.1% |\n  | 20x10 | 978.30 | 540.22 | 364.23 | 2,938 | 3,269 | 2,913 | -0.9% |\n  | 50x20 | 5,297 | 2,835 | 1,905 | 14,972 | 16,783 | 14,688 | -1.9% |\n\n  The ML client\u0027s reads of the params of a model (`_parse_response` of an `ExecutePlanResponse` whose `ml_command_result.param` is the Literal, then `deserialize_param` of it, as `JavaWrapper._call_java` reads `CountVectorizerModel.vocabulary`, the `labelsArray` of a `StringIndexerModel`, and the coefficients and the idf of models, of N values; \"arrays of strings\" is an array of four arrays of N/4 strings):\n\n  | Case | N | Parse: d90a730e | #973 | This PR | `deserialize_param` of the parse: d90a730e | #973 | This PR | vs d90a730e |\n  |---|---|---|---|---|---|---|---|---|\n  | strings | 100 | 25.16 | 20.82 | 16.93 | 370.05 | 389.55 | 368.69 | -0.4% |\n  | strings | 1,000 | 224.27 | 193.37 | 144.64 | 3,555 | 3,688 | 3,530 | -0.7% |\n  | strings | 10,000 | 2,174 | 1,908 | 1,414 | 35,055 | 36,595 | 34,877 | -0.5% |\n  | strings | 100,000 | 24,792 | 19,578 | 14,285 | 356,212 | 374,768 | 366,471 | +2.9% |\n  | strings | 1,000,000 | 282,315 | 217,655 | 158,562 | 3,603,822 | 3,791,374 | 3,640,256 | +1.0% |\n  | arrays of strings | 100 | 30.89 | 23.91 | 19.87 | 417.44 | 432.45 | 406.51 | -2.6% |\n  | arrays of strings | 1,000 | 232.89 | 198.77 | 147.71 | 3,630 | 3,833 | 3,601 | -0.8% |\n  | arrays of strings | 10,000 | 2,197 | 1,900 | 1,423 | 35,482 | 37,092 | 35,203 | -0.8% |\n  | arrays of strings | 100,000 | 24,972 | 19,279 | 14,355 | 355,809 | 375,353 | 357,248 | +0.4% |\n  | arrays of strings | 1,000,000 | 281,965 | 212,271 | 155,944 | 3,608,386 | 3,788,292 | 3,599,009 | -0.3% |\n  | DenseVector | 100 | 8.29 | 6.50 | 4.88 | 15.81 | 17.88 | 15.10 | -4.5% |\n  | DenseVector | 1,000 | 27.03 | 25.03 | 14.66 | 36.78 | 38.59 | 26.79 | -27.2% |\n  | DenseVector | 10,000 | 212.77 | 207.19 | 109.36 | 240.27 | 238.75 | 138.58 | -42.3% |\n  | DenseVector | 100,000 | 2,157 | 2,117 | 1,148 | 2,456 | 2,417 | 1,454 | -40.8% |\n  | DenseVector | 1,000,000 | 22,653 | 22,770 | 12,850 | 27,133 | 26,953 | 17,727 | -34.7% |\n  | SparseVector | 100 | 11.63 | 9.15 | 6.99 | 45.54 | 48.90 | 44.53 | -2.2% |\n  | SparseVector | 1,000 | 57.88 | 49.79 | 34.13 | 218.83 | 213.72 | 197.38 | -9.8% |\n  | SparseVector | 10,000 | 521.26 | 468.01 | 302.84 | 2,003 | 1,905 | 1,762 | -12.0% |\n  | SparseVector | 100,000 | 5,285 | 4,904 | 3,169 | 18,745 | 18,448 | 16,675 | -11.0% |\n  | SparseVector | 1,000,000 | 58,476 | 52,401 | 37,044 | 197,471 | 191,113 | 176,205 | -10.8% |\n\n  The cases of SPARK-62266 (`to_plan` of Columns, the parses of a plan of 3x2 and of the plan of 20x10 of 2,835 messages, and their reads):\n\n  | Case | d90a730e | #973 | This PR | PySpark (upb) |\n  |---|---|---|---|---|\n  | to_plan col | 2.09 | 1.60 | 1.44 | 0.77 |\n  | to_plan v \u003e 0 | 4.15 | 2.72 | 2.46 | 4.26 |\n  | to_plan concat(a, lit, upper(b)) | 6.19 | 4.00 | 3.55 | 7.91 |\n  | to_plan when/when/otherwise | 9.87 | 6.54 | 5.58 | 17.55 |\n  | to_plan 40 additions | 102.46 | 77.13 | 66.58 | 343.01 |\n  | to_plan v \u003e 0, read all | 8.41 | 8.64 | 7.82 | 8.62 |\n  | to_plan 40 additions, read all | 209.49 | 228.31 | 207.97 | 454.07 |\n  | to_plan v \u003e 0, SerializeToString | 5.15 | 3.65 | 3.36 | 4.61 |\n  | Plan.FromString small plan | 31.72 | 16.78 | 12.92 | 2.15 |\n  | Plan.FromString large plan | 964.61 | 529.23 | 364.88 | 49.42 |\n  | ParseFromString large plan | 966.72 | 529.73 | 363.99 | 98.76 |\n  | FromString small plan, read all | 93.57 | 100.40 | 95.15 | 67.59 |\n  | FromString large plan, read all | 2,777 | 3,246 | 2,901 | 2,009 |\n  | FromString large plan, SerializeToString | 1,164 | 738.94 | 555.76 | 132.95 |\n  | FromString large plan, a path of 3 | 968.46 | 546.31 | 369.43 | 49.69 |\n\n  `SerializeToString` (µs):\n\n  | `SerializeToString` of N strings | d90a730e | #973 | This PR |\n  |---|---|---|---|\n  | 1,000, a parse read whole | 61.98 | 63.26 | 62.05 |\n  | 1,000, a `deepcopy` of it | 46.78 | 48.21 | 47.17 |\n  | 1,000, a parse not read | 62.18 | 47.79 | 47.24 |\n  | 100,000, a parse read whole | 6,246 | 6,432 | 6,266 |\n  | 100,000, a `deepcopy` of it | 4,707 | 4,772 | 4,735 |\n  | 100,000, a parse not read | 6,263 | 4,752 | 4,813 |\n  | 1,000,000, a parse read whole | 69,053 | 69,748 | 70,506 |\n  | 1,000,000, a `deepcopy` of it | 54,817 | 55,652 | 58,041 |\n  | 1,000,000, a parse not read | 69,340 | 55,616 | 56,440 |\n\n  Of a message of a million messages (a `Literal` array of a million strings; CPU s, best of 3):\n\n  | Operation | d90a730e | #973 | This PR | PySpark |\n  |---|---|---|---|---|\n  | parse | 0.280 | 0.167 | 0.129 | 0.049 |\n  | parse, then a read of every message | 0.449 | 0.573 | 0.460 | 0.175 |\n  | the first read of the elements of a parse | 0 | 0.211 | 0 | 0 |\n  | `CopyFrom` of a parse that Python did not read | 0.199 | 0 | 0 | 0.098 |\n  | `CopyFrom`, `deepcopy`, `MergeFrom` of a message that Python read | 0.227, 0.233, 0.234 | 0.203, 0.215, 0.206 | 0.215, 0.228, 0.226 | 0.096, 0.100, 0.091 |\n  | `MergeFrom` into a message that has the repeated field | 0.383 | 0.242 | 0.224 | 0.090 |\n  | constructor of a list of a million messages | 0.241 | 0.212 | 0.230 | 0.323 |\n  | `SerializeToString` of a parse read whole, of a copy | 0.069, 0.056 | 0.070, 0.056 | 0.071, 0.058 | 0.036, 0.040 |\n  | `\u003d\u003d` of parses, of copies | 0.064, 0.052 | 0.053, 0.084 | 0.057, 0.052 | 0.114, 0.115 |\n  | release of a parse not read, of a copy | 0.074, 0.073 | 0.073, 0.074 | 0.038, 0.074 | 0.002, 0.003 |\n  | `CopyFrom` of a parse read and held, after three more parses (6 runs each) | 0.196 to 0.235 | 0.200 to 0.207 | 0.227 to 0.231 | |\n\n  The `CopyFrom` of a parse read and held of a million messages takes 0.23 s after three more parses in each run of this PR, where it took 0.20 s to 0.24 s on `d90a730e` (0.23 s in 2 of 6 runs): glibc trims the top of its heap when a copy is released, so that the next copy faults the 150 MB of its messages in again (37,000 faults). Of the trim turned off (`MALLOC_TRIM_THRESHOLD_`), the `CopyFrom` takes 0.19 s on either. The `CopyFrom`, `deepcopy` and `MergeFrom` of a parse read whole take 5% to 10% longer than of #973, whose reads copied one level of each message in a compact order, and as long as on `d90a730e`; the `SerializeToString` of a `deepcopy` of a million messages read whole, 6% longer than on `d90a730e` (and 1% at 100,000 messages).\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #976 from HyukjinKwon/SPARK-62312-flat-read.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "6b4b5a63614b19f8f4ebaabdb8eccbf350cde10b",
      "tree": "53108439bba2efc11a2357ce9e51f1761a6d28b8",
      "parents": [
        "b1f3f0564a0f0510a0b174f8670739e73d1ba296"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 02:38:32 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 02:38:32 2026 +0000"
      },
      "message": "[SPARK-62314][CONNECT][PYTHON] Document the unset children that upb\u0027s Clear and merges skip, of the addresses of its definitions of the fields, and upb\u0027s read of memory after a parse cut short in a string of a oneof\n\n### What changes were proposed in this pull request?\n\nDocs only. Two behaviours of upb that the drop-in does not have get rows in the protobuf section of `dev/parity/known-differences.md`, and entries in the protobuf runtime of `docs/compatibility.md`. The parse lockstep of SPARK-62266\u0027s tests and the aliasing fuzzer of the review of SPARK-62264 found them.\n\n**1. The unset children that upb\u0027s `Clear` and merges skip** (inherent)\n\nThe intent, in upb and in the drop-in:\n- A message keeps the unset children that Python reads of it, as `r.limit` of an empty `Relation`.\n- `Clear`, and the clear of `ParseFromString`, detach each child.\n- A merge makes each child of a field that the bytes set the parsed message of its field.\n- The drop-in does this for every child. upb skips some.\n\nWhy upb skips:\n- upb keeps the children in its `unset_subobj_map`, an `upb_inttable`. It has 8 slots up to 6 children, keyed by each field\u0027s `upb_FieldDef` address shifted right by 3.\n- A child whose slot is taken goes to the next free slot, chained after the first child of that slot.\n- `Clear` and the merges\u0027 `SyncSubobjs` walk the slots in order and remove each child they visit. Removing the first child of a slot moves the next child into that slot, which the walk has passed. So that child is skipped.\n\nWhat a user sees:\n- **After `Clear`:** the skipped child is still a child of the message, and a write sets it again.\n  - `r \u003d Relation(); s, s2 \u003d r.limit, r.sql; r.Clear(); s2.query \u003d \"x\"`: upb\u0027s `r` holds `sql`, the drop-in\u0027s is empty.\n  - After a `ParseFromString` of a `limit`: upb\u0027s `sql` replaces the parsed `limit`, which the drop-in keeps.\n- **After a merge:** the skipped child is not the parsed message, and a write replaces the parsed value.\n  - Of a `Join` whose `left`, `right` and `join_condition` were read, a `MergeFromString` of all three leaves upb\u0027s `join_condition` child not `j.join_condition`.\n  - A write to it then makes the field `unresolved_attribute { plan_id: 1 }`. The drop-in keeps the parsed `unparsed_identifier` too.\n\nWhy it is inherent:\n- **The rule, fixed by addresses.** The field definitions are 96 bytes apart and 16-byte aligned (protobuf 7.36.2, 64-bit). So two fields share a slot when their places in the message differ by an even number. Where the slots fall is the address of the message\u0027s field definitions modulo 64.\n- **The addresses vary.** They move with what the process allocated before upb built its pool:\n  - the environment and the modules imported before (`numpy`, `pandas` and `pyarrow` changed it);\n  - from one run to the next, the randomization of the process\u0027s addresses (ASLR).\n\n  Under `setarch -R`, runs of the same program and environment are the same whatever the hash seed: 12 runs of random seeds, and seeds 0 to 9. With ASLR on, a fixed `PYTHONHASHSEED\u003d0` still gave 2 sets in 16 runs.\n- **Measured** with a probe of PySpark 4.3.0\u0027s upb, each run a fresh process:\n  - `Clear` of an `AsOfJoin` with its 5 message fields read: 2 sets of skipped children over 40 runs;\n  - with its 6 fields read: 3 sets over 40 runs;\n  - `left`, `left_as_of` and `join_expr`, which share a slot: `join_expr` in 23 of 24 runs, `left_as_of` in 1 (alignments 0 and 16 against 48).\n- **A model** of the table, fed each run\u0027s field-definition addresses (read from upb\u0027s descriptors), predicted all 40 runs for every case of the probe: Clear of 1 to 6 children, merge and parse of 1 to 3, and the oneof.\n- **The stable subset.** With at most two children per slot, every address of this build gives the same result: of each pair in a slot, upb skips the one read second. The model checks this over all four alignments, for 6,612 read orders of up to 4 of 12 fields. This covers the `Relation` and `Join` cases above.\n\n  The drop-in still does not match it. The rule is the layout of one upb build: another protobuf version, or a 32-bit build, groups other fields. Matching it would also keep upb\u0027s stale children and their loss of the parsed message after a merge.\n\nThe fuzzer (`fuzz_copies.py --aliasing`, not in the tree; seeds 0 to 599, 1,000 steps) differed from upb on 14 seeds, and the row names them:\n- **9 of this skip:** 55, 105, 142, 166, 298, 328, 370, 373 and 459. Each is the bytes of a message after a write through a skipped child.\n  - 328: the `ml_command` and `sql_command` children of a `Command`, places 16 and 4, then `Command.Clear()`.\n  - 370: the `with_columns` and `with_columns_renamed` children of a `Relation`, places 22 and 18, then its `ParseFromString`.\n  - The other seven also hold children through a `Clear`, a parse or a merge of their parent before the mismatching write. 328 and 370 are traced in detail.\n- **5 of the pickle of an `Any`:** 175, 394, 408, 410 and 475. Each raises upb\u0027s `TypeError: Parameter to MergeFrom() (or CopyFrom()) must be instance of same class`. The row points to the existing row \"A pickle of the runtime\u0027s `Any` or `Timestamp`\".\n\n**2. A parse cut short in a string of a oneof that held a message** (intentional; upb discloses memory and can end its process)\n\nThe repro:\n```\nliteral \u003d Expression.Literal(string\u003d\"x\" * n)\nliteral.decimal.value \u003d \"1\"\ndata \u003d Expression.Literal(string\u003d\"y\" * 50).SerializeToString()[:-10]\nliteral.MergeFromString(data)  # DecodeError, as in the drop-in\n```\n\nWhat upb does:\n- The oneof holds `string`.\n- The string is the memory of the `Decimal` and what follows it, of the earlier length n.\n- `SerializeToString()` writes it: 102 bytes for n \u003d 100, 10,003 for 10,000 and 1,000,004 for 1,000,000. That discloses the process\u0027s memory, which a request may send to the server.\n- With n \u003d 100,000,000, the process ends with SIGSEGV in `SerializeToString()`.\n\nThe drop-in\u0027s string is empty, and `SerializeToString()` gives 2 bytes.\n\n`docs/compatibility.md` already said that upb reads that memory as the string. It now says what upb\u0027s serialization does with it, and points to the row.\n\n### Why are the changes needed?\n\nItem 90 of the SPARK-62207 follow-ups. These are K\u0027s findings from the lockstep tests of SPARK-62266 (#973) and the aliasing fuzzer: 9 of the fuzzer\u0027s 14 mismatching seeds come from (1). The parse lockstep crashed upb in `SerializeToString` (seed 55) while it truncated merges at random; the test no longer truncates.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. Documentation only.\n\n### How was this patch tested?\n\n- **Probes** against PySpark 4.3.0\u0027s upb (protobuf 7.36.2) and the drop-in at b1f3f056, each case in a fresh process, and the crash in a child process.\n  - `upb_stub_skips.py`: the oneof, `Clear`, merge and parse cases. With a pad allocated before the import, after importing `json`, `numpy`, `pandas` or `pyarrow`, and with fixed and random hash seeds, with and without `setarch -R`.\n  - 40 runs of each with random hash seeds. upb gave 3 distinct results; the drop-in gave the same in every run.\n  - `upb_three_of_a_slot.py`, with and without each source of variation.\n  - `upb_stub_model.py`: the model and its check against the 40 recorded runs.\n  - `upb_oneof_string_crash.py`: string lengths n of 0 to 100,000,000.\n- **The fuzzer seeds** 55, 105, 142, 166, 298, 328, 370, 373 and 459, replayed with `--aliasing --trace` on b1f3f056. All mismatch as recorded.\n- **Gates** (at 51c907b9):\n  - `scripts/check_doc_snippets.py`: 60 Rust snippets compile;\n  - ruff check and format;\n  - the guards of the offline, e2e and live Rust tests;\n  - `git diff --check`.\n  - `mkdocs build --strict` is not installed here; the PR adds no links or navigation, and CI\u0027s docs job runs it.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #975 from HyukjinKwon/SPARK-62314-upb-address-dependent-docs.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "b1f3f0564a0f0510a0b174f8670739e73d1ba296",
      "tree": "c6d3abf00dd3da79b3c24e091f3df6c9e418dd27",
      "parents": [
        "606e700a98b3cb51ac717053fb394a2d48a2af31"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 01:53:28 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 01:53:29 2026 +0000"
      },
      "message": "[SPARK-62310][CONNECT][PYTHON] Dispatch needConversion through the methods of the types that a field, an array, a map and a struct hold, of what they return, as PySpark does, at about twice PySpark\u0027s cost of a field, from 15 times\n\n### What changes were proposed in this pull request?\n\n`StructField.needConversion` cost about 15 times PySpark\u0027s: 895 ns, where PySpark\u0027s takes 60. So did the `_needConversion` that `StructType.add` and the constructor assign, of each field. 2,000 adds took 1.6 s, and PySpark\u0027s 0.12 s. Each call lowered the type that the field holds to its core type, and answered of the core type.\n\nThat also made it differ from PySpark\u0027s in three ways:\n\n- **(a) The values.** A field, an array and a map gave the bool of what the methods of the types that they hold return. PySpark\u0027s return the value as it is: `\u0027yes\u0027` of a subclass whose method returns `\u0027yes\u0027`, `0` of one of `0`, and of a map `key or value`.\n- **(b) Patched classes.** They read the native class of a type, not its method. A patch of `IntegerType.needConversion` reached `IntegerType().needConversion()`, but not a field, an array, a map or a struct of an `IntegerType`.\n- **(c) Inherited methods.** 13 native classes whose PySpark classes inherit `DataType.needConversion` defined their own: `NullType`, `BooleanType`, `ByteType`, `ShortType`, `IntegerType`, `LongType`, `FloatType`, `DoubleType`, `BinaryType`, `DecimalType`, `StringType`, `CharType` and `VarcharType`. A patch of `DataType.needConversion` reached none of them.\n\nThis PR makes them dispatch as PySpark\u0027s.\n\n**The dispatch**\n\n- `StructField.needConversion` is `self.dataType.needConversion()`, `ArrayType`\u0027s `self.elementType.needConversion()`, and `MapType`\u0027s `self.keyType.needConversion() or self.valueType.needConversion()`.\n  - Each returns what the method returns.\n  - Each goes through Python\u0027s lookup of the method, so of a patch, a Python subclass and an attribute of the instance, and of the `AttributeError` of a value that is not a type.\n- `_needConversion` is the list of what the fields\u0027 methods return, and `_needSerializeAnyField` is the bool of `any` of it.\n  - As PySpark\u0027s, the list is assigned first and `any` reads it back. So a value whose truth raises leaves the list assigned and `_needSerializeAnyField` as it was, after `add` too.\n\n**The classes**\n\n- The 13 classes above lose their own method and inherit the native base\u0027s `DataType.needConversion`, which returns `False`.\n- The classes that define their own in PySpark keep theirs:\n  - `True` of `DateType`, `TimestampType`, `TimestampNTZType`, `TimeType`, `DayTimeIntervalType`, `CalendarIntervalType`, `VariantType`, `GeometryType`, `GeographyType` and `StructType`;\n  - `ArrayType`, `MapType` and `StructField`, of the dispatch above (and `UserDefinedType`, of the shim);\n  - `YearMonthIntervalType`, of `PYSPARK_YM_INTERVAL_LEGACY`.\n- `vars(cls)`, and the `__qualname__` and `__doc__` of `needConversion`, are PySpark\u0027s of every class of `pyspark.sql.types` (a probe of all of them, and a test).\n- `YearMonthIntervalType.needConversion` reads `os.environ`, as PySpark\u0027s `os.environ.get(...)` does. It read the environment of the process, so of an `os.putenv` alone, where an array or a field of it read `os.environ`; now each reads `os.environ` through this method.\n\n**Deep types**\n\nA type nested past Python\u0027s recursion limit, or one that holds itself, raises PySpark\u0027s `RecursionError` (\"maximum recursion depth exceeded\").\n- Each level now calls the method of the type that it holds through Python\u0027s call machinery. Where CPython\u0027s check of a call of a native method crosses the limit first, its text ends in ` while calling a Python object`; the drop-in gives PySpark\u0027s text instead.\n- The depth at which it raises is PySpark\u0027s: 996 levels of arrays on the main thread, of a limit of 1000 (master: 997).\n- Threads of 128, 256 and 512 KiB give PySpark\u0027s results, of 400 to 1,100 levels and of types that hold themselves.\n- `dev/parity/known-differences.md` lists `needConversion()` among the uses whose fixed text the drop-in gives.\n\n**The readers**\n\n- `toInternal` and `fromInternal` of the shim read the values and `_needSerializeAnyField` of their truth, as PySpark\u0027s. They are the only readers of them.\n- No native code reads them. The conversions of `createDataFrame` and of the results choose their converters by the types, as PySpark\u0027s `_need_converter` does, and call no `needConversion`.\n\n**Where the time goes now**\n\nThe fidelity costs a call at each level: a field calls the method of its type, an array that of its element, and a map those of its key and its value.\n- PySpark\u0027s interpreter runs each level as a Python method of its own, with specialized lookups, in about 24 ns.\n- The drop-in\u0027s levels cost more. A field of an atomic type costs about 70 ns more than a call of a native method that does nothing (114 ns, against the 42 of `StringType().needConversion`). Each level of an array or a map below it adds about 125 ns. Release builds of variants, for the measurement only, measured:\n  - **the call** of the child\u0027s method through the C API, of the abi3 build (`PyObject_CallMethodObjArgs`: the lookup in the type and in the instance\u0027s `__dict__`, then the call), and PyO3\u0027s trampoline: about 45 to 75 ns a level. Of that, the trampoline\u0027s reference pool locks a mutex at each call of a native method, about 12 ns, as every native method of the extension does;\n  - **the read** of `dataType` or `elementType` of the instance\u0027s `__dict__`: about 15 ns. CPython does not specialize it for a class with a `__dict__` of its own; `StructField.dataType` costs 30 ns, and PySpark\u0027s 19;\n  - **the bound of the recursion and the check of the stack**: under 10 ns.\n- A variant that skipped the calls of exact native children cost 96 ns of a field of an `ArrayType(IntegerType())`, of 304 ns of the same build without the skip, where PySpark\u0027s is 83. That variant ignores patches, subclasses and attributes of the instance. A fast path that keeps them must look the method up as the call does, which costs about as much in the limited API: abi3 has no `_PyType_Lookup`, version tags or dict pointers. So this PR has no fast path.\n\nUnchanged: the core\u0027s `DataType::need_conversion` of the Rust API.\n\n### Why are the changes needed?\n\nItem 87 of the SPARK-62207 follow-ups. `StructField.needConversion` cost 15 times PySpark\u0027s, so the constructors and the adds of wide structs cost 7 to 13 times. Its results also differed from PySpark\u0027s ((a), (b) and (c) above).\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, toward PySpark\u0027s:\n- `needConversion()` of a field, an array or a map returns what the methods of the types that it holds return, as PySpark\u0027s: not a bool, of a subclass whose method returns another value. So do the elements of `_needConversion`. `toInternal` and `fromInternal` read them as before, of their truth.\n- A patch of `needConversion` of a class, or of `DataType`, reaches the fields, arrays, maps and structs of its types.\n- `IntegerType`, `StringType` and the other 11 classes have no `needConversion` of their own. They inherit `DataType`\u0027s, as PySpark\u0027s.\n- `YearMonthIntervalType.needConversion` reads `os.environ`, of the type and of an array, a map or a field of it.\n- `StructField.needConversion` is 3 to 8 times faster, `StructType.add` 5 times, and the constructor of a wide struct 3.5 to 4 times.\n\n### How was this patch tested?\n\n**New tests** (`test_dropin_offline.py`):\n- `test_need_conversion_returns_what_the_methods_of_the_types_return_as_pyspark`\n- `test_structs_keep_and_convert_of_the_values_of_need_conversion_as_pyspark`: the conversions of `toInternal` and `fromInternal` of these values, of tuples, lists, dicts and Rows, and `\u003d\u003d`, hashes, copies and pickles of them\n- `test_need_conversion_reads_patches_of_the_classes_as_pyspark`\n- `test_the_classes_that_define_need_conversion_are_pysparks`\n- `test_year_month_need_conversion_reads_os_environ_as_pyspark`\n- `test_need_conversion_of_deep_types_and_of_types_that_hold_themselves_as_pyspark`\n\nTheir expected values are PySpark 4.3.0\u0027s (the probes below). The first five fail on master: of (a), (a), (b), (c) and `os.environ`. The last passes on master, and keeps the text and the depths of the errors. No existing test asserted the methods of the classes or the bools, so none changed.\n\n**Probes against PySpark 4.3.0**, whose outputs are the same as PySpark\u0027s on this PR:\n- `need_semantics.py`: the native classes, subclasses with and without their own method, values that are not types, UDTs, nested and deep types, the year-month interval of `PYSPARK_YM_INTERVAL_LEGACY`, and patched `IntegerType` and `DataType`. Master differed on 7 of the 35 lines.\n- `need_raw_values.py`: the values of fields, arrays and maps of methods that return a str, `0`, `\u0027\u0027`, and an object whose truth raises. Also of structs:\n  - `_needConversion` and `_needSerializeAnyField`;\n  - `toInternal` and `fromInternal`;\n  - the constructor and `add` of a value whose truth raises;\n  - `\u003d\u003d`, copies and pickles;\n  - a struct of a patched class;\n  - `os.putenv` against `os.environ`.\n\n  Master differed on 13 of the first 28 lines. Then it raised the `ValueError` of the truth of a value in the constructor of a struct whose first field\u0027s value is true, where PySpark\u0027s `any` stops at the true value, so it gave none of the last 12.\n- `need_classes.py`: `vars(cls)`, `__qualname__` and `__doc__` of `needConversion` of the 37 classes of `pyspark.sql.types`. Master differed on 13, the 13 classes above.\n- `need_cycles.py`: types that hold themselves, and 400 to 1,100 nested levels, on the main thread and on threads of 128, 256 and 512 KiB. The same on master.\n\n**Before and after**, against PySpark 4.3.0, on a shared machine (a load of about 3 on 32 cores). Master is 51b986ca. Each number is the best of two rounds, each the best of 7 runs (3 of the adds, 5 of `createDataFrame`), in turn, with the automatic garbage collection off. A call is of a loop of 200,000 calls, of its overhead too.\n\n| | PySpark 4.3.0 | master | this PR | PR / PySpark |\n|---|---|---|---|---|\n| `StructField(StringType()).needConversion` | 60 ns | 895 ns | 114 ns | 1.9 |\n| `StructField(IntegerType())` | 59 ns | 635 ns | 115 ns | 1.9 |\n| `StructField(DateType())` | 59 ns | 635 ns | 116 ns | 2.0 |\n| `StructField(ArrayType(IntegerType()))` | 83 ns | 740 ns | 241 ns | 2.9 |\n| `StructField(ArrayType(DateType()))` | 86 ns | 741 ns | 246 ns | 2.9 |\n| `StructField(MapType(StringType(), IntegerType()))` | 109 ns | 1526 ns | 315 ns | 2.9 |\n| `StructField(MapType(StringType(), DateType()))` | 112 ns | 1522 ns | 324 ns | 2.9 |\n| `StructField` of 3 nested arrays of `IntegerType()` | 159 ns | 925 ns | 496 ns | 3.1 |\n| `StructField` of a struct of 3 fields | 60 ns | 120 ns | 120 ns | 2.0 |\n| `StructField` of a UDT | 60 ns | 552 ns | 118 ns | 2.0 |\n| `StringType().needConversion` | 35 ns | 52 ns | 42 ns | 1.2 |\n| `DateType().needConversion` | 35 ns | 94 ns | 45 ns | 1.3 |\n| `ArrayType(IntegerType()).needConversion` | 59 ns | 634 ns | 117 ns | 2.0 |\n| `MapType(StringType(), IntegerType()).needConversion` | 85 ns | 1395 ns | 190 ns | 2.2 |\n| `StructType` of 3 fields `.needConversion` | 35 ns | 57 ns | 45 ns | 1.3 |\n| `StructField.dataType` | 19 ns | 33 ns | 30 ns | 1.6 |\n| 2,000 adds, with metadata | 124 ms | 1608 ms | 318 ms | 2.6 |\n| `StructType` of 2,000 string fields | 0.20 ms | 1.60 ms | 0.43 ms | 2.2 |\n| `StructType` of 2,000 fields of 5 kinds | 0.26 ms | 1.73 ms | 0.49 ms | 1.9 |\n| `createDataFrame` of 10 rows of 2,000 longs, of a `StructType` | 25.2 ms | 5.7 ms | 5.7 ms | 0.2 |\n| `createDataFrame` of 10 rows of 2,000 longs, of names | 67.7 ms | 12.1 ms | 11.9 ms | 0.2 |\n| `createDataFrame` of 10 rows of 500 fields of 5 kinds | 9.8 ms | 4.2 ms | 4.2 ms | 0.4 |\n\n- A field of a struct costs what it cost: master answered `True` of a struct without a call, where this calls the struct\u0027s method, as PySpark\u0027s.\n- `createDataFrame` calls no `needConversion`, and costs what it cost. Each run includes one request of the configs to a local Spark 4.3.0 server.\n- **The ratios of #970\u0027s test** (`test_struct_type_add_with_metadata_costs_pysparks_and_matches_the_constructor`, bound 3), of a copy of its measurement: the CPU time of the adds over that of PySpark\u0027s needConversions of the same adds is 1.15 of 500 fields and 1.26 of 400 nested ones. Master\u0027s are 0.87 and 0.88, and PySpark\u0027s 1.06 and 1.11. The adds themselves take 20 ms of the 500 fields (master 100, PySpark 8.5) and 26 ms of the nested ones (master 35, PySpark 9.9).\n\n**The gates** (at ebd59fc7):\n- fmt, clippy 1.100.0 (`-D warnings`, of its exit code), doc, and `cargo test -p pyspark-rs --lib` (32 passed);\n- ruff 0.14.0, the no-stub audit, the stub, docstring and dispatch generators (`--check`, no drift: the stubs and the docstrings are of PySpark\u0027s source), the license checks, the guards and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n- the offline suite of `coverage.yml`, under `ulimit -v 16000000`: 7944 passed, 121 skipped, 1 xfailed (master\u0027s PyO3 subclass-cycle test);\n- `test_dropin_e2e.py` against a Spark 4.3.0 server, under `ulimit -v 16000000`: 366 passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #974 from HyukjinKwon/SPARK-62310-need-conversion-speed.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "606e700a98b3cb51ac717053fb394a2d48a2af31",
      "tree": "6b56a3dd3b80439609ca076b6919e4e5695d1688",
      "parents": [
        "d90a730e79fe216dffa9bb66e6a2eff566530e2f"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 00:57:18 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 00:57:19 2026 +0000"
      },
      "message": "[SPARK-62266][CONNECT][PYTHON] Parse into native values of no Python object for each message, and make the objects of a read at once\n\n### What changes were proposed in this pull request?\n\nThe drop-in\u0027s protobuf runtime (`crates/pyspark-rs/src/pbmsg`) parsed bytes into one Python object for each message. `Column.to_plan` parses the bytes of the expression that Rust builds, so the `to_plan` of `F.col(\"s.v\")` took 2.2 µs, against PySpark\u0027s 0.8. The copies of SPARK-62264 already hold what they copy natively (`Slot::Native`) and make the objects of a value when Python first reads it; the parse now does the same.\n\n**The change.**\n- **A native parse** (`codec::NativeParse`). A parse into a message that holds no field reads the bytes into native values, of no object for each message: `FromString`, `ParseFromString`, a `MergeFromString` of an empty message, and the drop-in\u0027s own parses (`parse_deep`, of `Column.to_plan`). It is a port of the parse into an object (`merge_inner`, `merge_field`, `merge_map_entry`): the same values, the errors in the same places, the unknown fields and their runs, closed enums, packed fields, the value of a string of a oneof that fails (upb reads the memory of the member held before), upb\u0027s limit of 100 levels (`Exceeded upb_DecodeOptions_MaxDepth`), and the same state at a failure. The message takes the parsed fields once the parse ends (`PyMessage::take_parsed`): an unset child that it gave out of a field that the parse set takes the parsed message, of every level, as upb\u0027s `SyncSubobjs`. A message that holds fields keeps the parse into objects, as upb\u0027s merge clears the member of a oneof that the message held before it reads the bytes of another member into it.\n- **The objects of a read** (`native::made_of`, `native::Whole`). The first read of a native value of up to 256 messages makes the objects of all its levels at once. A larger value is made of one level, as before, so that a read of a part of it makes the objects of that part. Either way the objects are made empty with no borrow of the message held, set once the field still holds the value, and then given their fields, running no Python code.\n- **The objects copy one level of the value** (`native::object_parts`). A string, bytes or unknown fields of 1 KiB or more, and a repeated scalar field of as much, is moved from a value that no other holds. The value is released once its objects have taken their fields. Of the values moved, as the objects of copies took them before, the memory of the native messages was released in holes between the values that stayed. A million such holes slowed every later allocation of the process down by up to 3.5 times: with a parse of a million messages read and held, the `CopyFrom` of it took 0.72 s after three more parses, master\u0027s 0.21 s. The copies of SPARK-62264 had the same holes once read (0.28 s for that `CopyFrom` of a copy that was read, 0.22 s of one that was not); their reads now copy too.\n- **A type keeps the class that the registry gave it** (`MessageDesc::class`, `kept_class`). Until a registration gives the type another class (`MessageDesc::class_changed`), the objects of a read are made without a lookup of the registry (a mutex and a SipHash of the full name) for each message.\n- The parse reads a run of the elements of a repeated message field without a lookup of the field and its messages for each element. `parse_deep` makes its message as `FromString` does, without a call of the class, and `Column.to_plan` reads `pyspark.sql.connect.proto` of the module imported once. A field and a map keep the message type of their values once it is looked up (`FieldDesc::message_type`, `MapDesc::value_message`).\n\n**Behaviour.** What Python reads is upb\u0027s, as before: the identity of the objects that a field gives, the bytes, the text, `\u003d\u003d`, presence, the errors and their order, the unknown fields, `DiscardUnknownFields`, the `DecodeError` of the limit of levels (at the same depth, of the same message), and `MergeFromString` and `ParseFromString` into existing messages: into an unset child, of any level, which is set in its parent, into a message that gave out unset children, and into a message of a container or of a map. The messages made at a read are not tracked by the garbage collector, as those of a copy are not. The objects are made later than before, at the first read rather than at the parse, as upb makes its objects: `gc.get_objects()` lists them once they are read.\n\n### Why are the changes needed?\n\nA Column\u0027s `to_plan` and a parse of a plan made an object for each message, which a plan that copies the message never reads. A Column of PySpark\u0027s API is turned into its message at each request, and the message is copied into the plan (natively, since SPARK-62264), so the objects were made for nothing.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo change of behaviour. Performance only (see the tables below): `to_plan`, the parse and a copy of a parse take less time; the first read of what a parse holds makes its objects then, so a parse read whole takes about as long as before: 4% to 14% longer of plans, up to 31% of a flat array of 100,000 messages.\n\n### How was this patch tested?\n\n- `python/tests/test_proto_rust_offline.py`, new tests:\n  - `test_parses_into_unset_children_and_held_messages_are_upbs`: 19 cases, compared with upb\u0027s. A parse into an unset child (of two levels too, of no bytes and of bytes that fail), into a message that gave out unset children of fields that the parse sets and does not set, into a message of a container and of a map. The reads, clears, merges and parses again of what a parse made, with the identities of what they give. `DiscardUnknownFields`, and the limit of 100 levels.\n  - `test_random_operations_on_parsed_messages_agree_with_upb` (6 seeds; 600 seeds once): the lockstep\u0027s random operations on messages that `FromString`, `ParseFromString` and `MergeFromString` parse, and parses again into them and into their messages, compared after each with upb\u0027s (bytes, presence, oneofs, text, identities).\n  - `test_a_collection_during_the_first_read_of_a_parse_finds_the_message`: a collection at each allocation of the first read (of 17, 255, 262 and 2,103 messages, so of both kinds of read), whose callback reads the whole message, finds it free and whole; the field gives the objects of the read from then on.\n  - `test_a_signal_during_the_first_read_of_a_parse_leaves_it_whole`: a signal during the first read of a repeated field of 200,000 messages of a parse interrupts it and leaves the message whole.\n- `test_python_thread_runs_before_operations_on_large_messages_finish[*-parse]` and `[*-map parse]` now tell that the parse is in progress by its reference to its data, as the parse makes no object.\n- The existing tests of the parse (`test_corrupt_bytes_fail_and_keep_what_upbs_parse_keeps`, `test_messages_that_fail_to_parse_keep_what_they_read_as_upbs`, `test_parse_errors_are_protobufs_decode_errors_as_upbs`, `test_messages_of_more_than_100_levels_fail_where_upb_parses_their_bytes`, ...) now run through the native parse: 181 passed under `ulimit -v 4000000`; without `protobuf`, 42 passed and 139 skipped.\n- The lockstep tests of messages, of constructor copies and of parses: 600 seeds each, no failure.\n- The review\u0027s fuzzer of SPARK-62264 (`fuzz_copies.py --aliasing`; 600 seeds of 1,000 steps), whose new messages are parses, on this PR and on master `afc6be24`: the digests of the drop-in\u0027s observations are the same for every seed. The same 14 seeds mismatch upb on both, as before this PR (a pickle of `Any`, and upb\u0027s unset children that its `Clear` and `SyncSubobjs` skip; see below).\n- The gates (`cargo fmt`, clippy 1.100.0, `cargo doc`, the binding\u0027s lib tests, ruff, the stub and dispatch generators, the guards, the stub test) pass. The offline suite of `coverage.yml`: 7939 passed, 121 skipped, 1 xfailed (under `ulimit -v 16000000`). `tests/test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n- The benchmark (µs per call, the best of interleaved rounds of fresh interpreters, each the best of 3 `timeit` runs; master is `afc6be24`, PySpark is pyspark-client 4.3.0 of upb; \"read all\" is `ListFields` of every message, to the bottom):\n\n  | Case | Master | This PR | PySpark |\n  |---|---|---|---|\n  | `to_plan` of `col(\"s.v\")` | 2.13 | 1.67 | 0.77 |\n  | `to_plan` of `v \u003e 0` | 4.09 | 2.75 | 4.18 |\n  | `to_plan` of `concat(a, lit(\"x\"), upper(b))` | 6.06 | 3.93 | 7.78 |\n  | `to_plan` of `when/when/otherwise` | 9.83 | 6.39 | 17.36 |\n  | `to_plan` of 40 additions (161 messages) | 98.78 | 75.92 | 342.69 |\n  | `to_plan` of `v \u003e 0`, read all | 8.46 | 8.73 | 8.60 |\n  | `to_plan` of 40 additions, read all | 213.30 | 230.69 | 456.47 |\n  | `to_plan` of `v \u003e 0`, `SerializeToString` | 5.17 | 3.65 | 4.61 |\n  | `Plan.FromString`, small plan (6 expressions, 95 messages) | 31.94 | 15.54 | 2.15 |\n  | `Plan.FromString`, large plan (200 expressions, 2,835 messages) | 965.18 | 503.19 | 49.02 |\n  | `ParseFromString`, large plan | 968.05 | 501.32 | 99.25 |\n  | `FromString`, small plan, read all | 94.84 | 98.91 | 67.54 |\n  | `FromString`, large plan, read all | 2875.62 | 3217.30 | 2041.00 |\n  | `FromString`, large plan, `SerializeToString` | 1165.26 | 714.08 | 132.80 |\n  | `FromString`, large plan, a path of 3 (`root.project.input.project.expressions[0]`) | 964.58 | 522.97 | 49.77 |\n\n  The parse alone, and the parse read whole, by size (µs; plans of `width` projections of `depth` levels, and `Literal` arrays of strings):\n\n  | Case | Master parse | This PR parse | Master read all | This PR read all |\n  |---|---|---|---|---|\n  | plan 5 × 2 | 50.34 | 24.47 | 157.01 | 163.72 |\n  | plan 20 × 10 | 963.10 | 514.89 | 2970.39 | 3343.04 |\n  | plan 50 × 20 | 5224.54 | 2690.81 | 15123.33 | 17303.67 |\n  | array of 100 | 20.74 | 13.57 | 37.79 | 45.42 |\n  | array of 1,000 | 205.05 | 130.73 | 374.29 | 437.17 |\n  | array of 10,000 | 2155.93 | 1300.30 | 3872.91 | 4579.47 |\n  | array of 100,000 | 25861.44 | 16435.74 | 43037.15 | 56565.73 |\n\n  So the time that a read of every message adds is less than what the parse saves, of plans (26% to 86% of it) and of arrays of 1,000 and 10,000 messages (85% and 83%), and about as much of an array of 100 (106%) and of a million (104%, below): a plan read whole takes 4% to 14% longer than before, and its parse alone half the time. A flat array of 100,000 messages read whole takes 31% longer, more than its parse saves (144% of it): its objects are made in a pass of their own over memory that no longer fits the caches.\n\n  Of a message of a million messages (a `Literal` array of a million strings; CPU s, best of 3):\n\n  | Operation | Master | This PR | PySpark |\n  |---|---|---|---|\n  | parse | 0.283 | 0.171 | 0.050 |\n  | parse, then a read of every message | 0.463 | 0.580 | 0.174 |\n  | the first read of the elements of a parse | 0 | 0.214 | 0 |\n  | `CopyFrom` of a parse that Python did not read | 0.203 | 0 | 0.097 |\n  | `CopyFrom`, `deepcopy`, `MergeFrom` of a message that Python read | 0.229, 0.236, 0.236 | 0.200, 0.206, 0.208 | 0.097, 0.102, 0.093 |\n  | `MergeFrom` into a message that has the repeated field | 0.387 | 0.245 | 0.093 |\n  | constructor of a list of a million messages | 0.245 | 0.209 | 0.326 |\n  | `SerializeToString`, `\u003d\u003d`, release of a parse | 0.070, 0.065, 0.075 | 0.070, 0.054, 0.074 | 0.038, 0.115, 0.002 |\n  | `CopyFrom` of a parse read and held, after three more parses | 0.200 | 0.209 | |\n\n  The read of a value of 256 messages or fewer makes its objects at once; a larger one is made a level at a time, so a read of a part of a large parse makes the objects of that part only.\n\nDifferences from upb that this PR keeps as they are (master has them, and the fuzzer finds them on both): upb\u0027s `Clear` of a message that gave out three unset children or more, and its `SyncSubobjs` of a parse or a copy into such a message, skip one of them after each that they take, in an order of the addresses of their fields (`r \u003d Relation(); s, s2 \u003d r.limit, r.sql; r.ParseFromString(b); s2.query \u003d \"x\"` sets `sql` in upb\u0027s `r`, and not in the drop-in\u0027s).\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #973 from HyukjinKwon/SPARK-62266-native-parse.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "d90a730e79fe216dffa9bb66e6a2eff566530e2f",
      "tree": "43edcefad32fc7f2bb8f4518918bb67ffbc90ab6",
      "parents": [
        "51b986cafc6ed0ace9a0acfadca3678c66c1ee79"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 00:37:33 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 00:37:33 2026 +0000"
      },
      "message": "[SPARK-62307][CONNECT][PYTHON] Release the server-side object of a native ML model of the Python client when Python finalizes the model, as PySpark\u0027s __del__ does\n\n### What changes were proposed in this pull request?\n\nPySpark 4.3.0 releases the server-side object of a Spark Connect ML model in `JavaWrapper.__del__`, which runs when Python finalizes the model. That includes the collector finalizing a reference cycle that holds it, since the collector runs every finalizer of a cycle before it breaks it. So a model that a finalizer of the cycle saves has lost its object: its members, its summary\u0027s members and its transforms raise `CONNECT_ML.CACHE_INVALID`.\n\nThe native models of the Python client released their object only when their Rust value was dropped, so a saved model kept working. This PR releases it when Python finalizes the model, as PySpark does:\n- **Core.** `CachedModelRef` has a `released` flag, which keeps its drop from deleting twice. A hidden `MlRef::release()` deletes the object once, through the same path as a drop, so exit, fork and threads with no active session behave as before. It does nothing for kept or referenced objects. A hidden `Model::training_summary()` is added too.\n- **Binding.**\n  - A model, its copies and its training summary share a count of their holders that Python has not finalized yet, and of the clones of the object that those holders keep.\n  - At the finalization of the last holder, the object is released, if every clone of it belongs to the holders. Otherwise the last drop deletes it, as before.\n  - Nothing runs Python in `tp_clear`, and no traverse changes. A miscount can only hold back a release, never cause an early one.\n- **Docs.** `docs/compatibility.md` has a bullet for a model of a fit or a load. `dev/parity/known-differences.md` documents what remains:\n  - when other holders of the object, such as a transform, a member DataFrame or a writer, still live at the last finalization, the deletion waits for them;\n  - KMeans, BisectingKMeans and GaussianMixture keep the release at the drop, as their summary dataset is a transform of the model;\n  - an explicit `__del__` releases a holder once.\n\n### Why are the changes needed?\n\nTo release the object of the server when PySpark releases it, so that a model that a finalizer saves behaves as PySpark\u0027s.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes: a model that a finalizer saves from a collected cycle has lost its server object, as in PySpark. Plain drops, copies and transforms that outlive the model keep their behavior.\n\n### How was this patch tested?\n\n- **New tests, which fail without the change:**\n  - An offline test of the Delete of a model saved from a collected cycle, with a summary and without, and of explicit `__del__`, plain drops, and summaries, transforms and copies that outlive the model.\n  - A live test of a model that a finalizer saves, of a fit with a summary, a fit of no summary and a load. It passes on PySpark 4.3.0 too.\n  - A core test of a release that deletes once.\n- **Probes against pyspark-client 4.3.0:**\n  - the resurrection shape of the review: 13 of 13 labels equal (2 differed before);\n  - 41 finalization shapes: 1 difference, documented: a kept transform keeps PySpark\u0027s model reachable;\n  - the clustering models: the documented remainder.\n- **The usual checks:** core tests, the binding\u0027s tests, clippy, rustdoc, rustfmt, ruff, the vendored check, the ML offline tests (2000), the GC tests of the offline suite, the offline suite under coverage (93.797%), and the live and no-protobuf e2e (639 and 452).\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Code\n\nThis pull request and its description were written by Isaac.\n\nCloses #972 from HyukjinKwon/SPARK-62307-ml-release-at-finalize.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "51b986cafc6ed0ace9a0acfadca3678c66c1ee79",
      "tree": "d89857f444de167ff1c08a3b0f88129cfc64a6f1",
      "parents": [
        "6c5ddbfd604167e59672fde393790f5a66076a32"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 00:31:29 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 00:31:29 2026 +0000"
      },
      "message": "[SPARK-62309][CONNECT][PYTHON] Make the tests of the checkpoints of the native conversions and of the cost of StructType.add independent of the scheduling and the load of the machine\n\n### What changes were proposed in this pull request?\n\nTwo tests failed under the load of a shared machine. This PR makes them deterministic, and keeps what each tests.\n\n**1. The checkpoints of the native conversions**\n\n`test_python_thread_runs_before_native_conversion_finishes` (`local_data_conversion_cases.py`) checks two things of each part of the native conversion of `createDataFrame`: another thread runs in it, and a signal interrupts it. It asserted this at a checkpoint that the operating system happened to schedule the other thread at, so five runs could all miss it. Master\u0027s Coverage run 45237312367 saw `{\u0027conversion_ended_at\u0027: ...}` with no `progress` in all five. `test_python_thread_runs_before_operations_on_large_messages_finish` (`test_proto_rust_offline.py`) used the same probe, with the same retries.\n\n- **The probe** (`_local_data_conversion_probe.py`) now takes its turn at each checkpoint itself. A profile function of the conversion\u0027s thread waits at each call that the conversion makes, until the probe\u0027s thread has taken its reading. Those calls are of the Python function of the conversion\u0027s checkpoints, every 1,024 steps (`ConversionBudget`), or of the Python code that an operation runs, as `MutableMapping.update` of a map of scalars. So:\n  - the reading falls at every checkpoint, of no scheduling;\n  - a part with no checkpoint is still read at none. A check: the probe reads nothing of a `list.sort` of ints, and reads a sort of a Python key.\n- **The signal:** with `cancel`, the probe interrupts the main thread at the checkpoint where it read the part. The handler raises before the checkpoint returns to the conversion, as it did.\n- **Each case runs once:** the retries go. So does the size that scheduling needed: 16,384 rows, values or messages, from 262,144, steps enough for checkpoints in each part. Every case still reads its part at a call of the checkpoint function of the native code (checked of each layout).\n- **Time:** the 42 cases take about 15 s, as they did on an idle machine (master: 18 s).\n\n**2. The cost of `StructType.add`**\n\n`test_struct_type_add_with_metadata_is_linear_and_matches_the_constructor` bounded 2,000 adds by 3 s of wall clock. That took about 2 s of an idle machine and 3.5 s of a loaded one. \"Linear\" was of each add: PySpark\u0027s add assigns `_needConversion` again of `[f.needConversion() for f in self]` at each add, so a loop of adds is quadratic in PySpark too. Of 500, 1,000, 2,000 and 4,000 adds, PySpark took 8, 32, 127 and 519 ms. A ratio of the times of n and 2n adds is therefore about 4 in both clients, of a good add and of a slow one alike, and cannot tell them apart.\n\nThe test, now `test_struct_type_add_with_metadata_costs_pysparks_and_matches_the_constructor`, compares two CPU times of this thread instead:\n- **The comparison:** the loop of adds against PySpark\u0027s own work of the same adds, the needConversions of the fields so far at each, of the same fields.\n- **The measurement:** each is the least of three runs, in turn, with the automatic garbage collection off. So the ratio is of their work, not of the load of the machine, which the CPU time of a thread does not count.\n- **The ratios:** the drop-in\u0027s add costs 0.88 of that work and PySpark\u0027s 1.06. The bound is 3. An add that reads every field and its JSON on each call costs 15.7 of it (the add that the test was written against took about 17 s for 2,000 fields).\n- **The sizes:** 500 fields and 400 nested ones, from 2,000 and 1,500. The equality of the struct with the constructor\u0027s is of no size, and stays.\n\n### Why are the changes needed?\n\nThe two tests failed CI under load. No code of the drop-in changes.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. Only tests change.\n\n### How was this patch tested?\n\n- **Under load:** each test was run 50 times, each run a pytest process of its own, under `ulimit -v 16000000`. Meanwhile release builds of the core and the binding ran from scratch in another worktree, four in a row, of 12 jobs (a load average of 11 to 26 on 32 cores). No run failed:\n  - `test_python_thread_runs_before_native_conversion_finishes`: 50 of 50 (18 cases each);\n  - `test_python_thread_runs_before_operations_on_large_messages_finish`: 50 of 50 (24 cases each);\n  - `test_struct_type_add_with_metadata_costs_pysparks_and_matches_the_constructor`: 50 of 50.\n- **On PySpark 4.3.0**, which the struct test runs on too: it passes.\n- **The gates** (at dd41252d):\n  - fmt, clippy 1.100.0, doc, and `cargo test -p pyspark-rs --lib` (32 passed);\n  - ruff 0.14.0, the no-stub audit, the stub and dispatch generators, the license checks, the guards and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`, under `ulimit -v 16000000`: 7937 passed, 121 skipped and 1 xfailed (master\u0027s PyO3 subclass-cycle test);\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server, under `ulimit -v 16000000`: 366 passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #970 from HyukjinKwon/SPARK-62309-deterministic-timing-tests.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "6c5ddbfd604167e59672fde393790f5a66076a32",
      "tree": "575ecca669f2d46c0a37c35c088cd49c8cc58e41",
      "parents": [
        "a335af726ab6155209d4c6f108b0f65f756d01dd"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 00:29:49 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Tue Nov 24 00:29:49 2026 +0000"
      },
      "message": "[SPARK-62306][CONNECT][PYTHON] Build the relation of a DataFrame of a member of an ML summary, or of a transform, at its request, as PySpark does\n\n### What changes were proposed in this pull request?\n\nThe DataFrames of the members of an ML training summary, and of a model\u0027s transform, built the relation of their dataset when the member was read or the transform was called. Building the relation is when the functions of the dataset\u0027s UDFs are pickled. So with a training DataFrame that held a UDF function that does not pickle, `job.p \u003d summary.predictions` raised `PicklingError`.\n\nPySpark 4.3.0 builds that child relation each time the plan is built: in `AttributeRelation.plan()` for summary members, and in `TransformerRelation.plan()` for transforms. So it returns the DataFrame and raises only at a request (`count`, `schema`, `columns`, `explain`, ...), again at each request.\n\nThis PR does the same:\n- **Core.**\n  - `LogicalPlan::MlTransform` gains a hidden `input_at: MlInputAt` (`Nowhere`, `TransformInput` or `SummaryDataset`). At request time, `to_proto_with` puts the relation of its `input` into the `Transform.input`, or into the `model_summary_dataset` of a clone of the node\u0027s `ml_relation`.\n  - Transforms of cached models, `VectorAssembler`, the feature transformers and the meta transformers now build their input at the request. So do the members of summaries, through `attribute_relation`.\n  - The node\u0027s input, owner and garbage-collection parts are unchanged.\n- **Unchanged, eager as in PySpark:** methods whose DataFrame arguments PySpark serializes at the call, such as `ChiSquareTest.test`, `Correlation.corr`, `PowerIterationClustering.assignClusters`, the LSH joins and `evaluate(df)`.\n- **Binding.** The transform of a DataFrame of another session builds its relation at the request too.\n- **Docs.** `docs/compatibility.md` describes when the plans are built, and has a Rust migration note on `MlTransform.input_at`.\n\n### Why are the changes needed?\n\nTo raise where PySpark raises, so that a program can keep such a DataFrame, for example in a cycle, and only fails when it is used.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes: these DataFrames raise the errors of building their dataset at their requests, not when they are made, as in PySpark.\n\n### How was this patch tested?\n\n- **New tests, each checked to fail without the change:**\n  - An offline test of LinearRegression, LogisticRegression and KMeans summary members, transforms and `VectorAssembler`, which raise only at a request, and of `ChiSquareTest.test` and `evaluate`, which raise at the call.\n  - A live test of the same, and of the transform of a DataFrame of another session. It passes on PySpark 4.3.0 too.\n  - A Rust test, with a counting and failing pickler, of one pickling per request and none at the member or the transform.\n  - A new shape of the GC cycle test, in which the predictions are kept after the model.\n- **Probes against pyspark-client 4.3.0:**\n  - every summary member of 7 models, transforms, and the helper methods: 273 labels, 0 differences (171 before);\n  - the transform of a DataFrame of another session: 0 differences.\n- **The usual checks:** core tests (1976), the binding\u0027s tests, clippy, rustdoc, rustfmt, ruff, the vendored check, the ML offline (2000) and live (816) tests, the GC tests of the offline suite, and the offline suite under coverage (93.797%).\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Code\n\nThis pull request and its description were written by Isaac.\n\nCloses #971 from HyukjinKwon/SPARK-62306-lazy-ml-relations.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "a335af726ab6155209d4c6f108b0f65f756d01dd",
      "tree": "e196f2b1507753109f94fbd60037628cfec9e52b",
      "parents": [
        "f71ddd17716f25a7e96d4d61a6760822de32ca3f"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 23:16:25 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 23:16:26 2026 +0000"
      },
      "message": "[SPARK-62303][CONNECT] Box the large fields of the variants of LogicalPlan that few plans have, so that a node of a plan is 184 bytes, from 648\n\n### What changes were proposed in this pull request?\n\nEach node of every plan of the core is the size of the largest variant of `LogicalPlan`, and every DataFrame derived from another has one node of its own. On master (f71ddd17, after #968 made every input a `SharedPlan` of 16 bytes) that size is 648 bytes. The largest variant, `GroupMap` (641 bytes), holds an inline UDF expression of 232 bytes, a state schema of 104 and a `TransformWithStateInfo` of 152. Most plans are projections, filters and aliases of a few dozen bytes, which paid the same 648.\n\nThis PR boxes the large fields of the variants that few plans have:\n\n| Variant | Field boxed | Before | After |\n|---|---|---|---|\n| `GroupMap` | `func`, `state_schema`, `transform_with_state_info` | 641 | 177 |\n| `MlTransform` | `ml_relation` (a `proto::Relation` of 352) | 384 | 40 |\n| `ApplyInPandasWithState` | `func` | 376 | 152 |\n| `CoGroupMap` | `func` | 320 | 96 |\n| `MapPartitions` | `func` | 281 | 57 |\n| `Unbuildable` | `error` (a `SparkError` of 248) | 272 | 32 |\n| `CommonInlineUdtf` | `return_type` | 229 | 133 |\n| `Catalog` | `catalog` (a `proto::Catalog` of 184) | 192 | 16 |\n| `Read` | `read_type` (a `ReadType` of 168) | 177 | 17 |\n\nVariant sizes are from `-Zprint-type-sizes`.\n\n- **The new size:** the largest variants are now `Parse`, `GroupMap` and `AsOfJoin` (177 bytes), of the 16 bytes of each of their inputs, so a node is 184 bytes.\n- **The test:** `plan::layout_tests::a_node_of_a_plan_is_184_bytes` pins it, and the 16 bytes of `SharedPlan`, so that a new field cannot make it grow again unseen.\n- **The lint:** the `allow(clippy::large_enum_variant)` of the enum goes, as it no longer applies.\n\nThe constructors of the core (the reads, the ML transforms, the maps of groups and cogroups, the UDTFs, the catalog, `unbuildable`) wrap the boxed fields. `plan_to_proto` reads through them, and so do the tests that build or match these variants: four unit tests of the reader and five integration test files. The `SharedPlan` inputs, their bits and the parts of the plans of #968 are untouched.\n\n### Why are the changes needed?\n\nItem 75 of the SPARK-62207 follow-ups (the user kept the object-state design) and the gc-aware review of #956: the memory and the time of the native plan of each DataFrame. The kept DataFrames of a session hold their nodes, and the plan IDs of a session keep each node\u0027s allocation alive until they prune it, so the size of a node is paid for every DataFrame.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo behaviour change. The fields hold what they held, and the plans, their relations and their errors are the same.\n\nFor the Rust API, the types of these fields of `LogicalPlan` change, a public enum. Code that builds or destructures these variants wraps or dereferences their boxes. The DataFrame API is unchanged.\n\n### How was this patch tested?\n\n- **New test:** `layout_tests::a_node_of_a_plan_is_184_bytes`.\n- **Before and after**, against a Spark 4.3.0 server on a shared machine. Before is master at f71ddd17.\n  - The review\u0027s `bench_dataframe_gc.py` (ns per operation with `gc.enable()`, the best of 5 repeats of three runs) and `gc_time.py` (100k kept DataFrames).\n  - The RSS per kept object, each case in a fresh process: 100k objects after 1000 warm-up ones, with the GC on.\n\n**RSS per kept object** (bytes, the mean over 100k objects):\n\n| Object | Before | After | PySpark 4.3.0 |\n|---|---|---|---|\n| `df.alias(\u0027a\u0027)` | 1793 | 1358 | 365 |\n| `df.limit(1)` | 1728 | 1327 | 368 |\n| `df.filter(\"id \u003e 0\")` | 1907 | 1503 | 557 |\n| `df.filter(c \u003e 0)` | 2303 | 1897 | 2540 |\n| `df.select(\u0027id\u0027)` | 2219 | 1778 | 1533 |\n\nSo each derived DataFrame is about 400-440 bytes smaller, the 464 bytes of its node less the allocator\u0027s rounding.\n\n**100k kept `filter` DataFrames** (`gc_time.py`, the best of 3 rounds):\n\n| | Before | After |\n|---|---|---|\n| build them | 528 ms | 519 ms |\n| `gc.collect()` over them | 74 ms | 75 ms |\n| RSS | +189 MB | +145 MB |\n| drop them and collect | 84 ms | 79 ms |\n\nThe rows over a UDF plan run in the same process after these, of their freed memory, so their RSS (114 and 110 MB) is not of the nodes alone.\n\n**ns per operation** (`bench_dataframe_gc.py`, the best of 3 rounds):\n\n| Operation | Before | After |\n|---|---|---|\n| `df.select(\u0027id\u0027)` | 2854 | 2884 |\n| `df.filter(c \u003e 1)` | 3591 | 3638 |\n| `df.withColumn(\u0027v\u0027, c + 1)` | 3835 | 3713 |\n| `df.alias(\u0027a\u0027)` | 1639 | 1610 |\n| `df.limit(1)` | 1533 | 1495 |\n| `DataFrame(df._plan, spark)` | 613 | 625 |\n| 100 chained `select`s | 310 us | 307 us |\n\nThe times are the same within the noise of the shared machine (a load of about 9), as the nodes are allocated once and moved into their `Arc`.\n\n- **The gates** (at 263f8d5a):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy --workspace --all-targets -- -D warnings`, and of the three crates;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 32 passed;\n  - the release crate tests of `rust.yml`:\n    - `cargo test -p apache-spark-connect -p apache-spark-connect-core --release`: 1976 passed, 18 ignored;\n    - `--features datafusion,polars`: 1451 passed;\n  - ruff, the no-stub audit, the stub and dispatch generators, the license checks, the guards and `test_type_stubs_offline.py`;\n  - the offline suite of `coverage.yml`, under `ulimit -v 16000000`: 7936 passed, 121 skipped, 1 xfailed (master\u0027s PyO3 subclass-cycle test), and 1 failed: `test_struct_type_add_with_metadata_is_linear_and_matches_the_constructor`, a timing bound of 3.0 s that took 3.49 s while the crate tests built beside it. It passes alone, twice, and does not touch plans;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server, under `ulimit -v 16000000`: 366 passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #969 from HyukjinKwon/SPARK-62303-plan-box.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "f71ddd17716f25a7e96d4d61a6760822de32ca3f",
      "tree": "6311e06ed050930e64fef2a7d33de66852569a7f",
      "parents": [
        "0cec9b1c59cd27f1ac0eb803c76e10f9b6b5e3c3"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 22:31:13 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 22:31:14 2026 +0000"
      },
      "message": "[SPARK-62305][CONNECT][PYTHON] Skip the parts of plans and expressions of no Python object in the garbage collection of the Python client, of a bit of each node\n\n### What changes were proposed in this pull request?\n\nSince #921 (SPARK-62235), the Python client\u0027s garbage-collection support walks every part of a plan or an expression, and keeps an entry of each, also of parts that hold no Python object below them. That made creating 10^5 plain DataFrames about 1.65× slower, and `col + i` Columns about 14% slower. This PR keeps one bit per node of the core\u0027s plans and expressions: \"a pickler or an owner is at or below this part\". The parts of no Python object are then neither walked nor known, and get no `SharedPart`.\n- **Core.**\n  - A new `plan::SharedPlan { node: Arc\u003cLogicalPlan\u003e, objects: bool }` is the type of every input field of a `LogicalPlan` (except `MlTransform.input`).\n  - `Expression`\u0027s node carries its bit too.\n  - A `DataFrame` carries the bit of its root beside its `Arc`, so a derivation reads it in O(1).\n  - The bit comes from the same `plan_parts`/`expression_parts` walk as `Part::held`, through a `Held` sink trait, so the two cannot drift. A hidden `PartRef::Node` carries a known bit.\n- **Binding.** `Parts::of`, `resolve` and `shared_parts_of` skip the parts whose bit is false.\n- **Clone check.** `SharedPlan::clone` tells the clone check, so it sees the clones of plan inputs too. More threaded offline tests run the watch of the reported parts.\n- **Docs.** The \"Rust migration for the 4.4 line\" section of `docs/compatibility.md` covers `SharedPlan`. The helpers take a `LogicalPlan`, a `Box` or an `Arc`, as before. `AGENTS.md` section 15 states the bit\u0027s rule.\n\n### Why are the changes needed?\n\nTo recover most of the cost that the garbage-collection support added to plain DataFrames and Columns.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo behavior change; it is faster. The Rust API\u0027s plan nodes take `SharedPlan` inputs, which the migration note covers.\n\n### How was this patch tested?\n\n- **Benchmarks (10^5 objects, best of several, against master):**\n\n  | Case | master | this PR |\n  |---|---|---|\n  | plain DataFrames | 139 ms | 91 ms |\n  | `col + i` Columns | 904 ms | 814 ms |\n  | 20000 filters of a plan of 2000 UDF columns | 35.8 ms | 32.8 ms |\n  | 20000 filters of a plan of 2000 plain columns | 26.4 ms | 17.3 ms |\n\n  UDF-bearing cases are unchanged. Memory is flat.\n- **Tests:**\n  - A test checks that the bit equals a full walk for every kind of plan and expression, including Sent subqueries and a GroupMap\u0027s `initial_input`, with false cases.\n  - A test checks that a part of no object is neither walked nor known.\n  - The clone check catches a planted GIL-free clone of a plan input.\n  - Eight mutations of the walk are all caught.\n- **Independent review: safe to merge.**\n  - 53 cycle shapes, one per input kind, plus subqueries, pickles, ML transforms and Observation owners, are collected as on master.\n  - A 120 s stress run with the clone check and the watcher on found 0 violations.\n- **Combined with #967 (SPARK-62304):** an owner counts as an object below a part, so the ML owners\u0027 parts are walked; 214 GC-related Python tests pass on the combination.\n- **The usual checks:** core tests (release, debug and wasm), the binding\u0027s tests, clippy, rustdoc, rustfmt, ruff, stubs, the offline suite under coverage, and e2e with and without protobuf.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Code\n\nThis pull request and its description were written by Isaac.\n\nCloses #968 from HyukjinKwon/SPARK-62305-gc-node-bit.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "0cec9b1c59cd27f1ac0eb803c76e10f9b6b5e3c3",
      "tree": "597d4b9c3949a3547ab2a1f52e7a5de7c93cec3a",
      "parents": [
        "608056523e1da586a60dcb4aea61ead53107800e"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 22:20:06 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 22:20:07 2026 +0000"
      },
      "message": "[SPARK-62290][SPARK-62292][CONNECT][PYTHON] Resolve the session of a DataFrame at its requests, and follow up the review of its `__dict__`\n\n### What changes were proposed in this pull request?\n\nTwo follow-ups of SPARK-62218 (#956), each in its own commits:\n- SPARK-62290 resolves the session of `_session` at the requests of a DataFrame, as PySpark does, and no longer in the methods that only make a plan.\n- SPARK-62292 covers the seven findings of the gc-aware review of #956, all LOW.\n\n**1. SPARK-62290: the session at the requests** (27d8a78e)\n\nA DataFrame\u0027s methods resolved its session (`self._session.client`) as they were called, also those that only make a plan. So a `_session` that is not a session raised at the method, where PySpark\u0027s raises at the request.\n\nThe read of a DataFrame is now two (`dataframe.rs`):\n- `PlanFrame::of` reads `_plan` and `_session` for a method that makes a plan. For the plan object of a DataFrame of the drop-in, it resolves no session: the method\u0027s plan is made of that plan object\u0027s plan, and the new DataFrame takes `_session` as it is.\n- `PlanFrame::request` (and `Frame::of`) is the read of a request. It resolves the session of `_session`, and gives the plan its plan IDs in that session through the identity cache, as before.\n\nThese read the plan alone:\n- the DataFrame\u0027s methods that make a plan, from `select` to `transpose`, and `observe`, `Observation._on`, `Column.isin` of a DataFrame and `_NativePlan(df)`;\n- `GroupedData.agg` and the plans of the maps of groups and cogroups. A DDL string of a return type is parsed of `_session` only then, as PySpark\u0027s `self._session._parse_ddl`.\n\nAlso:\n- The methods of two DataFrames compare the `session_id` of their sessions, as PySpark\u0027s `_check_same_session`. The plan of the other one gets its plan IDs in the session of the first one\u0027s plan when they differ.\n- The schema properties (`_schema`, `schema`, `columns`, `dtypes`) read `_cached_schema` first, as PySpark\u0027s `_schema`, and make a request only when there is none.\n\nA `_plan` of the Python client is still built, of the client of `_session`, by the first method that reads its plan, as the plans of the core are made of the plans of their inputs. The KD row says so.\n\n**2. SPARK-62292: the review findings** (a92b5798)\n1. **A replaced `_plan` was kept alive by the identity cache.** The DataFrame now drops the plan object that it built of a `_plan` of the Python client, or of the plan object of a DataFrame of another session, together with that `_plan`. It drops them at its first read of another `_plan` and at `__init__`, out of the lock. A flag spares the lock while it built none. PySpark frees the replaced plan at the assignment itself, which runs no code of the drop-in, so this stays a KD row (freed at the next read).\n2. **14 methods gave the core\u0027s session object as `_session`, not the DataFrame\u0027s.** Their DataFrames now take the DataFrame\u0027s `_session` (`self._df._session` for grouped data), as PySpark\u0027s `DataFrame(plan, session\u003dself._session)`. These are the aggregations of grouped data, their maps with and without state, the maps of cogroups, `mapInPandas`, `mapInArrow`, `crosstab`, `freqItems`, `replace`, `fillna` and `dropna`, and so `df.na` and `df.stat`.\n3. **Column lookups built a `_plan` that is not a plan object of the drop-in.** `_col`, `__getattr__`, the str items of `__getitem__` and its star, `colRegex`, `metadataColumn` and the as-of columns of `_joinAsOf` read `self._plan._plan_id`, as PySpark\u0027s. They use new doc-hidden constructors of the core (`Column::reference_of_plan`, `star_of_plan` and `regex_of_plan`). So:\n   - they build no plan and read no session;\n   - with `_session` deleted they give a Column, where they recursed into a `RecursionError`;\n   - a `_plan` that is not a plan raises the `AttributeError` of `_plan_id`, where they gave a Column.\n4. **`toLocalIterator()` read `_plan` and `_session` at the call.** It now reads them, and takes the parts of its plan, at the first row, as the body of PySpark\u0027s generator does.\n5. **A second `__init__` of a live DataFrame reset its native state.** The mutable borrow raised \"Already borrowed\" while a request of it ran on another thread, after the entries were already reassigned. It also reset the answers of `isLocal` and `semanticHash`. `__init__` now keeps the native state, as PySpark\u0027s class-level `functools.cache` keeps those answers. It drops the plan object of the old `_plan` and the schema that the core cached, and allocates no second native state.\n6. **Docs:**\n   - concurrent first reads of `_schema` send one analysis, where each of PySpark\u0027s threads sends its own;\n   - the plan object of a replaced `_plan` lives until the next read;\n   - the DataFrame is added to the classes of the subclass-cycle row (the same PyO3 limit as SPARK-62267\u0027s).\n\n   Item 4 needs no row, as it is fixed.\n\n**3. SPARK-62292: cheaper DataFrames** (4976d028), finding 7:\n- (a), the clone of the core DataFrame at each call of a method that makes a plan, is gone with SPARK-62290: the plan read borrows the plan object. #964 (SPARK-62293) made the core session one Arc.\n- (b), the second native state of `__init__`, is gone with finding 5.\n- (c): the `_cached_schema` of a method that keeps the schema of its input is now an entry of `__init__`, in its place in the `__dict__`, not a `setattr` afterwards.\n- The traverse of a DataFrame takes no lock while it converted no plan.\n- The execution that `_execution_info` was last set of is boxed, as most DataFrames never execute.\n\n**The changes:**\n- **`crates/pyspark-rs/src/dataframe.rs`:**\n  - `PlanFrame` and `Frame`;\n  - `plan_id_object`, `plan_id_value` and `column_of_plan`;\n  - `PyDataFrame::conversion_of` and `forget_conversion_unless`;\n  - the free schema reads `schema_entry`, `schema_property`, `property_schema` and `column_names_of`, of the object alone;\n  - `return_type_of`, and `map_result_of` of the session;\n  - the methods over them.\n- **`group.rs`, `stat_arguments.rs`, `observation.rs` and `column.rs`:** the plan reads and the sessions of their DataFrames. `plan_args::df_col` is removed.\n- **`crates/spark-connect`:** `Column::{reference_of_plan, star_of_plan, regex_of_plan}`, which `DataFrame::{column_reference, star, col_regex, metadata_column}` now use.\n- **Docs:** the KD rows \"The `__dict__` of the objects of a session\" and the subclass-cycle row, and `docs/compatibility.md` (the state of a DataFrame, the GC holders).\n\n### Why are the changes needed?\n\nSo that a DataFrame is PySpark\u0027s in where it reads its session and its plan:\n- its methods that make a plan, its Column lookups and its schema properties of a cached schema work of any `_session`, as PySpark\u0027s;\n- its derived DataFrames keep its `_session`, also a proxy;\n- `toLocalIterator` reads it at its first row.\n\nIt also fixes the \"Already borrowed\" of a second `__init__` while a request runs and the retention of a replaced `_plan`, and it makes a new DataFrame cheaper.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, towards PySpark\u0027s behaviour:\n- **A `_session` that is not a session**, or a proxy whose `client` raises, no longer raises at the methods that make a plan, at the Column lookups, or at the schema properties of a cached schema. Their requests raise, as PySpark\u0027s.\n- **The DataFrames of the methods of grouped data, the maps and the statistics and null functions** keep the DataFrame\u0027s `_session`.\n- **`df.id`, `df[\"id\"]`, `df[\"*\"]`, `df._col(\"id\")`, `colRegex` and `metadataColumn`** read `self._plan._plan_id`:\n  - of a `_plan` of the Python client, they build nothing;\n  - of a `_plan` that is not a plan, they raise the `AttributeError` of `_plan_id`.\n- **`toLocalIterator()`** reads the DataFrame at its first row.\n- **A second `__init__`** works while a request runs, and keeps the answers of `isLocal`, `semanticHash`, `isEmpty` and `inputFiles`.\n- **The two-DataFrame methods** compare the `session_id`s of the sessions, of their errors.\n\n### How was this patch tested?\n\n- **New tests, each passing on both clients and failing on the base (ad32575f):**\n  - `test_the_methods_of_a_dataframe_that_make_plans_resolve_no_session_as_pyspark` (SPARK-62290);\n  - `test_the_dataframes_of_the_methods_keep_the_session_of_their_dataframe_as_pyspark`;\n  - `test_the_columns_of_a_dataframe_are_of_the_plan_id_of_its_plan_as_pyspark`;\n  - `test_to_local_iterator_reads_its_dataframe_at_its_first_row_as_pyspark`;\n  - `test_a_dataframe_initialized_again_keeps_its_answers_as_pyspark`;\n  - `test_a_dataframe_frees_the_plan_that_it_built_of_a_replaced_plan_as_pyspark`.\n- **The review\u0027s probes of findings 1-5** (`beh_cache_retention`, `beh_proxy_session`, `beh_col_nonown`, `beh_badplan`, `beh_iterator_timing`, `conc_reinit`, `beh_reinit_caches`), re-run on this PR, the base and PySpark 4.3.0. Each now gives PySpark\u0027s output, but for these:\n  - `beh_cache_retention`\u0027s case of no read after the replacement (the KD row);\n  - the message of the `TypeError` of a request of a deleted `_session` (residue (b), the native transport).\n\n  On the base:\n  - 14 methods lost the proxy;\n  - 3 of the 4 retention cases kept the plan;\n  - the Column lookups of a Python plan recursed or built it;\n  - a re-init raised \"Already borrowed\";\n  - a re-init cost 2 analyses.\n- **The probe of deleted entries** (`_session`, `_plan` and the four others, against seven calls each): `select` and `filter` of a deleted `_session` now give PySpark\u0027s DataFrames. Only the transport\u0027s `TypeError` message differs.\n- **Coverage:** the offline suite of `coverage.yml` under `coverage.py` (`.coveragerc`): 93.84% (6938 of 7256 lines and 2512 of 2814 branches), against the floor of 93.0.\n- **The gates** (at 4976d028):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 32 passed;\n  - `cargo test -p apache-spark-connect -p apache-spark-connect-core --release --lib`: 858 and 426 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - `gen_connect_docstrings.py --check`, `check_classic_bindings.py` and the tooling tests of `scripts/tests`;\n  - the offline suite of `coverage.yml`, under `ulimit -v 16000000`: 7933 passed, 121 skipped, and 1 xfailed, master\u0027s test of the PyO3 limit of the subclass cycle (SPARK-62267);\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server, under `ulimit -v 16000000`: 366 passed.\n\n**The numbers with the GC on** (finding 7): the review\u0027s `bench_dataframe_gc.py` (`timeit` with `gc.enable()`, ns per operation, the best of 5 repeats of two runs) and `gc_time.py` (100k kept DataFrames), against a Spark 4.3.0 server on a shared machine. Before is master at ad32575f.\n\n| Operation | Before | After | PySpark 4.3.0 |\n|---|---|---|---|\n| `df.select(\u0027id\u0027)` | 3757 | 3430 | 63494 |\n| `df.filter(c \u003e 1)` | 4945 | 4698 | 69230 |\n| `df.withColumn(\u0027v\u0027, c + 1)` | 5173 | 4803 | 70450 |\n| `df.alias(\u0027a\u0027)` | 2383 | 2117 | 2138 |\n| `df.limit(1)` | 2354 | 2022 | 2197 |\n| `DataFrame(df._plan, spark)` | 680 | 626 | 307 |\n| `df._plan` | 44 | 45 | 24 |\n| `df._session` | 45 | 45 | 24 |\n| `df[\u0027id\u0027]` | 1005 | 972 | 1928 |\n| `df.id` | 1225 | 1315 | 2376 |\n| 100 chained `select`s | 393 us | 374 us | 6308 us |\n\n| 100k kept DataFrames of `filter` | Before | After | PySpark 4.3.0 |\n|---|---|---|---|\n| build them | 680 ms | 647 ms | 671 ms |\n| GC-tracked objects per DataFrame | 5 | 5 | 5 |\n| `gc.collect()` over them | 83 ms | 77 ms | 67 ms |\n| RSS | +200 MB | +194 MB | +56 MB |\n| drop them and collect | 124 ms | 123 ms | 33 ms |\n| build them, over a UDF plan | 868 ms | 835 ms | 679 ms |\n| GC-tracked objects per DataFrame, over a UDF plan | 6 | 6 | 5 |\n| `gc.collect()` over them, over a UDF plan | 141 ms | 132 ms | 72 ms |\n| RSS, over a UDF plan | +125 MB | +119 MB | +54 MB |\n| drop them and collect, over a UDF plan | 177 ms | 176 ms | 34 ms |\n\nA derived DataFrame is now as fast as PySpark\u0027s of `alias` and `limit`, and still far faster of an expression.\n\nWhat remains of the gap is mostly the memory of the native plan, and with it the time to free it:\n- RSS is about 1.9 KB per kept DataFrame, against PySpark\u0027s 0.56 KB.\n- Dropping and collecting 100k of them takes 3.7 times PySpark\u0027s time.\n- `LogicalPlan` of the core is 632 bytes, the size of its largest variant, for every node. That variant is `GroupMap`, of an inline UDF expression of 232 bytes, a state schema and a `TransformWithStateInfo`.\n- Boxing those fields, and those of `MlTransform`, `ApplyInPandasWithState`, `CoGroupMap`, `MapPartitions`, `Unbuildable`, `Catalog` and `Read`, would make it about 170 bytes, about 460 bytes less per derived DataFrame.\n- A trial of it is 54 changes across 15 files of the core, most of them constructors of `pyspark.ml`, so it is left out of this PR.\n\n`df.id` costs about 90 ns more, as it reads the `_plan_id` property of `self._plan`, as PySpark\u0027s `_col` does.\n\n- **Rebased onto master afc6be24** (with SPARK-62287, #963), every changed line identical to 4976d028 (on ad32575f), whose code the gates above ran on; ruff, `gen_type_stubs.py --check`, `cargo fmt --check` and clippy 1.100.0 with `-D warnings` pass on the rebased tree.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #966 from HyukjinKwon/SPARK-62292-dataframe-followups.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "608056523e1da586a60dcb4aea61ead53107800e",
      "tree": "8d14be0e3bd4a1b4b41918be3778a995f2028739",
      "parents": [
        "edea610beca25c4fb0dcb1a96700081e289a96a5"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 22:18:54 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 22:18:54 2026 +0000"
      },
      "message": "[SPARK-62304][CONNECT][PYTHON] Collect the reference cycles through the DataFrames that the native ML models of the Python client keep, as PySpark collects them\n\n### What changes were proposed in this pull request?\n\nThe native ML classes of the Python client keep DataFrames in Rust that Python\u0027s garbage collector did not see:\n- a model\u0027s training summary dataset;\n- the binary training sets of the models of a OneVsRestModel;\n- the summary dataset and argument plans of a DataFrame of a method of an ML object or helper, such as `summary.predictions`, `ChiSquareTest.test` or an `FPGrowthModel`\u0027s.\n\nSo a reference cycle through them was never collected, for example a function of a UDF of the training DataFrame that keeps the model. The model then stayed in the server\u0027s ML cache. PySpark collects such a cycle and deletes the model\u0027s object.\n\nThis PR reports those DataFrames\u0027 parts to the collector, under the rules of #921 (SPARK-62235):\n- **Core.** Hidden `Model::held_parts` and `Model::clear_held_parts`, both empty by default.\n  - A `training_summary_parts!` macro implements them for the 10 models with a summary: LogisticRegression, LinearSVC, FMClassification, MultilayerPerceptron, LinearRegression, GeneralizedLinearRegression, RandomForestClassification, KMeans, BisectingKMeans and GaussianMixture.\n  - OneVsRestModel, PipelineModel, CrossValidatorModel and TrainValidationSplitModel pass them on to their models.\n  - `Part::held` of an owner reports the parts of a `RelationTarget` (`ml::owner_parts`), and `attribute_relation` tells the clone check of its new references.\n- **Binding.**\n  - `ModelCore` holds `Parts` of its summary and of the core model\u0027s summaries. They are made in `fitted` and `duplicate`, reported in `__traverse__`, and released in `__clear__` and before `bind` or `give_up_object` replaces the model.\n  - The summary classes and the generic OneVsRest submodel get `Parts`, `GcReady`, `__traverse__` and `__clear__`.\n  - The transform of a model marks the parts of the model\u0027s copy busy.\n  - OneVsRestModel no longer keeps its fit datasets.\n- **Docs.** The native-ML bullet of the \"Garbage collection\" row of `dev/parity/known-differences.md` is removed. `docs/compatibility.md` states what the native ML objects report.\n\n### Why are the changes needed?\n\nWithout it, a model in such a cycle stays alive, with its object in the server\u0027s ML cache, fit after fit, where PySpark frees both.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes: cycles through these DataFrames are now collected, and their model\u0027s object is deleted from the ML cache, as in PySpark. The Rust API gains hidden, defaulted methods only.\n\n### How was this patch tested?\n\n- **New tests:**\n  - A core test of the exact reference counts of `held_parts` for LinearRegression, KMeans, OneVsRest, Pipeline, CrossValidator and TrainValidationSplit models, summaries and summary-method DataFrames.\n  - `test_the_cycles_through_a_udf_of_the_training_dataset_of_a_model_are_collected_as_pysparks`, for 4 models in 4 shapes plus OneVsRest. It fails without the change: every shape left its models alive.\n  - Fitted models with summaries in the creation-time traverse test and in the GIL-watch test.\n- **Probes against pyspark-client 4.3.0:**\n  - 10 estimators in 4 shapes, OneVsRest, summary-method and helper DataFrames, Pipelines, validators and `fitMultiple`: no differences.\n  - 300 fits in cycles keep tracked objects, the ML cache and RSS flat.\n- **Independent review: safe to merge.**\n  - A live watch of 4 threads making 44 kinds of ML call, with the clone check on, found 0 violations in 3 runs.\n  - An invariant scan of every SharedPart after 27 operations found 0 over-counts.\n- **The usual checks:** core tests, the binding\u0027s tests, clippy, rustdoc, rustfmt, ruff, stubs, the offline suite under coverage, the ML offline and live tests, and e2e with and without protobuf.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Code\n\nThis pull request and its description were written by Isaac.\n\nCloses #967 from HyukjinKwon/SPARK-62304-ml-gc-summaries.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "edea610beca25c4fb0dcb1a96700081e289a96a5",
      "tree": "11ac5c7892300860a56fc4fdbcc22b19c2bdb435",
      "parents": [
        "afc6be24d923014134024a65df574e98c4506a9c"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 22:11:33 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 22:11:33 2026 +0000"
      },
      "message": "[SPARK-62302][CONNECT] Add config, configs, app_name, master and create to the SparkSessionBuilder of the Rust API, as PySpark\u0027s SparkSession.Builder\n\n### What changes were proposed in this pull request?\n\n`SparkSessionBuilder` of the Rust API had only `remote` and `get_or_create`. This PR adds what PySpark 4.3.0\u0027s Spark Connect `SparkSession.builder` has:\n- `config(key, value)` and `configs(pairs)`, as PySpark\u0027s `config(key, value)` and `config(map\u003d...)`.\n  - The options keep the order in which they were first given, and a later value of a key replaces the earlier one, as PySpark\u0027s `_options` dict does.\n  - A `bool` is written `true` or `false`, as PySpark\u0027s `to_str` writes it.\n- `app_name(name)`, which sets `spark.app.name`, as `appName`.\n- `master(url)`, which has no effect, as PySpark\u0027s `master` over Spark Connect.\n- `create()`.\n\n`remote(url)` is now `config(\"spark.remote\", url)`, as in PySpark, so `config(\"spark.remote\", url)` works the same way.\n\nOnce the session connects, it gets the options as configurations in one silent `ConfigRequest.Set`, except `spark.remote` and `spark.master`, as PySpark\u0027s `_apply_options` does.\n\nThe Rust API keeps no active or default session, so `get_or_create` creates a session at each call, as `create` does, where PySpark\u0027s `getOrCreate` returns its active or default session. `docs/compatibility.md` (\"Rust migration for the 4.4 line\") and `docs/configuration.md` say so.\n\n### Why are the changes needed?\n\nWithout them, Rust users could not set session configurations, or an application name, when building a session, only with `spark.conf().set(...)` afterwards.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes: new methods on `SparkSessionBuilder` of the Rust API. Existing code keeps working.\n\n### How was this patch tested?\n\n- A unit test of the options\u0027 order, replacement, `remote`/`app_name`/`master`/`bool` handling, the configurations sent, and the error of no remote.\n- A live e2e test against a Spark 4.3.0 server, in `e2e_session_catalog.rs`: the session gets the builder\u0027s configurations, with a later value replacing an earlier one; `app_name` (a static configuration) is set silently, as in PySpark; and `create` makes a new session.\n- The doc example of `SparkSessionBuilder` compiles.\n- `e2e_session_catalog` (15) and `e2e_integration` (20) pass against the server; the lib tests (859), clippy, rustdoc, rustfmt, the tooling tests and the no-stub audit pass.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Code\n\nThis pull request and its description were written by Isaac.\n\nCloses #965 from HyukjinKwon/SPARK-62302-builder-config.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "afc6be24d923014134024a65df574e98c4506a9c",
      "tree": "05a2c20193a0846483221c66dbd207b136936f1b",
      "parents": [
        "ad32575ffa0b8bcd040390ce389004b81d838a86"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 21:33:43 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 21:33:44 2026 +0000"
      },
      "message": "[SPARK-62287][CONNECT][PYTHON] Make copy.deepcopy of the objects of the native classes of the data types of a native copier, of the copies and the memo of Python\u0027s protocol\n\n### What changes were proposed in this pull request?\n\nPySpark\u0027s data types are plain classes. `copy.deepcopy` copies them through `object.__reduce_ex__(4)` and `copy._reconstruct`: a new object of `cls.__new__(cls)`, kept in the memo, and then the deep copy of its `__dict__`, which `__dict__.update` sets. Since #957 and part 3 of SPARK-62251 (#961), the drop-in\u0027s native classes give the same reduce, so Python\u0027s `copy` makes PySpark\u0027s copies and memo. But it runs more Python code for each object than PySpark\u0027s does: a deep copy of a struct of 1,000 fields took 8.1 ms, where PySpark 4.3.0 takes 5.9 ms and part 2 took 6.4 ms. `DataFrame.schema` is such a copy, of the cached schema, as PySpark\u0027s.\n\n- **A native copier of exact classes.** `pyspark.sql.types` registers a copier of the extension in `copy`\u0027s dispatch of exact classes (`copy._deepcopy_dispatch`), for the 13 singleton classes and the 13 classes whose state is their `__dict__` (the types of parameters, `StructField`, `ArrayType`, `MapType` and `StructType`). `copy.deepcopy` looks the dispatch up by `type(x)`, so a subclass keeps Python\u0027s protocol.\n- **Python\u0027s copies and memo.** The copier makes what `copy.deepcopy` and `_reconstruct` make of these objects, step by step:\n  - the memo lookup first, also of an atomic object;\n  - `cls.__new__(cls)`, kept in the memo, and the deep copy of the `__dict__`;\n  - of a dict and a list in it, what `_deepcopy_dict` and `_deepcopy_list` do: the value before the key, as Python evaluates `y[deepcopy(key)] \u003d deepcopy(value)`, and the iteration of `items()`, of its `RuntimeError` of a dict that a copy changes;\n  - of any other object, `copy.deepcopy` itself, of the memo;\n  - the same entries of the memo and of its list of `_keep_alive`, in the same order, also of a memo that is not a dict, through its `get` and `__setitem__`;\n  - `__dict__.update` of the new object, which has no `__setstate__`, and the `copyreg._slotnames` of the class that `object.__reduce_ex__` reads;\n  - of a singleton, the instance, which the memo holds as its own copy, as the drop-in\u0027s reduce of `_parse_datatype_json_string` gives it.\n- **Python\u0027s hooks.** The copier checks, of each class once in a copy, that the class\u0027s MRO gives what it gave when the copier was registered for `__deepcopy__`, `__reduce_ex__`, `__reduce__`, `__getstate__`, `__setstate__`, `__new__`, `__getattribute__`, `__getattr__`, `__slotnames__`, `json` and `jsonValue`. It also checks that `copyreg.dispatch_table` has no entry for the class, and, of a singleton, that `pyspark.sql.types._parse_datatype_json_string` is the function that its reduce names. Of each object, it checks that its own `__dict__` has none of those hooks. Otherwise it calls Python\u0027s protocol as `copy.deepcopy` does past the dispatch: `__deepcopy__`, the reduce of the dispatch table, `__reduce_ex__(4)`, `__reduce__`, `copy.Error`, and `_reconstruct`.\n- **Recursion.** It counts the frames of Python\u0027s `copy` as levels of the interpreter\u0027s recursion (`Py_EnterRecursiveCall`), and the frames below `_reconstruct` too. On Python 3.11, whose frames count with C calls, its `RecursionError` comes at the same depths as Python\u0027s: from 100 nested structs and 248 nested arrays, as PySpark 4.3.0\u0027s. It grows its stack, so a thread of 128 KiB raises that `RecursionError` where PySpark\u0027s overflows the stack. From Python 3.12, which counts the frames of Python apart from C calls, a type of more levels than Python\u0027s limit copies where Python\u0027s protocol raises.\n- **Docs.** `docs/compatibility.md` describes the copier, its hooks and its recursion. The KD item of the depths of nested types states the thread of 128 KiB, and the inherent item of singletons states their memo entry.\n\n### Why are the changes needed?\n\nTo make `copy.deepcopy` of the data types, and so `DataFrame.schema`, faster than PySpark\u0027s again, of PySpark\u0027s copies and memo, since part 3 copies a struct as PySpark\u0027s plain class.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo change of what a copy is or of the memo, but its speed. A thread of 128 KiB raises `RecursionError` for a deep copy of about 100 nested structs, where it overflowed the stack.\n\n### How was this patch tested?\n\n**Offline tests.** Three tests are new:\n- of the copies of the native copier against those of Python\u0027s protocol, with the copier taken out of `copy`\u0027s dispatch: the classes of the objects, the originals that the copy shares, the entries of the memo and its list of `_keep_alive`, of 12 cases and of a memo of a dict subclass;\n- of PySpark 4.3.0\u0027s copies and memo of a struct that holds a field twice, a field that holds itself, a list of the same struct, and a memo that holds a type already, as literal descriptions;\n- of the hooks: a subclass of its own `__reduce_ex__`, an object of its own `__deepcopy__`, an entry of `copyreg.dispatch_table`, and a `__deepcopy__` patched over a native class.\n\nThey also pass on pyspark-client 4.3.0.\n\n**Lockstep against pyspark-client 4.3.0.** A probe of 16 cases, each of a dict memo and of a memo of a dict subclass, describes the copies and the memo of no address:\n- the native copier, Python\u0027s protocol of the drop-in (the copier out of the dispatch) and part 3 give the same for all 32;\n- PySpark 4.3.0 gives the same for 30. The 2 that differ are of a struct of singletons, which is the inherent difference of the KD: their copy is the instance, which the memo holds as its own copy, where PySpark\u0027s copy is another object, kept alive.\n\n**Recursion depths**, of the first depth that raises, on the main thread of Python 3.11:\n\n| | PySpark 4.3.0 | part 3 | This PR |\n|---|---|---|---|\n| `copy.deepcopy` of nested structs | 100 | 99 | 100 |\n| `copy.deepcopy` of nested arrays | 248 | 248 | 248 |\n\nOn a thread of 256 KiB, all three raise from 100 nested structs. On one of 128 KiB, PySpark\u0027s and part 3\u0027s overflow the stack from 100, and this PR raises `RecursionError` from 100.\n\n**Probes against pyspark-client 4.3.0** match as for part 3: 1,339/1,339 of the types of parameters, 2,061/2,061 of arrays, maps and fields, 1,680/1,684 of structs, 18/18 of the copies by identity, 49/49 of the pickles of `__slots__` subclasses, 316/341 of nested types (part 3\u0027s 25: `RecursionError` texts and three uses of 600 levels), and SPARK-62219\u0027s and SPARK-62230\u0027s 369/370 and 152/152.\n\n**Speed.** The minimum of 7 interleaved rounds against part 3 (at d62fdd2f, before its rebase, of the same code), of the copies and of the guardrail paths:\n\n| Path | Base | This PR | Ratio |\n|---|---|---|---|\n| `copy.deepcopy` of 1,000 fields | 7,929 µs | 3,385 µs | 0.43 |\n| `copy.copy` of 1,000 fields | 2.6 µs | 2.5 µs | 0.96 |\n| a pickle of 1,000 fields | 2,444 µs | 2,410 µs | 0.99 |\n| a pickle of 40 levels | 434 µs | 433 µs | 1.00 |\n| `json()` of 1,000 fields | 4,229 µs | 4,231 µs | 1.00 |\n| `json()` of 40 nested levels | 1,577 µs | 1,607 µs | 1.02 |\n| `json()` of 1,000 decimals | 4,679 µs | 4,754 µs | 1.02 |\n| `json()` of 300 arrays of maps | 5,245 µs | 5,253 µs | 1.00 |\n| proto of 1,000 fields | 1,184 µs | 1,188 µs | 1.00 |\n| proto of 40 nested levels | 574 µs | 578 µs | 1.01 |\n| proto of 1,000 decimals | 1,341 µs | 1,345 µs | 1.00 |\n| proto of 300 arrays of maps | 1,502 µs | 1,503 µs | 1.00 |\n| proto of 8 fields | 12.4 µs | 12.2 µs | 0.98 |\n| a cast\u0027s plan of 1,000 fields | 1,389 µs | 1,400 µs | 1.01 |\n| a cast\u0027s plan of 40 nested levels | 945 µs | 1,015 µs | 1.07 |\n| a cast\u0027s plan of 1,000 decimals | 1,558 µs | 1,536 µs | 0.99 |\n| `df.to` of 1,000 fields | 301 µs | 302 µs | 1.00 |\n| `df.to` of 1,000 decimals | 305 µs | 309 µs | 1.02 |\n| `df.to` of 8 fields | 4.6 µs | 4.6 µs | 1.00 |\n| `df.to(1,000 fields).schema` | 8,322 µs | 3,794 µs | 0.46 |\n| `createDataFrame` of 200 rows of 20 longs | 387 µs | 406 µs | 1.05 |\n| `createDataFrame([], 1,000 fields)` | 4,063 µs | 4,146 µs | 1.02 |\n| `createDataFrame` of 200 rows of a decimal, a string, a time and a long | 517 µs | 539 µs | 1.04 |\n| `createDataFrame` of a pandas frame of 1,000 rows of 3 longs | 1,368 µs | 1,378 µs | 1.01 |\n| `toInternal` of such a row | 5.3 µs | 5.4 µs | 1.02 |\n| `fromInternal` of such a row | 11.1 µs | 11.0 µs | 0.99 |\n| a UDF column of a decimal return type | 263 µs | 284 µs | 1.08 |\n| a UDF column of a struct of 1,000 fields | 2,687 µs | 2,840 µs | 1.06 |\n| `mapInPandas` of 1,000 fields | 1,475 µs | 1,524 µs | 1.03 |\n| `mapInPandas` of 8 fields | 64.6 µs | 65.1 µs | 1.01 |\n\n`df.to(1,000 fields).schema` is PySpark\u0027s `copy.deepcopy` of the cached schema. No path but the copies runs code of this PR; of the three that the minima put above 1.05 (a cast\u0027s plan of 40 levels 1.07, a UDF column of a decimal 1.08, `createDataFrame` of 200 rows of 20 longs 1.05), the medians of 6 to 8 alternating loops of 2 seconds are 1.01, 0.98 and 1.01. PySpark 4.3.0 takes 5.9 ms for the deep copy of 1,000 fields, and part 2 took 6.4 ms.\n\n**Gates:**\n- build, rustfmt, clippy (1.100.0), rustdoc, ruff, the stub audit, the generators, the guards, the licenses and the stub tests pass.\n- `pyspark-rs` lib tests: 32 passed.\n- The offline suite: 7,616 passed, 121 skipped, 110 xfailed.\n- e2e against Spark 4.3.0: 361 passed.\n- `scripts/check_vendored_upstream.sh` was not run, as no vendored path is touched.\n\n- **Rebased onto master e7a0883f** (the merge of #961, SPARK-62251 part 3), with every changed line identical to fc189bad, whose code the gates above ran on (7f0227e9).\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #963 from HyukjinKwon/SPARK-62287-deepcopy.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "ad32575ffa0b8bcd040390ce389004b81d838a86",
      "tree": "c2bf65f511d80620798d79a33ff84e14b7f60681",
      "parents": [
        "0a7cd513deef0d132ac243f186db9763a4c9ae3b"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 19:24:35 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 19:24:36 2026 +0000"
      },
      "message": "[SPARK-62218][CONNECT][PYTHON] Keep the state of a DataFrame in its `__dict__`, as PySpark\u0027s, of a plan object that holds the plan of the core\n\n### What changes were proposed in this pull request?\n\nThis is the last sub-task of SPARK-62207, after SPARK-62208 (#926) to SPARK-62214 (#954) and SPARK-62217 (#953, the Column, the WindowSpec and the TableArg). It covers the DataFrame of `pyspark.sql.connect.dataframe`.\n\nPySpark\u0027s Connect DataFrame is a plain Python object. Its `__init__` sets six entries of its `__dict__`, and its methods read and set them:\n- `_plan`, its plan object, and `_session`, its session, which its requests read as `self._plan.to_proto(self._session.client)`;\n- `_support_repr_html`, which `_repr_html_` sets and `__repr__` reads;\n- `_cached_schema` and `_cached_schema_serialized`, which `_schema` sets of a request and `schema` loads;\n- `_execution_info`, which the actions and the writers\u0027 callbacks set and `executionInfo` gives.\n\n`isStreaming` is a `functools.cached_property`, which keeps its answer in the `__dict__` too. The drop-in\u0027s DataFrame kept all of this in its native state, so `vars(df)` was empty, `df._plan` was a new object at each read, and `df._cached_schema` was the Column of `__getattr__`. This PR makes the `__dict__` the state, in four commits that each keep the tests green.\n\n**1. The plan object holds the plan of the core** (948b1808). `df._plan` is a `_DataFramePlan` (of `pyspark.sql.connect.plan`), which subclasses a new native base, `_NativePlan`, and PySpark\u0027s `LogicalPlan`:\n- `_NativePlan` holds the DataFrame of the core of the plan and a `crate::gc::Parts` of it, which its `__traverse__` reports;\n- its `__dict__` holds PySpark\u0027s four fields of `LogicalPlan` (`_child`, `_root_plan_id`, `_references`, `_plan_id_with_rel`);\n- it holds no DataFrame, as PySpark\u0027s plan object holds none, so the old `_df` field and its cycle per DataFrame go;\n- `plan(session)`, `observations`, `__reduce__`, `__copy__` and `__deepcopy__` read the native base.\n\n**2. `_plan` and `_session` are entries** (dbf9aee2):\n- `DataFrame(plan, session)` is PySpark\u0027s `__new__` and `__init__`. `__init__` sets `_plan` and `_session` as they are given, with PySpark\u0027s checks (`MISSING_VALID_PLAN`, `NO_ACTIVE_SESSION`).\n- The methods that make DataFrames set the plan object of their plan and the `_session` of the DataFrame of the method. So `df._plan is df._plan`, and `DataFrame(df._plan, s)._plan` and `copy.copy(df)._plan` are `df._plan`.\n- Each method reads `self._plan` and `self._session` at the call (`Frame::of` in `dataframe.rs`). The DataFrame holds no plan and no parts.\n- A `_plan` that is a plan of the Python client, or the plan object of a DataFrame of another session, is built at the first request after it is set. The DataFrame keeps the result in an identity cache.\n- The plan objects of the methods are made with the GIL held. Their plans take their plan IDs then, in the order in which they are made, as PySpark\u0027s `LogicalPlan.__init__` takes them.\n- The caches of the core that belong to a DataFrame and not to its plan stay with the DataFrame (`DataFrameCaches`): `isLocal` and the information of its last execution.\n- `copy.copy` is `DataFrame(self._plan, self._session)` with its state. `copy.deepcopy` copies `_plan` and then `_session` with the memo, as PySpark\u0027s reduce does. A DataFrame whose `_plan` is a plan of the Python client pickles with PySpark\u0027s own reduce, so a pickle builds no plan.\n\n250585c1 makes two small speedups of the reads of step 2.\n\n**3. The rest of the state is entries** (546d703c):\n- `_schema` is PySpark\u0027s. It returns `_cached_schema`, else requests the schema and keeps it with its pickle (`CPickleSerializer().dumps`, or None with PySpark\u0027s warning).\n  - The request does not use a schema that the core cached, as PySpark requests the schema whenever `_cached_schema` is None. Concurrent first reads still ask the server once.\n  - `schema` loads the pickle, or else deep-copies `_schema`.\n  - `columns`, `dtypes`, `printSchema` and `__repr__` read `_schema` as PySpark\u0027s, with the `__getattr__` fallback of an `AttributeError`.\n- These methods set `res._cached_schema \u003d self._cached_schema`, as PySpark\u0027s list does: alias, coalesce, the repartitions, dropDuplicates, distinct, filter, limit, sort, sortWithinPartitions, sample, hint, randomSplit and observe.\n  - `to` sets its schema.\n  - The map functions set a `StructType` or the parsed DDL.\n  - The set operations set `_merge_cached_schema`.\n- collect, toArrow, toPandas, the temporary views and the checkpoints set `_execution_info`, as PySpark\u0027s do. The writers\u0027 callback is PySpark\u0027s `df._execution_info \u003d ei`.\n- `isStreaming` is a `functools.cached_property` of the native class.\n- `__getattr__`, `_col` and the string items of `__getitem__` read `_plan` alone, as PySpark\u0027s `_col` does.\n- The DataFrames of the readers and of the table-valued functions keep the object that the reader or the functions hold as their `_session`, and their requests resolve it. A reader or a `spark.tvf` of an object that is not a session no longer raises at `load`, `table` or the function.\n\n**GC (for the review).** The holder of the parts of a DataFrame\u0027s plan is its plan object, as in PySpark, where the DataFrame holds its plan object:\n- **No parts on the DataFrame.** `PyDataFrame` has no `Parts`. Its `__dict__` (`_plan`, `_session`, the schema objects, the `ExecutionInfo`) is traversed as that of a plain object.\n- **The identity cache.** It holds the plan object that the DataFrame made of a `_plan` that is not the plan object of a DataFrame of its session. `__traverse__` reports it together with that `_plan`. It is replaced out of its lock, and `__traverse__` only `try_lock`s it.\n- **GIL-free calls.** A request takes the plan object with the GIL held. Its GIL-free call names that plan object\u0027s parts (`Frame::parts`), where it named `self.parts` before. A call of two DataFrames names both plan objects.\n- **The per-call view.** It is a DataFrame of the core of the plan object\u0027s plan, with the session of `_session` and the caches of the DataFrame. It is made and dropped with the GIL held, as a clone that a request holds while it runs.\n- **Derived plan objects.** They are made with the GIL held, and `Parts::of` the new root runs then.\n- **Tests.** gc-shared\u0027s derived-plan and holder tests pass unchanged: `test_holders_that_share_a_plan_report_each_reference_once`, `test_cycles_are_collected_while_calls_run_that_clone_no_part_of_them` (now of `frame._plan`), and `test_objects_traversed_while_they_are_created_do_not_crash` with the plan objects.\n\n**The changes:**\n- **`crates/pyspark-rs/src/dataframe.rs`:** `Frame`, `NewDataFrame` (the new DataFrame of a method, whose conversion makes its plan object and its entries), `PyNativePlan`, the state above, and the methods rewritten over `Frame`.\n- **The consumers of the old `PyDataFrame.dataframe`:** `group.rs`, `session.rs`, `ml.rs`, `ml/*.rs`, `observation.rs`, `reader_plans.rs`, `tvf.rs`, `pipelines.rs` and `column.rs`. The functions of `catalog.rs`, `functions.rs`, `pyarrow_import.rs` and `stat_arguments.rs` that make DataFrames return a `NewDataFrame`.\n- **`crates/spark-connect/src/dataframe.rs`:** doc-hidden `DataFrameCaches` (`new`, `execution_info`, `forget_schema`), `DataFrame::caches`, `with_session_and_caches` and `is_numbered_in`.\n- **`python/pyspark/sql/connect/plan.py`:** `_DataFramePlan` over `_NativePlan`.\n- **`python/pyspark/sql/dataframe.py`:** installs the `isStreaming` cached property on the native class before the public base reads its attributes.\n- **`python/pyspark/sql/connect/readwriter.py`:** the callback sets `_execution_info`.\n- **Removed:**\n  - `PyDataFrame.dataframe` and `parts`, with the `_plan` and `_session` getters;\n  - `support_repr_html`, `is_streaming`, `schema_object`, `execution_info_object`, `written_execution_info` and `copy_schema`;\n  - `fresh_schema_request`, `columns_read_error`, `dataframe_of_plan`, `_set_execution_info` and the `Core` variant of `PropertySchema`.\n- **Docs:**\n  - the KD row \"The `__dict__` of the objects of a session\", now \"intentional; the plans are the core\u0027s\";\n  - \"Subclasses\";\n  - \"What a plan build does for a pickle\";\n  - `docs/compatibility.md`: the state of a DataFrame, the DataFrame of a read, and the writers\u0027 `_df`, `_write_stream._child` and `_source_plan`, which are `df._plan` now.\n\nOf the 415 generic cases of `tests/test_dropin_object_state_offline.py`:\n\n| | Same as PySpark | Differ |\n|---|---|---|\n| Before, master at 60858c27 | 383 | 32 |\n| After, this PR | 415 | 0 |\n\nThe DataFrame group of `_DIFFERS_BY_CHANGE`, its last, is gone, including the writers\u0027 cases that moved there in SPARK-62212 to SPARK-62214 and its three specific tests. So the table is empty.\n\n**What still differs** (the KD rows):\n- `_plan` is the drop-in\u0027s `_DataFramePlan`, not PySpark\u0027s plan classes. This is residue (c) of the design, stated in \"Plans of a DataFrame\u0027s relation\".\n- The methods resolve the session of `_session` as they are called, also those that only make a plan, because the plans are the core\u0027s. PySpark reads `self._session.client` at its requests. So a `_session` that is not a session raises at the method where PySpark raises at the request, for example the Column of `__getattr__` of a deleted `_session`. The requests raise a `TypeError` in both clients, with a message of the native transport (residue (b)).\n- A `_plan` of the Python client is built at the first request after it is set, not again at each request.\n\n**The micro-benchmark** (decision 2 of the design). Each value is ns per operation, the best of 5 repeats of two runs, against a Spark 4.3.0 server, with no request sent, on a shared machine. Before is master at 60858c27.\n\n| Operation | Before | After | PySpark 4.3.0 |\n|---|---|---|---|\n| `df.select(\u0027id\u0027)` | 3184 | 4897 | 52661 |\n| `df.filter(c \u003e 1)` | 4281 | 6142 | 58851 |\n| `df.withColumn(\u0027v\u0027, c + 1)` | 4470 | 6172 | 60217 |\n| `df.alias(\u0027a\u0027)` | 1255 | 2528 | 2241 |\n| `df.limit(1)` | 1175 | 2448 | 2285 |\n| `DataFrame(df._plan, spark)` | 1810 | 686 | 312 |\n| `df._plan` | 887 | 46 | 26 |\n| `df._session` | 263 | 45 | 27 |\n| `df[\u0027id\u0027]` | 808 | 1072 | 1918 |\n| `df.id` | 1051 | 1313 | 2380 |\n| 100 chained `select`s | 366 us | 518 us | 5256 us |\n\nThe cost is about 1.3 to 1.9 us per derived DataFrame (its plan object, its plan ID, its six entries, and the read of the `_plan` and the `_session` of its input), and about 260 ns per Column lookup, more than the design\u0027s estimate of 300 ns per DataFrame. About 20% of the per-call cost is the clone and the drop of the core `SparkSession` (12 Arcs) in the view of each call. Making the core session a single Arc is tracked as a separate follow-up. Reads of `df._plan` and `df._session` are now plain dict reads, and `DataFrame(df._plan, spark)` is 2.6 times faster, since it builds no plan.\n\n### Why are the changes needed?\n\nSo that the DataFrame is PySpark\u0027s in its `__dict__`, its copies and pickles, its subclasses and its partly built objects:\n- `vars(df)`, `df._plan is df._plan`, `df._cached_schema` (a StructType, not a Column), PySpark\u0027s schema caching sequence, the assignment and the deletion of the entries;\n- `copy.copy(df)._plan is df._plan`;\n- a subclass whose `__init__` does not call its base, which raises PySpark\u0027s `RecursionError`.\n\nIt also removes the native emulation of these behaviours: the copy schema, the written execution info and the per-DataFrame parts.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, to PySpark\u0027s behaviour:\n- `vars(df)` has PySpark\u0027s six entries, in its order, and `isStreaming` after its first read.\n- `df._plan` is one object. `DataFrame(df._plan, s)` and `copy.copy(df)` keep it.\n- `df._cached_schema`, `df._cached_schema_serialized`, `df._support_repr_html` and `df._execution_info` are PySpark\u0027s state, not Columns of `__getattr__`. Setting them changes what `schema`, `columns`, `__repr__` and `executionInfo` give, as in PySpark.\n- `DataFrame(plan, session)` builds nothing when it is made, as PySpark\u0027s. A `KeyboardInterrupt` or a `SystemExit` of the build is raised by the request, and the next request builds again.\n- A DataFrame keeps its session object alive through `_session`, as PySpark\u0027s.\n- The class\u0027s `inspect.signature` is PySpark Connect\u0027s `(*args, **kwargs)`.\n- The plan IDs of the plans of the methods follow the order in which the plans are made, as PySpark\u0027s.\n- `schema` of a schema nested about 340 levels deep raises the `RecursionError` of its copy, as PySpark\u0027s does from about 200 levels. `_schema` and `columns` still read it.\n- A reader or `spark.tvf` of an object that is not a session raises at the first request of its DataFrame, as PySpark\u0027s, and no longer at `load`, `table` or the function.\n\n### How was this patch tested?\n\n- **New tests, each passing on both clients and failing without this PR:**\n  - `test_the_plan_and_the_session_of_a_dataframe_are_its_dict_as_pyspark`;\n  - `test_the_state_of_a_dataframe_is_its_dict_as_pyspark`;\n  - `test_a_dataframe_whose_session_is_deleted_raises_at_its_requests_as_pyspark`;\n  - `test_the_request_of_is_streaming_takes_the_call_site_of_functools_as_pyspark`;\n  - `test_dataframes_of_plans_build_them_at_their_requests_as_pyspark`, which replaces the test of the build at construction;\n  - `test_a_plan_object_holds_the_plan_and_not_its_dataframe_as_pyspark`.\n- **Rewritten tests** of the old behaviours, each checked on PySpark 4.3.0 where it runs there:\n  - the observe `_on` test;\n  - the kept-apart conf;\n  - the native subclass and signature of `test_ml_offline.py`;\n  - the deep-response tests, which read `_schema`.\n- **`tests/test_dropin_object_state_offline.py`:** on this branch, 710 passed, with no xfail; with PySpark 4.3.0, 710 passed.\n- **A probe of deleted entries** (`_session`, `_plan` and the four others) with both clients, against seven calls each. Only the residue above differs.\n- **Coverage:** the offline suite of `coverage.yml` under `coverage.py` (`.coveragerc`): 93.90% (6909 of 7223 lines and 2491 of 2788 branches), against the floor of 93.0, of 7895 passed and 121 skipped.\n- **The gates** (at 546d703c):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 32 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - `gen_connect_docstrings.py --check`, `check_classic_bindings.py` and the tooling tests of `scripts/tests`;\n  - the offline suite of `coverage.yml`: 7895 passed and 121 skipped, with no xfail;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n\n- **An independent gc-aware review** (29 cycle shapes collected as on PySpark 4.3.0; the 17 shapes freed at their last reference with the GC off match PySpark; a stress of `_plan`/`_session` replacement from every thread, with the clone checker on, about 130k GIL-free clones with 0 violations) found nothing blocking. It also measured live DataFrames with the garbage collector on, which the `timeit` numbers above (GC off) do not show:\n  - each DataFrame has 5 GC-tracked objects, as PySpark\u0027s does, where it had 1 before;\n  - `gc.collect()` over 100k live DataFrames takes 94-97 ms, against 68-79 ms before (149-153 ms over a plan with a UDF, against PySpark\u0027s 76 ms);\n  - building 100k DataFrames that are kept takes 740 ms, against 350 ms before;\n  - each DataFrame takes about 420 B more RSS.\n\n  These, and the review\u0027s LOW findings, are for SPARK-62292.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #956 from HyukjinKwon/SPARK-62218-dataframe-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "0a7cd513deef0d132ac243f186db9763a4c9ae3b",
      "tree": "ac952a0d016c09c2573ec05c54153a8fd519056f",
      "parents": [
        "0b4769c37bcab90572bef3d8ed8cdb26adec5ff2"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 18:20:15 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 18:20:15 2026 +0000"
      },
      "message": "[SPARK-62293][CONNECT] Hold the state of a SparkSession behind one Arc, so that a clone is one reference count\n\n### What changes were proposed in this pull request?\n\n`spark_connect::SparkSession` held its 12 fields in an `Arc` each: the client, the plan IDs, the tags, the last execution, the progress handlers and the source of their ids, the Python accumulators, the check of the metrics of the Observations, the handler of the ML fit warnings, the stopped flag, the server version and the listener bus. So a clone made 12 atomic increments, and its drop 12 decrements. Since SPARK-62218 (#956), each call of a method of a DataFrame of the Python client clones the session: the DataFrame of the core of its requests holds a clone (`Frame::of`), and so does a DataFrame that it returns. In a `perf` profile of 400,000 calls of `df.alias(\u0027a\u0027)` there, `SparkSession::clone` and the drop glue of `SparkSession` take 7.6% of the samples (3.8%, and 2.0% and 1.8% of two copies of the drop glue).\n\nThe state of a session is now one `SessionInner`, behind one `Arc`:\n- `SparkSession` is `{ inner: Arc\u003cSessionInner\u003e }` and derives `Clone`. A clone is one reference count, and a session is one pointer: `size_of::\u003cSparkSession\u003e()` is 8 (it was 96), and `size_of::\u003cDataFrame\u003e()` is 40 (it was 128).\n- The parts of the state that objects hold apart from the session keep an `Arc` of their own:\n  - the client: a `RuntimeConf` holds it, and `is_same_session` compares it;\n  - the plan IDs: subquery expressions and the placeholders of plans hold them, and `DataFrame::of_plan_in` compares them;\n  - the registry of the progress handlers: the executions in flight hold it, without the session;\n  - the listener bus: each `StreamingQueryManager` holds it, and its worker a `Weak` of it.\n- The other fields are fields of the state, without an `Arc` each: the tags, the last execution, the id source of the progress handlers, the Python accumulators, the metrics check, the ML fit warning handler, the stopped flag and the server version. `profiler::PythonAccumulators` keeps its handler in a `Mutex` of its own, and its `WeakPythonAccumulators` goes.\n- `WeakSparkSession` is one `Weak\u003cSessionInner\u003e`: `downgrade` and `upgrade` are one `Weak` each, where they were 12.\n- `new_session`, `new_session_of_user`, `clone_session_with_id` and `clone_session_with_id_of_user` make their session with `SparkSession::new`. Their `new_session_of` built the same fresh state, and goes.\n- The methods read the client through the `client()` accessor, which some already used, and the other fields as `self.inner.\u003cfield\u003e`.\n\n**What does not change.**\n- **The API.** No public signature or type changes. `SparkSession` and `WeakSparkSession` keep `Clone`. Their auto traits are unchanged, and so are those of `DataFrame` and `StreamingQueryManager`: `Send`, `Sync` and `Unpin`, and neither `UnwindSafe` nor `RefUnwindSafe`. A probe of the base and of this branch checked them.\n- **The sharing of clones.** Every place that makes or changes a session was checked:\n  - `SparkSession::new` (of the builder) makes a fresh state;\n  - `new_session` and `clone_session` make a fresh state of a new client;\n  - `Clone` and `WeakSparkSession::upgrade` give the same state.\n\n  No method takes `\u0026mut self`, and no `with_*` method returns a changed clone. So no field was per clone, and none is: clones share all of the state, as before.\n- **The weak handle.** `upgrade` succeeds exactly while a handle of the session is alive, as before: the id source of the progress handlers was held by the sessions only, so the 12 upgrades failed when the last handle dropped. The handle keeps none of the state: the last handle drops it, also when weak handles are left.\n- **The drop order.** The last handle drops the fields in their declaration order, which is kept: the client first and the listener bus last. A part that another object holds outlives the session, as before.\n- **Shutdown.** `stop()`, `close()`, `close_at_once()` and `is_stopped()` read and write the one stopped flag and the one client of the clones, and `close_at_once()` cancels the listener bus, as before. The exit hook of the Python binding keeps `WeakSparkSession`s, which upgrade as before.\n- **Forks.** The state of a generation of the process (`fork::ForkLocal`, `PerGeneration`) is of the client, its runtime and the binding, not of these fields. None of it moves.\n\n### Why are the changes needed?\n\nA clone and its drop of a session are now about 11 times faster, and the Python client makes them for each call of a method of a DataFrame.\n\n**Rust**: a micro-benchmark, not committed, built as an example of the crate on the base (60858c27) and on this branch. Each value is in ns per operation: the best of 6 interleaved rounds, of the best of 7 runs each.\n\n| Operation | Before | After | Speedup |\n|---|---|---|---|\n| `spark.clone()` and its drop | 135.7 | 12.1 | 11.3x |\n| `spark.clone()`, 1000 held, then dropped | 142.5 | 14.1 | 10.1x |\n| `weak.upgrade()` and its drop | 145.5 | 16.9 | 8.6x |\n| `spark.downgrade()` and its drop | 144.1 | 16.9 | 8.5x |\n| `df.alias(\"a\")` and its drop | 319.3 | 187.4 | 1.7x |\n| `spark.range(3)` and its drop | 258.3 | 133.9 | 1.9x |\n| `spark.clone()` and its drop, on 4 threads at once (wall time per operation) | 1052 (median 1110) | 57 (median 110) | 10x to 18x |\n\n**Python**: the drop-in, at the head of #956 (546d703c) and at its merge with this branch, which differ in these two files only. Each value is in ns per call: the best of 12 interleaved rounds, of the best of 7 `timeit` runs each, with the collector off (timeit\u0027s default) and on (`gc.enable()` in its setup). The medians of the rounds give the same picture.\n\n| Call | GC | Before | After | Change |\n|---|---|---|---|---|\n| `df.alias(\u0027a\u0027)` | off | 2503 | 2354 | -6.0% |\n| `df.alias(\u0027a\u0027)` | on | 2522 | 2310 | -8.4% |\n| `df.select(\u0027id\u0027)` | off | 4715 | 4520 | -4.1% |\n| `df.select(\u0027id\u0027)` | on | 4737 | 4458 | -5.9% |\n| `df[\u0027id\u0027]` | off | 1059 | 936 | -11.6% |\n| `df[\u0027id\u0027]` | on | 1050 | 945 | -10.0% |\n| 100 chained `select(\u0027id\u0027)` | off | 490,180 | 457,685 | -6.6% |\n| 100 chained `select(\u0027id\u0027)` | on | 488,830 | 459,319 | -6.0% |\n\nIn the `perf` profile of 400,000 calls of `df.alias(\u0027a\u0027)`, the clone and the drop of a session have no samples of their own after the change: each is one atomic operation, inlined into its caller. Before, they had 7.6% of the samples.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo. Clones of a session are cheaper, and the behaviour is the same.\n\n### How was this patch tested?\n\n- **New unit tests** in `session.rs`:\n  - `a_clone_of_a_session_is_one_reference_to_its_state`: a session is one pointer; a clone, an upgraded weak handle and the session of a DataFrame are the same state, each counted once; and a clone counts none of the parts (the client, the plan IDs, the registry of the progress handlers and the listener bus);\n  - `sessions_and_their_weak_handles_are_send_and_sync`.\n- **Existing unit tests**:\n  - The tests of the server version read the field of the state, which has no `Arc` of its own any more: `version_cache_follows_session_identity` compares its address in the clones and in new sessions, and `version_cache_recovers_after_lookup_panics` poisons its lock through a reference.\n  - The tests of the weak handle and of the sharing of clones pass unchanged: `a_weak_session_upgrades_while_a_handle_of_it_is_alive`, `a_weak_session_keeps_none_of_the_state_of_the_session`, `session_clone_shares_state`, `stop_is_idempotent_and_marks_stopped` and `a_session_whose_client_closed_is_stopped_and_is_not_released`.\n- **A probe** (not committed) of the auto traits of `SparkSession`, `WeakSparkSession`, `DataFrame` and `StreamingQueryManager`, on the base and on this branch: the same.\n- **The gates:**\n  - `cargo test -p apache-spark-connect -p apache-spark-connect-core --release`: 1970 passed, 18 ignored, in 121 suites (the unit tests of the two crates: 858 and 426);\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 32 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7854 passed, 121 skipped, 36 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed;\n  - the Rust live tests of CI, of the connect-e2e job of `build_python_connect.yml` and of the `SPARK_REMOTE` pass of `coverage.yml` (45 test files), in release, serially, against the same server: 302 passed.\n\n- **Rebased onto master e7a0883f**, with every changed line identical to 12c0e850 (on 60858c27), whose tree the gates above ran on; `cargo fmt --check` and clippy 1.100.0 with `-D warnings` pass on the rebased tree.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #964 from HyukjinKwon/SPARK-62293-session-one-arc.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "0b4769c37bcab90572bef3d8ed8cdb26adec5ff2",
      "tree": "64277559db57c9e28d331b4ec473ffa7f95c6b15",
      "parents": [
        "e7a0883f8a3aaa5085602a78975c90e16a8e77df"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 18:00:28 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 18:00:28 2026 +0000"
      },
      "message": "[SPARK-62272][CONNECT][PYTHON] Hold no borrow of a message while Python code may run, match upb\u0027s unset children of CopyFrom and ClearField, and inline pbmsg::grow, of the follow-ups of the reviews of the native copies and of merges into descendants\n\n### What changes were proposed in this pull request?\n\nThe follow-ups of the independent reviews of SPARK-62264 (the native copies of the drop-in\u0027s protobuf runtime, `crates/pyspark-rs/src/pbmsg`) and of SPARK-62270, each a commit of its own; SPARK-62264 (#955) and SPARK-62270 (#958) are merged:\n\n1. **The text format holds no borrow of the message while Python code runs** (MEDIUM, new in SPARK-62264). The drop-in\u0027s writer of protobuf\u0027s text format (`_proto_message_to_string`, of the client\u0027s plan logging) held the message borrowed while it expanded an `Any` of a known type. The expansion parses the `Any` into a new message, whose allocations may start a collection of the garbage collector, of Python code. A first read of a native field of the message there (`PyMessage::materialize`) raised `PanicException: Already borrowed: PyBorrowMutError`, in the same thread (a gc callback) or in another one that the code gave the GIL to: 300 of 300 reads of the review\u0027s probe. The writer now writes a native copy of the message, taken with no checkpoint (`ConversionBudget::never`), as the writer held the GIL. upb\u0027s writer of `str()` and `repr()` runs no Python code and writes the message as it is. `_proto_unknown_field_pairs` copies the bytes before it makes its list. `materialize` takes its borrows with `try_borrow`/`try_borrow_mut`, so a message that Rust code borrows meanwhile is Python\u0027s `RuntimeError`, never a panic.\n2. **The first read of a copy\u0027s repeated message field or map of messages is documented as interruptible** (docs). It makes the objects of the messages of the checkpoints of a budget, every 1,024 messages (`native::made_of`), as the other operations of many steps do. `docs/compatibility.md` lists it with them: another thread can take the GIL there, and a signal interrupt the read, which leaves the field as it was.\n3. **The cost of a read of every message of a copy** (perf, optional). A materialization that fills the messages of a container in place, without a second list of them and without a clone of their descriptor, read a fresh `CopyFrom` of 100,000 messages in 39.4 ms, of 40.5 ms (3%): its cost is that of the objects, as the eager copy\u0027s was, so it was left out. The numbers stay those of SPARK-62264\u0027s description.\n4. **The lockstep tests compare identities, and the probes are tests** (tests).\n   - `_Lockstep.compare_identities` checks, at each comparison, whether each message field, repeated message field and its first message gives the object that it gave before, of either runtime alike.\n   - It found one difference, which the drop-in now shares with upb. upb\u0027s `ClearField` of a member of a oneof sets an unset child of the member that Python holds in its message first (its `EnsureReified`), then clears the field. So the member that the message holds is cleared too. Of one that Python no longer holds (upb holds its unset children weakly) it is not:\n     ```python\n     a \u003d Relation(); c \u003d a.crosstab; a.show_string.vertical \u003d True\n     a.ClearField(\"crosstab\")   # upb: a is empty; the drop-in kept show_string\n     ```\n   - The probes of the review are tests: threads that read, change, replace and copy the same native copies at once at a switch interval of a microsecond; a signal during the first read of a copy of 200,000 messages, which leaves it whole; and the copies of copies across a registration of another class of their type, on a small stack.\n5. **The unset children of every level of a `CopyFrom`\u0027s message take the copied messages** (pre-existing). Of `p \u003d Plan(); stub \u003d p.root; deep \u003d stub.read; p.CopyFrom(Plan(root\u003drel))`, a change of `deep` replaced the copied `read` with `deep` and dropped the copied paths and options, which upb keeps. As upb\u0027s `Reify` of the child (its `SyncSubobjs`), the child\u0027s unset children of the fields that the copy sets now take the copy\u0027s messages in turn, of any level (`PyMessage::adopt`).\n6. **A pickle of the runtime\u0027s `Any`** (pre-existing). It is documented as inherent. The message pickles as upb\u0027s, of `protobuf`\u0027s class, so the pickle loads wherever `protobuf` does (the Python worker of the server). So a round trip gives a message of another class: it equals the runtime\u0027s, and the runtime\u0027s `MergeFrom` and `CopyFrom` take it. Its own `MergeFrom` refuses the runtime\u0027s message, of upb\u0027s `TypeError`, as upb\u0027s methods take messages of their own class only. The other half of this follow-up, what a second `__init__` of a repeated field whose values fail midway keeps, is upb\u0027s since SPARK-62270.\n7. **A native copy grows its stack at the map entries** (hardening). `MapEntries::native_copy` copied the value of an entry, a level of its own, with no check of the stack (`At::grown`). So a chain of maps whose entries are at the levels of a multiple of 16 never grew it, and a `copy.deepcopy` of 20,000 such levels on a thread of 256 KiB ended the process (SIGSEGV). The entry\u0027s level now grows it.\n\n8. **An unset child is held by Python of what Python holds below it too** (of item 4\u0027s fix). upb\u0027s unset children and their containers hold their parents strongly, so its `ClearField` clears the oneof of an unset child that Python holds through an unset child of it, of any level, or a container of one: `a \u003d Relation(); g \u003d a.crosstab.input; a.show_string.vertical \u003d True; a.ClearField(\"crosstab\")` gives upb\u0027s empty message, where the child\u0027s own reference count kept `show_string`. The runtime\u0027s unset children hold their parents weakly, and each message holds its unset children and containers, so `held_by_python` walks the unset children below the child and their containers.\n9. **The container of a first read, and a merge\u0027s new child, are made with no borrow of the message held** (pre-existing on master). The first read of a repeated message field, a map or a repeated scalar field (`field_value`) took the message\u0027s mutable borrow, then made the weak reference of the container\u0027s owner and the container, both of the garbage collector. A collection that their allocation started, whose callback read the message (`ListFields()`), or the thread that it gave the GIL to, raised `PanicException: Already mutably borrowed` (3 of 3 cases, and 30 of 30 reads of another thread). The containers are made first now (`container_of`), and the field takes one only if it holds none by then, as `materialize` sets its objects. The unset child of a message field and the new child of a merge (`child_for_merge_of`) are made so too. Their borrows are `try_borrow`/`try_borrow_mut`, a `RuntimeError` of a message that Rust code borrows meanwhile, never a panic.\n10. **`pbmsg::grow` is inlined** (perf). `SerializeToString` and `ByteSize` took 8 to 14% longer from SPARK-62270 on, of an encoder that it did not change. The closures of `codec::write` and `measure` were no longer inlined into their instantiation of `grow`, of the other instantiations that SPARK-62270 added. `grow` is `#[inline]` now. The best of 7 interleaved rounds, µs per call:\n\n    | Case | Master | Before | After | upb |\n    |---|---|---|---|---|\n    | `MergeAction(condition\u003dbig).SerializeToString()` | 11.90 | 13.42 | 12.13 | 6.56 |\n    | its parse\u0027s `SerializeToString()` | 14.67 | 16.25 | 15.10 | 6.54 |\n    | `command.SerializeToString()` (a command of two clauses) | 2.53 | 2.85 | 2.60 | 1.21 |\n    | its parse\u0027s `SerializeToString()` | 3.20 | 3.44 | 3.28 | 1.21 |\n    | `MergeAction(condition\u003dbig).ByteSize()` | 5.42 | 6.21 | 5.37 | 6.57 |\n\n    `#[inline(always)]` gives the same.\n\n### Why are the changes needed?\n\nThe review of SPARK-62264 found the panic of item 1, new in SPARK-62264, and the follow-ups 2 to 7: a missing line of the documentation, a cost to state, tests to keep, two pre-existing differences from upb, and a stack overflow of a deep copy of maps. The review of SPARK-62270 and of this stack found items 8 to 10: an unset child that item 4\u0027s fix missed, the panic of a first read, which master has too, and the cost of the encoder.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, as upb\u0027s:\n- the first read of a field during the text format no longer raises a `PanicException`;\n- `ClearField` of a oneof member whose unset child Python holds clears the oneof\u0027s member;\n- an unset child below the first level of a `CopyFrom`\u0027s message holds the copied message;\n- a deep copy of nested maps no longer overflows a small stack;\n- `ClearField` of a oneof member whose unset child Python holds below it clears the oneof\u0027s member;\n- the first read of a container no longer raises a `PanicException` when a collection, or a thread that it gave the GIL to, reads the message.\n\nThe documentation states the interruptible first read and the class of an `Any` of a pickle.\n\n### How was this patch tested?\n\n- New tests of `python/tests/test_proto_rust_offline.py`, each failing before its change:\n  - `test_a_first_read_of_a_collection_of_the_text_format_finds_the_message` and `test_a_first_read_of_another_thread_during_the_text_format_finds_the_message` (the review\u0027s `probe_reentrancy.py` and `probe_reentrancy_threads.py`), and `test_unknown_field_pairs_of_a_collection_find_the_message`;\n  - `test_clear_field_of_a_member_of_an_unset_child_held_clears_its_oneof_as_upbs`, and the identity comparisons of the 14 lockstep tests; 100 seeds more of either lockstep test agree;\n  - `test_copies_into_unset_children_of_many_levels_keep_what_they_copied_as_upbs`;\n  - `test_copies_of_many_levels_of_maps_grow_the_stack_at_their_entries`, of a process of its own of 4 GB, whose segfault failed it before;\n  - the cases of the unset children held below a oneof member, of `test_clear_field_of_a_member_of_an_unset_child_held_clears_its_oneof_as_upbs` (the review\u0027s `probes2/clearfield_held`), 11 cases as upb\u0027s;\n  - `test_a_collection_during_the_first_read_of_a_container_finds_the_message` (the review\u0027s `probes2/weak_gc`) and `test_another_thread_during_the_first_read_of_a_container_finds_the_message`, its cross-thread form.\n- The adopted probes pass before and after: `test_threads_that_read_change_and_copy_the_same_copies_at_once_see_them_whole`, `test_a_signal_during_the_first_read_of_a_copy_leaves_it_whole` and `test_copies_of_copies_across_a_registration_are_of_the_classes_of_their_copy`.\n- The gates of the stack (`cargo fmt`, clippy 1.100.0, `cargo doc`, the binding\u0027s lib tests, ruff, the stub and dispatch generators, the guards, the stub test): pass. The offline suite of `coverage.yml` (under `ulimit -v 16000000`): 7825 passed, 121 skipped, 75 xfailed. `tests/test_dropin_e2e.py` against a Spark 4.3.0 server: 365 passed. `test_proto_rust_offline.py`: 172 passed (under `ulimit -v 4000000`), and 40 passed, 132 skipped without `protobuf`.\n\n- **Rebased onto master 9332d397** (the merge of #958), with every changed line identical to the stack the gates above ran on (c59b8c19 on edecb67c).\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #962 from HyukjinKwon/SPARK-62272-review-followups.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "e7a0883f8a3aaa5085602a78975c90e16a8e77df",
      "tree": "fdfac790ee3cf627c87f3101c63a170c255d81ce",
      "parents": [
        "9332d397e665d9ab40841850a9e4bb35302e0953"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 16:59:01 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 16:59:01 2026 +0000"
      },
      "message": "[SPARK-62251][SPARK-62229][SPARK-62231][CONNECT][PYTHON] Keep the fields, names and _needConversion of StructType in its __dict__, as PySpark\u0027s, so that its copies share them and a subclass\u0027s __init__ assigns through its attributes\n\n### What changes were proposed in this pull request?\n\nPySpark\u0027s `StructType` is a plain class. Its `fields`, `names`, `_needConversion` and `_needSerializeAnyField` are entries of its `__dict__`: its `__init__` and `add` assign them as `self.\u003cname\u003e \u003d value`, and its methods read them as `self.\u003cname\u003e`. The drop-in kept them in Rust, which caused these differences:\n- `vars(t)` was empty;\n- a copy made new lists of `_needConversion` and of the state that the getters made (SPARK-62229);\n- the native `__init__` did not assign through a subclass\u0027s setters, so a property over a setter\u0027s state read it unwritten, and the uses read the fields that the native `__init__` was given (SPARK-62231);\n- a subclass whose `__init__` did not call its class\u0027s had no fields, where PySpark\u0027s raises `AttributeError`;\n- `simpleString()`, `repr()` and `treeString()` read the native fields over a `fields` property.\n\nThis is part 3 of SPARK-62251, after part 1 (#949) and part 2 (#957: ArrayType, MapType and StructField). It closes SPARK-62229 and SPARK-62231.\n\n- **Parameters in `__dict__`.** `StructType` keeps the four in its `__dict__`. `__init__` and `add` assign them through `setattr`, as PySpark\u0027s:\n  - the fields as they are given: a tuple stays a tuple, and no fields (`if not fields`) are a new empty list;\n  - the names of `[f.name for f in fields]`;\n  - the `needConversion()` of the elements as the struct iterates them.\n\n  So a subclass\u0027s setters run, of their errors (`property \u0027names\u0027 of \u0027Fixed\u0027 object has no setter`).\n- **Reads as PySpark\u0027s.** Its methods read the entries as PySpark\u0027s read `self.\u003cname\u003e`, of a subclass\u0027s property too:\n  - `__iter__`, `__len__` and `__getitem__` of `self.fields` (an index\u0027s `IndexError` is PySpark\u0027s `INDEX_OUT_OF_RANGE`), and a name lookup of `for field in self`;\n  - `fieldNames()` of `list(self.names)`;\n  - `simpleString()`, repr, `jsonValue()` and `treeString()` of the elements as `for f in self` gives them;\n  - `\u003d\u003d` of the `__dict__`s;\n  - the lowering of the elements of `self.fields`: of a list, walked by index as its iterator reads it, of its length at each step, so a field appended while a field\u0027s type is read is lowered too, as PySpark\u0027s `for field in data_type.fields`, of no iterator object.\n- **Pickles and copies.** It pickles and copies as PySpark\u0027s plain class does, `copyreg.__newobj__` of the class and the `__dict__`, also at protocols 0 and 1. So `copy.copy` shares its `fields`, `names` and `_needConversion` lists, as PySpark\u0027s (SPARK-62229).\n- **Guards removed.** Two guards stood for the native `__init__` that did not assign through setters, and both are removed:\n  - the guard of the pandas row path for a struct whose `names` and `fields` are not as many (`names_as_many_as_fields`);\n  - #946\u0027s guard of local data (`local_fields_as_assigned`), which sent a struct whose `names` or `fields` raise, or are not as many, to the native conversion.\n\n  Such data now converts with PySpark\u0027s conversion, of the errors of its reads of `names` and `fields`, as PySpark\u0027s does: of a `names` property that raises, `createDataFrame([(1,)], schema)` raises its error, as PySpark 4.3.0\u0027s does, where it converted the rows.\n- **A struct\u0027s own `names`.** A struct whose class defines `names` now takes PySpark\u0027s conversion and sends its `json()`, as PySpark\u0027s, since `names` is one of what PySpark\u0027s conversion reads (`json_reads_of_its_own` checks the four parameters of the struct). Probed against PySpark 4.3.0 on a server, of a `names` property that upper-cases the names:\n  - a pandas frame is `struct\u003cA:bigint\u003e` (it was `struct\u003ca:bigint\u003e`);\n  - a dict is taken by the names (`Row(a\u003d2)` of `{\"A\": 2, \"a\": 1}`; it was `Row(a\u003d1)`);\n  - a class whose `typeName()` is not `struct` fails on the server with `ParseException`, as PySpark\u0027s `json()` does (it converted).\n- **Docs.** The KD and `docs/compatibility.md` items of the parameters of a struct, of SPARK-62231, of the copies of a struct and of a struct\u0027s `simpleString`/repr/`treeString` over a `fields` property are removed or rewritten. The KD item of local data under customized types (#946) keeps one difference, the native conversion without PyArrow, which is the drop-in\u0027s intentional fallback, as for pandas DataFrames. The KD and `docs/compatibility.md` items of the depths of nested types state those of `copy.deepcopy` and pickling of nested structs, which are now of the `__dict__`s in Python, as PySpark\u0027s: from about 100 and 125 nested structs on Python 3.11\u0027s main thread and on a thread of 256 KiB, as PySpark 4.3.0\u0027s (they were about 250 and 500), and a thread of 128 KiB overflows from there, as PySpark\u0027s does.\n\n### Why are the changes needed?\n\nTo match PySpark\u0027s state, reads, copies and errors of `StructType`: `vars()`, setters of subclasses, uninitialized subclasses, shared copies, and pickles.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. For `StructType`:\n- `vars(t)` holds its parameters;\n- a subclass\u0027s setters run in `__init__` and `add`;\n- an uninitialized subclass raises PySpark\u0027s `AttributeError`;\n- `copy.copy` shares its lists;\n- the pickles are of the `__dict__`, as PySpark\u0027s.\n\n### How was this patch tested?\n\n**Offline tests.** The tests that encoded the old behaviour are rewritten to PySpark\u0027s:\n- the golden pickles of PySpark\u0027s types, whose structs now hold PySpark\u0027s `__dict__`;\n- the pickles of the types of abstract types;\n- the reduces of structs with user-defined types and metadata;\n- the known differences of `test_arrow_handoff.py` of a property of no setter patched over a struct\u0027s `fields` or `names`, which now give PySpark\u0027s error;\n- a pandas frame under a struct of a `names` property, whose table is now of the names that the property reads, as PySpark\u0027s `_deduplicate_field_names` makes it, and whose relation is of the `json()` of the struct, of the `typeName()` of its class;\n- #946\u0027s test of local data, which gains a struct whose `names` property raises;\n- the comments of the tests of a struct whose `fields` property reads its setter\u0027s state, which now reads the fields that `__init__` assigned.\n\nFour tests are new:\n- of a struct\u0027s `__dict__`, its assignments and its reads;\n- of its copies and pickles (SPARK-62229);\n- of subclasses that assign through their attributes, or never initialize their class (SPARK-62231);\n- of the lowering of a struct whose `fields` list a field appends to as its type is read, which follows the appended field, as PySpark\u0027s `for field in data_type.fields`.\n\nAll of these also pass on pyspark-client 4.3.0.\n\n**Probes against pyspark-client 4.3.0:**\n- 4 cases of structs, each of about 420 uses: 1,680/1,684 match, where part 2 matches 1,017. The 4 that differ are the addresses of a generator in the repr of a `vars()`. The uses include:\n  - assignments of `fields` and `names` of other values;\n  - raw `__dict__` writes;\n  - setter-backed, uninitialized, iterating and `__slots__` subclasses;\n  - every pickle protocol;\n  - the uses in fields and arrays.\n- `copy.copy` and `copy.deepcopy` of the types, by identity: 18/18, where part 2 matches 16.\n- The probes of parts 1 and 2 still match: 1,339/1,339, 2,061/2,061, 49/49, and 316/341, of the same 25 as part 2 (the `RecursionError` texts of self-holding and very deep types, and three uses of 600 levels that PySpark stops). SPARK-62219\u0027s and SPARK-62230\u0027s probes still match: 369/370, where the miss is a Spark stage number, and 152/152.\n\n**Speed.** The guardrail paths, the minimum of 7 interleaved rounds against part 2 (#957, at 226f6cb5, before its rebase onto #953, which changes none of these paths):\n\n| Path | Base | This PR | Ratio |\n|---|---|---|---|\n| `json()` of 1,000 fields | 4,378 µs | 4,198 µs | 0.96 |\n| `json()` of 40 nested levels | 1,586 µs | 1,560 µs | 0.98 |\n| `json()` of 1,000 decimals | 4,891 µs | 4,675 µs | 0.96 |\n| `json()` of 300 arrays of maps | 5,371 µs | 5,240 µs | 0.98 |\n| proto of 1,000 fields | 1,216 µs | 1,187 µs | 0.98 |\n| proto of 40 nested levels | 595 µs | 574 µs | 0.96 |\n| proto of 1,000 decimals | 1,381 µs | 1,348 µs | 0.98 |\n| proto of 300 arrays of maps | 1,503 µs | 1,503 µs | 1.00 |\n| proto of 8 fields | 12.6 µs | 12.4 µs | 0.98 |\n| a cast\u0027s plan of 1,000 fields | 1,413 µs | 1,377 µs | 0.97 |\n| a cast\u0027s plan of 40 nested levels | 993 µs | 940 µs | 0.95 |\n| a cast\u0027s plan of 1,000 decimals | 1,562 µs | 1,535 µs | 0.98 |\n| `df.to` of 1,000 fields | 338 µs | 302 µs | 0.89 |\n| `df.to` of 1,000 decimals | 338 µs | 301 µs | 0.89 |\n| `df.to` of 8 fields | 5.0 µs | 4.6 µs | 0.92 |\n| `df.to(1,000 fields).schema` | 6,913 µs | 8,293 µs | 1.20 |\n| `createDataFrame` of 200 rows of 20 longs | 398 µs | 388 µs | 0.98 |\n| `createDataFrame([], 1,000 fields)` | 4,327 µs | 4,091 µs | 0.95 |\n| `createDataFrame` of 200 rows of a decimal, a string, a time and a long | 532 µs | 502 µs | 0.94 |\n| `createDataFrame` of a pandas frame of 1,000 rows of 3 longs | 1,336 µs | 1,359 µs | 1.02 |\n| `toInternal` of such a row | 5.6 µs | 5.2 µs | 0.93 |\n| `fromInternal` of such a row | 11.6 µs | 10.9 µs | 0.94 |\n| a UDF column of a decimal return type | 264 µs | 265 µs | 1.00 |\n| a UDF column of a struct of 1,000 fields | 2,909 µs | 2,814 µs | 0.97 |\n| `mapInPandas` of 1,000 fields | 1,520 µs | 1,516 µs | 1.00 |\n| `mapInPandas` of 8 fields | 66.2 µs | 64.6 µs | 0.98 |\n\n`df.to(1,000 fields).schema` is not a plan build: the schema is PySpark\u0027s `copy.deepcopy` of the cached struct (see below).\n\nOff these paths, of 5 interleaved rounds of all the benches:\n- `copy.deepcopy` of 1,000 fields 6,597 µs → 7,974 µs (1.21), and so `df.to(1,000 fields).schema`: the copy is Python\u0027s `copy.deepcopy` of the `__dict__`s, as PySpark\u0027s, where part 2 copied a struct through its JSON. Master (035a1c9c) takes 8.1 ms and PySpark 4.3.0 5.9 ms. SPARK-62287 follows with a native copier of exact classes, of the same copies and memo.\n- A pickle of 1,000 fields 2,347 µs → 2,512 µs (1.07) and of 40 levels 400 µs → 446 µs (1.12): PySpark\u0027s pickle of the `__dict__`, where part 2 pickled a struct by its JSON.\n- `simpleString()` of 1,000 fields 461 µs → 486 µs (1.05).\n- Faster: `\u003d\u003d` of 1,000 fields 3,810 µs → 2,355 µs (0.62), of 1,000 fields of metadata 19,384 µs → 264 µs, and of 40 levels 256 µs → 56 µs, all of the `__dict__`s; `copy.copy` of 1,000 fields 21.7 µs → 2.6 µs; `hash()` 0.83 and `repr()` 0.84 of 1,000 fields; `df.to` 0.89-0.92.\n\n**Gates**, of the same code on part 2 before its merge (d62fdd2f), and after the rebase onto master (9ad02b80) rustfmt, clippy (1.100.0), ruff, the stub audit and the stub generator:\n- build, rustfmt, clippy (1.100.0), rustdoc, ruff, the stub audit, the generators, the guards, the licenses and the stub tests pass.\n- `pyspark-rs` lib tests: 32 passed.\n- The offline suite: 7,613 passed, 121 skipped, 110 xfailed.\n- e2e against Spark 4.3.0: 361 passed.\n- `scripts/check_vendored_upstream.sh` was not run, as no vendored path is touched.\n\n- **Rebased onto master 9ad02b80** (the merge of part 2, #957). The one conflict, in the depth paragraph of `known-differences.md`, keeps this change\u0027s struct text and part 2\u0027s array sentence once. The gates above ran on the same code before the rebase (d62fdd2f). rustfmt, clippy 1.100.0, ruff, the stub audit and `gen_type_stubs.py --check` pass on the rebased tree.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #961 from HyukjinKwon/SPARK-62251-part3-struct-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "9332d397e665d9ab40841850a9e4bb35302e0953",
      "tree": "488624bc65867d7d169d7d40efa4aef71c9e1812",
      "parents": [
        "1abf0ce853da4975436e6a272311d51282a09f24"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 16:56:26 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 16:56:27 2026 +0000"
      },
      "message": "[SPARK-62270][CONNECT][PYTHON] Merge a snapshot of the value, as upb serializes it first, and set the keywords of a constructor in upb\u0027s order, so that a merge into a message that the value holds ends as upb\u0027s\n\n### What changes were proposed in this pull request?\n\n`MergeFrom` of the drop-in\u0027s protobuf runtime (`crates/pyspark-rs/src/pbmsg`) read its argument a field at a time while it wrote the message, after it had set an unset message in its parent (`mark_present`). Into a message below the argument the argument grew as it was read:\n\n```python\nr \u003d proto.Relation(); r.limit.limit \u003d 1\nt \u003d r.limit.input\nt.MergeFrom(r)   # a recursion without bound, until the memory runs out (a fuzz run reached 114 GB)\n```\n\nThrough a repeated field or a map it merged the argument as the merge changed it. upb serializes the argument first, then parses the bytes into the message, so the merge reads what the argument was.\n\nThe keywords of a constructor had the same hazard: a second `__init__` of a message held a mutable borrow of it while it converted the values, so a value that holds the message (`limit \u003d r.limit; limit.__init__(input\u003dr)`) raised a `PanicException` (\"Already mutably borrowed\"). So did Python code of a value (an `__iter__`, an `__index__`) that reached the message under construction through `gc.get_objects()`, which lists it, as upb\u0027s.\n\n**The change.**\n- **`MergeFrom` merges a snapshot** (`Snapshot`, `merge_native`). It takes a native copy of its argument first, as upb serializes it first (its bytes, past upb\u0027s limit of a parse of 100 levels, of upb\u0027s `DecodeError` at the same depths). It then sets the message in its parent and merges the copy. A field that the message does not hold, and of which it gave out no unset child, takes the copy\u0027s value as it is, moved where no other value holds it. So `append`, `extend` and a merge into an empty message make no object of what they merge, as a constructor\u0027s copy makes none.\n- **The keywords are set in upb\u0027s order** (`PyMessage::init_fields`, of upb\u0027s `InitAttributes`). No borrow of the message is held while Python code runs. The rules:\n  - An unset child is set in its parent first, of any keyword arguments (`**{}` too), as upb\u0027s `EnsureReified`.\n  - A message of a message field merges into the message that the field has, of a snapshot, as `MergeFrom`. A mapping sets the fields of that message, set in its parent first.\n  - The values of a repeated message field are appended in turn, as upb appends each and then merges into it. The native copies of a list or a tuple of messages are still made at once and set as one native value. The copy watches for the message (`At::watching`), and a value that holds it is appended in turn.\n  - The values of a repeated scalar field are those of the container\u0027s `extend` (`PySequence_Fast`, of upb\u0027s error `TypeError: must assign iterable`).\n  - A name of no field is upb\u0027s `ValueError`, of the value None too.\n- **`add(**kwargs)` appends its message first**, then sets its fields, and removes it of a failure, as upb\u0027s `add` does.\n- **A repeated field of messages extended (or merged) by itself** takes the messages that it has first, as a list\u0027s `extend` of itself does. upb\u0027s grows the field as it reads it, until its process ends.\n\n**The behaviour changes.** Each row ran in a process of its own under `ulimit -v 4000000`, on upb of PySpark\u0027s 4.3.0 client, on the drop-in before (master `2bd2ff3e`, whose runtime is #955\u0027s) and on the drop-in after:\n\n| Reproducer | upb | Before | After |\n|---|---|---|---|\n| `r \u003d Relation(); r.limit.limit \u003d 1; t \u003d r.limit.input; t.MergeFrom(r)` | `limit { input { limit { limit: 1 } } limit: 1 }` | a recursion until the memory runs out (`PanicException: mmap failed to allocate stack` under the cap) | upb\u0027s |\n| `d \u003d DataType(struct\u003d{\"fields\": [{\"name\": \"a\", \"data_type\": {\"string\": {}}}]}); t \u003d d.struct.fields[0].data_type; t.MergeFrom(d)` | the inner `data_type { string { } }` | the inner `data_type { struct { } }` | upb\u0027s |\n| `r \u003d Relation(limit\u003d{\"limit\": 1}); r.__init__(limit\u003d{\"input\": {\"range\": {\"end\": 2}}})` | `limit { input { range { end: 2 } } limit: 1 }` | `limit { input { range { end: 2 } } }` (the field set anew) | upb\u0027s |\n| `p \u003d Relation(project\u003d{\"expressions\": [{\"literal\": {\"integer\": 1}}]}); p.__init__(project\u003dp.project)` | two expressions | one | upb\u0027s |\n| `r \u003d Relation(); t \u003d r.limit.input; t.__init__(range\u003d{\"end\": 1})` | `r` is `limit { input { range { end: 1 } } }` | `r` is empty | upb\u0027s |\n| `r \u003d Relation(limit\u003d{\"limit\": 1}); limit \u003d r.limit; limit.__init__(input\u003dr)` | `limit { input { limit { limit: 1 } } limit: 1 }` | `PanicException: Already mutably borrowed` | upb\u0027s |\n| `d \u003d DataType(); f \u003d d.struct.fields.add(name\u003d\"a\"); f.data_type.struct.fields.add(name\u003d\"b\", data_type\u003df.data_type)` | the inner `fields { name: \"b\" data_type { struct { fields { name: \"b\" } } } }` | the inner `data_type { struct { } }` | upb\u0027s |\n| `Relation(common\u003d{\"plan_id\": 1}, with_relations\u003d{\"references\": It()})`, whose `It.__iter__` sets `plan_id` of the message under construction (of `gc.get_objects()`) | `common { plan_id: 9 } ...` | `PanicException: Already mutably borrowed` | upb\u0027s |\n| `Relation(nope\u003dNone)` | `ValueError: Protocol message Relation has no \"nope\" field.` | accepted | upb\u0027s |\n| `Ints(values\u003d5)` | `TypeError: must assign iterable` | `TypeError: Argument for field spark.connect.Ints.values is not iterable` | upb\u0027s |\n| `w \u003d WithRelations(references\u003d[rel]); w.__init__(references\u003d[rel, 5])` | `TypeError`, of 3 references (the new one of `5` empty) | `TypeError`, of 1 | upb\u0027s |\n| `p.project.expressions.extend(p.project.expressions)` | the process ends (SIGSEGV) | grows until the memory runs out (`MemoryError` under the cap) | two expressions, as a list |\n| `r \u003d Relation(limit\u003d{\"limit\": 1}); t \u003d r.limit.input; t.CopyFrom(r)` | the process ends (SIGSEGV) | `limit { input { limit { limit: 1 } } limit: 1 }` | the same |\n\nWhere upb\u0027s process ends, the drop-in copies the value first, as of a copy taken before. The cases are a `CopyFrom` into a message below the value (also a set one, an entry of a map or an item of a repeated field of it), a map of messages of a constructor or a `MergeFrom` of a value that holds the map (`n.next.__init__(children\u003d{\"a\": n})`, of a plugin\u0027s type: the protos of Spark Connect have no such map), and `extend` by itself. `dev/parity/known-differences.md` (\"Copies into a message that the value holds\") lists them, and the changes above, with their reproducers.\n\n### Why are the changes needed?\n\nA merge into a message below its argument recursed without bound in the drop-in: a fuzz run of the review of SPARK-62264 reached 114 GB and was OOM-killed. The same paths raised `PanicException`s, and the merges, constructors and `add` of a value that holds the message gave other messages than upb\u0027s.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, toward upb\u0027s behaviour, as the table above lists. A second `__init__` merges a message field into the message that the field has, rather than setting it anew. `add(**kwargs)` appends its message before it sets the fields. A repeated field extended by itself doubles. A name of no field of a constructor raises upb\u0027s `ValueError` of the value None too. A merge into a message below its argument ends, of upb\u0027s result.\n\n### How was this patch tested?\n\n- `python/tests/test_proto_rust_offline.py`:\n  - `test_merges_into_a_message_that_the_value_holds_are_upbs`: 25 groups of cases, of `MergeFrom`, `CopyFrom` of a message below the value, a second `__init__`, `add`, `append`, `extend`, `insert`, the maps, `MergeFromString` and `ParseFromString` of its own bytes, and the values past the limit of a parse. Each runtime runs them in a process of its own of 4 GB, as a recursion without bound fails there.\n  - `test_copies_into_a_message_that_the_value_holds_copy_the_value_first`: the 9 cases where upb\u0027s process ends. The drop-in gives the copy-first result; upb runs each case in a process of its own, which its crash ends, else it must give the drop-in\u0027s result.\n  - `test_code_of_a_value_that_reaches_the_message_under_construction_finds_upbs`: 7 cases of Python code that reaches the message under construction through `gc.get_objects()` and reads or changes it, compared with upb\u0027s.\n  - `test_a_second_init_keeps_what_upbs_keeps_of_a_failure`: 15 cases of what a second `__init__` and `add` keep of a failure midway.\n  - `test_constructors_raise_the_errors_of_upbs_beside_the_copies` now has no difference left (it allowed one: the second constructor of a field set).\n  - Each new test fails on master (the recursion ends in its capped process) and passes here.\n- The probes of the review (`probe_merge_into_descendant.py`, `probe_copy_into_stub_descendant.py`, `probe_merge_aliasing.py`, `probe_partial.py`), and 55 cases more, give upb\u0027s results, or the copy-first result where upb crashes.\n- The gates (`cargo fmt`, clippy 1.100.0, `cargo doc`, the binding\u0027s lib tests, ruff, the stub and dispatch generators, the guards, the stub test): pass. The offline suite of `coverage.yml`: 7814 passed, 121 skipped, 75 xfailed (under `ulimit -v 16000000`, as grpc\u0027s server reserves more than 4 GB; the cases that may recurse cap themselves at 4 GB). `tests/test_dropin_e2e.py` against a Spark 4.3.0 server: 365 passed. `test_proto_rust_offline.py` without `protobuf`: 38 passed, 132 skipped (of the stack).\n- The benchmark: µs per call, the best of 5 interleaved rounds of fresh interpreters, each the best of 3 `timeit` runs (`bench/cases79.py`). Before is master\u0027s runtime (the pbmsg of #955, `fb15f984`, identical to `2bd2ff3e`\u0027s), after is this stack, PySpark is pyspark-client 4.3.0 of upb:\n\n  | Case | Before | After | PySpark |\n  |---|---|---|---|\n  | `Assignment(key\u003dk, value\u003dv)` | 1.32 | 1.45 | 1.12 |\n  | `MergeAction(condition\u003dc)` | 1.68 | 1.82 | 1.06 |\n  | `MergeAction(condition\u003dc, assignments\u003d[a])` | 2.19 | 2.29 | 1.88 |\n  | `build update` (`_build_merge_action` of `update({\"v\": v})`, `to_plan` included) | 14.51 | 14.87 | 11.35 |\n  | `merge command of 2 clauses` | 8.32 | 8.40 | 11.68 |\n  | `MergeAction(condition\u003dbig)` (161 messages) | 27.12 | 27.32 | 11.08 |\n  | `Relation().MergeFrom(relation)` | 1.24 | 0.77 | 0.54 |\n  | `MergeAction().MergeFrom(action)` | 2.68 | 1.00 | 0.96 |\n  | `MergeAction().MergeFrom(built)` (161 messages) | 2.09 | 0.76 | 10.73 |\n  | `filled.MergeFrom(built)` (into a message of the same fields) | 1.02 | 1.47 | 13.05 |\n  | `assignments.add(key\u003dk, value\u003dv)` | 1.51 | 1.58 | 1.31 |\n  | `assignments.append(a)` | 2.02 | 0.96 | 0.65 |\n  | `assignments.extend([a] * 10)` | 16.98 | 6.32 | 5.60 |\n  | `MergeAction(action_type\u003d1).__init__(condition\u003dc)` | 2.14 | 2.23 | 1.20 |\n  | `Expression(unresolved_function\u003d{dict of 2 messages})` | 3.38 | 3.39 | 1.98 |\n  | `Literal.Array(elements\u003d[1000 messages])` | 137.00 | 120.06 | 305.02 |\n  | `Deduplicate(column_names\u003d[1000 str])` | 56.24 | 57.88 | 20.93 |\n  | `Ints(values\u003d[1000 int])` | 20.13 | 24.71 | 20.37 |\n\n  A merge into an empty message or field makes no object of what it merges, so `append`, `extend` and `MergeFrom` into a new message take half the time or less. Of a message of a million messages, `MergeFrom` takes 0.23 s, before 0.29 s and upb 0.09 s. A merge into a message that holds the merged fields already copies the snapshot first: 0.33 s for a million messages, before 0.22 s and upb 0.08 s. A constructor holds no borrow of its message while Python code runs, which takes about 0.1 µs more per message field; the ints of a repeated field take 5 ns more each.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #958 from HyukjinKwon/SPARK-62270-merge-into-descendant.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "1abf0ce853da4975436e6a272311d51282a09f24",
      "tree": "1d0f8278502810038b088d1e27a070bd9a5eb846",
      "parents": [
        "c558b5249f504416bf65f316986dd37bae1df2a6"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 16:34:46 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 16:34:46 2026 +0000"
      },
      "message": "[SPARK-62294][CONNECT][TESTS] Give the explain-mode test of the core the plan compression of a failed lookup, so that it needs no server\n\n### What changes were proposed in this pull request?\n\nThe Rust test `dataframe::plan_construction_tests::explain_string_takes_the_explain_modes_of_pyspark` took about 10 minutes, in `rust.yml` too.\n- Its session points at `sc://localhost:15002`, where no server listens.\n- `explain_string` builds the plan first, which looks up the plan compression of the session, and that lookup retries until its budget ends.\n\nThat order is PySpark 4.3.0\u0027s: `DataFrame._explain_string` calls `self._plan.to_proto(client)`, whose `_set_relation_in_plan` runs `get_configs` for the plan compression, and swallows its failure as threshold -1 and algorithm `NONE`. Only then does `_analyze` check the explain mode and raise `VALUE_NOT_ALLOWED`. So the client keeps that order. The test now sets the plan compression of a failed lookup on its client, as a binding sets PySpark\u0027s `_plan_compression_threshold`, so it builds the plan without a request and needs no server.\n\n### Why are the changes needed?\n\nThe test spent about 10 minutes of each Rust CI run waiting for a server that does not exist.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo, only a test changes.\n\n### How was this patch tested?\n\n- The test passes in under 0.01 s, against about 10 minutes before, and still checks `VALUE_NOT_ALLOWED` for each invalid mode.\n- All 856 lib tests of `apache-spark-connect` pass in 2.15 s.\n- clippy and rustfmt.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Code\n\nThis pull request and its description were written by Isaac.\n\nCloses #960 from HyukjinKwon/SPARK-62294-explain-mode-first.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "c558b5249f504416bf65f316986dd37bae1df2a6",
      "tree": "0d7daaf7285a25cd8ea2f43c2cfc029e581a9cac",
      "parents": [
        "9ad02b80660cce5d89618c1dfd525822552ca486"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 16:18:55 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 16:18:55 2026 +0000"
      },
      "message": "[SPARK-62267][CONNECT][PYTHON] Pickle subclasses of Column and TableArg as their class, render foreign expressions and window frames as PySpark\u0027s, honour patches of Column in the window fast paths, and untrack expressions of no Python object\n\n### What changes were proposed in this pull request?\n\nThis is the follow-up of SPARK-62217 (#953, the `Column`, `WindowSpec` and `TableArg` of `pyspark.sql.connect`), for the findings of its review. Each finding is fixed to match PySpark, or documented where it is inherent.\n\n**Fixes:**\n- **Pickles of subclasses (MEDIUM-1).** In PySpark, the pickle of an object of a subclass of `Column` or `TableArg` unpickles as the subclass. In the drop-in it unpickled as the base class, as the pickle reduces through `_column_reduce.column_of` and `table_arg_of`. Now the reduce of an object of a subclass is `_column_reduce.instance_of(cls, make, args)`:\n  - `make(*args)` gives back the object of the base class, as before;\n  - `cls.__new__(cls)` makes the object of the subclass, which takes the entries of that object\u0027s `__dict__`, and for a table argument its native session ID (`TableArg._take_session_of`);\n  - the pickle then sets the other entries of the `__dict__`, as of a plain object.\n  This works of `pickle` and of cloudpickle, and on a Python worker of the server, where the classes are PySpark Connect\u0027s. A `WindowSpec` subclass already pickled as itself.\n- **Expressions that do not render (MEDIUM-2).** A Column of an `Expression` of the user\u0027s class converts it of its `to_plan`. Before, the conversion also called its `repr` at once. A class whose `__repr__` gives None, as PySpark\u0027s base `Expression` does, or raises, then made every use of the Column raise, where PySpark sends the plan and fails only at `repr`. Now:\n  - the rendering of such an expression is its `str`, as PySpark\u0027s expressions render the expressions that they hold;\n  - an error of it becomes the unrenderable error of the node, raised anew at each `repr` of the Columns made of it. A builtin error is kept as its kind; another is a kept exception of no plan (`errors::kept_exception_error`).\n  The sort orders of a window\u0027s ordering do the same.\n- **The frame of a window expression in its repr (LOW-3).** The repr of `F.sum(\"x\").over(w)` showed `WindowFrame(ROW_FRAME, 0, 0)` for a frame of a bound that its build refuses, where PySpark shows the bound. Such bounds are a row bound beyond an int, a bool, or an int beyond a long. The repr now shows the `WindowFrame` as it is (`WindowFrame(ROW_FRAME, -1099511627776, 0)`, `True`, `False`), as PySpark\u0027s `WindowExpression.__repr__` does. A new hidden `Expression::unbuildable_rendered` of the core carries that rendering, in a new `rendered` field of `UnbuildableExpression`.\n- **`TableArg.orderBy` of a subclass (LOW-5).** It sorts each Column by `F._sort_col`, of the `asc()` of a Column of a subclass too, by the same dispatch as the window\u0027s `orderBy`.\n- **Patches of `Column` (LOW-6).** The fast paths of the windows now run only of the class `Column` as the module made it. The module remembers its `__getattribute__` and its `asc` once it installed its `__getattr__` (`column::remember_column_class`), and compares each with one lookup of the class. A patch of `Column.asc` or `Column.__getattribute__` (a library\u0027s, or a classic patch that the metaclass forwards) is then called where PySpark\u0027s `_sort_col` and the methods of a Column call it. The fast paths that this gates are the sort orders of `orderBy` and the expressions of column names in `partitionBy`. The methods of a Column read `_expr` through the attribute lookup of the class again: the direct read of #953 bypassed a patched `__getattribute__`, which the class\u0027s slot does not show, as the class already has a Python `__getattr__`.\n- **Performance (LOW-7):**\n  - A `_ColumnExpression` whose parts hold no `SharedPart` reaches no Python object, now or later, and is untracked (`PyObject_GC_UnTrack`, `Parts::holds_no_shared`). So a Column is of 2 tracked objects (the Column and its `__dict__`) instead of 3.\n  - `window_spec_of` reads the window\u0027s state of its attribute lookup without the recursion guard, which only the Column\u0027s native `__getattr__` needs.\n  - An origin reads its call site of the frame of the thread (`PyEval_GetFrame`). It reads the cache of `is_debugging_enabled` at once once it is set (calling the function before that, and when it is patched), checks the file of a frame as a Python str, and formats the line of an int at once, of interned names. With a session, every Column method that captures an origin is cheaper than before SPARK-62217.\n  - A window method reads the call site once for its `col` and `asc_nulls_first` origins (`origin::CallSiteOrigin`).\n- **INFO-8, fixed:**\n  - `Column.__init__` binds its arguments as CPython binds them to `def __init__(self, expr)`, of the same errors (`takes 2 positional arguments but 3 were given`, `got multiple values for argument \u0027expr\u0027`, `got an unexpected keyword argument`).\n  - A partitioning or an ordering of a window that is not a list raises PySpark\u0027s `TypeError` of its concatenation (`can only concatenate list (not \"tuple\") to list`).\n\n**Documented, in `dev/parity/known-differences.md`:**\n- **LOW-4, inherent to PyO3 0.29.** A cycle of a Python subclass and an object of it that the subclass holds (`Sub.inst \u003d Sub(e)`) is not collected. CPython\u0027s `subtype_traverse` leaves the visit of the class to the base\u0027s traversal when that is a heap type, as PyO3\u0027s classes are, and PyO3\u0027s traversal does not visit the class. This is pre-existing for `GroupedData`, `Catalog` and the others, and is now in the \"Garbage collection\" row, with a strict xfail test.\n- **The `RecursionError` of a Column whose `__init__` never ran.** Its message is CPython\u0027s of the check that stops the recursion: `repr` gives `maximum recursion depth exceeded`, where PySpark\u0027s adds `while calling a Python object`.\n- **The order of `getMessageParameters()`.** The core keeps the parameters of an error in a map of their names (`{\u0027arg_name\u0027, \u0027max\u0027, \u0027min\u0027}` of `VALUE_NOT_BETWEEN`, where PySpark\u0027s are in the order of its code). This is a new row; it covers every error that the core raises.\n- **An entry of `_orderSpec` that is not a sort order** is sorted ascending with nulls first, where PySpark sends the empty `SortOrder` of its `to_plan(session).sort_order`.\n- **Errors at `over()`.** A window whose `__init__` never ran, or whose lists are not lists, raises at `over()`. PySpark\u0027s `over()` keeps the window and raises when a DataFrame selects the window expression (`_collect_references`) and at `repr`.\n- **KD\u0027s list of PySpark\u0027s classes of `pyspark.sql.connect.expressions`** now names `UnresolvedNamedLambdaVariable` and `DistributedSequenceID` too.\n- **The Subclasses row and `docs/compatibility.md`** say again that the pickles of the subclasses are of the subclass. They describe the renderings, the sorts of subclasses and the patches of `Column`.\n\n### Why are the changes needed?\n\nThey make the review\u0027s findings behave as in PySpark: pickles of subclasses, user expressions with a failing `repr`, the repr of window frames, the sorts of table arguments of subclasses and patches of the class `Column`. They also bring the collector\u0027s cost of Columns back near what it was before SPARK-62217, and make origins cheaper. The rest is documented.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, as above. The numbers, against #943\u0027s build (the base of SPARK-62217) and #953\u0027s:\n\nWith a session (origins captured), ns per call, best of two rounds of 7 × 20,000 calls with the collector off. The base is #943\u0027s build (before SPARK-62217):\n\n| | #943 | #953 | this PR |\n|---|---|---|---|\n| `F.col(\u0027a\u0027)` | 5249 | 5440 | 3847 |\n| `c + 1` | 2877 | 3108 | 2109 |\n| `c.isNull()` | 2609 | 2829 | 1898 |\n| `Window.partitionBy(\u0027a\u0027)` | 6169 | 6399 | 4914 |\n| `w.orderBy(\u0027a\u0027)` | 3127 | 3601 | 2681 |\n| `Window.orderBy(c)` | 3007 | 6823 | 5401 |\n| `s.over(w)` | 2713 | 3095 | 2174 |\n\n`Window.orderBy(c)` keeps the read of the call site of the `asc_nulls_first` origin of its sort order, which PySpark captures too and #943 did not. PySpark 4.3.0 takes about 100 µs for it, of `inspect.stack()`.\n\nWithout a session (no origins), best of three rounds of 50,000 calls with the collector off:\n\n| | #943 | #953 | this PR |\n|---|---|---|---|\n| `F.col(\u0027a\u0027)` | 3375 | 3622 | 3503 |\n| `c + 1` | 1126 | 1423 | 1256 |\n| `c.alias(\u0027x\u0027)` | 1366 | 1627 | 1500 |\n| `c.isNull()` | 935 | 1166 | 1042 |\n| `repr(c)` | 160 | 216 | 217 |\n| `Window.partitionBy(\u0027a\u0027)` | 4088 | 4519 | 4457 |\n| `w.orderBy(\u0027a\u0027)` | 1225 | 1750 | 1599 |\n| `F.sum(c).over(w)` | 6030 | 6587 | 6366 |\n\nMemory and the collector, of 200,000 Columns of `c + i` (`mem_columns.py`, `gc_time.py` of the review):\n\n| | #943 | #953 | this PR |\n|---|---|---|---|\n| RSS per Column | 609 B | 777 B | 776 B |\n| Objects that the collector tracks per Column | 1 | 3 | 2 |\n| `gc.collect()` | 28 ms | 54 to 56 ms | 31 to 32 ms |\n\nThe memory per Column is that of SPARK-62217\u0027s design (its `_ColumnExpression` and its `__dict__`), which this PR keeps.\n\n### How was this patch tested?\n\n- **`tests/test_dropin_object_state_offline.py`:** eight new tests. Seven pass with both clients, and the strict xfail passes with PySpark 4.3.0:\n  - pickles of module-level subclasses of `Column`, `WindowSpec` and `TableArg`, of `pickle` and cloudpickle, unpickle as the subclass, with their `__dict__`;\n  - a Column of an `Expression` whose `__repr__` gives None or raises is sent, a Column made of it renders it at `repr` only, and so does a window of it;\n  - the repr of a window expression shows a bound of `-2**40`, `True`, `False` and `2**64` as it is;\n  - `TableArg.orderBy` and `Window.orderBy` sort a Column of a subclass by its `asc()`;\n  - a partitioning or an ordering that is not a list raises PySpark\u0027s `TypeError` when a DataFrame selects the window expression;\n  - `Column.__init__` raises CPython\u0027s errors of its arguments;\n  - in a new interpreter, patches of `Column.asc` and `Column.__getattribute__` are called by `Window.orderBy` and `isNull` as in PySpark (1 and 3 reads of `_expr`);\n  - a cycle of a subclass and an object of it is collected: a strict xfail with the drop-in (LOW-4), which passes with PySpark.\n\n  On this branch: 682 passed and 36 xfailed. With PySpark 4.3.0: 718 passed.\n- **`tests/test_dropin_offline.py`:** a new test: the `_ColumnExpression` of no Python object is not tracked by the collector, one of a UDF is tracked, and a cycle through it is collected.\n- **The review\u0027s probes** (`rv-62217/probes`), on this branch against PySpark 4.3.0:\n  - `beh_subpickle`, `beh_reentry`, `beh_tablearg_sub`, `beh_window`, `beh_args`, `beh_descr` and `beh_sort_origin` give PySpark\u0027s output.\n  - `beh_frames` differs only by the order of the parameters of `VALUE_NOT_BETWEEN` (documented).\n  - `beh_state` differs by the documented residues: the signatures\u0027 annotations, the classes of the expressions, the window of `over()`, the non-sort ordering, the `RecursionError` suffix, and the assigned ints.\n  - The gc probes `gc_cycles2`, `gc_cycles3`, `p_shapes_collected` and `p_copies_free` give #953\u0027s results. `gc_cycles` and `gc_subclass_type_cycle` differ from PySpark only by the subclass↔class cycle (LOW-4).\n- **The gates:**\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 31 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7846 passed, 121 skipped, 37 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n\n- **Rebased onto master 60858c27** (the merge of #953), with every changed line identical to e90a41e1, the commit the gates above ran on. ruff and `gen_type_stubs.py --check` pass on the rebased tree.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #959 from HyukjinKwon/SPARK-62267-column-followups.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "9ad02b80660cce5d89618c1dfd525822552ca486",
      "tree": "ee6a800e43fe6e92d2c9a2cf93d81acc768c2986",
      "parents": [
        "60858c2741e9435d038f5050b273d6876db83a2f"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 15:39:46 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 15:39:46 2026 +0000"
      },
      "message": "[SPARK-62251][CONNECT][PYTHON] Keep the parameters of ArrayType, MapType and StructField in their __dict__, as PySpark\u0027s, and read them as PySpark\u0027s methods do\n\n### What changes were proposed in this pull request?\n\nPySpark\u0027s `ArrayType`, `MapType` and `StructField` are plain classes. Their parameters are entries of their `__dict__`, of any value, and their methods read them as `self.\u003cname\u003e`. The drop-in kept them in Rust, which caused these differences:\n- `vars(t)` was empty;\n- an assignment of a value that is not a type was parsed as DDL or raised at the assignment, where PySpark keeps it and its later uses fail;\n- a subclass whose `__init__` did not call its class\u0027s had the class\u0027s defaults, where PySpark\u0027s raises `AttributeError`;\n- the native `__init__` did not assign through a subclass\u0027s properties, so a setter-backed property read its state unwritten, and a class attribute (`nullable \u003d False`) was not shadowed by the instance\u0027s own;\n- `simpleString()`, `repr()` and `treeString()` read the native values where a subclass overrides an attribute with a property;\n- a name that is not a str was sent as its `str()`, where PySpark\u0027s plan raises protobuf\u0027s `TypeError`.\n\nThis is part 2 of SPARK-62251. Part 1 (#949, merged) covers the atomic types of parameters, and part 3 covers `StructType`, with SPARK-62229 and SPARK-62231.\n\n- **Parameters in `__dict__`.** `ArrayType` (`elementType`, `containsNull`), `MapType` (`keyType`, `valueType`, `valueContainsNull`) and `StructField` (`name`, `dataType`, `nullable`, `metadata`) keep their parameters as entries of their `__dict__`. `__init__` asserts the types and the name as PySpark\u0027s does, and assigns each parameter through `setattr`, so a subclass\u0027s property setter runs, of its errors (`property of \u0027StructField\u0027 object has no setter`).\n- **Reads as PySpark\u0027s.** Each method reads the attributes as PySpark\u0027s reads `self.\u003cname\u003e`: the `__dict__` entry of the native class, or through Python for a subclass (a property, a `__getattr__`) and for a property patched over the class.\n  - repr and `simpleString` format them with Python\u0027s `%`, as PySpark\u0027s do;\n  - `jsonValue`/`json` write a field, an array or a map that the core type does not hold by PySpark\u0027s algorithm, of the `jsonValue` of each child, of its own errors (`\u0027str\u0027 object has no attribute \u0027jsonValue\u0027`);\n  - `needConversion` calls the child\u0027s own method;\n  - `\u003d\u003d` compares the `__dict__`s;\n  - a struct\u0027s `names` holds the `name` of each field as the field reads it, of any value, and its `treeString` of a name that is not a str raises the error of PySpark\u0027s `escape_meta_characters` (`\u0027int\u0027 object has no attribute \u0027replace\u0027`).\n- **Plans.** The proto of a plan takes the entries as PySpark\u0027s `pyspark_types_to_proto_types` sets them in protobuf\u0027s fields: a flag that is not an int raises `\u0027NoneType\u0027 object cannot be interpreted as an integer`, and a name that is not a str raises `bad argument type for built-in operation` (bytes of UTF-8 are taken). The other uses take the truth of a flag and the str of a name, as before.\n- **Pickles and copies.** They pickle and copy as PySpark\u0027s plain classes do, `copyreg.__newobj__` of the class and the `__dict__`, also at protocols 0 and 1, and `copy.copy` shares the values. `__reduce__()` of a type whose state is its `__dict__` (also #949\u0027s types of parameters) gives the same, where PySpark\u0027s gives copyreg\u0027s `_reconstructor` of `object.__new__`, which CPython refuses for a native class.\n- **Construction.** An array, a map, a field and a struct are made of the objects alone, as PySpark\u0027s, so a `UserDefinedType` in them has none of its methods called (`jsonValue()`, `sqlType()`, `module()`, `scalaUDT()`) until a use reads it. Before, each construction lowered it. A field of a name or metadata of a lone surrogate is made, as PySpark\u0027s, where its constructor raised `UnicodeEncodeError`; its `json()`, `jsonValue()`, `\u003d\u003d`, pickles and `treeString()` are PySpark\u0027s.\n- **Local data.** SPARK-62258 (#946) converts local data under a type that overrides what PySpark\u0027s conversion reads with that conversion. Part 2 removes the differences of #946\u0027s KD item that are of fields:\n  - the `names` of a struct are those that each field\u0027s `name` reads, by which PySpark\u0027s conversion takes a dict: `{\"a\": 1, \"renamed\": 2}` under a field `a` whose `name` reads `renamed` is `Row(renamed\u003d2)`, as PySpark\u0027s (it was `Row(renamed\u003d1)`);\n  - a field\u0027s setter-backed property reads what `__init__` gave it, and the field\u0027s own attributes shadow a class attribute (`nullable \u003d False`);\n  - a property of no setter patched over a field\u0027s attribute raises PySpark\u0027s `AttributeError` at `StructField(...)`.\n\n  Without PyArrow, the native types convert the rows, and they read a field\u0027s attributes as Python reads them: under a field whose `dataType` property reads `StringType()` over `a long`, `[(1,)]` is `struct\u003ca:string\u003e` of `Row(a\u003d\u00271\u0027)` (it was `struct\u003ca:bigint\u003e`). A struct whose `names` or `fields` reads otherwise than its `__init__` assigned (SPARK-62231) still converts by the native types, for part 3.\n- **Subclass reads of `json()`.** SPARK-62236\u0027s `json_reads` lists the parameters no more, as they are not attributes of the classes. A subclass that defines one still writes its JSON by PySpark\u0027s algorithm (`json_reads_of_its_own`), and a property patched over the class is read by the lowering, as Python reads it.\n- **pandas fast paths.** `_pandas_input.py` checked that `StructField`\u0027s `name`, `dataType`, `nullable` and `metadata` were the native getset descriptors. It now checks that the class defines none of them, so a property patched over one still declines the fast paths.\n- **Speed.**\n  - A struct\u0027s base core type and those of arrays and maps are markers of their kind, which no use reads. So `StructType.__init__` reads only the names and the `needConversion()` of its fields, as PySpark\u0027s does.\n  - The lowering of a struct reads the `__dict__` of each field of the native class in one walk, as long as `StructField` has no class attribute over a parameter. It checks that through one view of the class\u0027s namespace, kept for all lowerings, which shows a patch of the class as it is made. It keeps the UTF-8 text of each name by its str object (abi3-py39 has no zero-copy UTF-8 read of a str). It takes an exact bool flag, and an atomic child of no parameters, without further checks.\n  - A type of parameters, such as a decimal, reads its parameters with one check of its class for all of them.\n  - The lowering of a level checks for an array, a map or a struct before the classes of no parameters, which a container is none of, so a level of a nested type makes none of those checks.\n  - A string of the native class, with no patch over its `isUTF8BinaryCollation`, reads its collation without a method call in its repr and `simpleString`.\n- **Docs.** In the KD and `docs/compatibility.md`, these items now cover only `StructType` (part 3): the parameters not in `__dict__`, the setter-backed properties and class attributes, `simpleString`/`repr`/`treeString` of properties, the lone-surrogate repr, and the `\u003d\u003d` of user attributes. Three KD items are rewritten. The lone-surrogate field item now lists what still differs: `simpleString()`, `DataFrame.to`\u0027s cached schema, and a cast\u0027s plan of such metadata. The `UserDefinedType` item is no longer about construction. The local-data item of #946 no longer lists the names of a struct, the setter-backed properties and class attributes of fields, or a property of no setter patched over a field.\n\n### Why are the changes needed?\n\nTo match PySpark\u0027s state, reads and errors of arrays, maps and fields: `vars()`, assignments of any value and their later errors, uninitialized subclasses, properties of subclasses and patched classes, plans of names and flags that protobuf refuses, and pickles.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. For `ArrayType`, `MapType` and `StructField`:\n- `vars(t)` holds the parameters;\n- an assignment of any value is kept, and the later uses fail as PySpark\u0027s do;\n- an uninitialized subclass raises PySpark\u0027s `AttributeError`;\n- a subclass\u0027s properties and class attributes read as in PySpark, in `repr`, `simpleString`, `treeString`, `json` and the plans;\n- a plan of a name that is not a str, or of a flag that is not an int, raises protobuf\u0027s `TypeError`, as PySpark\u0027s;\n- the pickles are of the `__dict__`, as PySpark\u0027s.\n\n### How was this patch tested?\n\n**Offline tests.** The tests that encoded the old behaviour are rewritten to PySpark\u0027s:\n- the golden pickles of PySpark\u0027s types, whose arrays, maps and fields now hold PySpark\u0027s `__dict__`;\n- the pickles of arrays and maps of abstract types;\n- the subclasses that do not initialize their class;\n- the known differences of `test_arrow_handoff.py` of a property of no setter patched over a field\u0027s attribute, which now give PySpark\u0027s error;\n- #946\u0027s test of local data without PyArrow, whose native types now read a field\u0027s `dataType` property; the test also gains the dict taken by the names that the fields\u0027 `name` reads, a setter-backed `dataType`, and a class attribute `nullable \u003d False`, each as PySpark 4.3.0\u0027s conversion gives it.\n\nThree tests are new: of the `__dict__` and the reads of arrays, maps and fields, of their pickles and copies, and of the subclasses that read their own attributes. All of these also pass on pyspark-client 4.3.0.\n\n**Probes against pyspark-client 4.3.0:**\n- 11 cases of arrays, maps and fields, each of about 190 uses: 2,061/2,061 match, where #949 matches 1,084. The uses include:\n  - assigned values of each kind;\n  - raw `__dict__` writes and deletions;\n  - uninitialized, property and `__slots__` subclasses;\n  - every pickle protocol;\n  - the uses in structs and arrays.\n- Nested types, edits in place, properties at nested levels and patched classes: 316/341, where #949 matches 222. The 25 that differ are of self-holding types and of types of 600 and 2,000 levels, which #949 shares: the suffix text of their `RecursionError` (`while getting the str of an object`), and three uses of 600 levels that PySpark stops, of its recursion limit (`simpleString()`, `repr()`) or of upb\u0027s depth limit (the proto), where the drop-in\u0027s grown stack does not.\n- #949\u0027s probes still match: 1,339/1,339 of the atomic types and 49/49 of the `__slots__` pickles. SPARK-62219\u0027s and SPARK-62230\u0027s probes still match: 369/370, where the miss is a Spark stage number, and 152/152.\n\n**Speed.** The guardrail paths, the minimum of 7 interleaved rounds against master (035a1c9c):\n\n| Path | Base | This PR | Ratio |\n|---|---|---|---|\n| `json()` of 1,000 fields | 4,313 µs | 4,369 µs | 1.01 |\n| `json()` of 40 nested levels | 1,624 µs | 1,583 µs | 0.98 |\n| `json()` of 1,000 decimals | 4,756 µs | 4,812 µs | 1.01 |\n| `json()` of 300 arrays of maps | 5,465 µs | 5,345 µs | 0.98 |\n| proto of 1,000 fields | 1,223 µs | 1,212 µs | 0.99 |\n| proto of 40 nested levels | 592 µs | 593 µs | 1.00 |\n| proto of 1,000 decimals | 1,370 µs | 1,370 µs | 1.00 |\n| proto of 300 arrays of maps | 1,585 µs | 1,512 µs | 0.95 |\n| proto of 8 fields | 12.4 µs | 12.6 µs | 1.02 |\n| a cast\u0027s plan of 1,000 fields | 1,428 µs | 1,422 µs | 1.00 |\n| a cast\u0027s plan of 40 nested levels | 952 µs | 990 µs | 1.04 |\n| a cast\u0027s plan of 1,000 decimals | 1,588 µs | 1,572 µs | 0.99 |\n| `df.to` of 1,000 fields | 338 µs | 331 µs | 0.98 |\n| `df.to` of 1,000 decimals | 369 µs | 332 µs | 0.90 |\n| `df.to` of 8 fields | 4.9 µs | 5.0 µs | 1.02 |\n| `df.to(1,000 fields).schema` | 8,440 µs | 6,826 µs | 0.81 |\n| `createDataFrame` of 200 rows of 20 longs | 385 µs | 390 µs | 1.01 |\n| `createDataFrame([], 1,000 fields)` | 4,116 µs | 4,221 µs | 1.03 |\n| `createDataFrame` of 200 rows of a decimal, a string, a time and a long | 498 µs | 507 µs | 1.02 |\n| `createDataFrame` of a pandas frame of 1,000 rows of 3 longs | 1,348 µs | 1,342 µs | 1.00 |\n| `toInternal` of such a row | 5.7 µs | 5.6 µs | 0.98 |\n| `fromInternal` of such a row | 11.7 µs | 11.5 µs | 0.98 |\n| a UDF column of a decimal return type | 258 µs | 265 µs | 1.03 |\n| a UDF column of a struct of 1,000 fields | 2,967 µs | 2,744 µs | 0.92 |\n| `mapInPandas` of 1,000 fields | 1,627 µs | 1,498 µs | 0.92 |\n| `mapInPandas` of 8 fields | 67.6 µs | 66.2 µs | 0.98 |\n\nOff these paths, of 5 interleaved rounds of all the benches:\n- `simpleString()` of 1,000 fields 400 µs → 464 µs (1.16) and of 8 fields 3.3 µs → 4.3 µs, `repr()` of 1,000 fields 497 µs → 560 µs (1.13), and `hash()`, which is of the repr, 521 µs → 574 µs (1.10): as PySpark\u0027s, they format each field with Python\u0027s `%`, of its attributes as Python reads them.\n- A pickle of 1,000 fields 1,419 µs → 2,355 µs (1.66), and of 40 levels 348 µs → 400 µs (1.15): the reduce of a struct reads each field\u0027s `__dict__` to tell whether its JSON keeps all of its state. Part 3 pickles a struct as PySpark\u0027s plain class.\n- A struct\u0027s `__getitem__` of a name of 8 fields 0.3 µs → 0.5 µs, which reads each field\u0027s `name`, as PySpark\u0027s; `ArrayType(LongType())` 0.8 µs → 1.0 µs, as `__init__` assigns through `setattr`.\n- Faster: a field, an array or a struct of nested types is made of the objects alone (`StructField(\u0027f\u0027, \u003c40 levels\u003e)` 62 µs → 1.0 µs, 1,000 fields 4,421 µs → 2,186 µs, 40 levels 6,445 µs → 352 µs), `toNullable` of 1,000 fields 0.45 and of 40 levels 0.05, `\u003d\u003d` of 1,000 fields 0.66, and `copy.deepcopy` of 1,000 fields 0.81.\n\n**Gates:**\n- build, rustfmt, clippy (1.100.0), rustdoc, ruff, the stub audit, the generators, the guards, the licenses and the stub tests pass.\n- `pyspark-rs` lib tests: 32 passed.\n- The offline suite: 7,609 passed, 121 skipped, 110 xfailed.\n- e2e against Spark 4.3.0: 361 passed.\n- `scripts/check_vendored_upstream.sh` was not run, as no vendored path is touched.\n\n- **Rebased onto master 2bd2ff3e**, with every changed line identical to 226f6cb5 (on 035a1c9c), the commit the gates above ran on. The change overlaps master\u0027s since then only in `dev/parity/known-differences.md`, `docs/compatibility.md` and `python/tests/test_dropin_offline.py`, which merge cleanly.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #957 from HyukjinKwon/SPARK-62251-part2-containers-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "60858c2741e9435d038f5050b273d6876db83a2f",
      "tree": "aa1af6ecccdf0ad9d0069267691692a7a30223c6",
      "parents": [
        "2bd2ff3e26af4ddd3b6133fb9200498bafedd0fe"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 14:52:29 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 14:52:30 2026 +0000"
      },
      "message": "[SPARK-62217][CONNECT][PYTHON] Keep the expressions of Column, WindowSpec and TableArg in their `__dict__` as PySpark\u0027s, on handles that hold their parts, and construct and subclass them of PySpark\u0027s arguments\n\n### What changes were proposed in this pull request?\n\nThis is the tenth sub-task of SPARK-62207, which closes the rows \"The `__dict__` of the objects of a session\" and \"Subclasses\" of `dev/parity/known-differences.md`. It covers the `Column`, the `WindowSpec` and the `TableArg` of `pyspark.sql.connect`, on master after #954 (SPARK-62214, the merge writer).\n\nIn PySpark these are plain Python classes:\n- `Column.__new__(cls, *args, **kwargs)` is `object.__new__(cls)`, `__getnewargs__` gives `(self._expr,)`, and `__init__(expr)` raises `NOT_EXPECTED_TYPE` of an object that is not an `Expression` and sets `self._expr`. Each method reads `self._expr` and makes a new Column of a new expression object, `__repr__` is `\"Column\u003c\u0027%s\u0027\u003e\" % self._expr.__repr__()`, `outer()` is `Column(self._expr)`, `to_plan(session)` is `self._expr.to_plan(session)`, and `__getattr__` is `self[item]`, so a Column whose `__init__` never ran raises a `RecursionError`.\n- `WindowSpec.__new__(cls, partitionSpec, orderSpec, frame)` is `object.__new__(cls)`, and `__init__` asserts a list of expressions, a list of `SortOrder`s and a `WindowFrame` or None, of a bare `AssertionError`, and keeps them as `_partitionSpec`, `_orderSpec` and `_frame`. `partitionBy`, `orderBy`, `rowsBetween` and `rangeBetween` make a `WindowSpec(...)` of the entries that they do not replace, shared.\n- `TableArg.__init__(subquery_expr)` keeps any object as `_subquery_expr`, whose fields its methods read.\n- `over(window)` is `Column(WindowExpression(self._expr, window))`, which holds the window: its message is built of the window\u0027s lists and frame at each request, and so are the errors of the frame bounds.\n\nIn the drop-in, these objects held their state natively:\n- `vars(col)` was empty. `_expr` was a native getter, the Column held its core expression and the `Parts` of it, and the class was neither subclassable (`not an acceptable base type`) nor constructible (`cannot create \u0027Column\u0027 instances`).\n- A window held its core window; `_partitionSpec`, `_orderSpec` and `_frame` were properties made at each read, and its pickle was `pyspark.sql.connect._window_reduce`.\n- `_subquery_expr` was a property, not in `vars()`, which could not be set.\n- A frame bound of `True` or of an int beyond a long raised at `rowsBetween`, where PySpark raises at the request.\n\nThe object-state test file of SPARK-62208 compares these objects with goldens captured from PySpark 4.3.0:\n\n| | Passed | Strict xfails |\n|---|---|---|\n| Before, master ef55bfc1 | 632 | 74 |\n| After, this PR | 675 | 35 |\n\nThis PR fixes the 39 generic cases of the group \"the Column, the WindowSpec and the TableArg\" of `_DIFFERS_BY_CHANGE`, which is deleted: the `vars`, `attributes`, `copies`, `construct`, `uninit` and `foreign` cases of the Column, the Column of a DataFrame, the WindowSpec, the TableArg and the TableArg of `partitionBy`. The other 4 passing tests are new (below).\n\n**The changes:**\n- `crates/pyspark-rs/src/column.rs`:\n  - `PyColumn` holds nothing. Its `#[new]` takes any arguments, as PySpark\u0027s `__new__`, and `__init__(expr)` takes a `_ColumnExpression` or an `Expression` of `pyspark.sql.connect.expressions`, raises `NOT_EXPECTED_TYPE` of another object, and sets `_expr` through `state::assign`.\n  - `ColumnOut`: every method and function that makes a Column gives a core Column, which its conversion makes into a `_ColumnExpression` (once, with the GIL, and so its `Parts::of`) and a Column of the base class that holds it as `_expr`. `_ColumnExpression` keeps gc-shared\u0027s `parts` unchanged, and is now the only holder of the parts of a Column\u0027s expression.\n  - The methods read `_expr` at the call, through `state::attr` (`column_of`): of the `__dict__`, or of a property or a `__getattr__` of a subclass, with the `RecursionError` of a Column whose `__init__` never ran. `Expr` reads it once per method, where PySpark\u0027s method reads it, after the checks of the arguments.\n  - `expression_value`: a `_ColumnExpression` is its own core expression. Another object, such as a `LiteralExpression` or an `Expression` of a class of the user\u0027s, is the message of its `to_plan` (of the client of the active session) at each use, sent as it is, of its own origin, and rendered as its `repr`.\n  - `outer()`, `__repr__`, `to_plan` and `__getnewargs__` are PySpark\u0027s, of `_expr`. `__repr__` renders a `_ColumnExpression` natively.\n  - `expression_attr` reads `_expr` of a Column of the class itself by the generic lookup of its type and its `__dict__`, which is what the class\u0027s lookup does before its `__getattr__`, without the trampoline of that `__getattr__`. A missing `_expr` and a subclass take the full lookup, of PySpark\u0027s errors. `expression_object` makes the `_ColumnExpression` of the GIL that the caller holds.\n  - `__copy__` and `__deepcopy__` are those of a plain object: `__new__` of the arguments of `__getnewargs__`, and the `__dict__`. `__reduce__` pickles the core expression of `_expr` as before, with the other entries of the `__dict__` as its state.\n  - Removed: the `_expr` getter, the native expression and `Parts` of the Column, and its `__traverse__` and `__clear__`: PyO3\u0027s traversal of the `__dict__` reports the `_ColumnExpression`.\n- `crates/pyspark-rs/src/window.rs`:\n  - `PyWindowSpec` holds nothing. `#[new]` takes PySpark\u0027s three arguments. `__init__` asserts PySpark\u0027s types and sets the three entries. `__getnewargs__`, `__getstate__`, and a `__reduce_ex__` of `copyreg.__newobj__` and the `__dict__` at every protocol.\n  - `partitionBy` and `orderBy` make the lists of the `_expr` of `_to_cols(cols)` (of `F._sort_col(c)` for `orderBy`). `rowsBetween` and `rangeBetween` compare the bounds with the thresholds and make PySpark\u0027s `WindowFrame`. Each makes a window of the base class, of the entries that it does not replace.\n  - Fast paths of the same results: the `_ColumnExpression` of the `F.col` of a column name, and of the `asc()` of a name or of a Column of the class, is made at once, with no intermediate Column object. A Column of a subclass calls its own `asc()`. The origins of `col` and of `asc_nulls_first` are of one read of the call site per call (`origin::CallSiteOrigin`), as no Python frame is entered between them; they are PySpark\u0027s, by a probe of both clients. The bounds and the thresholds of an exact `int` are compared natively, and `WindowFrame` is called positionally.\n  - `window_spec_of` makes the core window of the state at the call, for `over`, of the items of an exact list at once (another iterable of its iterator). The partitioning is of `expression_value`. The ordering is of `sort_order_of`: a sort order of the client as it is, and of another object the `sort_order` of its `to_plan`. The bounds of `_frame` are converted as PySpark\u0027s `WindowExpression.to_plan` converts them: 0, the unbounded sentinels, `VALUE_NOT_BETWEEN` of a row bound beyond an int32, and protobuf\u0027s errors of a bool and of an int beyond a long. Each request of a plan of the window expression raises that error (`Expression::unbuildable`).\n  - `__repr__` is of the `__dict__`.\n  - Removed: `FrameArgument`, `ConvertedBound`, `frame_bounds`, `held_bound_error`, `boundary_not_between`, `expression_list` and the native getters.\n- `crates/pyspark-rs/src/tablearg.rs`:\n  - `PyTableArg` holds the ID of the session of its DataFrame only, for its pickle (of the active session, of a `TableArg(subquery_expr)`). `#[new]` takes any arguments, and `__init__(subquery_expr)` keeps any object.\n  - The methods read `_subquery_expr` at the call. The `_ColumnExpression` of the subquery of a table argument is that table argument (`TableArg::of_column`). Another object raises the `AttributeError` of the fields of PySpark\u0027s `SubqueryExpression` that the method reads first (`_partition_spec`, `_with_single_partition`), and then a `TypeError`, as the drop-in has no plan of it.\n  - `to_plan` is `self._subquery_expr.to_plan(session)`. The copies are those of a plain object, and the pickle is as before, with the other entries of the `__dict__` as its state.\n- `crates/spark-connect/src/table_arg.rs`: `TableArg::of_column` (doc-hidden), with a unit test.\n- `crates/pyspark-rs/src/origin.rs`: `CallSiteOrigin`, which gives the origins of several API functions of one native call of one read of the call site.\n- `dataframe.rs`, `functions.rs`, `group.rs`, `ml/stat.rs`, `observation.rs`, `pipelines.rs`, `reduce.rs` and `stat.rs`: the Column return sites give `ColumnOut`, and the Column arguments are read of their `_expr` (`column_of`). `asTable()` gives the table argument object, and the merge clauses, conjunctions and `exists`/`scalar` return their errors.\n- `python/pyspark/sql/connect/window.py`: no `_window_reduce`, which is removed, as the window pickles as PySpark\u0027s plain object, also to a Python worker of the server.\n- **Docs:**\n  - `dev/parity/known-differences.md`:\n    - The `__dict__` row lists the state of the three classes.\n    - It states residue (a): the window expression of `over` and a Column made of a Column of PySpark\u0027s `Expression` are of the state at the call.\n    - It states residue (c): the expressions that the drop-in makes are `_ColumnExpression`s, of PySpark\u0027s `to_plan` and `repr` but not of its classes and fields. The `orderSpec` of `WindowSpec(...)` takes the client\u0027s sort orders only, as `pyspark.sql.connect.expressions` has no `SortOrder`.\n    - The Subclasses row lists the three classes among the subclassable ones, with their `__init__` checks and uninit errors, and drops them from the list of the native classes, which this empties. It says that the pickles of a subclass of `Column` and of `TableArg` unpickle as the base class, with the other entries of the `__dict__` kept, where PySpark\u0027s unpickle as the subclass (until SPARK-62267).\n    - The \"Public base and native MRO\" row says that a data descriptor without a setter patched over `_expr`, `_partitionSpec` or `_subquery_expr` raises its `AttributeError`, as PySpark\u0027s.\n  - `docs/compatibility.md`: a paragraph on the state of the three classes, with the client\u0027s sort orders of `orderSpec`, and the frame bounds at the request. Also the `_subquery_expr` paragraph, the gc holders, the patched descriptors, and the subclass lists.\n\nWhat still differs, as the rows now say:\n- **Until SPARK-62267:** the pickle of an object of a subclass of `Column` or `TableArg` unpickles as the base class, with the other entries of its `__dict__`, as the pickle reduces of the expression; copies, and the window\u0027s pickles, are of the subclass.\n- **Inherent, residue (a):** a Column that a method makes is a value of the core, of the expressions at the call. So a later change of the lists of a window is not in a window expression made of it before, where PySpark\u0027s `WindowExpression` holds the window. A Column made of a Column of a `LiteralExpression` holds the message of its `to_plan` then, where PySpark\u0027s holds the object. The Column of the `LiteralExpression` itself sends its `to_plan` at each request, as PySpark\u0027s.\n- **Inherent, residue (c):** `_expr`, `_subquery_expr` and the window lists hold `_ColumnExpression`, as the expressions are the core\u0027s tree. It has PySpark\u0027s `to_plan` and `repr`, but not PySpark\u0027s classes and fields (`ColumnReference._unparsed_identifier`, `SortOrder._child`, `SubqueryExpression._plan`). Of PySpark\u0027s classes, the drop-in\u0027s `pyspark.sql.connect.expressions` has `Expression` and `LiteralExpression`, which a Column takes, but no `SortOrder`: so the `orderSpec` of `WindowSpec(...)` takes the client\u0027s sort orders only (`asc()`, `desc()` and the others).\n- An `_expr` that is not an expression (`col._expr \u003d 1`) raises the `AttributeError` of its `to_plan` at the first method, where PySpark\u0027s methods raise the errors of its expression classes (`\u0027int\u0027 object has no attribute \u0027alias\u0027`, an `AssertionError`).\n\n**A choice that departs from the design:** a Column of an `Expression` of PySpark\u0027s classes converts it at each use, and keeps no identity cache of the conversion. PySpark builds the message of the expression at each request, so a change of the fields of the expression object is in the next request (`literal._value \u003d 6`), as it now is in the drop-in. The converted message holds no Python object, so no parts are reported, and the native Column holds nothing, not even a `GcReady`. The cost is one `to_plan` per use of such a Column, a rare path.\n\n**Garbage collection:** `PyColumn`, `PyWindowSpec` and `PyTableArg` have no `__traverse__` of their own. PyO3\u0027s traversal of their `__dict__` reports the `_ColumnExpression`s, and each `_ColumnExpression` reports the parts of its expression. gc-shared\u0027s probes `p_shapes_collected.py` (17 shapes) and `p_copies_free.py` (5 cases) give True for every case on this branch. `test_holders_that_share_a_plan_report_each_reference_once` and `test_objects_traversed_while_they_are_created_do_not_crash` pass unchanged.\n\n### Why are the changes needed?\n\nIn PySpark, code that reads or writes the state of a Column, a window or a table argument works because the state is in their `__dict__`. Examples: `vars(col)`, `Column(col._expr)`, `Column(LiteralExpression(...))`, `col._expr \u003d other._expr`, `WindowSpec(*args)`, a subclass of `Column`, and `w._partitionSpec` that a library reads. Until now none of these worked in the drop-in.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. The `Column`, `WindowSpec` and `TableArg` of `pyspark.sql.connect` keep their state in their `__dict__`, as PySpark\u0027s:\n- `vars(F.col(\"a\"))` is `{\u0027_expr\u0027: a}`, `vars(Window.partitionBy(\"a\"))` has `_partitionSpec`, `_orderSpec` and `_frame`, and `vars(df.asTable())` has `_subquery_expr`;\n- the classes construct of PySpark\u0027s arguments and subclass;\n- `Column(expr)` takes the expression of another Column or an `Expression` of `pyspark.sql.connect.expressions`, and raises `NOT_EXPECTED_TYPE` of another object;\n- `WindowSpec(...)` asserts PySpark\u0027s types, and the window\u0027s methods share its lists;\n- the errors of the frame bounds of `True` and of an int beyond a long are raised at the request, as PySpark\u0027s;\n- a window pickles as PySpark\u0027s plain object.\n\nMaking a Column costs about 190 to 260 ns more, for the `_ColumnExpression` and the `__dict__` of each, which the design keeps, and the read of `_expr` by the next method. The cuts here, the direct read of `_expr` and the handle made of the caller\u0027s GIL token, are within the noise of the runs (about 50 ns). The window methods make no intermediate Column, and their origins take one read of the call site per call. The numbers are the best of five rounds of 50,000 calls, with the collector off and no session, in ns per call. The base is #943\u0027s build, whose Column and window code is master\u0027s:\n\n| | Before | After | |\n|---|---|---|---|\n| `F.col(\u0027a\u0027)` | 3420 | 3607 | +187 |\n| `c + 1` | 1116 | 1379 | +263 |\n| `c.alias(\u0027x\u0027)` | 1361 | 1601 | +240 |\n| `F.sum(c)` | 4788 | 4821 | +33 |\n| `c.isNull()` | 930 | 1144 | +214 |\n| `repr(c)` | 159 | 196 | +37 |\n| `Window.partitionBy(\u0027a\u0027)` | 4099 | 4378 | +279 |\n| `w.orderBy(\u0027a\u0027)` | 1232 | 1558 | +326 |\n| `F.sum(c).over(w)` | 6015 | 6505 | +490 |\n\nBefore the window fast paths, `w.orderBy(\u0027a\u0027)` took 2907 ns, `Window.partitionBy(\u0027a\u0027)` 4711 and `F.sum(c).over(w)` 6919.\n\n### How was this patch tested?\n\n- **`tests/test_dropin_object_state_offline.py`:** the group \"the Column, the WindowSpec and the TableArg\" is deleted from `_DIFFERS_BY_CHANGE`. On this branch: 675 passed and 35 xfailed. With PySpark 4.3.0: 710 passed. Four new tests cover what this PR adds, and pass with both clients:\n  - a Column keeps the expression that it is given: `Column(col._expr)` and `outer()` share it; a `LiteralExpression` and an `Expression` of the user\u0027s class are sent of their `to_plan`, without the origin of the call, of their fields at each request; `NOT_EXPECTED_TYPE` of four other objects;\n  - a Column reads its expression of its `__dict__`: an assigned `_expr`, a subclass\u0027s property, and the `RecursionError` of a deleted one;\n  - window specifications assert PySpark\u0027s arguments (six cases), share their lists and frame, and the window expression of `over` is of the lists then, of an expression of the user\u0027s too;\n  - a table argument reads its subquery of its `__dict__`: of another\u0027s `_subquery_expr`, and the `AttributeError` of `_partition_spec` of an `int`.\n- **`tests/test_dropin_offline.py`:**\n  - `test_freed_instances_release_their_dict_as_pyspark`: `vars()` of a Column holds `_expr`.\n  - `test_window_frame_bounds_are_compared_asserted_and_converted_as_pyspark`: the errors of `True` and of an int beyond a long are raised at the build of the plan.\n  - A new test, `test_a_column_whose_expression_is_replaced_holds_and_reports_the_new_expression_only`: the old expression is freed with its UDF\u0027s function at once, the `__dict__` holds the new one, and no reference is reported more than it is held.\n- **`tests/test_dropin_window_tablearg_offline.py`:** the pickles of a table argument have a new `_subquery_expr` of the same `repr`, and a window copies and pickles its three entries at every protocol.\n- **`tests/test_dropin_e2e.py`:** a new live test, `test_columns_windows_and_table_arguments_keep_their_state_in_their_dict_as_pysparks`. Against a Spark 4.3.0 server:\n  - a Column of a `LiteralExpression` and a Column of an assigned `_expr` give their rows;\n  - a `WindowSpec` of PySpark\u0027s arguments gives the running sums;\n  - a row frame bound beyond an int raises `VALUE_NOT_BETWEEN` at `collect()`;\n  - a UDTF of a `TableArg` of another\u0027s `_subquery_expr` counts its rows.\n\n  It passes with both clients.\n- **The gates:**\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 31 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7838 passed, 121 skipped, 36 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 366 passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #953 from HyukjinKwon/SPARK-62217-object-state-column.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "2bd2ff3e26af4ddd3b6133fb9200498bafedd0fe",
      "tree": "730d7b62dc742ffc3ffe2b39f7550a9c8beff859",
      "parents": [
        "29d93adf54fa5242aa0335e95d8967ec36326ad5"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 13:08:28 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 13:08:28 2026 +0000"
      },
      "message": "[SPARK-62264][CONNECT][PYTHON] Copy the messages of a constructor natively, of no Python object, and make the objects of a copy when Python reads them\n\n### What changes were proposed in this pull request?\n\nA message of the drop-in\u0027s protobuf runtime (`crates/pyspark-rs/src/pbmsg`) given to a constructor, such as `proto.MergeAction(condition\u003dc)` or `proto.MergeAction.Assignment(key\u003dk, value\u003dv)`, was copied in `message_for_field`:\n- first `deeper_than`, a walk of the message for upb\u0027s depth limit of a parse, which visits every message of a message that is not too deep;\n- then `duplicate_with`, a deep copy that made a Python object of every message, repeated field and map below it: a registry lookup of its class (a global mutex and a SipHash of its full name), a GC allocation, PyO3\u0027s atomic borrows and a TLS read of the stack\u0027s room per level, and their deallocation when the copy died.\n\n`CopyFrom`, `copy.copy` and `copy.deepcopy` made the same copy. PySpark\u0027s merge clause, which SPARK-62214 runs on the drop-in\u0027s messages, builds a `MergeAction` and its `Assignment`s of the messages of its Columns this way, and its merge copies them again into an `Expression`, a `MergeIntoTableCommand` and a `Command`.\n\nOn master, the two constructors of one `update({v: x})` clause took 7.2 µs, and PySpark\u0027s 3.2 µs. About 5 µs of that was the copies of 11 messages and 2 containers. A flat profile of them:\n\n| Category | Share |\n|---|---|\n| the allocation and deallocation of the objects of the copies | 18.2% |\n| the copy code | 14.7% |\n| the registry lookups of their classes | 10.4% |\n| the TLS read of `stacker::maybe_grow` per level | 6.1% |\n| PyO3\u0027s borrow checks | 5.6% |\n| PyO3\u0027s trampolines (its reference pool\u0027s mutex at each call) | 5.8% |\n| the depth walk | 1.5% |\n| the keyword arguments of the constructors | 20.3% |\n| the interpreter and the rest | 16.5% |\n\n**The change.** A copy now holds what it copies natively, and makes the Python objects of it when Python reads them:\n- **Native values** (`pbmsg/native.rs`). A slot of a field may hold `Slot::Native(Value)`: an immutable copy of the value of a message field (`Native`, whose slots hold scalars and native values only), a repeated scalar field, a repeated message field (with the class of its container) or a map, behind an `Arc`, of no Python object. `PyMessage` holds its descriptor, its slots and its unknown fields as `Fields`, the struct that a native message holds too, so every reader reads both through one function.\n- **Copies are native.** `copy_parts` reads the message under a short borrow, as before: its scalars, its repeated scalars and the native values that it holds, which it shares (a message of scalars only at once). It then copies its messages, containers of messages and maps after the borrow, in their places, a step of the interrupt budget per message copied, as before. `copy_as`/`duplicate_with` still give an object of the class that they chose before, of native fields. `message_for_field` gives the native copy itself, so `proto.MergeAction(condition\u003dc, assignments\u003d[a])` makes no Python object but the `MergeAction`. So do the repeated message fields of a constructor whose values are all messages of the runtime. A copy of a copy shares what the copy holds: `proto.Expression(merge_action\u003daction)` copies an action of any size at once.\n- **The depth is bounded in the copy.** The copy counts the levels of the message as `deeper_than` does (a message, a repeated message, a map entry and the message of its value each a level), and stops at the first message past the limit. The constructor and `copy.copy` then copy the message of its bytes, as before, of upb\u0027s `DecodeError`. A native value keeps its depth, so neither the copy nor `deeper_than` (of `MergeFrom`) walks it. The copy reads the room of the stack every 16 levels.\n- **Objects on the first read** (`PyMessage::materialize`). Python reads a native value only through an object:\n  - The first `__getattribute__` of the field, `ListFields`, and every operation that changes the field or needs its container (`MergeFrom`, a parse into the message, a second `__init__`) make the object of one level of the value. It is a message whose own values stay native, a container of messages, a container of scalars, or a map. `CopyFrom` into a message gives an unset child that it gave out the fields of the copy, as before.\n  - The object is allocated empty, with no borrow of the message held, and set in the slot only if the slot still holds the same value. Then it takes the value\u0027s fields, moved when no other copy holds them.\n  - The field gives that object from then on.\n  - The readers that give no object read native values as they are: serialization, `ByteSize`, `\u003d\u003d`, `repr`/`str`, the text format, `IsInitialized`, `FindInitializationErrors` and the copies. `DiscardUnknownFields` changes a native value of a clone of what it shares.\n- **Classes.** `_proto_register_classes` counts a generation when it gives a full name another class, and keeps the class that each name had before. A native message keeps the generation of its copy, and its objects are of the class registered then. So a class registered between a copy and its read changes nothing, as the eager copy made its objects at once.\n- **Drops.** A native message of 64 levels or more is dropped a level at a time, as a Rust drop has no trashcan; the objects keep CPython\u0027s.\n- Two smaller changes of the constructor\u0027s path: an int of 64 bits is converted at once (`PyLong_AsLongLongAndOverflow`), without PyO3\u0027s 128-bit conversion, which the stable ABI makes of shifts of the int; and the name `items` of the keywords\u0027 `items()` is interned.\n\n**The benchmark** (`bench.md`): µs per call, the best of 7 interleaved rounds of fresh interpreters, each the best of 3 `timeit` runs. Before is master b6126ae5, after is this PR, PySpark is pyspark-client 4.3.0 of upb. The messages of the Columns are each client\u0027s own `to_plan`:\n\n| Case | Before | After | PySpark |\n|---|---|---|---|\n| `Assignment(key\u003dk, value\u003dv)` | 2.09 | 1.34 | 1.12 |\n| `MergeAction(condition\u003dc)` | 3.04 | 1.68 | 1.07 |\n| `MergeAction(condition\u003dc, assignments\u003d[a])` | 5.07 | 2.29 | 1.96 |\n| `build update`: `_build_merge_action` of `update({\"v\": v})`, `to_plan` included | 18.28 | 14.92 | 12.14 |\n| `build updateAll` | 0.95 | 0.85 | 0.43 |\n| `merge command of 2 clauses` | 42.22 | 8.47 | 12.00 |\n| `command.SerializeToString()` | 3.65 | 2.91 | 1.21 |\n| `MergeAction(condition\u003dbig)`, an expression of 40 additions, 161 messages | 58.41 | 27.16 | 11.08 |\n| `MergeAction(condition\u003dbig).SerializeToString()` | 16.80 | 13.71 | 6.58 |\n| `copy.deepcopy(big)` | 53.75 | 27.75 | 13.13 |\n| `copy.copy(c)` | 2.07 | 1.11 | 2.63 |\n| `Plan().root.CopyFrom(relation)` | 1.70 | 1.15 | 0.68 |\n| `MergeAction(condition\u003dc).condition.unresolved_function.arguments[0]` | 3.28 | 3.13 | 1.48 |\n\n- `merge command of 2 clauses` is the body of PySpark\u0027s `merge()` up to the request: copies of copies, which share what they copy.\n- `build update` and `build updateAll` are PySpark\u0027s `_build_merge_action` (SPARK-62214\u0027s clause), of the `to_plan` of its Columns. The rest of their gap to PySpark is outside the copies: the parse of `to_plan` (`v.to_plan(client)` takes 2.2 µs, PySpark\u0027s 0.8), and PyO3\u0027s handling of keyword arguments. PyO3 builds a dict of them for `__new__` and for `__init__`, and encodes each name to UTF-8 under the stable ABI: `MergeAction(condition\u003dNone)` takes 0.30 µs more than `MergeAction()`, upb\u0027s 0.08.\n- What reading costs now. A field that is read makes its object when it is first read. A program that reads every message of a copy pays the native copy and the objects: for the expression of 161 messages read to the bottom, 183 µs, before 160 µs and PySpark 115 µs. Large flat copies of a message that a parse made cost a little less than before: `CopyFrom` of a literal array of a million literals takes 0.24 s, before 0.26 s and upb 0.10 s, and `MergeFrom` takes 0.30 s, as before.\n\n`docs/compatibility.md` says so in its paragraph of the objects of the runtime\u0027s messages.\n\n### Why are the changes needed?\n\nPySpark\u0027s Python code runs more and more of its plans and commands on the drop-in\u0027s messages: the merge clauses of SPARK-62214, the readers, writers and their commands, and `pyspark.ml`\u0027s commands. Their constructors copied each message as Python objects, two to three times as slow as upb\u0027s copies, and their copies of copies (the merge command) again in full: 41 µs against PySpark\u0027s 12 µs for the command of two clauses.\n\n### Does this PR introduce _any_ user-facing change?\n\nNo change of behaviour. The copies give the same messages, of the same bytes, text, equality, fields, presence and pickles. They have the same independence from their sources and from each other, and the same identity of the objects of their fields at each read. Their objects are of the same classes, not tracked by the garbage collector, and of no parent or owner, as the copies\u0027 objects were. The same errors come from the same values in the same order, and the same `DecodeError` from the same depths.\n\nOnly speed changes, and what Python cannot read through the protobuf API: when the objects are allocated and how many. So `sys.getrefcount` of a class, `gc.get_count()` and the memory of a copy change.\n\n### How was this patch tested?\n\n- **New tests in `tests/test_proto_rust_offline.py`**, each run of the same code on the runtime\u0027s messages and on upb\u0027s:\n  - `test_constructor_copies_are_independent_of_their_sources_as_upbs`: changes of copies and of their sources, of a message field, a nested message, a repeated field of messages and of scalars, a map of messages and of scalars, a oneof, and copies of copies.\n  - `test_random_operations_on_constructor_copies_agree_with_upb` (6 seeds; 300 seeds once): random operations of the lockstep on messages, on the copies that a message field, a repeated field and a map make of them, and on copies of those copies, compared after each.\n  - `test_constructor_copies_keep_their_identity_as_upbs`: `n.f is n.f`, nested, containers, items, map values, `ListFields`, and not the source; weak references; the objects untracked by the GC and `gc.get_referents`.\n  - `test_operations_on_constructor_copies_are_upbs`: bytes, `ByteSize`, text, `\u003d\u003d`, `ListFields`, `HasField`, copies, merges, `Clear`, `DiscardUnknownFields`, parses, of copies whose fields no object was made of yet; pickles of the runtime\u0027s.\n  - `test_constructor_copies_fail_from_the_depths_of_upbs`: PySpark\u0027s merge chain of constructors (Assignment, MergeAction, Expression, MergeIntoTableCommand, Command) of chains of 46, 47, 48, 49, 100 and 120 additions, of an origin on the leaf column. The `DecodeError` comes first at 47 for an assignment, 48 for a clause condition and 49 for the merge condition, at the same constructor and of the same message as upb\u0027s; and `copy.copy` of each.\n  - `test_constructors_raise_the_errors_of_upbs_beside_the_copies`: messages of other types, ints, lists, fields of no name before and after a copy, bad enums before and after, Timestamps of a `datetime`, a str and a Timestamp.\n  - `test_copies_of_copies_change_alone_as_upbs`: `DiscardUnknownFields`, changes and merges of copies that share their native values.\n  - `test_fields_of_constructor_copies_change_as_upbs`: an unset child that `CopyFrom` fills, `MergeFrom` into an unset child, a parse into a copy, a second `__init__`, `ClearField`, a oneof, the methods of the containers and maps of a copy, merges of copies, `ListFields` and Timestamps.\n  - `test_copies_of_messages_of_proto2_and_editions_are_upbs`: copies of required fields (of `LEGACY_REQUIRED` too), groups, delimited messages, closed enums and maps of messages of the plugin\u0027s files; their missing fields, `EncodeError`, bytes, text and JSON.\n  - `test_copies_are_of_the_classes_registered_when_they_were_made`: a class registered between a copy and its read.\n  - `test_deep_copies_build_compare_and_drop_on_a_small_stack`: a message of 30,000 levels copied (`copy.deepcopy`, `CopyFrom`), compared, encoded, discarded of its unknown fields, read to the bottom and dropped on a thread of 512 KiB; its constructor copy fails at upb\u0027s limit.\n- **A new Rust test**, `pbmsg::native::tests::deep_native_messages_drop_a_level_at_a_time`: a native message of a million levels drops on the 2 MiB stack of a test thread.\n- **The new tests pass on master\u0027s extension too**, so they describe the behaviour as it was. A probe of 17 sequences of operations on copies, unset children, merges and parses gives the same results (bytes, identities, classes, GC tracking, errors) on master and on this PR.\n- **One test changed:** `test_python_thread_runs_before_operations_on_large_messages_finish[constructor of a list]` read the progress of the constructor from the references to the class of its messages, which no object of the copies holds now. It now reads the references to the list, which the constructor holds while it copies. It passes on master and on this PR.\n- The existing deep tests are kept: `test_messages_of_more_than_100_levels_fail_where_upb_parses_their_bytes`, `test_copy_from_and_eq_of_protobufs_messages_take_any_depth_as_upbs`, `test_deep_messages_discard_and_build_on_a_small_stack` and `test_a_command_expression_too_deep_to_send_raises_recursion_error_as_pyspark`.\n- **The Rust and Python gates** (`gates.sh build rust py`), all passing: `cargo fmt --all --check`; clippy 1.100.0 of `-D warnings`; `cargo doc` of `-D warnings`; `cargo test -p pyspark-rs --lib`, 38 passed; ruff 0.14.0, `test_ruff_excludes.py`, `scripts/audit_no_stubs.sh`, the stub and dispatch generators, the test-list guards and the license checks; `test_type_stubs_offline.py`, 15 passed, 4 skipped; the offline suite of `coverage.yml`, 7,419 passed, 121 skipped, 163 xfailed.\n- **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 359 passed, 5 subtests passed. The tests without `protobuf` (CI\u0027s parity job) of `tests/test_proto_rust_offline.py`: 32 passed, 125 skipped.\n\n- **Rebased onto master c81099b3**, with every changed line identical to 59a7e1ec (on b6126ae5), the commit the gates above ran on; the change overlaps master only in `docs/compatibility.md`.\n\n- **An independent review** (about 870k lockstep fuzz steps against upb and master, 43 targeted scenarios, threads, signals, 30k-level copies on a 512 KiB stack) found every observable identical to master. It also measured the cost of copying and then reading all of a copy at more than this text first said:\n  - CopyFrom or deepcopy of a parsed 100k-literal list, then a read of all of it: 1.26-1.27× master;\n  - the first full read of a fresh copy: 1.61×;\n  - a 161-message expression copied and then read in full: 1.12×.\n\n  Copies alone and partial reads cost 0.2-0.73× of master. Its findings for a follow-up: a first read of a copy\u0027s field while another thread prints the message can raise a borrow error; the GIL release of the first read of large copied containers; more tests of the native path.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #955 from HyukjinKwon/SPARK-62264-pbmsg-copy.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "29d93adf54fa5242aa0335e95d8967ec36326ad5",
      "tree": "8a0d0a31b6d4daef030d7b2854640c43ef9c4885",
      "parents": [
        "ef55bfc11620a9521432091ac1f814055c67d5f0"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 12:22:16 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 12:22:16 2026 +0000"
      },
      "message": "[SPARK-62257][CONNECT][PYTHON] Pool the transport\u0027s connections by resolved address, of each channel\u0027s own resolution and pick_first, as gRPC\u0027s subchannel pool does\n\n### What changes were proposed in this pull request?\n\nA follow-up of SPARK-62234 (#944): the two differences that its KD row \"Custom gRPC channels\" listed \"until SPARK-62257\".\n\ngrpcio\u0027s channels share their connections through gRPC\u0027s global subchannel pool, which keys a subchannel by its resolved address and the channel arguments (credentials included), while each channel has a resolver and a `pick_first` of its own over the subchannels of the addresses that its own resolution gives. The transport pooled one connection by target instead (`CHANNELS` of `ChannelKey` in `client.rs`, and the target-level state machine of `Connector` in `connector.rs`), so:\n1. the channels that shared a connection resolved the name again once between them as it failed, where each grpcio channel resolves it of its own;\n2. a new channel used the shared connection whatever addresses its own resolution gave.\n\nSo the transport now has the structure of gRPC\u0027s:\n- **`connector::subchannel` (new)**: the subchannels of the process, per generation of `fork()`, keyed by (address, `SubchannelArgs`): the origin of the calls (`grpc.default_authority` and the scheme), the keepalive, the tunnel of a proxy and its `Proxy-Authorization`, the name that TLS verifies and how (gRPC\u0027s check or webpki\u0027s), local credentials, the dialect, and the call credentials of a channel of its own (a token), which no other channel shares; the roots that TLS trusts are those of the process, which it reads once, the system\u0027s store too, as the first TLS channel is made, as grpcio computes its default roots once. A subchannel has gRPC\u0027s connectivity state (idle, connecting, ready, transient failure): it connects to its one address only when a channel asks it to, of the tunnel and the TLS of its arguments at connect time, with the deadline of the longer of 20 s and its backoff; in grpcio\u0027s dialect a failure leaves it in transient failure until gRPC\u0027s backoff from the start of the attempt ends (1 s, x1.6 up to 120 s, 20 % jitter), then idle; a connection that ends leaves it idle and starts its backoff again. Its connection is that of a channel of tonic of its own, whose connector hands over the connection that the subchannel made, so every channel that picked it multiplexes its calls on the one connection; the drop of the connection by hyper tells the subchannel that it ended (`Handover`\u0027s `ConnectionEnd`), and so does the server\u0027s GOAWAY, which `Handover` sees as it follows the frames that it gives hyper (`FrameWatch`), as gRPC\u0027s subchannel goes idle at a GOAWAY while hyper keeps the connection for the calls in flight. A call that tonic sends as the connection ends, as one that picked the subchannel just before, makes the connector ask for a connection again: it takes the one that the subchannel holds if it is still open, else that of one attempt, which it makes, or waits for while one is in progress, as it is, also as it ended since, which then fails the call of its end, or it fails the call of `UNAVAILABLE` of the failure of that attempt, or of the last failure in transient failure, at once; so a call makes one attempt at most, as a call of the transport did before, and the connector holds the subchannel only while it reads its state, so that a subchannel that no channel holds any more is freed as a call waits for its attempt, which then fails.\n- **`connector::pick_first` (new)**: `ClientChannel`, the channel of each client (each lease of a `SparkConnectClient`, of each generation), with a resolver and a `pick_first` of its own:\n  - the first call resolves the name (SPARK-62234); a failure fails the calls at once and is tried again in the background a backoff after its end (SPARK-62233), and the channel connects once it resolves, also of no call;\n  - a ready subchannel of its addresses, of any channel, is picked at once, the first in their order; else the addresses are connected in turn, of happy eyeballs (250 ms, or at once once the attempt fails), skipping those in transient failure; the others are let go once one is picked;\n  - once every subchannel failed: transient failure, of the last failure; each subchannel connects again as its backoff ends, and the channel asks its resolver for a re-resolution each time all of them failed again;\n  - the end of the picked subchannel\u0027s connection, or its GOAWAY, asks for a re-resolution and leaves the channel idle: the next call connects to the latest addresses (the channel keeps that subchannel until then, so that its next pass takes a connection that the subchannel made meanwhile for a call that tonic sent as the connection ended, rather than a new subchannel of the address);\n  - the resolver resolves again when asked, no sooner than 30 s after the start of its last resolution, in the background (SPARK-62233, now of each channel); a resolution that fails after one that succeeded keeps the addresses of that one; one that comes while ready takes at once the first subchannel of its addresses that is ready, of any channel, its own too, and of none lets go of the picked subchannel, whose connection ends once no other channel holds it, and is idle, so that the next call connects to the new addresses, as gRPC 1.85.1\u0027s `pick_first` (\"dropping existing connection and going IDLE\");\n  - after 30 min without a call, a channel in transient failure stops connecting and makes its resolver again; the close of its client (`SparkConnectClient::close`, a session\u0027s `stop()`) lets go of its subchannels, whose connections end once no other channel holds them, as grpcio\u0027s `close`.\n  - A Rust client\u0027s channel resolves at each call that needs a connection and fails that call (and those that waited for it) of the failure, as tonic\u0027s channel, of no backoff nor background work, and asks no subchannel to connect again once its pass failed; it shares the subchannels of the process as before.\n- **`metadata::Checked`** takes the connection that the client\u0027s channel picks for each call (the pick waits are ended by the close of the client, as #917\u0027s cancel of the calls in flight); `poll_ready` is ready at once. An error of a call before its response, of its pick, of the readiness of its channel of tonic or of its response, is `CANCELLED` (`Channel closed!`) once the client closed its channel, as grpcio\u0027s `close` cancels the calls in flight, whatever ended it, as the connector of a subchannel that the close let go of while the call waited for its attempt; the close marks the channel closed before it lets go of its subchannels. `ChannelFactory::channel` makes a `ClientChannel` of each lease; `PooledChannel`, `ChannelKey`, `CHANNELS`, `Connector`, `ChannelResolution`, the target-wide resolution cache of `Target` and its `TargetKey` are gone.\n- **The details of a call that the end of its connection fails**, in the dialect of grpcio: a failed write of the connection fails the call of grpcio\u0027s text of its error, `Stream removed (sendmsg: Broken pipe (32))`, where it was tonic\u0027s `transport error` (`Handover`\u0027s writes and flushes, and `stream_removed_in`); and the end of a connection of which h2 or hyper kept no cause, of the streams that h2 ends as hyper drops the connection after its first failure (`connection closed because of a broken pipe`, `stream closed because of a broken pipe`) and of a request that hyper did not send as the connection closed, is `Stream removed (Socket closed)`, where it was tonic\u0027s `transport error` and hyper\u0027s `operation was canceled`. The code stays `UNAVAILABLE`, a cancellation that the client makes (the close of its channel, a deadline) keeps its code and its text, and the Rust client keeps tonic\u0027s message.\n- `dev/parity/known-differences.md`: the row \"Custom gRPC channels\" no longer lists the two differences; the row \"The connections of the transport\" describes the subchannels, and the text of a call that the end of its connection fails, which is `Socket closed` where h2 dropped the cause (inherent: h2 0.4 keeps no cause there, and grpcio\u0027s own text depends on the timing); the row of the details of a failure that the client detects lists `Stream removed (sendmsg: Broken pipe (32))`. `docs/compatibility.md` describes them, of the Rust API and of the Python client.\n\nChecked on three clients against a Spark 4.3.0 server, of the probes of this PR (`p_steps.py`, a counting relay of each address on 127.0.0.1-.3 and a DNS responder of a zone of `s.h.test`, each probe in a process of its own, no retry policy): pyspark-client 4.3.0 (grpcio 1.85.1), the drop-in before this PR (the tip of SPARK-62254), and now.\n\n**Connections** that a program of sessions of one target opens, after each session runs `range(2).count()` (the first session, its `newSession()`, its `cloneSession()`, another `remote()`):\n\n| target | sessions | pyspark-client 4.3.0 | before | now |\n|---|---|---|---|---|\n| `sc://127.0.0.1:\u003cport\u003e` | 1, 2, 3, 4 | 1, 1, 1, 1 | 1, 1, 1, 1 | 1, 1, 1, 1 |\n| `sc://localhost:\u003cport\u003e/;token\u003dt` | 1, 2, 3, 4 | 1, 2, 3, 4 | 1, 2, 3, 4 | 1, 2, 3, 4 |\n| `sc://localhost:\u003cport\u003e/;use_ssl\u003dtrue` (a TLS relay of a CA of the probes) | 1, 2, 3, 4 | 1, 1, 1, 1 | 1, 1, 1, 1 | 1, 1, 1, 1 |\n| `sc://localhost:\u003cport\u003e/;use_ssl\u003dtrue;token\u003dt` | 1, 2, 3, 4 | 1, 2, 3, 4 | 1, 2, 3, 4 | 1, 2, 3, 4 |\n\n**DNS queries** of `dns://127.0.0.1:\u003cdns\u003e/s.h.test:\u003cport\u003e`, of the same four sessions: one resolution (`A` and `AAAA`) of each session, on all three clients.\n\n**Addresses that change between sessions** (`s.h.test` of the zone at each session; where the calls of a session went, of the relay of each address):\n\n| a session of | pyspark-client 4.3.0 | before | now |\n|---|---|---|---|\n| .1 (the first) | a connection to .1 | a connection to .1 | a connection to .1 |\n| .2, a `newSession()` | a new connection to .2 | the connection to .1 | a new connection to .2 |\n| [.3, .1], .3 of a server that accepts and never answers, .1 connected | .1 at once, no attempt to .3 | the connection to .1 | .1 at once, no attempt to .3 |\n| [.3, .1] in a fresh process | .3 first, .1 250 ms later | .3 first, .1 250 ms later | .3 first, .1 250 ms later |\n| [.2, .1], both connected | .2 (the first; .1 in 2 of 5 runs of a clone, a race of grpcio) | the connection to .1 | .2 |\n| .4, of no server | `failed to connect to all addresses; last error: UNKNOWN: ipv4:127.0.0.4:\u003cport\u003e: Failed to connect to remote host: Connection refused` | count\u003d2, of the connection to .1 | the same failure as grpcio\u0027s |\n\n**After a connection failure**, of two sessions of one connection (`DNS` \u003d the resolutions of each session, at the times of the probe):\n\n| case | pyspark-client 4.3.0 | before | now |\n|---|---|---|---|\n| the relay resets the connection 31 s after the resolutions, no call | both re-resolve at once (31.2 s), the next calls open 1 connection | none until the next call, then 1 | both re-resolve at once (31.2 s), 1 connection |\n| the reset 2 s after the resolutions (at 0 s and 1.1 s) | each re-resolves 30 s after its own (30.0 s, 31.2 s) | none until the next call, then 1 | 30.0 s, 31.1 s |\n| refused for 65 s, then listening | each re-resolves every 30 s while it cannot connect (30, 60, 90, 120 s) | one between them (41 s) | 30, 60, 90 s, until its subchannel reconnected (77 s here, 114 s of grpcio\u0027s, of the backoff\u0027s jitter) |\n| the reset 31 s after, the DNS server answering SERVFAIL | the re-resolution fails (retried 1, 1.5, 2.6 s after its end), the next call connects to the previous address | the next call fails: `errors resolving s.h.test:\u003cport\u003e: ... DNS server returned general failure` | as grpcio: retried, and the call connects to the previous address |\n| a first resolution of NXDOMAIN, the name added 10 s later | the call fails; retried in the background (0.8, 2.7, 4.8, 8.8, 16.4 s) of no call, and connected in the background at 16.4 s | no retry without a call | retried at 0.9, 2.3, 5.2, 8.9, 15.7 s, connected at 15.7 s |\n| a graceful GOAWAY (NO_ERROR, the connection left open) 31 s after the resolutions, no call in flight | the connection closes, both re-resolve at once, the next calls open 1 connection | the connection closes; one re-resolution between them, at the next call | as grpcio |\n| the same GOAWAY while a query of 8 s is in flight on the connection | both re-resolve at once, 1 new connection, the old one closes once the query ends | one re-resolution between them, at the next call (a release of the query, 1.5 s later), 1 new connection | as grpcio |\n| `stop()` of the last session of the connection | the connection closes; a new session connects again | the connection stays while the session objects live | as grpcio |\n| a resolution that comes while connected and gives another address (.1 reset at 2 s and connected again, the name moved to .2, the re-resolution at 30 s) | the connection to .1 closes at the resolution, of no attempt to .2; the next call connects to .2 | no resolution again; the calls stay on .1 | as grpcio |\n\n**A server that closes each connection once it sent its settings**, 3 rounds of 30 calls of no retry policy (each of `UNAVAILABLE` on all three clients), the connections that the server accepted in each round and the details of the 90 failures:\n\n| client | connections of each round | details |\n|---|---|---|\n| pyspark-client 4.3.0 | 6,051, 7,816, 4,154 (grpcio connects again while its picked subchannel is not ready for the call) | `Stream removed (recvmsg:Connection reset by peer (104))` 48, `Stream removed (sendmsg: Broken pipe (32))` 30, `Stream removed (sendmsg: Connection reset by peer (104))` 6, `Stream removed (Socket closed)` 6 |\n| before | 30, 30, 30 | `Stream removed (Socket closed)` 38, `Stream removed (recvmsg:...)` 35, `transport error` 17 |\n| now | 60, 44, 60 (two at most of each call: of the pass of its channel, and of the connector, once the connection that the pass made ended before the call took it) | `Stream removed (recvmsg:...)` 49, `Stream removed (Socket closed)` 41 |\n\n**The DNS probe sets of SPARK-62232** (D\u0027s harness and cases, on the ports of this PR: a responder of the zone of `probe.test` at 127.0.0.1 and [::1], the namespaces of dead nameservers, `HOSTALIASES`, `LOCALDOMAIN` and `RES_OPTIONS`), each case in a process of its own, of the outcome of its call and the queries that the responder received, against pyspark-client 4.3.0:\n\n| sets | cases | outcomes (before / now) | query lists (before / now) |\n|---|---|---|---|\n| cases1, `HOSTALIASES`, the 11 namespaces, `LOCALDOMAIN`, `RES_OPTIONS` (25 cases again), the errors of DNS, the order of the addresses, `TC, TCP refused`, the first UDP query dropped of a fresh responder | 107 | 107 / 107 | 107 / 107 |\n| a re-resolution of 4 calls, of NXDOMAIN and of a refused port | 2 | 2 / 2 | 1 / 2 |\n| the timeouts | 10 | 9 / 9 | 8 / 8 |\n\n119 of 119 cases ran: 118 outcomes and 117 query lists match now (118 and 116 before); a sample of the sets run again on the final head (cases1, the errors of DNS, the re-resolution) matches in all its 35 outcomes and query lists. Of the 4 calls 2 s apart of NXDOMAIN, grpcio resolves the name at 0, 1.1, 2.8 and 5.1 s, of its backoff in the background, and the drop-in now at 0, 1.1, 2.7 and 5.0 s, where it resolved at the calls (0, 2 and 4 s). The timeout set differs the same before and now: `first UDP query dropped` of that set is of the probe (the responder had dropped its one query for grpcio\u0027s run already; the set of that case alone, of a fresh responder, matches), and `TC then TCP closed` (a server that closes its TCP connection after each answer) is SPARK-62232\u0027s case of the TCP queries before each close, whose failure grpcio gave as `DNS query cancelled` in this run, of its timing, where SPARK-62232\u0027s run of it matched.\n\n### Why are the changes needed?\n\nSo that the sessions of a process connect, resolve and recover as PySpark\u0027s do: a new session connects to the addresses that its own resolution gives (a name that moved, a load balancer\u0027s new addresses), fails of its own addresses, and each session\u0027s channel resolves its name again of its own as its connection fails or ends, as grpcio\u0027s channels do.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, in the dialect of grpcio (the Python client), as PySpark\u0027s channels: a session connects to the addresses of its own resolution, also while another session of the process is connected elsewhere; each session resolves its name again in the background as its connection ends (no sooner than 30 s after its last resolution), and every 30 s while it cannot connect; a resolution that fails after one that succeeded no longer fails the calls; a first resolution that failed is tried again in the background and connects once it succeeds; the `stop()` of the last session of a connection closes it; a resolution that comes while a session is connected and gives none of the addresses that the process is connected to closes its connection once no other session uses it, and its next call connects to the new addresses; a call that the end of its connection fails has grpcio\u0027s `Stream removed (sendmsg: ...)` of a failed write, and `Stream removed (Socket closed)` where it had `transport error` or `operation was canceled`. The connections that a process opens to one address are as before (one for the sessions of no token, one for each session of a token). In the Rust API, a client\u0027s first call resolves the name of its target, and a client whose name resolves to other addresses connects to them; clients of the same target still share their connection.\n\n### How was this patch tested?\n\n- **New Rust tests** in `spark-connect-core`, of `connector::tests` (against loopback servers of the tests, of their own pools of subchannels): `each_channel_connects_to_the_subchannels_of_its_own_addresses` (a ready subchannel of its addresses taken at once, the first in their order, no attempt to an address before it; its own addresses otherwise; its own failure), `each_channel_of_a_connection_that_ends_resolves_its_name_again_of_its_own` (at once past 30 s of the last resolution, else once the 30 s are over, of each channel), `a_channel_in_transient_failure_resolves_its_name_again_every_30_s` (two channels of one subchannel, and a Rust client\u0027s at each call), `a_resolution_that_fails_after_one_that_succeeded_keeps_its_addresses`, `a_first_resolution_that_failed_is_tried_again_and_connects_in_the_background`, `a_ready_channel_takes_a_ready_subchannel_of_a_new_resolution_else_it_goes_idle` (the first ready subchannel of the new addresses, of another channel too, at once, of no attempt to an address before it; of none, idle, of the picked subchannel let go and no attempt, and the next call connects to the new address), `the_subchannel_of_two_channels_connects_again_once_of_each_backoff_until_both_close`, `the_close_of_a_channel_lets_go_of_its_subchannels`, `a_tls_connection_is_shared_by_the_channels_of_its_name_and_credentials_only` (another TLS name, plaintext, or call credentials of its own share no connection; the channel of another name fails its own handshake of the name), `a_goaway_of_the_server_is_seen_in_its_frames_wherever_they_are_cut`, `a_goaway_of_the_server_ends_the_connection_of_its_subchannel_for_new_calls`, `a_channel_takes_the_connection_that_its_subchannel_made_for_a_call_as_its_own_ended`, the connector of the channel of tonic of a subchannel once its connection ended (`the_connector_of_a_subchannel_makes_one_attempt_once_its_connection_ended`, of both dialects, and none more in transient failure; `the_connector_of_a_subchannel_fails_of_an_attempt_that_timed_out_past_its_backoff`, at its deadline; `the_connector_of_a_subchannel_gives_the_connection_of_its_attempt_as_it_is`, of a server that closes each connection, and one attempt only of a held connection that ended; `a_subchannel_is_freed_as_the_connector_of_a_dropped_call_waits_for_its_attempt`; `a_call_on_the_connection_of_a_subchannel_whose_server_went_away_fails_of_one_attempt`, a real call of tonic of `UNAVAILABLE` of its one attempt, within its deadline), `a_failed_pass_of_a_rust_client_makes_one_attempt_of_each_address`, `a_tls_of_the_system_s_roots_trusts_those_that_the_process_read`, `a_failed_write_of_a_connection_is_a_removed_stream_in_grpcio_s_dialect` (of `EPIPE` and `ECONNRESET`, of the writes, the vectored writes and the flushes) and `the_end_of_a_connection_of_no_cause_that_h2_or_hyper_kept_is_a_closed_socket` (h2\u0027s two errors of no cause, a request that a connection of hyper closed unsent, and the cancellations of the client, which keep their codes and texts) and `a_call_that_waits_for_its_connector_as_its_client_closes_is_cancelled` (of both dialects, of the order of the close and of the failure of the connector seen first: `CANCELLED` of `Channel closed!`, which no retry policy retries); and of `client`: `the_calls_and_the_releases_of_a_client_go_over_the_connection_of_its_channel` (two clients of two tokens: the calls and the background release of each go over its own connection, by the port of its client), `the_close_of_the_last_client_of_a_connection_ends_it`, `a_call_of_a_server_that_closes_each_connection_at_once_makes_two_connections_at_most` (of the Rust API, of no retry) and `the_roots_of_the_tls_channels_are_read_once_per_process`. The tests of the connector\u0027s state machine, of SPARK-62233 (`a_failed_resolution_is_tried_again_a_backoff_after_its_end`) and of SPARK-62234 (`each_new_channel_resolves_its_name_of_its_own_before_its_first_call`, now of channels that share a subchannel) run on `ClientChannel`; the tests of a paused clock connect to a Unix socket of no file, whose attempt fails as it starts, or to a Unix socket of the test, whose connection is made as `connect` returns, so that the clock does not advance while an attempt waits for its socket. The failure texts, TLS, proxy, local credentials, `dns://` and Unix socket tests run as before, through a pass of a new `ClientChannel` (`attempt`). The tests of #917\u0027s close (`deadlines.rs`: `calls_in_flight_as_their_channel_is_closed_end_at_once_before_their_response`, `a_read_in_flight_as_its_channel_is_closed_ends_at_once`, the reattaches of a closed client), of SPARK-62252\u0027s call host (`a_call_host_that_the_certificate_is_not_of_fails_each_call_of_unauthenticated`) and of the Rust API\u0027s sharing (`the_clients_of_a_target_share_the_connection_of_the_process_to_it`) pass unchanged but for the latter\u0027s check of the pooled channel, which is gone.\n- **`cargo test -p apache-spark-connect-core --release`**: 426 passed (lib), and every integration test binary.\n- **`cargo test -p apache-spark-connect -p apache-spark-connect-core --release`**, alone: 1,967 passed, 0 failed, 18 ignored, over 121 test binaries.\n- **The Rust and Python gates** (`gates.sh build rust py`), all passing: `cargo fmt --all --check`; clippy 1.100.0 of `-D warnings`; `cargo doc` of `-D warnings`; `cargo test -p pyspark-rs --lib`, 32 passed; ruff 0.14.0, `test_ruff_excludes.py`, `scripts/audit_no_stubs.sh`, the stub and dispatch generators, the test-list guards and the license checks; `test_type_stubs_offline.py`, 15 passed, 4 skipped; the offline suite of `coverage.yml`, 7,602 passed, 121 skipped, 110 xfailed (its fork tests among them: a child\u0027s sessions and its parent\u0027s run there, a child that frees a parent\u0027s session leaves the parent its held connection, a child closes the descriptors of its parent).\n- **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 361 passed.\n- **Probes of three clients**: the tables above.\n- **Size**: `lib_pyspark.so` of release is 73,499,784 B, of 73,397,016 B of master (+102,768 B, +0.14 %), of the same target dir.\n- **Dependencies**: none new; `Cargo.lock`, `LICENSE-binary` and the JNI inventory are unchanged.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #948 from HyukjinKwon/SPARK-62257-subchannels.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "ef55bfc11620a9521432091ac1f814055c67d5f0",
      "tree": "ab946499ccf21efbc355ac48564da0efcbe3f38f",
      "parents": [
        "1ae9e6bac493bf3cba1d244db05de501fc40e0a6"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 11:35:24 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 11:35:25 2026 +0000"
      },
      "message": "[SPARK-62214][CONNECT][PYTHON] Make MergeIntoWriter and its clauses PySpark Connect\u0027s classes, adapted from PySpark 4.3.0, whose state is their `__dict__`, and whose merge sends PySpark\u0027s command\n\n### What changes were proposed in this pull request?\n\nThis is a sub-task of SPARK-62207. It comes after SPARK-62208 (#926), SPARK-62209 (#929), SPARK-62211 (#936, the readers), SPARK-62212 (#950, the writers) and SPARK-62213 (#952, the stream writer), and is stacked on SPARK-62213 (#952). It covers the merge writer, `df.mergeInto(table, condition)`, and its clauses.\n\nPySpark\u0027s `MergeIntoWriter` is a plain Python class. Its state:\n- `_client`, the client of the session;\n- `_target_table`, `_source_plan` (the plan of the DataFrame) and `_condition`;\n- `_callback`, which sets the `ExecutionInfo` of the merge as the DataFrame\u0027s;\n- `_schema_evolution_enabled`;\n- `_matched_actions`, `_not_matched_actions` and `_not_matched_by_source_actions`, lists of the `MergeAction` messages of its clauses.\n\nIts clauses, the nested classes `WhenMatched`, `WhenNotMatched` and `WhenNotMatchedBySource`, hold `writer` and `_condition`. A clause method builds its `MergeAction` with `_build_merge_action`, of the messages of its condition and assignments, when it is called, and appends it to the writer\u0027s list. `merge()` builds the `MergeIntoTableCommand` of those lists and runs it with `self._client.execute_command(...)`. The drop-in\u0027s writer and clauses were native classes with their own state, which emulated those steps in Rust. As for the readers, the writers and the stream writer, this PR makes them PySpark\u0027s own classes.\n\n**Provenance.** `MergeIntoWriter` and its clauses are **adapted** from Apache Spark v4.3.0\u0027s `python/pyspark/sql/connect/merge.py`. The file keeps its Apache license header, and the module header comment names the source file. It is not a verbatim copy, so it is not in the vendored-file registry.\n\nThe only adaptations:\n- `df.mergeInto` passes the callback of `df.write` (`_execution_info_callback` of SPARK-62212), which records the merge\u0027s `ExecutionInfo` as the DataFrame\u0027s `executionInfo`.\n- ruff modernized the annotations (`Dict` to `dict`).\n- The module\u0027s doctest runner `_test` is not kept, as for the readers and writers.\n\nThe merge command is PySpark\u0027s too: it is built over pbmsg, and its source plan is the core\u0027s placeholder (`df._plan.plan(client)`). The drop-in client\u0027s `execute_command` executes it.\n\n**The changes:**\n- **`python/pyspark/sql/connect/merge.py`:** the adapted `MergeIntoWriter` and its clauses, which replace the re-export of the native class.\n- **`crates/pyspark-rs/src/dataframe.rs`:** `mergeInto` returns `MergeIntoWriter(plan\u003dself._plan, session\u003dself._session, table\u003dtable, condition\u003dcondition, callback\u003dcb)`, as PySpark\u0027s does.\n- **Removed:**\n  - the native `MergeIntoWriter`, `WhenMatched`, `WhenNotMatched` and `WhenNotMatchedBySource`, with their clause, condition and table helpers;\n  - `WriterState` and `WriterParts`, the shared state of the native writers, of which the merge writer was the last, with their unit test and `gc::wait_for_no_counted_call`, which only that test used;\n  - `reduce::thread_local_reduce` and `reduce::copy_instance_dict`, of the native writer\u0027s pickle and copy.\n- **Stubs:** `merge.pyi` is regenerated, now with `_build_merge_action`, and the digest of its docstrings in `tests/golden/stub_docstrings.json`, captured with pyspark-client 4.3.0. The aliased classic merge writer joins the undeclared names of the stub test.\n- **Docs:**\n  - The `__dict__`, Subclasses and gc rows of `dev/parity/known-differences.md` and the matching paragraphs of `docs/compatibility.md`. The merge writer moves from the native list to the PySpark classes. With no native writer left, the gc text no longer names `WriterParts`.\n  - A new KD row, \"A deep Column in the commands of `writeTo` and `mergeInto`\", and the deep-plan paragraph of `docs/compatibility.md` (below).\n\nOf the 415 generic cases of `tests/test_dropin_object_state_offline.py`:\n\n| | Same as PySpark | Differ |\n|---|---|---|\n| Before, SPARK-62213 at 0f0b5ebb | 319 | 96 |\n| After, this PR | 344 | 71 |\n\nTwo merge writer cases move to the DataFrame group (SPARK-62218): the `vars` of `MergeIntoWriter` and of `MergeIntoWriter of its clauses`. They check `writer._source_plan is df._plan`. The drop-in\u0027s DataFrame gives a new plan object at each read of `_plan`, as with the other writers.\n\n**Merges against PySpark 4.3.0.** The probe makes each call with both clients on the mock server. It records what the call raises, or else the merge command that the server receives: the target table, the condition, and the kind, condition and assignments of each action, in their order. All 37 cases are the same:\n- every clause kind, with and without a condition, and several clauses in their order;\n- `withSchemaEvolution`, and a merge of no clause;\n- tables and conditions that are not str or Column (5, bytes, None, a str that UTF-8 can\u0027t encode, a SQL string);\n- assignments of a key or a value that is not a str or a Column, of an empty dict or None, and of a mapping that is not a dict;\n- a clause whose action raised, which is not added.\n\n| Case | PySpark 4.3.0 | Drop-in |\n|---|---|---|\n| `whenMatched().updateAll().merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: updateAll | same |\n| `whenMatched(c).update({v: x}).merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: update if (s.v \u003e 0) [expr(v)\u003ds.v] | same |\n| `whenMatched().delete().merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: delete | same |\n| `whenNotMatched().insertAll().merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), not_matched: insertAll | same |\n| `whenNotMatched(c).insert({v: x, id: y}).merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), not_matched: insert if (s.v \u003c 9) [expr(v)\u003ds.v, expr(id)\u003d1] | same |\n| `whenNotMatchedBySource().updateAll().merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), not_matched_by_source: updateAll | same |\n| `whenNotMatchedBySource(c).update({v: 0}).merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), not_matched_by_source: update if (t.v \u003e 1) [expr(v)\u003d0] | same |\n| `whenNotMatchedBySource().delete().merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), not_matched_by_source: delete | same |\n| `every clause, twice, in order` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: delete if (s.v \u003e 0); updateAll, not_matched: insertAll; insert if True [expr(v)\u003d2], not_matched_by_source: delete | same |\n| `withSchemaEvolution().merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: delete, with schema evolution | same |\n| `merge() of no clause` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id) | same |\n| `mergeInto(5, c).merge()` | call: TypeError bad argument type for built-in operation | same |\n| `mergeInto(bad, c).merge()` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `mergeInto(b\u0027t\u0027, c).merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id) | same |\n| `mergeInto(None, c).merge()` | sent table \u0027\u0027, on (t.id \u003d\u003d s.id) | same |\n| `mergeInto(t, \u0027id \u003d 1\u0027).merge()` | call: AttributeError \u0027str\u0027 object has no attribute \u0027to_plan\u0027 | same |\n| `mergeInto(t, 5)` | value: MergeIntoWriter | same |\n| `mergeInto(t, None).merge()` | call: AttributeError \u0027NoneType\u0027 object has no attribute \u0027to_plan\u0027 | same |\n| `whenMatched(\u0027v \u003e 0\u0027).updateAll()` | call: AttributeError \u0027str\u0027 object has no attribute \u0027to_plan\u0027 | same |\n| `whenMatched(5)` | value: WhenMatched | same |\n| `whenMatched(5).delete()` | call: AttributeError \u0027int\u0027 object has no attribute \u0027to_plan\u0027 | same |\n| `whenNotMatched(None).insertAll().merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), not_matched: insertAll | same |\n| `update({v: \u0027x\u0027})` | call: AttributeError \u0027str\u0027 object has no attribute \u0027to_plan\u0027 | same |\n| `update({v: 5})` | call: AttributeError \u0027int\u0027 object has no attribute \u0027to_plan\u0027 | same |\n| `update({5: x})` | call: AssertionError  | same |\n| `update({bad: x})` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `update({\u0027a b\u0027: x}).merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: update [expr(a b)\u003ds.v] | same |\n| `update({}).merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: update | same |\n| `update(None).merge()` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: update | same |\n| `update([(v, x)])` | call: AttributeError \u0027list\u0027 object has no attribute \u0027items\u0027 | same |\n| `insert({v: lit(bad)})` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `insert(5)` | call: AttributeError \u0027int\u0027 object has no attribute \u0027items\u0027 | same |\n| `insert({v: x}).insert again` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), not_matched: insert [expr(v)\u003ds.v]; insert [expr(id)\u003d3] | same |\n| `a clause that raised is not added` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id), matched: delete | same |\n| `the clause after a change of its condition` | sent table \u0027t\u0027, on (t.id \u003d\u003d s.id) | same |\n| `the writer of a clause is the writer` | value: list | same |\n| `the condition of a clause is its argument` | value: bool | same |\n\nThe cases are a test, `test_the_merges_send_what_pysparks_merge_writer_sends` (37 cases, run with both clients).\n\n**A deep Column.** PySpark\u0027s merge makes the messages of its command and its actions of the messages of its Columns, and protobuf copies them by parsing, of 100 levels at most. The drop-in\u0027s Columns hold an expression of any depth, but the copy fails in the same way, from the same depth. Of a chain of `+`, with the call-site origins of a session, on the mock server:\n\n| Additions | Where | PySpark 4.3.0 | Drop-in, this PR | Drop-in, before |\n|---|---|---|---|---|\n| 46 | an assignment | sent | sent | sent |\n| 47 | an assignment | `DecodeError` (`Exceeded upb_DecodeOptions_MaxDepth`) | the same | sent |\n| 47 | a clause condition | sent | sent | sent |\n| 48 | a clause condition | `DecodeError` | the same | sent |\n| 48 | the condition of `mergeInto` | sent | sent | sent |\n| 49 | the condition of `mergeInto` | `DecodeError` | the same | sent |\n| 60 to 450 | any | `DecodeError` | the same | sent |\n| 500 to 744 | any | `RecursionError` of its `to_plan` | `DecodeError` | sent |\n\nBoth fail from 47, 48 and 49 additions; only the error past about 500 levels differs. PySpark\u0027s `to_plan` recurses and hits Python\u0027s recursion limit first, where the drop-in builds the message of a Column natively, without Python\u0027s recursion limit. Past 745 levels, both clients raise a `RecursionError`. The KD row \"A deep Column in the commands of `writeTo` and `mergeInto`\" says so, with the partitioning columns of SPARK-62212. The plan of the DataFrame, the placeholder of its relation, is still never decoded in Python. `test_a_command_expression_too_deep_to_send_raises_recursion_error_as_pyspark` checks a merge of 40 additions, which is sent, and the DecodeError of 60 and 744, for each of the three.\n\n**GC.** `test_a_writer_in_a_cycle_through_a_udf_is_collected` now covers `mergeInto` too, run with both clients. It builds a cycle of the merge writer, its DataFrame (its `_source_plan`, and the callback) and the function of a UDF of the plan, which refers to the writer. One collection frees all three. The gc-shared clone check of `conftest.py` is on for every offline test and reports no violation.\n\n**The client\u0027s cost of the merge writer**, in µs per call (best of 5). The clauses send nothing, and the merge is on the mock server, whose round trip is the same for every client:\n\n| | Before (native writer) | After (this PR) | PySpark 4.3.0 |\n|---|---|---|---|\n| `df.mergeInto(t, cond)` | 1.06 | 6.76 | 1.07 |\n| `mergeInto().whenMatched().updateAll()` | 2.20 | 8.47 | 2.25 |\n| `mergeInto().whenMatched(c).update({v: x})` | 5.48 | 48.78 | 17.00 |\n| `mergeInto().whenMatched().delete().whenNotMatched().insertAll().merge()` | 882 | 896 | 1416 |\n\n`df.mergeInto` costs more than PySpark\u0027s: `self._plan` and `self._session.client` are made at each read in the drop-in (0.9 and 1.6 µs), where PySpark\u0027s are attributes. A clause of assignments costs more too: it builds the messages of its Columns, `expr(k)` and the condition with the drop-in\u0027s protobuf runtime, whose message constructors walk each message argument to upb\u0027s depth limit and then make a deep copy of it, a Python object for each nested message (`pbmsg/message.rs`, `message_for_field`), slower than upb in C. That is tracker item 73. A merge\u0027s client cost stays well under PySpark\u0027s, because the transport is native.\n\n**What remains:**\n- **The `_source_plan` of a merge writer is the plan object that `df._plan` gave when `mergeInto` was called.** The drop-in makes a new one at each read (SPARK-62218).\n- **The rest is the residue of the KD row:** requests go through the native transport, through `client.execute_command`.\n\n### Why are the changes needed?\n\nSo that the merge writer and its clauses are PySpark\u0027s, by construction: their `__dict__`, clause actions, errors and their order, commands, copies and pickles. The native writer state, `WriterState` and `WriterParts`, which existed only to emulate PySpark\u0027s dicts and messages, goes with the last native writer.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes:\n- `df.mergeInto(table, condition)` is PySpark Connect\u0027s `MergeIntoWriter`, whose state is its `__dict__`, and its clauses are its nested classes. A pickle of one is a plain object of its class.\n- A merge of a Column of more than 100 message levels now fails as in PySpark (above): from 47 additions for an assignment, 48 for a clause condition and 49 for the condition of `mergeInto`. Before, the native merge sent it up to 745 levels.\n\n### How was this patch tested?\n\n- **`tests/test_dropin_object_state_offline.py`:**\n  - On this branch: 632 passed and 74 xfailed, with the 56 read cases, the 80 write cases, the 84 start cases, the 37 merge cases, the 10 started-event cases and the 4 GC cases.\n  - With PySpark 4.3.0: 706 passed.\n- **The merge, clause, depth, cycle, docstring, stub, reduce, pickle, worker and execution-info tests of `tests/test_dropin_offline.py`, `tests/test_dropin_class_modules_offline.py` and `tests/test_type_stubs_offline.py`:** 688 passed, 1 skipped. `test_a_command_expression_too_deep_to_send_raises_recursion_error_as_pyspark` is updated as above.\n- **`tests/test_dropin_e2e.py`** against a Spark 4.3.0 server, the merge and execution-info tests: 5 passed.\n- **The probes above.**\n- **`tests/test_dropin_e2e.py`** against a Spark 4.3.0 server, the whole file: 360 passed.\n- **The gates** (at 75f51c7d):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 31 passed (the unit test of `WriterState` goes with it);\n  - ruff 0.14.0, the no-stub audit, `gen_connect_docstrings.py --check`, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7784 passed, 121 skipped, 75 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 360 passed.\n\n- **Rebased onto master c81099b3** (the merge of #952), with every changed line identical to 75f51c7d, the commit the gates above ran on. `cargo fmt --check`, clippy 1.100.0 with `-D warnings`, ruff and `gen_type_stubs.py --check` pass on the rebased tree.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #954 from HyukjinKwon/SPARK-62214-merge-writer-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "1ae9e6bac493bf3cba1d244db05de501fc40e0a6",
      "tree": "a81a224bce667140af466111ed2050f4acb14e8f",
      "parents": [
        "c81099b3c84ff71fe41344ad419b9bc0f26c8037"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 11:23:31 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 11:23:32 2026 +0000"
      },
      "message": "[SPARK-62260][CONNECT][PYTHON] Import the modules that the native classes of the Python client name in their __module__ when their objects are made, so that cloudpickle pickles them by reference, as it does PySpark\u0027s\n\n### What changes were proposed in this pull request?\n\ncloudpickle pickles a class by reference only when the module that its `__module__` names is in `sys.modules` and holds the class at its `__qualname__` (`_should_pickle_by_reference`). Otherwise it pickles the class by value, as a dynamic class, and copies its methods. PySpark\u0027s classes are defined in their modules, so an object of one always has its module imported. The drop-in\u0027s native classes only name PySpark Connect\u0027s modules (`pyspark.sql.connect.group`, `pyspark.sql.connect.streaming.query`, ...), and the paths that make their objects did not import those modules. After `import pyspark`, no `pyspark.sql.connect.*` module is loaded, and the drop-in\u0027s `import pyspark.sql.connect.session` loaded 3 of them, where PySpark\u0027s loads 30.\n\nSo in a new interpreter, a UDF or a `foreachBatch` function that captured such an object pickled its class by value, and the server\u0027s Python worker failed:\n- `AttributeError: type object \u0027GroupedData\u0027 has no attribute \u0027agg\u0027`;\n- the same for `PandasCogroupedOps.applyInArrow`, `StreamingQuery.awaitTermination` and `DataFrameNaFunctions.drop`.\n\n`test_foreach_batch_captures_the_readers_writers_and_groups_as_pyspark` failed 9 of 9 when it ran alone or in a `-k` subset. It passed in the full e2e run only because earlier tests had imported the modules. The bug surfaced when SPARK-62210 (#931) removed the old reducer of GroupedData, whose worker helper imported the module, and when SPARK-62209 made StreamingQuery pickle as a plain object.\n\n**Which classes.** Each object was made in a new interpreter, by the user calls only, against a mock server, and compared with pyspark-client 4.3.0 (60 objects):\n\n| | Before | After and PySpark |\n|---|---|---|\n| Pickled by value: `cloudpickle.dumps(obj)` pickles the class as a dynamic class | `RuntimeConf`, `Catalog`, `TableValuedFunction`, `DataSourceRegistration`, `MergeIntoWriter` and its `WhenMatched`, `WhenNotMatched` and `WhenNotMatchedBySource`, `DataFrameNaFunctions`, `DataFrameStatFunctions`, `GroupedData` (of `groupBy`, `groupby`, `rollup`, `cube`, `groupingSets` and `pivot`), `PandasCogroupedOps`, `StreamingQuery` (of `start` and `toTable`) | none |\n| Not by reference, though their own reducers do not pickle the class | `DataFrame`, `DataFrameReader`, `DataFrameWriter`, `DataFrameWriterV2`, `DataStreamReader`, `DataStreamWriter`, `Column`, `TableArg` | none |\n| By reference already | `SparkSession` and its `Builder`, `StreamingQueryManager` and its listener bus, `WindowSpec`, `Observation` | the same |\n\nAfter the change, all 60 objects give PySpark\u0027s results: the class, its module loaded, pickled by reference, the same outcome of the dump, and no class by value. The dumps of `spark.conf`, `spark.streams`, its bus, `spark.client` and a `MergeIntoWriter` fail with the `TypeError` of a lock or a thread-local of the client, in both clients.\n\nNot affected: the native ML classes, whose objects are always of their public subclasses, which `pyspark.ml.connect` registers when it is imported; the native classes of `pyspark.ml.stat`, likewise; the base classes of the Rust protobuf runtime, whose class pickles are a known difference already; and the internal stream and iterator objects, which do not pickle in either client.\n\n**The changes**, by PySpark\u0027s module layout:\n- `python/pyspark/sql/connect/session.py` imports PySpark\u0027s lines when it is imported: `DataFrame` of `.dataframe`, `RuntimeConf` of `.conf`, `DataFrameReader` of `.readwriter`, `DataStreamReader` of `.streaming.readwriter` and `StreamingQueryManager` of `.streaming.query`. These bind the names that PySpark\u0027s module has. It also imports the modules `observation` and `table_arg`, under private names: PySpark\u0027s import of the session loads them through its client and its module of UDTFs.\n- `python/pyspark/sql/connect/dataframe.py` imports, as PySpark\u0027s does: `GroupedData`, `MergeIntoWriter`, `DataFrameWriter`, `DataFrameWriterV2` and `DataStreamWriter`, and the module `column`. PySpark\u0027s imports the Column as `ConnectColumn`; the drop-in\u0027s stub of the module, generated from PySpark\u0027s, does not declare that alias (the generator re-exports only names imported under their own names), so the module is bound under a private name, and the stub and the module still agree.\n- `python/pyspark/sql/connect/streaming/readwriter.py` already imports `StreamingQuery` of `.streaming.query`, as PySpark\u0027s does, since SPARK-62213 (#952) made its `DataStreamWriter` PySpark\u0027s class, so this change does not touch it.\n- `crates/pyspark-rs/src/session.rs`: `spark.tvf` and `spark.dataSource` import `pyspark.sql.connect.tvf` and `.datasource`, as PySpark\u0027s properties do. `spark.catalog`, a `functools.cached_property` of `pyspark.sql.connect.session` since SPARK-62216, imports `pyspark.sql.connect.catalog` itself, as PySpark\u0027s does. The import of the session does not import these modules, as PySpark\u0027s does not.\n- `crates/pyspark-rs/src/column.rs`: `Column._of_expression` imports `pyspark.sql.connect.column`. A Column of a plain pickle unpickles with it (`_column_reduce.column_of`) and needs no session, so the session\u0027s imports do not cover it; PySpark\u0027s unpickle imports the module of the class.\n\nAfter `import pyspark.sql.connect.session`, the drop-in now loads every module of a native class that PySpark\u0027s import loads (`column`, `conf`, `dataframe`, `group`, `merge`, `observation`, `readwriter`, `streaming.query`, `streaming.readwriter` and `table_arg`). It does not load `catalog`, `tvf`, `datasource` and `window`, and neither does PySpark. Its other modules (`client`, `plan`, `functions`, `proto`, ...) stay lazy, as before, and grpc is still not imported. There is no cycle: no module imports the module of the session when it is imported, and each module imports on its own.\n\n**Import time** of `import pyspark.sql.connect.session` (`python -X importtime`, median of 21 runs, Python 3.11, on a shared machine):\n\n| Code | Before | After |\n|---|---|---|\n| `import pyspark; import pyspark.sql.connect.session`: the line of the session module, of what it imports after `pyspark` | 0.5 ms (min 0.5) | 1.9 ms (min 1.8) |\n| `import pyspark.sql.connect.session`: the whole import, of which `import pyspark` is about 300 ms | 361.5 ms (min 301.7) | 348.7 ms (min 311.6) |\n\nThe runs of the two trees were interleaved, under the same load of the machine. The session module costs 1.4 ms more: about 1.3 ms is the 10 modules of the classes (`dataframe` with `_column_reduce` 0.45 ms, `streaming.readwriter` 0.25 ms, the others 0.06 to 0.11 ms each). The whole import is within the noise of the machine. The modules of `catalog`, `tvf` and `datasource` (about 0.07 ms each) are imported by their properties, not by the import.\n\n**Type stubs:** `scripts/gen_type_stubs.py` re-exports a name that PySpark\u0027s module imports under its own name when the drop-in\u0027s module binds it too, so the regenerated stubs of `pyspark.sql.connect.session` and `.dataframe` now re-export those names (`from pyspark.sql.connect.dataframe import DataFrame as DataFrame`, ...), as type checkers of PySpark\u0027s source let a user import them from those modules. No other stub changes.\n\n**Docs:** `docs/compatibility.md` gets a paragraph after the classes of the objects of a session: their modules are imported when the objects are made, and cloudpickle pickles them by reference, in a new interpreter too. `dev/parity/known-differences.md` said nothing of it, and no difference is left for these classes.\n\n### Why are the changes needed?\n\nA program that starts a `foreachBatch` query or a UDF whose function captures grouped data, cogrouped data, a streaming query, the na or stat functions of a DataFrame, or the catalog, table-valued functions or data sources of a session failed on the server\u0027s Python worker. PySpark\u0027s worker runs it. Whether it failed depended on what the program had imported before.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes:\n- in a new interpreter, a UDF or a `foreachBatch` function that captures one of the objects above pickles it as PySpark\u0027s does, and the server\u0027s Python worker uses it;\n- `_should_pickle_by_reference` of the class of each object is True, as PySpark\u0027s;\n- after `import pyspark.sql.connect.session`, `sys.modules` has the modules of the classes above, as PySpark\u0027s has. The module of the session has PySpark\u0027s names `DataFrame`, `RuntimeConf`, `DataFrameReader`, `DataStreamReader` and `StreamingQueryManager`, the module of the DataFrame has `GroupedData`, `MergeIntoWriter`, `DataFrameWriter`, `DataFrameWriterV2` and `DataStreamWriter`, and the module of the stream readers and writers has `StreamingQuery`.\n\n### How was this patch tested?\n\n- **`tests/test_dropin_class_modules_offline.py`:** a new test, `test_the_classes_of_the_objects_of_a_new_interpreter_pickle_by_reference_as_pysparks`. It makes 28 objects, each in a new interpreter, 4 at a time, by the calls of a program only, against a mock server:\n  - the session, its `conf`, `catalog`, `read`, `readStream`, `streams`, `tvf` and `dataSource`;\n  - a DataFrame, its `write`, `writeTo`, `writeStream`, `mergeInto` and the three clauses, `na`, `stat`, `groupBy`, `pivot`, `cogroup`, a Column and `asTable`;\n  - a started streaming query, of the start result that the mock gives;\n  - a Column, a WindowSpec and an Observation of no session, and a Column of a plain pickle of the test\u0027s process that a new interpreter unpickles with no session.\n\n  Each object must be of PySpark\u0027s class, cloudpickle must pickle its class by reference, and its pickle must pickle no class by value. Before the change, 24 of the 28 fail. With the Python changes alone, `catalog`, `tvf`, `dataSource` and the unpickled Column still fail. After the change, all pass, in about 6 s. `_mock_connect_server.py` gets `mock_connect_server()`, a mock server without a session of the test\u0027s process, which `mock_connect_session()` now uses.\n- **`tests/test_dropin_e2e.py`:** a new live test, `test_foreach_batch_captures_groups_and_queries_in_a_new_interpreter_as_pyspark`, with the cases `groupBy`, `cogroup`, `streamingQuery` and `namespaces`. Each case runs a program in a new interpreter that makes a session and the captured object only, and a trigger-once `foreachBatch` query whose function uses the object on the server\u0027s Python worker:\n  - `agg` of grouped data;\n  - `applyInArrow` of cogrouped data;\n  - `id`, `isActive` and `awaitTermination(0.1)` of a query;\n  - `na.drop()`, `stat.crosstab`, `catalog.currentDatabase()`, `tvf.range(2)` and the class of `spark.dataSource`.\n\n  pyspark-client 4.3.0 gives the expected results (`2`, `3`, `(True, True, False)`, `(3, 2, \u0027default\u0027, 2, \u0027DataSourceRegistration\u0027)`). Before the change, the drop-in fails all four, with the `AttributeError`s above.\n- **Each targeted test alone, in a process of its own**, against a Spark 4.3.0 server: the 9 cases of `test_foreach_batch_captures_the_readers_writers_and_groups_as_pyspark`, which failed 9 of 9 alone before, and the 4 of the new test: 13 passed. `-k test_foreach_batch_captures` in one process: 13 passed.\n- **A probe of 60 objects** (not committed), in new interpreters against a mock server, compared with pyspark-client 4.3.0: 35 differed before, and none after. The modules of `catalog`, `tvf`, `datasource` and `window` are not loaded by the import of the session, as in PySpark.\n- **The gates:**\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 37 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_type_stubs.py --check` (after regenerating the three stubs), `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7381 passed, 121 skipped, 169 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 361 passed.\n\n- **Rebased onto master c81099b3**, after #936 (the readers), #950 and #952 (the writers), #951 and #949. The `StreamingQuery` import of `streaming/readwriter.py` and its stub are master\u0027s now, and every other changed line is identical to 5245f04c\u0027s rebase. `gen_type_stubs.py --check`, ruff, `cargo fmt --check` and clippy pass on the tree. Earlier, **rebased onto master 30d257d0**, after SPARK-62216 (#943) moved `spark.catalog` into a Python `cached_property` that imports its module. That leaves this change\u0027s import in the former Rust getter with no place, so it is dropped. These are the only changed lines that differ from 5245f04c, the commit the gates above ran on. `cargo fmt --check`, clippy 1.100.0 with `-D warnings`, ruff and `scripts/gen_type_stubs.py --check` pass on the rebased tree.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #947 from HyukjinKwon/SPARK-62260-native-class-modules.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "c81099b3c84ff71fe41344ad419b9bc0f26c8037",
      "tree": "5c343fd43caf21a03f7a7530b4c25e496958bd4d",
      "parents": [
        "035a1c9c3ae16a6509d14b743376b904fb2c4619"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 10:10:32 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 10:10:35 2026 +0000"
      },
      "message": "[SPARK-62213][CONNECT][PYTHON] Make DataStreamWriter PySpark Connect\u0027s class, adapted from PySpark 4.3.0, whose state is its `__dict__`, and whose start sends PySpark\u0027s command and posts the started event to the `post_to_all` of the session\u0027s listener bus\n\n### What changes were proposed in this pull request?\n\nThis is a sub-task of SPARK-62207. It comes after SPARK-62208 (#926), SPARK-62209 (#929, the streaming queries, their manager and its listener bus), SPARK-62211 (#936, the readers) and SPARK-62212 (#950, the writers). It covers the stream writer, `df.writeStream`.\n\nPySpark\u0027s `DataStreamWriter` is a plain Python class. Its state:\n- `_session`;\n- `_write_stream`, a `WriteStreamOperation` of `pyspark.sql.connect.plan`, of the plan of the DataFrame;\n- `_write_proto`, the `WriteStreamOperationStart` message of `_write_stream`, whose fields the setters set.\n\nA start builds the command of `_write_stream`, runs it with `self._session.client.execute_command(cmd)`, makes the `StreamingQuery` of the result, and posts the query\u0027s started event, decoded, with `self._session.streams._sqlb.post_to_all(start_event)`. The drop-in\u0027s stream writer was a native class with its own state, which emulated those steps in Rust. As for the readers (#936) and the writers (SPARK-62212), this PR makes the stream writer PySpark\u0027s own class.\n\n**Provenance.** `DataStreamWriter` is **adapted** from Apache Spark v4.3.0\u0027s `python/pyspark/sql/connect/streaming/readwriter.py`, next to the `DataStreamReader` of #936. `WriteStreamOperation` comes from its `python/pyspark/sql/connect/plan.py`. Both files keep their Apache license header, and the module header comment names the source files. These are not verbatim copies, so they are not in the vendored-file registry.\n\nThe only adaptations:\n- The last line of the start, the post of the started event, goes through `_post_query_started(post_to_all, start_event, event_json)`. The event is decoded first, as PySpark decodes it, and `self._session.streams._sqlb.post_to_all` is resolved as PySpark resolves it. Then:\n  - when that is the native bus\u0027s own method (the `post_to_all` method descriptor of the native `StreamingQueryListenerBus`, kept when the module initializes, bound to a bus of that exact class), the call runs inside the core\u0027s `post_started`. So a removal of a listener from another thread waits for the delivery, as PySpark\u0027s bus holds its lock while it posts, and the native listeners of the session get the event too;\n  - anything else is called with the event, as PySpark calls it: a patch of `post_to_all` on the bus or on its class, the method of a subclass of the bus, or a bus of another class.\n- `foreach` uses the classic `DataStreamWriter._construct_foreach_function`, as PySpark\u0027s does. The drop-in\u0027s own copy of it is removed.\n- `Trigger`, the drop-in\u0027s native class of the module, stays.\n- ruff modernized the annotations, with `noqa: B904/UP031` where PySpark\u0027s code is kept as it is.\n\n**The changes:**\n- **`python/pyspark/sql/connect/streaming/readwriter.py`:** the adapted `DataStreamWriter`.\n- **`python/pyspark/sql/connect/plan.py`:** PySpark\u0027s `WriteStreamOperation`.\n- **`crates/pyspark-rs/src/streaming.rs`:** `_post_query_started` and the kept method descriptor (`NATIVE_POST_TO_ALL`), registered in `lib.rs`.\n- **`crates/spark-connect/src/streaming.rs`:** `StreamingQueryManager::post_started`, a `#[doc(hidden)]` method that runs a delivery of a started event as the core\u0027s own writer does (the removal-waits-for-delivery tracking).\n- **`crates/pyspark-rs/src/dataframe.rs`:** `writeStream` returns `DataStreamWriter(self._plan, self._session)`.\n- **Removed:**\n  - the native `DataStreamWriter`, its state, copies and reduce, and `post_started_event`;\n  - the helpers that only it used: `stream_column_names`, `query_name_of`, `trigger_pair`, `trigger_of`, `streaming_function_command`, `WriterState::set`, `coerce_option_value`, `kwargs_skip_none`, `writer_path`, `writer_column_items`, `str_dict`, `reduce::state_reduce`, `reduce::reduce_with_instance_dict` and `options::str_text`;\n  - `pyspark/sql/connect/_state_reduce.py`, whose stream writer reduce was the last of its reduces (`stream_writer_reduce`, `_worker_stream_writer`, `_worker_foreach_commands`, `_PlanOfDataFrame`), since the session builder became PySpark\u0027s (SPARK-62215). With it goes the `request_schema` flag of the unpickle of a DataFrame (`_column_reduce.dataframe_of`, `DataFrame._of_relation`), which only `_PlanOfDataFrame` cleared. A stream writer now pickles as PySpark\u0027s plain object, which a worker without the drop-in loads as PySpark\u0027s class.\n- **Stubs:** `WriteStreamOperation` leaves the generator\u0027s `UNRESOLVED_IMPORTS`. The `PySparkAttributeError` and `PySparkRuntimeError` extras of the module go, since only the removed `_construct_foreach_function` imported them. The stubs are regenerated. The aliased classic stream writer joins the undeclared names of the stub test.\n- **Docs:** the `__dict__`, Subclasses, gc and listener-bus parts of `dev/parity/known-differences.md` and of `docs/compatibility.md`. The stream writer moves from the native list to the PySpark classes. The started event is described as above. The gc paragraphs of `docs/compatibility.md` no longer list the readers and writers of #936 and SPARK-62212 among the native holders of plan parts and options, since those PRs left them stale.\n\nOf the 415 generic cases of `tests/test_dropin_object_state_offline.py`:\n\n| | Same as PySpark | Differ |\n|---|---|---|\n| Before, master at dd756c29 (#950) | 308 | 107 |\n| After, this PR | 319 | 96 |\n\nThree stream writer cases move to the DataFrame group (SPARK-62218): the `vars` of the two stream writer objects and `test_the_message_of_a_stream_writer_is_the_message_of_its_operation`. They check `writer._write_stream._child is df._plan`. The drop-in\u0027s DataFrame gives a new plan object at each read of `_plan`, as with the writers of SPARK-62212.\n\n**Starts against PySpark 4.3.0.** The probe makes each call with both clients on the mock server, whose start result has no started event. It records what the call raises, or else the start command that the server receives and the query it gives back. All 84 cases are the same: start and toTable with their arguments, outputMode, format, option and options (None, bool, float, int and bytes keys, strs that can\u0027t be encoded), partitionBy and clusterBy, queryName, every trigger kind and its errors, foreach (a function, an object with `process`, with `open`/`process`/`close`, without `process`, a function that does not pickle) and foreachBatch.\n\n| Case | PySpark 4.3.0 | Drop-in |\n|---|---|---|\n| `start()` | sent {} | same |\n| `start(p)` | sent {\"sink\":[\"path\",\"p\"]} | same |\n| `start(\u0027\u0027)` | sent {} | same |\n| `start(5)` | call: TypeError bad argument type for built-in operation | same |\n| `start(bad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `start(p, format\u003djson, outputMode\u003dappend, partitionBy\u003da, queryName\u003dq, k\u003d1)` | sent {\"format\":\"json\",\"options\":[[\"k\",\"1\"]],\"partitioning\":[\"a\"],\"output_mode\":\"append\",\"query_name\":\"q\",\"sink\":[\"path\",\"p\"]} | same |\n| `start(k\u003dNone)` | sent {} | same |\n| `start(k\u003dTrue)` | sent {\"options\":[[\"k\",\"true\"]]} | same |\n| `start(k\u003dbad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `start(**{1: v})` | call: TypeError keywords must be strings | same |\n| `start(queryName\u003d\u0027\u0027)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `queryName` must be a non-empty string, got \u0027\u0027. | same |\n| `start(partitionBy\u003d[a, b])` | sent {\"partitioning\":[\"a\",\"b\"]} | same |\n| `toTable(t)` | sent {\"sink\":[\"table_name\",\"t\"]} | same |\n| `toTable(\u0027\u0027)` | sent {} | same |\n| `toTable(5)` | call: TypeError bad argument type for built-in operation | same |\n| `toTable(bad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `toTable(t, format\u003ddelta, outputMode\u003dcomplete, partitionBy\u003d[a, b], queryName\u003dq, k\u003dv)` | sent {\"format\":\"delta\",\"options\":[[\"k\",\"v\"]],\"partitioning\":[\"a\",\"b\"],\"output_mode\":\"complete\",\"query_name\":\"q\",\"sink\":[\"table_name\",\"t\"]} | same |\n| `outputMode(append).start()` | sent {\"output_mode\":\"append\"} | same |\n| `outputMode(b\u0027append\u0027).start()` | sent {\"output_mode\":\"append\"} | same |\n| `outputMode(5)` | call: TypeError bad argument type for built-in operation | same |\n| `outputMode(None)` | call: TypeError bad argument type for built-in operation | same |\n| `outputMode(bad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `format(console).start()` | sent {\"format\":\"console\"} | same |\n| `format(5)` | call: TypeError bad argument type for built-in operation | same |\n| `format(None)` | call: TypeError bad argument type for built-in operation | same |\n| `format(bad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `option(k, v).start()` | sent {\"options\":[[\"k\",\"v\"]]} | same |\n| `option(k, None).start()` | sent {} | same |\n| `option(k, True).start()` | sent {\"options\":[[\"k\",\"true\"]]} | same |\n| `option(k, 1.5).start()` | sent {\"options\":[[\"k\",\"1.5\"]]} | same |\n| `option(5, v)` | call: TypeError bad argument type for built-in operation | same |\n| `option(b\u0027k\u0027, v).start()` | sent {\"options\":[[\"k\",\"v\"]]} | same |\n| `option(bad, v)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `option(k, bad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `option(k, b\u0027v\u0027).start()` | sent {\"options\":[[\"k\",\"b\u0027v\u0027\"]]} | same |\n| `options(a\u003d1, b\u003dNone).start()` | sent {\"options\":[[\"a\",\"1\"]]} | same |\n| `options(**{1: v})` | call: TypeError keywords must be strings | same |\n| `partitionBy(a, b).start()` | sent {\"partitioning\":[\"a\",\"b\"]} | same |\n| `partitionBy([a, b]).start()` | sent {\"partitioning\":[\"a\",\"b\"]} | same |\n| `partitionBy((a,)).start()` | sent {\"partitioning\":[\"a\"]} | same |\n| `partitionBy(a).partitionBy(b).start()` | sent {\"partitioning\":[\"b\"]} | same |\n| `partitionBy().start()` | sent {} | same |\n| `partitionBy(5)` | call: TypeError bad argument type for built-in operation | same |\n| `partitionBy(a, 5)` | call: TypeError bad argument type for built-in operation | same |\n| `partitionBy(bad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `partitionBy([a], b)` | call: TypeError bad argument type for built-in operation | same |\n| `clusterBy(a).start()` | sent {\"clustering\":[\"a\"]} | same |\n| `clusterBy([a, b]).start()` | sent {\"clustering\":[\"a\",\"b\"]} | same |\n| `clusterBy(5)` | call: TypeError bad argument type for built-in operation | same |\n| `queryName(q).start()` | sent {\"query_name\":\"q\"} | same |\n| `queryName(\u0027\u0027)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `queryName` must be a non-empty string, got \u0027\u0027. | same |\n| `queryName(\u0027  \u0027)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `queryName` must be a non-empty string, got \u0027  \u0027. | same |\n| `queryName(5)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `queryName` must be a non-empty string, got \u00275\u0027. | same |\n| `queryName(None)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `queryName` must be a non-empty string, got \u0027None\u0027. | same |\n| `queryName(bad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `trigger()` | call: PySparkValueError [ONLY_ALLOW_SINGLE_TRIGGER] Only a single trigger is allowed. | same |\n| `trigger(5)` | call: TypeError DataStreamWriter.trigger() takes 1 positional argument but 2 were given | same |\n| `trigger(processingTime\u003d1 second).start()` | sent {\"trigger\":[\"processing_time_interval\",\"1 second\"]} | same |\n| `trigger(processingTime\u003d\u0027 1 second \u0027).start()` | sent {\"trigger\":[\"processing_time_interval\",\"1 second\"]} | same |\n| `trigger(processingTime\u003d\u0027\u0027)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `processingTime` must be a non-empty string, got \u0027\u0027. | same |\n| `trigger(processingTime\u003d5)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `processingTime` must be a non-empty string, got \u00275\u0027. | same |\n| `trigger(processingTime\u003dbad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surrogates not allowed | same |\n| `trigger(once\u003dTrue).start()` | sent {\"trigger\":[\"once\",true]} | same |\n| `trigger(once\u003dFalse)` | call: PySparkValueError [VALUE_NOT_ALLOWED] Value for `once` has to be amongst the following values: [True]. | same |\n| `trigger(once\u003d1)` | call: PySparkValueError [VALUE_NOT_ALLOWED] Value for `once` has to be amongst the following values: [True]. | same |\n| `trigger(availableNow\u003dTrue).start()` | sent {\"trigger\":[\"available_now\",true]} | same |\n| `trigger(availableNow\u003dFalse)` | call: PySparkValueError [VALUE_NOT_ALLOWED] Value for `availableNow` has to be amongst the following values: [True | same |\n| `trigger(continuous\u003d1 second).start()` | sent {\"trigger\":[\"continuous_checkpoint_interval\",\"1 second\"]} | same |\n| `trigger(continuous\u003d\u0027\u0027)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `continuous` must be a non-empty string, got \u0027\u0027. | same |\n| `trigger(realTime\u003d5 seconds).start()` | sent {\"trigger\":[\"real_time_batch_duration\",\"5 seconds\"]} | same |\n| `trigger(realTime\u003d5)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `realTime` must be a non-empty string, got \u00275\u0027. | same |\n| `trigger(processingTime\u003d1 s, once\u003dTrue)` | call: PySparkValueError [ONLY_ALLOW_SINGLE_TRIGGER] Only a single trigger is allowed. | same |\n| `trigger(once\u003dTrue).trigger(availableNow\u003dTrue).start()` | sent {\"trigger\":[\"available_now\",true]} | same |\n| `foreach(f).start()` | sent {\"foreach_writer\":[\"python_function\",true,true]} | same |\n| `foreach(process).start()` | sent {\"foreach_writer\":[\"python_function\",true,true]} | same |\n| `foreach(open, process, close).start()` | sent {\"foreach_writer\":[\"python_function\",true,true]} | same |\n| `foreach(no process)` | call: PySparkAttributeError [ATTRIBUTE_NOT_CALLABLE] Attribute `process` in provided object `f` is not callable. | same |\n| `foreach(process not callable)` | call: PySparkAttributeError [ATTRIBUTE_NOT_CALLABLE] Attribute `process` in provided object `f` is not callable. | same |\n| `foreach(5)` | call: PySparkAttributeError [ATTRIBUTE_NOT_CALLABLE] Attribute `process` in provided object `f` is not callable. | same |\n| `foreach(unpicklable)` | call: PySparkPicklingError [STREAMING_CONNECT_SERIALIZATION_ERROR] Cannot serialize the function `foreach`. If you ac | same |\n| `foreachBatch(f).start()` | sent {\"foreach_batch\":[\"python_function\",true,true]} | same |\n| `foreachBatch(5).start()` | sent {\"foreach_batch\":[\"python_function\",true,true]} | same |\n| `foreachBatch(unpicklable)` | call: PySparkPicklingError [STREAMING_CONNECT_SERIALIZATION_ERROR] Cannot serialize the function `foreachBatch`. If y | same |\n| `foreachBatch(f).foreach(f).start()` | sent {\"foreach_writer\":[\"python_function\",true,true],\"foreach_batch\":[\"python_function\",true,true]} | same |\n\nThe cases are a test, `test_the_stream_writes_send_what_pysparks_writer_sends` (84 cases, run with both clients).\n\n**The started event.** `test_the_started_event_is_posted_to_the_post_to_all_of_the_bus` runs a start and a toTable with each of five buses:\n- the session\u0027s own bus, unchanged;\n- a patch of `post_to_all` on the bus;\n- a patch on its class, which calls the original;\n- a subclass of the bus whose `post_to_all` calls `super()`;\n- a bus of another class.\n\nA listener sits on the list of the bus in each case. The test checks what is called, with the decoded event once, and whether the listener gets the event. It runs with both clients, 10/10 on each. The listener is put on the list itself, because PySpark\u0027s `addListener` fails against the mock server: its listener-bus responses carry no session ID. The same matrix with listeners added by `addListener`, of the native registrations, is `test_streaming_started_event_goes_to_the_post_to_all_of_the_bus` of `streaming_listener_cases.py` (20 cases). The existing tests of the started event pass unchanged: its decode errors, the shared typed event, and a removal that waits for the delivery.\n\n**GC.** `test_a_writer_in_a_cycle_through_a_udf_is_collected` now covers `writeStream` too, run with both clients. It builds a cycle of the stream writer, its DataFrame (through the plan of its `_write_stream`) and the function of a UDF of the plan, which refers to the writer. One collection frees all three. The gc-shared clone check of `conftest.py` is on for every offline test and reports no violation.\n\n**The probes of SPARK-62249** have no stream writer case: its options are a protobuf map of str keys. On this branch they match as before:\n- `p_writer_lock_deadlock.py`: no deadlock in all 8 cases;\n- `p_compare_calls.py`: the same output as with the SPARK-62249 fix, zero violations;\n- `p_options_partial.py`: the same as PySpark 4.3.0.\n\n**The client\u0027s cost of the stream writer**, in µs per call (best of 5). The setters send nothing, and the starts are on the mock server, whose round trip is the same for every client:\n\n| | Before (native writer) | After (this PR) | PySpark 4.3.0 |\n|---|---|---|---|\n| `sdf.writeStream` | 0.78 | 2.72 | 2.20 |\n| `writeStream.format().option().outputMode().queryName().trigger()` | 6.29 | 5.46 | 3.65 |\n| `writeStream.foreachBatch(f)` | 24.6 | 30.6 | 25.1 |\n| `writeStream.format().option().start()` | 665 | 670 | 1283 |\n| `writeStream.format().toTable(t)` | 658 | 682 | 1268 |\n\n`df.writeStream` itself costs more, since it makes PySpark\u0027s `WriteStreamOperation` and its message in Python. The setters set the fields of the message, of the drop-in\u0027s protobuf runtime, a little slower than PySpark\u0027s upb. A start\u0027s client cost stays about half of PySpark\u0027s, because the transport is native.\n\n**What remains:**\n- **The `_write_stream._child` of a stream writer is the plan object that `df._plan` gave when `writeStream` was read.** The drop-in makes a new one at each read (SPARK-62218).\n- **That plan object holds the DataFrame**, where PySpark\u0027s does not. So a DataFrame that keeps its stream writer (`df.w \u003d df.writeStream`) is a reference cycle, which the collector frees, where PySpark frees the DataFrame at its last reference. The native writer held the core\u0027s plan and not the DataFrame. This waits for SPARK-62218 too.\n- **The rest is the residue of the KD row:** requests go through the native transport, through `client.execute_command`.\n\n### Why are the changes needed?\n\nSo that the stream writer is PySpark\u0027s, by construction: its `__dict__`, `_write_stream` and `_write_proto`, setters, errors and their order, commands, the functions of foreach and foreachBatch, copies, pickles, and the post of the started event. The native writer state that existed only to emulate PySpark\u0027s dict, `WriteStreamOperation` and the reduce goes.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes:\n- `df.writeStream` is PySpark Connect\u0027s `DataStreamWriter`, whose state is its `__dict__`, with PySpark\u0027s `WriteStreamOperation` as `_write_stream`. A pickle of it is a plain object of its class.\n- The started event of a start goes to what `spark.streams._sqlb.post_to_all` is, as in PySpark. A patch of the method, a subclass of the bus or another bus is now called. Before, the event went to the native registrations only.\n- A listener that a user puts on `spark.streams._sqlb._listener_bus` directly gets the started event, also when the bus has no registered listener. Before, it did not.\n- The bus of a second manager of the session, such as `StreamingQueryManager(spark)._sqlb`, no longer gets the started events of `spark.streams`\u0027s writer, as in PySpark. Before, every bus with registrations in the session did.\n- `df.w \u003d df.writeStream` is a reference cycle, freed by the collector (above).\n\n### How was this patch tested?\n\n- **`tests/test_dropin_object_state_offline.py`:**\n  - On this branch: 569 passed and 99 xfailed, with the 56 read cases, the 80 write cases, the 84 start cases, the 10 started-event cases and the 3 GC cases.\n  - With PySpark 4.3.0: 668 passed.\n- **The stream, listener, foreach, trigger, worker, pickle and reduce tests of `tests/test_dropin_offline.py`:** 481 passed. These include the 79 listener lifecycle tests and the 20 new registration cases. Five tests checked the native writer and are updated:\n  - `test_stream_writers_keep_the_pickles_of_their_functions_as_pyspark` reads the pickles of foreachBatch from `_write_proto`, of the writer and of its copies, as PySpark\u0027s keeps them;\n  - `test_worker_reconstructors_rebuild_the_readers_writers_and_streams_as_pyspark`: a stream writer pickles as PySpark\u0027s plain object and rebuilds with its format, output mode and query name;\n  - `test_worker_reconstructors_replay_every_setting_as_pyspark` compares the state of each rebuilt writer, stream reader and stream writer with the original\u0027s (its `__dict__`, without its DataFrame, plan and session; messages by their bytes). Since SPARK-62212 it compared the args of a plain reduce, which said nothing. It covers the trigger, partitioning, clustering and foreach/foreachBatch pickles of a stream writer;\n  - `test_the_holes_of_pickled_udfs_are_filled_on_a_python_worker_as_pyspark`: the reduce of a DataFrame ends with the function that fills its holes, as `request_schema` is gone;\n  - `test_a_dataframe_of_the_plan_of_another_does_not_keep_it_as_pyspark` checked that a stream writer does not keep its DataFrame, which held when the native writer held the core\u0027s plan. Its stream writer cases are now `test_a_stream_writer_does_not_keep_its_dataframe_as_pyspark`, a strict xfail of the drop-in (SPARK-62218, \"What remains\" above), which passes with PySpark 4.3.0.\n- **`tests/test_type_stubs_offline.py`** (15 passed, 4 skipped) and **`tests/test_dropin_class_modules_offline.py`** (279 passed, with the docstring golden): pass.\n- **`tests/test_dropin_e2e.py`** against a Spark 4.3.0 server: 360 passed, the whole file. On their own, the stream, foreach, listener, trigger and query tests (`-k \"stream or Stream or foreach or listener or Listener or trigger or Trigger or toTable or query or Query\"`) give 30 passed and 3 failed. The 3 failures are `test_foreach_batch_captures_the_readers_writers_and_groups_as_pyspark[groupBy, pivot, cogroup]`, which fail on the base too when run without the rest of the suite: cloudpickle pickles the native `GroupedData` by value when `pyspark.sql.connect.group` was never imported (tracked separately). This PR\u0027s import of `pyspark.sql.connect.streaming.query` fixes the same failure of its other 6 cases, of a captured `StreamingQuery`.\n- **The probes above.**\n- **The gates** (at 0f0b5ebb, on master dd756c29):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 32 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_connect_docstrings.py --check`, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7721 passed, 121 skipped, 100 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 360 passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #952 from HyukjinKwon/SPARK-62213-stream-writer-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "035a1c9c3ae16a6509d14b743376b904fb2c4619",
      "tree": "24c355ca4813e078ee1004bbab469f12eb16b675",
      "parents": [
        "dcc7fef957d4d4381a3d7110ab6175430dfcd9f7"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 09:35:55 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 09:35:58 2026 +0000"
      },
      "message": "[SPARK-62251][CONNECT][PYTHON] Keep the parameters of the atomic data types in their __dict__, as PySpark\u0027s, and raise PySpark\u0027s error of a pickle of a __slots__ subclass at protocols 0 and 1\n\n### What changes were proposed in this pull request?\n\nPySpark\u0027s data types are plain classes. Their parameters are entries of their `__dict__`, of any value, and their methods read them. The drop-in kept the parameters in Rust, which caused these differences:\n- `vars(t)` was empty;\n- assigning a value that the core type does not hold raised at the assignment;\n- a subclass whose `__init__` did not call its class\u0027s had the class\u0027s defaults, where PySpark\u0027s raises `AttributeError`;\n- setting `srid` changed a spatial type\u0027s JSON, where PySpark\u0027s keeps the `_crs` that its constructor set.\n\nThis is part 1 of SPARK-62251, for the atomic types of parameters. Part 2 covers `ArrayType`, `MapType` and `StructField`. Part 3 covers `StructType`, with SPARK-62229 and SPARK-62231. It follows SPARK-62230 (#942).\n\n- **Parameters in `__dict__`.** These types keep their parameters as entries of their `__dict__`, as PySpark\u0027s `__init__` sets them, including `hasPrecisionInfo`, `_crs` and `_alg`:\n  - `DecimalType`, `StringType`, `CharType`, `VarcharType` and `TimeType`;\n  - `DayTimeIntervalType` and `YearMonthIntervalType`;\n  - `GeometryType` and `GeographyType`.\n\n  Their effect on each use:\n  - repr, `simpleString` and `jsonValue` read the attributes and format them with Python\u0027s `%` and `format`, as PySpark\u0027s methods do, so their errors are PySpark\u0027s (`%d format: a real number is required, not str`);\n  - `\u003d\u003d` compares the `__dict__`s;\n  - the core type is made of the entries, as protobuf\u0027s int fields of the proto take them (`Expected an int, got a boolean`, `Value out of range`);\n  - a raw `t.__dict__[\"scale\"] \u003d 3` counts too.\n- **Inside containers.** A type whose `__dict__` its core type does not hold, such as one with a value that a user set, calls its own methods in the types that hold it, as a type of a Python subclass does. A struct\u0027s JSON of such a type is PySpark\u0027s, of its own errors.\n- **Pickles.** These types pickle and copy as PySpark\u0027s plain classes do, as `copyreg.__newobj__` and the `__dict__`, also at protocols 0 and 1. The pickle is PySpark\u0027s own, byte for byte.\n- **`__slots__` subclasses.** A subclass of `__slots__` of any type, with no `__getstate__` of its own, raises PySpark\u0027s `TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled` at protocols 0 and 1.\n- **Intervals.** The interval types have PySpark\u0027s `_fields`, `_inverted_fields` and `_str_repr`.\n- **Speed.** The minimum of 5 interleaved rounds of this commit (1c3f53af) against master 30d257d0, under a load average of about 20:\n\n| Path | Base | This PR | Ratio |\n|---|---|---|---|\n| `json()` of 1,000 fields | 4,305 µs | 4,324 µs | 1.00 |\n| `json()` of 40 nested levels | 1,600 µs | 1,626 µs | 1.02 |\n| `json()` of 1,000 decimals | 4,631 µs | 4,748 µs | 1.03 |\n| proto of 1,000 fields | 1,264 µs | 1,248 µs | 0.99 |\n| proto of 1,000 decimals | 1,436 µs | 1,392 µs | 0.97 |\n| a cast\u0027s plan of 1,000 fields | 1,491 µs | 1,448 µs | 0.97 |\n| a cast\u0027s plan of 40 nested levels | 1,014 µs | 957 µs | 0.94 |\n| a cast\u0027s plan of 1,000 decimals | 1,664 µs | 1,609 µs | 0.97 |\n| `df.to` of 1,000 fields | 377 µs | 334 µs | 0.88 |\n| `df.to` of 1,000 decimals | 440 µs | 378 µs | 0.86 |\n| `createDataFrame` of 200 rows of 20 longs | 389 µs | 371 µs | 0.95 |\n| `createDataFrame([], 1,000 fields)` | 4,129 µs | 4,053 µs | 0.98 |\n| `createDataFrame` of 200 rows of a decimal, a string, a time and a long | 536 µs | 482 µs | 0.90 |\n| `toInternal` of such a row | 5.8 µs | 5.7 µs | 1.00 |\n| `fromInternal` of such a row | 11.7 µs | 11.8 µs | 1.01 |\n| a UDF column of a decimal return type | 278 µs | 264 µs | 0.95 |\n| a UDF column of a struct of 1,000 fields | 3,216 µs | 3,173 µs | 0.99 |\n| `mapInPandas` of 1,000 fields | 1,708 µs | 1,666 µs | 0.98 |\n\nOff these paths: `simpleString()` of 1,000 fields 358 µs → 396 µs (1.11) and `hash()` of them 475 µs → 520 µs (1.10), as a string\u0027s `simpleString` calls its `isUTF8BinaryCollation()` (part 2 reads the native one directly); `repr(DecimalType(10, 2))` 0.6 µs → 0.8 µs, of Python\u0027s `%`; and a cast Column, which builds no plan, 8.6 µs → 9.1 µs.\n\n**Gates:**\n- build, rustfmt, clippy (1.100.0), rustdoc, ruff, the stub audit, the generators, the guards, the licenses and the stub tests pass.\n- `pyspark-rs` lib tests: 37 passed.\n- The offline suite: 7,405 passed, 121 skipped, 163 xfailed.\n- e2e against Spark 4.3.0: 359 passed. One test, `test_plans_of_a_few_hundred_levels_are_sent_as_pyspark`, raised `NO_ACTIVE_SESSION` when the server restarted during the run, and passed when run again.\n- `scripts/check_vendored_upstream.sh` was not run, as no vendored path is touched.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #949 from HyukjinKwon/SPARK-62251-type-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "dcc7fef957d4d4381a3d7110ab6175430dfcd9f7",
      "tree": "5c2f6402892bb5cfbfffdfd9cbe3560e2f2fb411",
      "parents": [
        "dd756c293718f2f4834088fbda9e184662e2e7fc"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 09:23:27 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 09:23:29 2026 +0000"
      },
      "message": "[SPARK-62250][CONNECT][PYTHON] Keep the state of the Python client\u0027s SparkConnectClient in its __dict__, read at the start of each request, as PySpark\u0027s client keeps it\n\n### What changes were proposed in this pull request?\n\nA follow-up of the `__dict__` state PRs, after SPARK-62216 (#943), on master 868b718f (design section 4.12).\n\nPySpark\u0027s `SparkConnectClient` keeps its state in the attributes of its `__dict__`, and reads them as each request is built. The drop-in\u0027s client is a facade of the native transport. Before this PR:\n- its `__dict__` held only `thread_local`, `_builder`, `_user_id`, `_session_id`, `global_user_context_extensions` and `global_user_context_extensions_lock`;\n- `_closed`, `_server_session_id` and `_use_reattachable_execute` were properties over the native session;\n- the other attributes raised `AttributeError`: `_retry_policies`, `_max_retry_exception_elapsed_time`, `_rpc_deadlines`, `_allow_arrow_batch_chunking`, `_preferred_arrow_chunk_size`, `_session_hooks`, `_progress_handlers`, `_profiler_collector`, `_plan_compression_threshold`, `_plan_compression_algorithm` and `_release_session_on_exit`. The transport kept their values as the constructor or a setter gave them.\n\nSo:\n- **The state is the `__dict__` of the client** (`python/pyspark/sql/connect/client/core.py`, `_new_client_state`). It has the 20 attributes of PySpark\u0027s client, in its order and of its values. The clients of a session share it, as PySpark\u0027s session has one client, and `copy.copy` of a client makes a dict of its own. One value is made later: the `[DefaultPolicy()]` of `_retry_policies` is made when the attribute is first read, or the client copied (`_DefaultRetryPolicies`). The module of the policies, the vendored `retries`, imports grpcio, which the drop-in does not require, and which a session and its queries do not import (`test_a_session_and_its_queries_import_no_grpc_unless_a_log_needs_it`). The methods read and set the attributes as PySpark\u0027s:\n  - `set_retry_policies` sets `_retry_policies`;\n  - `enable_reattachable_execute` and `disable_reattachable_execute` set `_use_reattachable_execute`;\n  - `register_progress_handler`, `remove_progress_handler` and `clear_progress_handlers` change `_progress_handlers`, and the session\u0027s `registerProgressHandler`, `removeProgressHandler` and `clearProgressHandlers` call them;\n  - `spark.profile` is a `Profile` of `_profiler_collector`;\n  - `close()` sets `_closed`, and so do `stop()` and the drop of the session\u0027s last object;\n  - `is_closed` reads `_closed`, so a client whose `__init__` never ran raises PySpark\u0027s `AttributeError` of `_closed`.\n- **The transport reads the attributes as each call starts, under the GIL.** The refresher that already reads `_session_id`, `_user_id`, the extensions and the tags (`_RequestContext`, `_call_settings`) now also gives the transport (`apply_call_settings` in `crates/pyspark-rs/src/interrupt.rs`):\n  - `_closed`, which marks the native session closed or opens it again, and `_server_session_id`;\n  - `_rpc_deadlines`, `_allow_arrow_batch_chunking` and `_preferred_arrow_chunk_size`, for the calling thread. An execution keeps those of the start of its call for its reattaches and releases;\n  - `_use_reattachable_execute`, `_retry_policies` and `_max_retry_exception_elapsed_time`;\n  - `_plan_compression_threshold` and `_plan_compression_algorithm`. A None of either makes the next plan look them up again, as PySpark\u0027s `_get_plan_compression_threshold_and_algorithm` does;\n  - the `_session_hooks` list, for the calling thread and the session, and the number of the `_progress_handlers`.\n\n  A thread of the transport that runs the requests of a call, as one of the fits of the classes of a OneVsRest, takes the deadlines and the result chunking of the last call that started, and calls the hooks of the session\u0027s client.\n\n  Of the values that the native session keeps for all of its calls, a call gives it only those that differ from what it has.\n- **Each call writes back what its responses set** (`_write_back`): the `_closed` of a server-side session change, the `_server_session_id` of the first response, and the plan compression settings of their lookup.\n- **Some attributes are read when they are used.** The progress handlers are read at each progress and the profiler collector at each update, of the client of the call, or of the copy whose method made it (`calling_copy_state`). The exit hook reads `_closed` and `_release_session_on_exit`, as PySpark\u0027s `_on_exit` does.\n- **`_closed` is the client\u0027s own.** The `close()` of a copy sets the copy\u0027s `_closed` and closes the channel that it shares with its client. The client stays open, and its requests raise grpc\u0027s `ValueError` of a closed channel, as PySpark\u0027s. `is_stopped`, `getActiveSession`, `getOrCreate`, `stop()` and the exit read the `_closed` of the session\u0027s client. So a call of a closed copy, which marks the native session closed for its requests, does not stop the session. `_close_sessions_at_exit`, the exit seam of the test suites, sets the `_closed` of the clients it closes.\n- **A client kept apart from its session keeps all its attributes.** The closed session that stands for it once the program dropped the session reads them.\n- **Core** (`crates/spark-connect-core/src/client.rs`, in the `ThreadRequestContext` and plan compression regions only). Both are doc-hidden binding hooks, with unit tests:\n  - `ThreadRequestContext` gains `rpc_deadlines` and `result_chunking` overrides, set by `set_thread_call_settings` and read first by each RPC (`call_rpc_deadlines`, `call_result_chunking`). A thread of no request context of a binding takes the latest that a binding gave. The client clone of an execution keeps them (`of_call_settings`). A nested call restores them with the rest of the thread\u0027s context;\n  - `PlanCompressionSettings`, PySpark\u0027s `(threshold, algorithm)` pair, as the lookup reads it (-1 and `NONE` for a disabled compression), with `plan_compression_settings()` and `set_plan_compression_settings()`.\n- **Docs:**\n  - a new KD row, \"The attributes of `SparkConnectClient`\". It states the attributes that the native transport replaces (`_channel`, `_internal_stub` and the `_stub` property, `_artifact_manager`, `_release_futures`, `_zstd_module`) and what stays different (see below);\n  - \"Retry and reattach\" says that the policies, the deadlines and the reattachability are attributes of the client, read as each call starts;\n  - the copy clause of \"`SparkConnectClient.thread_local`\" is removed: a copy has its own attributes now;\n  - \"Client session ID\" now covers a response of an empty server-side session ID;\n  - the row \"A `client` kept apart from its session\" is removed, as such a client keeps all its attributes now;\n  - `docs/compatibility.md` describes the `__dict__` of the client.\n\nChecked on both clients against a Spark 4.3.0 server. Each case runs in its own process from a neutral directory.\n\n| case | pyspark-client 4.3.0 | master (30d257d0) | drop-in now |\n|---|---|---|---|\n| closed_true_then_false | raises SparkConnectException NO_ACTIVE_SESSION ; True ; [Row(id\u003d0)] ; False | raises SparkConnectException NO_ACTIVE_SESSION ; True ; [Row(id\u003d0)] ; False | raises SparkConnectException NO_ACTIVE_SESSION ; True ; [Row(id\u003d0)] ; False |\n| close_then_reopen | (True, True, True) ; raises SparkConnectException NO_ACTIVE_SESSION ; raises ValueError None Cannot invoke ... | (True, True, True) ; raises SparkConnectException NO_ACTIVE_SESSION ; raises ValueError None Cannot invoke ... | (True, True, True) ; raises SparkConnectException NO_ACTIVE_SESSION ; raises ValueError None Cannot invoke ... |\n| stop_closed | (True, True, True) | (True, True, True) | (True, True, True) |\n| closed_getorcreate | False ; [Row(id\u003d0)] | False ; [Row(id\u003d0)] | False ; [Row(id\u003d0)] |\n| server_session_id_changed | raises SparkConnectException NO_ACTIVE_SESSION ; (True, \u0027not-the-session\u0027) | raises SparkConnectException NO_ACTIVE_SESSION ; (True, \u0027not-the-session\u0027) | raises SparkConnectException NO_ACTIVE_SESSION ; (True, \u0027not-the-session\u0027) |\n| server_session_id_none | [Row(id\u003d0)] ; True | [Row(id\u003d0)] ; True | [Row(id\u003d0)] ; True |\n| server_session_id_int | raises TypeError None bad argument type for built-in operation | (no output) | raises TypeError None bad argument type for built-in operation |\n| deadline_analyze | raises SparkConnectGrpcException None \u003c_InactiveRpcError of RPC that terminated with: / status \u003d StatusCode... | StructType([StructField(\u0027id\u0027, LongType(), False)]) ; StructType([StructField(\u0027id\u0027, LongType(), False)]) | raises SparkConnectGrpcException None \u003c_InactiveRpcError of RPC that terminated with: / status \u003d StatusCode... |\n| deadline_in_place | raises dataclasses.FrozenInstanceError None cannot assign to field \u0027config\u0027 | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_rpc_deadlines\u0027 | raises dataclasses.FrozenInstanceError None cannot assign to field \u0027config\u0027 |\n| deadline_none | raises AttributeError None \u0027NoneType\u0027 object has no attribute \u0027reattachable_execute_plan\u0027 | [Row(id\u003d0)] | raises AttributeError None \u0027NoneType\u0027 object has no attribute \u0027reattachable_execute_plan\u0027 |\n| hooks_append | 1 ; 1 | (no output) | 1 ; 1 |\n| hooks_new_session | 0 ; 1 ; False | (no output) | 0 ; 1 ; False |\n| progress_append | (True, True) | (no output) | (True, True) |\n| progress_rebind | (True, True) | (False, None) | (True, True) |\n| progress_register_methods | True ; 1 ; [] ; raises ValueError None list.remove(x): x not in list | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_progress_handlers\u0027 ; raises Attri... | True ; 1 ; [] ; raises ValueError None list.remove(x): x not in list |\n| reattachable_methods | True ; False ; 3 ; True | True ; False ; 3 ; True | True ; False ; 3 ; True |\n| retry_methods | (True, False) ; (True, True) ; 3 ; 3 | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_retry_policies\u0027 ; raises Attribut... | (True, False) ; (True, True) ; 3 ; 3 |\n| chunking | 5 | 5 | 5 |\n| compression | 5 ; (0, \u0027ZSTD\u0027) ; 5 ; (10485760, \u0027ZSTD\u0027) | 5 ; (0, \u0027ZSTD\u0027) ; 5 ; (None, \u0027ZSTD\u0027) | 5 ; (0, \u0027ZSTD\u0027) ; 5 ; (10485760, \u0027ZSTD\u0027) |\n| profiler | raises AttributeError None \u0027Profile\u0027 object has no attribute \u0027_profiler_collector\u0027 | raises AttributeError None \u0027Profile\u0027 object has no attribute \u0027_profiler_collector\u0027 | raises AttributeError None \u0027Profile\u0027 object has no attribute \u0027_profiler_collector\u0027 |\n| uninitialized | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_closed\u0027 ; {} | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_session_cache\u0027 ; {} | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_closed\u0027 ; {} |\n| subclass | [\u0027_allow_arrow_batch_chunking\u0027, \u0027_artifact_manager\u0027, \u0027_builder\u0027, \u0027_channel\u0027, \u0027_closed\u0027, \u0027_internal_stub\u0027] ;... | [\u0027_builder\u0027, \u0027_session_id\u0027, \u0027_user_id\u0027, \u0027global_user_context_extensions\u0027, \u0027global_user_context_extensions_l... | [\u0027_allow_arrow_batch_chunking\u0027, \u0027_builder\u0027, \u0027_closed\u0027, \u0027_max_retry_exception_elapsed_time\u0027, \u0027_plan_compress... |\n| copy | (True, True) ; False ; 1 | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_progress_handlers\u0027 ; True ; raise... | (True, True) ; False ; 1 |\n| copy_close | (False, True, False) ; True ; raises ValueError None Cannot invoke RPC on closed channel! ; raises ValueErr... | (True, True, True) ; False ; raises SparkConnectException NO_ACTIVE_SESSION ; raises SparkConnectException ... | (False, True, False) ; True ; raises ValueError None Cannot invoke RPC on closed channel! ; raises ValueErr... |\n| copy_closed_call | raises SparkConnectException NO_ACTIVE_SESSION ; (False, False) ; True ; True ; 1 ; raises SparkConnectExce... | raises SparkConnectException NO_ACTIVE_SESSION ; (True, True) ; False ; False ; raises SparkConnectExceptio... | raises SparkConnectException NO_ACTIVE_SESSION ; (False, False) ; True ; True ; 1 ; raises SparkConnectExce... |\n| copy_own_settings | (True, True) ; True ; (True, False, 1, 0) ; raises SparkConnectException NO_ACTIVE_SESSION ; (True, False) ; 1 | (False, True) ; True ; (False, False, 0, 0) ; raises SparkConnectException NO_ACTIVE_SESSION ; (True, True)... | (True, True) ; True ; (True, False, 1, 0) ; raises SparkConnectException NO_ACTIVE_SESSION ; (True, False) ; 1 |\n| copy_progress | 1 ; (True, [True], []) ; [Row(s\u003d28)] ; (1, [True]) | (no output) | 1 ; (True, [True], []) ; [Row(s\u003d28)] ; (1, [True]) |\n| pickle | raises TypeError None cannot pickle \u0027_thread._local\u0027 object ; raises TypeError None cannot pickle \u0027_thread.... | raises TypeError None cannot pickle \u0027_thread._local\u0027 object ; raises TypeError None cannot pickle \u0027_thread.... | raises TypeError None cannot pickle \u0027_thread._local\u0027 object ; raises TypeError None cannot pickle \u0027_thread.... |\n| client_constructor | (3, False, False, False, 4096, True, 9.5, False, None, None) | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_retry_policies\u0027 | (3, False, False, False, 4096, True, 9.5, False, None, None) |\n| new_session_settings | (False, True, True, False, False) | raises AttributeError None \u0027SparkConnectClient\u0027 object has no attribute \u0027_rpc_deadlines\u0027 | (False, True, True, False, False) |\n\n- master: 10/30; drop-in now: 29/30.\n\nThe case that still differs is `subclass`, a subclass of the client made of a connection string. Its sorted `vars()` lack the attributes that the native transport replaces (`_artifact_manager`, `_channel`, `_internal_stub`). The order and the values of the other entries are PySpark\u0027s.\n\nA `_plan_compression_threshold` that is a float now compresses as PySpark compares it (0.5 and NaN give PySpark\u0027s results).\n\nWhat stays different, as the new KD row says:\n- PySpark\u0027s client reads its attributes as each request is built, and at each RPC. The transport reads them as each call starts, for all the requests of the call. So a change during a call, as by a progress handler or another thread, applies from the next call on. The attributes that the responses set are written when the call ends, where PySpark\u0027s are set as the response arrives.\n- The closed flag, the server-side session ID, the reattachability, the retry policies and the plan compression settings are the native session\u0027s, for all of its calls. So calls of a copy and of its client that run at once on different threads, with different values, get those of the call that started last. The deadlines, the result chunking and the session hooks are per thread.\n- PySpark\u0027s execution calls the handlers of the list that `_progress_handlers` held as it started. The drop-in reads the attribute at each progress, so a list assigned during an execution is called from its next progress on.\n- A response of an empty server-side session ID is not observed. A Spark server sends one only in its answer to the release of a session that it does not have. `_server_session_id` stays None, where PySpark\u0027s becomes the empty string.\n- Until it is read, `vars(client)[\"_retry_policies\"]` is `\u003cthe [DefaultPolicy()] of the client, made when it is read\u003e`, of which the transport retries as of `DefaultPolicy()`.\n- A `_plan_compression_threshold` that is neither an int nor a float, such as a str, compresses no plan. PySpark\u0027s plans raise the `TypeError` of its comparison with 0 (`\u0027\u003e\u003d\u0027 not supported between instances of \u0027str\u0027 and \u0027int\u0027`).\n- The fits of the classes of a OneVsRest, which the transport runs on threads of its own, carry the deadlines and the result chunking of the last call that started.\n\n### Why are the changes needed?\n\nPySpark\u0027s tests and some libraries read and set the attributes of `spark.client`. With this change they see PySpark\u0027s state, and the next requests use it.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes:\n- `vars(spark.client)` holds PySpark\u0027s attributes, and setting one, or changing the object that it holds, applies from the next call on;\n- the `close()` of a copy of a client leaves the client open, of the `ValueError` of a closed channel, where the client was closed of `NO_ACTIVE_SESSION`;\n- a call of a closed copy no longer makes `getActiveSession()` and `getOrCreate()` skip the session;\n- a client kept apart from its dropped session keeps its server-side session ID and its reattachability.\n\n### How was this patch tested?\n\n- **New offline tests** in `python/tests/test_dropin_offline.py`, against the mock server:\n  - `test_the_state_of_a_client_is_the_dict_of_its_attributes_as_pysparks`: the keys, order and values of `vars(client)`, also of a subclass, the `[DefaultPolicy()]` made at its read and shared by a copy, the attributes that are not there, and the `AttributeError` of an uninitialized client;\n  - `test_the_attributes_of_a_client_are_read_at_the_start_of_each_request_as_pysparks`: the result chunking and the reattach options of the requests, the session hooks (appended and assigned), a config deadline (`DEADLINE_EXCEEDED`), and the retries of `_retry_policies`;\n  - `test_the_plan_compression_settings_of_a_client_are_its_attributes_as_pysparks`: set before the first plan (no lookup), a threshold of 0, `NONE`, and None (looked up again);\n  - `test_a_client_and_its_copies_are_closed_of_their_own_closed_as_pysparks`: `_closed` of the client and of a copy, `getActiveSession`, and the `close()` of a copy;\n  - `test_the_progress_handlers_and_the_profiler_collector_of_a_client_are_its_own_as_pysparks`: appended and assigned handlers, the session\u0027s methods, and those of a copy; the collector, also of a copy.\n\n  `test_client_of_a_connection_as_pyspark` now asserts `_max_retry_exception_elapsed_time`. The kept-apart test passes as before.\n- **New exit tests** in `python/tests/test_exit_cleanup_offline.py`: `_release_session_on_exit` set and unset after the creation, `_closed` set, and a closed copy. They pass on pyspark-client 4.3.0 too.\n- **New e2e test** in `python/tests/test_dropin_e2e.py`, `test_the_attributes_of_a_client_are_its_dict_read_at_each_request_as_pyspark`: the order of `vars(client)`, hooks, reattachability, plan compression at a threshold of 0, progress handlers, and the `close()` of a copy. It passes on both clients.\n- **Core unit tests**: `the_call_settings_of_a_thread_are_its_own_and_its_executions_keep_them` and `the_plan_compression_settings_are_those_of_pyspark_s_client`. `cargo test -p apache-spark-connect-core --lib`: 403 passed.\n- `test_ml_connect_one_vs_rest_logs_the_warning_of_each_class_fit_as_pyspark` covers the hooks of the fits of a OneVsRest, which run on the transport\u0027s own threads.\n- **The Rust and Python gates** (`gates.sh build rust py`):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps`;\n  - `cargo test -p pyspark-rs --lib`: 37 passed;\n  - ruff 0.14.0, `test_ruff_excludes.py`, `scripts/audit_no_stubs.sh`, the stub and dispatch generators, the test-list guards and the license checks;\n  - `test_type_stubs_offline.py`: 15 passed, 4 skipped;\n  - the offline suite of `coverage.yml`: 7,411 passed, 121 skipped, 163 xfailed.\n- **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 361 passed.\n- `scripts/check_vendored_upstream.sh` was not run, as no vendored path is touched.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #951 from HyukjinKwon/SPARK-62250-client-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "dd756c293718f2f4834088fbda9e184662e2e7fc",
      "tree": "bbe8895b0ffffa9f33a8fe1170a1711e2ecd1ed3",
      "parents": [
        "c3513938352c79797e802306d826afd6c63b6ed0"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 08:32:59 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 08:33:01 2026 +0000"
      },
      "message": "[SPARK-62212][CONNECT][PYTHON] Make DataFrameWriter and DataFrameWriterV2 PySpark Connect\u0027s classes, adapted from PySpark 4.3.0, whose state is their `__dict__`, and whose writes send PySpark\u0027s command\n\n### What changes were proposed in this pull request?\n\nThis is a sub-task of SPARK-62207. It comes after SPARK-62208 (#926), SPARK-62209 (#929) and SPARK-62211 (#936, the readers). It covers the writers, `df.write` and `df.writeTo(table)`.\n\nPySpark\u0027s `DataFrameWriter` and `DataFrameWriterV2` are plain Python classes, subclasses of `OptionUtils`. Their state:\n- `_df`, the plan of the DataFrame;\n- `_spark`;\n- `_write`, a `WriteOperation` or `WriteOperationV2` of `pyspark.sql.connect.plan`, whose fields the setters set;\n- `_callback`;\n- `_table_name`, for V2.\n\nA write builds the command of `_write` and runs it with `self._spark.client.execute_command(...)`, then calls `self._callback(ei)`. The drop-in\u0027s writers were native classes with their own option and argument state, and they emulated those steps in Rust. As for the readers (#936), this PR makes the writers PySpark\u0027s own classes.\n\n**Provenance.** `DataFrameWriter` and `DataFrameWriterV2` are **adapted** from Apache Spark v4.3.0\u0027s `python/pyspark/sql/connect/readwriter.py`. `WriteOperation` and `WriteOperationV2` come from its `python/pyspark/sql/connect/plan.py`. Both files keep their Apache license header, and the modules carry a header comment that names the source files. These are not verbatim copies, so they are not in the vendored-file registry.\n\nThe only adaptations:\n- `df.write` and `df.writeTo` pass a callback that records the write\u0027s `ExecutionInfo` as the DataFrame\u0027s `executionInfo` (`_set_execution_info`). On a Python worker of the server, where the DataFrame is PySpark\u0027s, the callback sets `_execution_info` as PySpark\u0027s does.\n- ruff modernized the annotations.\n\nThe writer code itself is PySpark\u0027s. The command is PySpark\u0027s too: it is built over pbmsg, and its input relation is the core\u0027s placeholder (`df._plan.plan(client)`). The drop-in client\u0027s `execute_command` executes it, as it does for any command of the Python client.\n\n**The changes:**\n- **`python/pyspark/sql/connect/readwriter.py`:** the adapted writers, next to the adapted readers of #936.\n- **`python/pyspark/sql/connect/plan.py`:** PySpark\u0027s `WriteOperation` and `WriteOperationV2`. `WriteOperation.print` carries the docstring that PySpark\u0027s inherits from `LogicalPlan.print`, as `Read.print` already does.\n- **`crates/pyspark-rs/src/dataframe.rs`:**\n  - `write` and `writeTo` return `DataFrameWriter(self._plan, self._session, cb)` and `DataFrameWriterV2(self._plan, self._session, table, cb)`.\n  - `_set_execution_info` records the `ExecutionInfo` of a write. `executionInfo` then gives it until a later execution of the DataFrame replaces it. Python\u0027s garbage collector sees it.\n- **Removed:**\n  - the native `DataFrameWriter` and `DataFrameWriterV2` with their shared state (kept arguments, options, unsent provider/table/columns, `WriterParts` holders of their own), copies and reduces;\n  - the writer helpers of `readwriter.rs` (save mode, bucket count, column checks) and of `options.rs` (`writer_entry`, `property_entry`, `OptionBuilder`, `set_option(s)_skip_none`, `set_opts`), and `GilMutex::replace`;\n  - the writer reduces of `_state_reduce.py`. A writer now pickles as PySpark\u0027s plain object, which a worker without the drop-in loads as PySpark\u0027s class.\n- **SPARK-62249 (#928):** its writer half is deleted with them. The option unit tests of `options.rs` exercise `change_options` through a test helper, since the session builder still uses it.\n- **Stubs:** `WriteOperation` and `WriteOperationV2` leave the generator\u0027s `UNRESOLVED_IMPORTS`, because the drop-in has them now. The stubs are regenerated. The aliased classic writers join the undeclared names of the stub test.\n- **Docs:** the `__dict__`, Subclasses and gc rows of `dev/parity/known-differences.md` and the matching paragraphs of `docs/compatibility.md`. The writers move from the native list to the PySpark classes. The deep-plan paragraph of `docs/compatibility.md` gets the partitioning columns of `writeTo` (below).\n\nOf the 419 generic cases of `tests/test_dropin_object_state_offline.py`:\n\n| | Same as PySpark | Differ |\n|---|---|---|\n| Before, #936 at 8c93e387 | 215 | 204 |\n| After, this PR | 237 | 182 |\n\nFive writer cases move to the DataFrame group (SPARK-62218): the `vars` of the four writer objects and `test_the_write_operation_of_a_writer_is_what_its_save_builds`. They check `writer._df is df._plan`. The drop-in\u0027s DataFrame gives a new plan object at each read of `_plan`, and caching one would make a cycle per DataFrame (DataFrame → plan object → DataFrame). PySpark\u0027s is one object, so these cases wait for SPARK-62218.\n\n**Writes against PySpark 4.3.0.** The probe makes each call with both clients on the mock server. It records what the call raises, or else the write command that the server receives. All 80 cases are the same: modes, formats, partitionBy, bucketBy, sortBy and clusterBy, the option kinds (None, bool, int, bytes and unhashable keys, strs that can\u0027t be encoded), save, saveAsTable, insertInto, jdbc and the format shortcuts, and V2\u0027s using, option, tableProperty, partitionedBy, clusterBy, create, replace, createOrReplace, append, overwrite and overwritePartitions.\n\n| Case | PySpark 4.3.0 | Drop-in |\n|---|---|---|\n| `mode(append).save(p)` | sent {\"kind\":\"write_operation\",\"mode\":1,\"save\":\"path\",\"path\":\"p\"} | same |\n| `mode(bogus).save(p)` | call: PySparkValueError [UNSUPPORTED_OPERATION] bogus is not supported. | same |\n| `mode(b\u0027append\u0027).save(p)` | call: PySparkValueError [UNSUPPORTED_OPERATION] b\u0027append\u0027 is not supported. | same |\n| `mode(5).save(p)` | call: AttributeError \u0027int\u0027 object has no attribute \u0027lower\u0027 | same |\n| `mode(None).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\"} | same |\n| `format(5).save(p)` | call: TypeError bad argument type for built-in operation | same |\n| `format(bad).save(p)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `format(parquet).save()` | sent {\"kind\":\"write_operation\",\"source\":\"parquet\"} | same |\n| `save(5)` | call: TypeError bad argument type for built-in operation | same |\n| `save(bad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `save(p, format\u003djson, mode\u003doverwrite, k\u003d1)` | sent {\"kind\":\"write_operation\",\"source\":\"json\",\"mode\":2,\"save\":\"path\",\"path\":\"p\",\"options\":[[\"k\",\"1\" | same |\n| `option(k, None).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\"} | same |\n| `option(k, True).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\",\"options\":[[\"k\",\"true\"]]} | same |\n| `option(5, v).save(p)` | call: TypeError bad argument type for built-in operation | same |\n| `option(b\u0027k\u0027, v).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\",\"options\":[[\"k\",\"v\"]]} | same |\n| `option(bad, v).save(p)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `option(k, bad).save(p)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `option([1], v)` | call: TypeError unhashable type: \u0027list\u0027 | same |\n| `options(k\u003dbad).save(p)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `partitionBy(a, b).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\",\"partitioning\":[\"a\",\"b\"]} | same |\n| `partitionBy([a, b]).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\",\"partitioning\":[\"a\",\"b\"]} | same |\n| `partitionBy(5).save(p)` | call: TypeError bad argument type for built-in operation | same |\n| `partitionBy(bad).save(p)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `bucketBy(2, a).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\",\"bucket\":[[\"a\"],2]} | same |\n| `bucketBy(x, a)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `numBuckets` should be int, got str. | same |\n| `bucketBy(True, a).save(p)` | call: TypeError Field spark.connect.WriteOperation.BucketBy.num_buckets: Expected an int, g | same |\n| `bucketBy(0, a).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\"} | same |\n| `bucketBy(2**40, a).save(p)` | call: ValueError Value out of range: 1099511627776 | same |\n| `bucketBy(2, [a], b)` | call: PySparkValueError [CANNOT_SET_TOGETHER] `col` of type list and `cols` should not be s | same |\n| `bucketBy(2, [])` | call: IndexError list index out of range | same |\n| `bucketBy(2, a, 5)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `cols` should be list[str], got int. | same |\n| `bucketBy(2, 5)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `col` should be list[str], got int. | same |\n| `sortBy(a, b).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\",\"sort\":[\"a\",\"b\"]} | same |\n| `sortBy((a,), b)` | call: PySparkValueError [CANNOT_SET_TOGETHER] `col` of type tuple and `cols` should not be  | same |\n| `sortBy(5)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `col` should be list[str], got int. | same |\n| `clusterBy(a).save(p)` | sent {\"kind\":\"write_operation\",\"save\":\"path\",\"path\":\"p\",\"clustering\":[\"a\"]} | same |\n| `clusterBy()` | call: AssertionError clusterBy needs one or more clustering columns. | same |\n| `clusterBy(5).save(p)` | call: TypeError bad argument type for built-in operation | same |\n| `saveAsTable(t)` | sent {\"kind\":\"write_operation\",\"save\":\"table\",\"table\":[\"t\",1]} | same |\n| `saveAsTable(5)` | call: TypeError bad argument type for built-in operation | same |\n| `saveAsTable(t, format\u003dparquet, mode\u003dappend, partitionBy\u003da)` | sent {\"kind\":\"write_operation\",\"source\":\"parquet\",\"mode\":1,\"save\":\"table\",\"table\":[\"t\",1],\"partition | same |\n| `insertInto(t)` | sent {\"kind\":\"write_operation\",\"save\":\"table\",\"table\":[\"t\",2]} | same |\n| `insertInto(t, overwrite\u003dTrue)` | sent {\"kind\":\"write_operation\",\"mode\":2,\"save\":\"table\",\"table\":[\"t\",2]} | same |\n| `insertInto(t, overwrite\u003dFalse)` | sent {\"kind\":\"write_operation\",\"mode\":1,\"save\":\"table\",\"table\":[\"t\",2]} | same |\n| `insertInto(5)` | call: TypeError bad argument type for built-in operation | same |\n| `jdbc(url, t)` | sent {\"kind\":\"write_operation\",\"source\":\"jdbc\",\"options\":[[\"dbtable\",\"t\"],[\"url\",\"jdbc:x\"]]} | same |\n| `jdbc(url, t, mode\u003doverwrite, properties)` | sent {\"kind\":\"write_operation\",\"source\":\"jdbc\",\"mode\":2,\"options\":[[\"dbtable\",\"t\"],[\"url\",\"jdbc:x\"], | same |\n| `jdbc(url, t, properties int key)` | call: TypeError keywords must be strings | same |\n| `csv(p, header\u003dTrue)` | sent {\"kind\":\"write_operation\",\"source\":\"csv\",\"save\":\"path\",\"path\":\"p\",\"options\":[[\"header\",\"true\"]] | same |\n| `json(p, mode\u003dbogus)` | call: PySparkValueError [UNSUPPORTED_OPERATION] bogus is not supported. | same |\n| `parquet(p, partitionBy\u003da, compression\u003dsnappy)` | sent {\"kind\":\"write_operation\",\"source\":\"parquet\",\"save\":\"path\",\"path\":\"p\",\"options\":[[\"compression\" | same |\n| `text(p, lineSep\u003dbad)` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `orc(p)` | sent {\"kind\":\"write_operation\",\"source\":\"orc\",\"save\":\"path\",\"path\":\"p\"} | same |\n| `xml(p, rowTag\u003dr)` | sent {\"kind\":\"write_operation\",\"source\":\"xml\",\"save\":\"path\",\"path\":\"p\",\"options\":[[\"rowTag\",\"r\"]]} | same |\n| `v2 create()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":1} | same |\n| `v2 using(delta).create()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"provider\":\"delta\",\"mode\":1} | same |\n| `v2 using(5).create()` | call: TypeError bad argument type for built-in operation | same |\n| `v2 replace()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":5} | same |\n| `v2 createOrReplace()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":6} | same |\n| `v2 append()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":4} | same |\n| `v2 overwrite(col)` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":2,\"condition\":true} | same |\n| `v2 overwrite(str)` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":2,\"condition\":true} | same |\n| `v2 overwrite(5)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `col` should be Column or str, got int. | same |\n| `v2 overwritePartitions()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":3} | same |\n| `v2 option(k, None).append()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":4} | same |\n| `v2 option(k, True).append()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":4,\"options\":[[\"k\",\"true\"]]} | same |\n| `v2 option(5, v).append()` | call: TypeError bad argument type for built-in operation | same |\n| `v2 option(k, bad).append()` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `v2 options(k\u003d1).append()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":4,\"options\":[[\"k\",\"1\"]]} | same |\n| `v2 tableProperty(p, v).create()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":1,\"properties\":[[\"p\",\"v\"]]} | same |\n| `v2 tableProperty(p, None).create()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":1} | same |\n| `v2 tableProperty(5, v).create()` | call: TypeError bad argument type for built-in operation | same |\n| `v2 tableProperty(p, bad).create()` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n| `v2 partitionedBy(col).create()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":1,\"partitioning\":1} | same |\n| `v2 partitionedBy(str, str).create()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":1,\"partitioning\":2} | same |\n| `v2 partitionedBy(5)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `col` should be Column or str, got int. | same |\n| `v2 clusterBy(a, b).create()` | sent {\"kind\":\"write_operation_v2\",\"table\":\"t\",\"mode\":1,\"clustering\":[\"a\",\"b\"]} | same |\n| `v2 clusterBy(5).create()` | call: TypeError bad argument type for built-in operation | same |\n| `v2 writeTo(5).create()` | call: TypeError bad argument type for built-in operation | same |\n| `v2 writeTo(bad).create()` | call: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: surro | same |\n\nThe cases are a test, `test_the_writes_send_what_pysparks_writers_send` (80 cases, run with both clients).\n\n**GC.** `test_a_writer_in_a_cycle_through_a_udf_is_collected` (for `write` and `writeTo`, run with both clients) builds a cycle: a writer, its DataFrame (its `_df` and the `_child` of its `_write`) and the function of a UDF of the plan, which refers to the writer. One collection frees all three, as with PySpark. The gc-shared clone check of `conftest.py` is on for every offline test, including the writer tests, and reports no violation.\n\n**The probes of SPARK-62249 on the new writers** match PySpark 4.3.0:\n- `p_writer_lock_deadlock.py`: no deadlock in all 8 cases (v1-format, v1-mode, v1-option, v2-using, v2-option, v2-property, reader, builder). The other call takes 0.40 s, as with PySpark.\n- `p_compare_calls.py`: the same outcomes as PySpark\u0027s for the reader, stream reader, writer, writer v2 and builder, with every call returning and every option kept. Zero violations.\n\n**The client\u0027s cost of the writes**, in µs per call (best of 5). The setters send nothing, and the saves are on the mock server, whose round trip is the same for every client:\n\n| | Before (native writers) | After (this PR) | PySpark 4.3.0 |\n|---|---|---|---|\n| `df.write` | 1.57 | 3.24 | 2.61 |\n| `df.write.format().mode().option().partitionBy()` | 6.84 | 3.85 | 3.36 |\n| `df.writeTo(t).using().option().tableProperty()` | 10.70 | 3.73 | 2.70 |\n| `df.write.format().mode().option().save(p)` | 942 | 867 | 2186 |\n| `df.writeTo(t).using().create()` | 905 | 863 | 2159 |\n\n`df.write` itself costs more, since it makes PySpark\u0027s `WriteOperation` and callback in Python. The setters and the writes cost less than the native writers did. A write\u0027s client cost stays well under PySpark\u0027s, because the transport is native.\n\n**What remains:**\n- **The `_df` of a writer is the plan object that `df._plan` gave when `write` was read.** The drop-in makes a new one at each read (SPARK-62218).\n- **The rest is the residue of the KD row:** requests go through the native transport, through `client.execute_command`.\n\n**The native option state is removed** (the last commit). The readers (SPARK-62211), these writers and the session builder (SPARK-62215) keep their options in dicts, as PySpark\u0027s, so nothing constructs the native option state any more, which `#![deny(warnings)]` and Clippy reject as dead code. Removed:\n- `UnencodableOptions`, `OptionObject`, `change_options`, and the `SharedObjects` trait with its `_SharedObjects` class, which reported the objects of the options to the garbage collector;\n- `crate::gc::GilMutex`, its guard, its count of the locks held and `check_no_lock_held`, which guarded that state in the check of the clones of the tests;\n- the helpers that only the native readers and writers called: `option_key`, `reader_option_text`, `stream_option_text`, `OptionText::literal` and `reduce::optional_object`;\n- the tests of all of these.\n\n`OptionKey::Object` keeps only the kind of its object, which `plan_entry` reads for the plans of the readers. The check of the clones, `AGENTS.md` and `docs/compatibility.md` no longer describe the removed state. No behavior changes.\n\n### Why are the changes needed?\n\nSo that the writers are PySpark\u0027s, by construction: their `__dict__` and `_write`, setters, errors and their order, commands, copies, pickles and MRO with `OptionUtils`. The native writer state that existed only to emulate PySpark\u0027s dict and `WriteOperation` goes, together with the half of #928 that fixed its races.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. `df.write` and `df.writeTo(table)` are PySpark Connect\u0027s `DataFrameWriter` and `DataFrameWriterV2`, subclasses of `OptionUtils`, and their state is their `__dict__`, with PySpark\u0027s `WriteOperation`/`WriteOperationV2` as `_write`. A pickle of a writer is a plain object of its class.\n\nA deep partitioning column of `writeTo(...).partitionedBy` now fails as it does in PySpark. PySpark\u0027s `WriteOperationV2.command` extends its repeated field with the messages of the partitioning columns, and protobuf copies each one by parsing it, which upb caps at 100 levels. A chain of 48 `+` is sent, and a chain of 49 raises upb\u0027s `DecodeError` (`Exceeded upb_DecodeOptions_MaxDepth`), on both clients, with the call-site origins of a session. Before this change the native writer sent a partitioning column of up to 745 levels. The overwrite condition, which the command copies with `CopyFrom`, is still sent up to 745 levels. `docs/compatibility.md` says so.\n\n### How was this patch tested?\n\n- **`tests/test_dropin_object_state_offline.py`:**\n  - On this branch: 436 passed and 130 xfailed, with the 56 read cases, the 80 write cases and the 2 GC cases.\n  - With PySpark 4.3.0: 566 passed.\n- **The writer, worker and execution-info tests of `tests/test_dropin_offline.py`** (`-k \"write or Write or writer or Writer or saveAsTable or insertInto or jdbc or bucket or partitionBy or worker or execution_info or executionInfo\"`): 119 passed.\n- `test_worker_reconstructors_rebuild_the_readers_writers_and_streams_as_pyspark` is updated: a writer pickles as PySpark\u0027s plain object, and the simulated worker imports PySpark\u0027s DataFrame and client modules, which a real worker has.\n- Two tests of `tests/test_dropin_offline.py` that checked the native writers are updated (8edb33c2):\n  - `test_cycles_are_collected_while_calls_run_that_clone_no_part_of_them`: the collector sees the parts of the DataFrame of an in-flight `writeTo(...).append()`, since PySpark\u0027s writer builds its command of the plan at the call, with the GIL held, and no call clones them. The cycles through other DataFrames are still collected meanwhile.\n  - `test_a_command_expression_too_deep_to_send_raises_recursion_error_as_pyspark`: the overwrite condition at the bound of 745 levels is sent. A partitioning column of 40 additions is sent, and ones of 60 and 744 raise the `DecodeError` above.\n- **`tests/test_type_stubs_offline.py`** (15 passed, 4 skipped) and **`tests/test_dropin_class_modules_offline.py`** (with the docstring golden): pass.\n- **`tests/test_dropin_e2e.py`** against a Spark 4.3.0 server, the write, table, merge and foreachBatch tests (`-k \"write or Write or writer or save or insert or table or merge or jdbc or bucket or foreach\"`): 44 passed. That includes a writer that a foreachBatch function captures, whose callback runs on the server\u0027s Python worker.\n- **The probes above.**\n- **The gates** (at 99cc3e76, on e0f34ac0):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 37 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_connect_docstrings.py --check`, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7553 passed, 121 skipped, 130 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 356 passed.\n\n- **The last commit** (the removal of the native option state), on its tree: the same gates pass, with `cargo test -p pyspark-rs --lib` 32 passed (the removed state\u0027s tests go with it), the offline suite 7571 passed, 121 skipped, 116 xfailed, and `test_dropin_e2e.py` 459 passed (433 passed and 111 skipped without protobuf).\n- **Rebased onto master c3513938** (the merge of #936). The `known-differences.md` and `docs/compatibility.md` hunks are merged with SPARK-62216\u0027s (#943) and SPARK-62211\u0027s. Every other changed line is identical to the commits the gates above ran on. `cargo fmt --check`, clippy 1.100.0 with `-D warnings`, ruff and `gen_type_stubs.py --check` pass on the rebased tree.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #950 from HyukjinKwon/SPARK-62212-writers-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "c3513938352c79797e802306d826afd6c63b6ed0",
      "tree": "573aad45a3eeca9f670803c40962ce00345259c7",
      "parents": [
        "868b718f8d6bc22f2e1e0851460095e7638debff"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 07:29:05 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 07:29:07 2026 +0000"
      },
      "message": "[SPARK-62211][CONNECT][PYTHON] Make DataFrameReader and DataStreamReader PySpark Connect\u0027s classes, adapted from PySpark 4.3.0, whose state is their `__dict__`, over the native plans of their reads\n\n### What changes were proposed in this pull request?\n\nThis is a sub-task of SPARK-62207, after SPARK-62208 (#926) and SPARK-62209 (#929). The sub-tasks close two rows of `dev/parity/known-differences.md`, \"The `__dict__` of the objects of a session\" and \"Subclasses\". This PR covers the readers, `spark.read` and `spark.readStream`.\n\nPySpark\u0027s `DataFrameReader` and `DataStreamReader` are plain Python classes, subclasses of `OptionUtils`. Their state is `_client`, `_format`, `_schema` and `_options`, plus `_source_name` for the stream reader. Their methods read that state and make the plans of the reads. The drop-in\u0027s readers were native classes with the state in Rust: options shared between copies, a GIL-only mutex, and special tracking of values that UTF-8 cannot encode. They emulated PySpark\u0027s behaviour method by method. This PR makes the readers PySpark\u0027s own classes instead.\n\n**Provenance.** `OptionUtils`, `DataFrameReader` and `DataStreamReader` are **adapted** from Apache Spark v4.3.0\u0027s `python/pyspark/sql/connect/readwriter.py` and `python/pyspark/sql/connect/streaming/readwriter.py`. They keep those files\u0027 Apache license header, and the modules carry a header comment that names the source files. They are not verbatim copies, so they are not in the vendored-file registry (`scripts/check_vendored_upstream.sh`), which covers only byte-identical files.\n\nWhat changes from PySpark\u0027s code:\n- The plans of the reads are native: `_DataSource`, `_Read`, `_RelationChanges` and `_Parse` instead of `pyspark.sql.connect.plan`\u0027s classes.\n- `_df` makes the native DataFrame of a plan, from the session of `_client`.\n- ruff modernized the annotations (`Dict` to `dict`) and the import order.\n\nThe rest is PySpark\u0027s code.\n\n**The changes:**\n- **`python/pyspark/sql/connect/readwriter.py` and `streaming/readwriter.py`:** the adapted classes, as described above. The writers and `Trigger` are still imported from the extension.\n- **`crates/pyspark-rs/src/reader_plans.rs` (new):** the native plan constructors and `_read_dataframe`.\n  - Each constructor makes PySpark\u0027s plan assertions when it is called, in the same order and with the same bare `AssertionError`s. For `DataSource` these are: format, schema, the options of non-None values (key and value must be strs), paths, predicates, and source name.\n  - The constructor keeps the arguments in the form the core reader takes.\n  - It also keeps the first error that PySpark\u0027s plan raises when it is sent, in PySpark\u0027s order: a str that UTF-8 cannot encode, or a map entry that protobuf refuses (for example an option of None in `table`/`changes`).\n  - `_read_dataframe(plan, client)` makes the core DataFrame from the session of `client`, as `state::session_of_value` resolves it. That DataFrame fails each request with the plan\u0027s error, if any.\n- **`spark.read` and `spark.readStream`** return `DataFrameReader(self)` and `DataStreamReader(self)`, a new object at each access, as PySpark\u0027s do.\n- **Removed:**\n  - the native `DataFrameReader` and `DataStreamReader` and their state (shared options, unsent format, unencodable schema and options, `__copy__`/`__reduce__`/`__setstate__`/`_of_state`, `__traverse__`/`__clear__`);\n  - the reader option helpers of `options.rs`, `constructor_session` and `with_subclass`;\n  - the reader reduces of `_state_reduce.py`. A reader now pickles as PySpark\u0027s plain object, which a worker without the drop-in loads as PySpark\u0027s class.\n  - In all, about 2900 lines go and 1340 come.\n- **SPARK-62249 (#928):** its reader half is deleted with the native reader state, since it is now dead code. Its writer half stays, because the writers stay native. The option tests of `options.rs` now exercise `change_options` through `writer_entry`.\n- **Stubs:** `OptionUtils` exists at run time now, so it leaves `TYPE_ONLY`. The stubs are regenerated, so they re-export the names that the reader modules import, as PySpark\u0027s do (`AnalysisException`, `to_str`, ...). The classic readers, which the modules import under aliases for their docstrings (`PySparkDataFrameReader`, `PySparkDataStreamReader`), are listed as undeclared.\n- **Docs:** in `dev/parity/known-differences.md`:\n  - The row \"A batch reader\u0027s option of None\" is removed, since that behaviour is PySpark\u0027s now.\n  - The `__dict__` row lists the readers among the objects whose state is their `__dict__`, and states their residue.\n  - The Subclasses row and the `TYPE_ONLY` row are updated.\n  - `docs/compatibility.md` gets the same changes: a paragraph on the adapted readers, the `OptionUtils` MRO, and the option of None.\n\nOf the 419 generic cases of `tests/test_dropin_object_state_offline.py`, the 31 reader cases now pass:\n\n| | Same as PySpark | Differ |\n|---|---|---|\n| Before, master 21a4ffd3 | 184 | 235 |\n| After, this PR | 215 | 204 |\n\nOne case stays: `foreign` of `DataStreamReader`, moved to the DataFrame group (SPARK-62218). PySpark\u0027s DataFrame of a stream reader of a non-session object (`DataStreamReader(1).format(\"rate\").load()`) resolves the session only at a request. The drop-in\u0027s `_df` makes the native DataFrame at once, which needs the session. The batch reader\u0027s `foreign` case passes, because its probe makes a request.\n\n**Error paths of the reads, against PySpark 4.3.0.** The probe makes each call with both clients on the mock server. It records what the call raises, or else what the first request of its DataFrame (`schema`) raises. All 56 cases are the same:\n\n| Case | PySpark 4.3.0 | Drop-in |\n|---|---|---|\n| `format(int).load()` | call: AssertionError | same |\n| `format(bad).load()` | request: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: | same |\n| `format(None).load()` | ok | same |\n| `schema(int)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `schema` should be str or struc | same |\n| `schema(bad).load()` | request: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: | same |\n| `option(int key).load()` | call: AssertionError | same |\n| `option(key, None).load()` | ok | same |\n| `option(key, None).table()` | request: TypeError bad argument type for built-in operation | same |\n| `option(bad key).load()` | request: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: | same |\n| `option(bad value).table()` | request: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: | same |\n| `option(bytes key).table()` | ok | same |\n| `option(bytes key).load()` | call: AssertionError | same |\n| `option(unhashable)` | call: TypeError unhashable type: \u0027list\u0027 | same |\n| `_options[k]\u003d5 load()` | call: AssertionError | same |\n| `_options[k]\u003d5 table()` | request: TypeError bad argument type for built-in operation | same |\n| `_schema\u003d5 load()` | call: AssertionError | same |\n| `load(path list)` | ok | same |\n| `load(path tuple)` | call: AssertionError | same |\n| `load(list of int)` | call: AssertionError | same |\n| `load(bad path)` | request: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: | same |\n| `load(int path)` | call: AssertionError | same |\n| `load(path, schema\u003dint)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `schema` should be str or struc | same |\n| `load(path, k\u003dbad)` | request: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: | same |\n| `json(int)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `path` should be str, list, or  | same |\n| `json(df)` | ok | same |\n| `json(df, schema\u003dddl)` | ok | same |\n| `csv(int)` | call: AssertionError | same |\n| `csv(tuple)` | call: AssertionError | same |\n| `xml(int)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `path` should be str, list, or  | same |\n| `parquet(int)` | call: AssertionError | same |\n| `text(int)` | call: AssertionError | same |\n| `orc(None)` | ok | same |\n| `jdbc(column without bounds)` | call: AssertionError lowerBound can not be None when ``column`` is specified | same |\n| `jdbc(predicates)` | ok | same |\n| `jdbc(predicates tuple)` | call: AssertionError | same |\n| `jdbc(predicates of int)` | call: AssertionError | same |\n| `jdbc(properties int key)` | call: TypeError keywords must be strings | same |\n| `jdbc(url None)` | ok | same |\n| `table(int)` | request: TypeError bad argument type for built-in operation | same |\n| `table(bad)` | request: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: | same |\n| `table(bytes)` | ok | same |\n| `changes(schema)` | call: AnalysisException [_LEGACY_ERROR_TEMP_1189] User specified schema not supporte | same |\n| `stream format(int).load()` | call: AssertionError | same |\n| `stream schema(int)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `schema` should be str or struc | same |\n| `stream option(k, None)` | value: {} | same |\n| `stream option(k, True)` | value: {\u0027k\u0027: \u0027True\u0027} | same |\n| `stream load(int)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `path` must be a non-emp | same |\n| `stream load(\u0027  \u0027)` | call: PySparkValueError [VALUE_NOT_NON_EMPTY_STR] Value for `path` must be a non-emp | same |\n| `stream load(bad)` | request: UnicodeEncodeError \u0027utf-8\u0027 codec can\u0027t encode character \u0027\\udc80\u0027 in position 1: | same |\n| `stream name(int)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `source_name` should be str, go | same |\n| `stream name(\u0027a b\u0027)` | call: PySparkValueError [INVALID_STREAMING_SOURCE_NAME] Invalid streaming source nam | same |\n| `stream json(int)` | call: PySparkTypeError [NOT_EXPECTED_TYPE] Argument `path` should be str, got int. | same |\n| `stream table(int)` | request: TypeError bad argument type for built-in operation | same |\n| `stream option(k, None).table()` | ok | same |\n| `stream changes(schema)` | call: AnalysisException [_LEGACY_ERROR_TEMP_1189] User specified schema not supporte | same |\n| `stream _source_name\u003d5 load()` | call: AssertionError | same |\n\nThe cases are now a test, `test_the_reads_raise_what_pysparks_plans_raise` (56 cases, run with both clients).\n\n**The probes of SPARK-62249**, rerun on this branch, still match PySpark 4.3.0:\n- `p_writer_lock_deadlock.py`: no deadlock in all 8 cases (v1-format, v1-mode, v1-option, v2-using, v2-option, v2-property, reader, builder). The other call takes 0.40 s, as with PySpark.\n- `p_compare_calls.py`: the same outcomes as PySpark\u0027s, with every call returning and every option kept, for the reader, stream reader, writers and builder. Zero violations.\n- `p_options_partial.py`: `options(a\u003d\"1\", b\u003dBad(), c\u003d\"3\")` raises at `b` and keeps `{\"a\": \"1\"}`, for both readers, as PySpark\u0027s.\n\n**Speed of building the plan of a read**, with no request: the best of 5 runs of 20000 calls, in µs per call. The \"before\" column is master af3c5fa0 with the native readers, without #928:\n\n| | Before (native readers) | After (this PR) | PySpark 4.3.0 |\n|---|---|---|---|\n| `spark.read` | 0.53 | 0.46 | 0.36 |\n| `spark.read.format().option().load()` | 5.41 | 3.67 | 4.55 |\n| `spark.read.csv(path, header\u003dTrue)` | 9.97 | 7.52 | 8.65 |\n| `spark.read.table(name)` | 2.48 | 1.86 | 3.05 |\n| `spark.readStream.format().load()` | 4.26 | 2.83 | 5.36 |\n\nThe Python readers are faster than the native ones were. The native readers\u0027 cost was their option machinery (the shared state and the encodability tracking), which the plain dict replaces.\n\n**What remains** is the residue that the KD row states:\n- **The session of a read is resolved when the read makes its DataFrame.** For a reader of a proxy of a session, PySpark\u0027s DataFrame resolves it at a request. This lasts until the DataFrame keeps its session in its `__dict__` (SPARK-62218).\n- **The plan of a read is the core\u0027s, made at the read.** PySpark\u0027s `Read` plan of `table` keeps the reader\u0027s options dict, so a later `option` changes its requests.\n- **The other residue of the row is as before:**\n  - jdbc with predicates: the core\u0027s `jdbc` sets an option of `url`/`dbtable` that is not in `_options` as \"\".\n  - The requests go through the native transport.\n\n### Why are the changes needed?\n\nSo that the readers are PySpark\u0027s, and code that relies on their state behaves the same with the drop-in: their `__dict__`, setters, format methods, errors, copies and pickles, and their MRO with `OptionUtils`. It also deletes the native state that existed only to emulate PySpark\u0027s dict, including the half of #928 that fixed races in that emulation.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. `spark.read` and `spark.readStream` are PySpark Connect\u0027s `DataFrameReader` and `DataStreamReader`, subclasses of `OptionUtils`, and their state is their `__dict__`. Some results change to PySpark\u0027s:\n- `read.option(\"k\", None)` keeps `{\"k\": None}` in `_options`. `load` leaves it out of its plan; `table` and `changes` fail their requests with protobuf\u0027s `TypeError`.\n- A failed read keeps the format that its `load` set.\n- `DataFrameReader(any object)` constructs, and the first use of the object raises PySpark\u0027s `AttributeError`.\n- A pickle of a reader is a plain object of its class.\n\n### How was this patch tested?\n\n- **`tests/test_dropin_object_state_offline.py`:**\n  - On this branch: 275 passed and 204 xfailed. That is 219 + 56 cases, including the 56 read cases.\n  - With PySpark 4.3.0: 479 passed.\n- **The reader, pickle and worker tests of `tests/test_dropin_offline.py`** (`-k \"read or Read or reader or Reader or load or jdbc or table or csv or json or parquet or worker or pickle\"`): 562 passed.\n- Four tests that asserted the native readers\u0027 own semantics are updated to PySpark\u0027s, each checked against PySpark 4.3.0:\n  - `test_reader_setters_mutate_and_return_self`: `options(skipped\u003dNone)` keeps `None`;\n  - `test_reader_reusable_after_failed_read`: a failed `json` keeps the format `json`;\n  - `test_pyspark_pickles_of_readers_catalogs_and_registrations_load_as_pyspark`: the `None` option is kept;\n  - `test_worker_reconstructors_rebuild_the_readers_writers_and_streams_as_pyspark`: a reader pickles as a plain object.\n- `test_a_reader_subclass_pickle_is_of_its_class_on_a_worker_as_pyspark`, a test of the removed reader reduce, is replaced by `test_a_reader_subclass_pickle_is_of_its_class_as_pyspark`.\n- **`tests/test_dropin_class_modules_offline.py`** (with the docstring golden), **`tests/test_type_stubs_offline.py`** (15 passed, 4 skipped) and the reader and stream tests of **`tests/test_dropin_e2e.py`** against a Spark 4.3.0 server (62 passed): all pass.\n- **The probes above.**\n- **The gates** (at 8c93e387):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 37 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_connect_docstrings.py --check`, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7388 passed, 121 skipped, 204 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 354 passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #936 from HyukjinKwon/SPARK-62211-readers-dict.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "868b718f8d6bc22f2e1e0851460095e7638debff",
      "tree": "e6370e21b9d3fcd62e6f6f8b4813e850fb02bbb3",
      "parents": [
        "b6126ae5311ef23cb38842bb1996b60915adec64"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 07:24:22 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 07:24:24 2026 +0000"
      },
      "message": "[SPARK-62258][CONNECT][PYTHON] Convert the local data of createDataFrame under a type subclass that overrides what PySpark\u0027s LocalDataToArrowConversion reads, as PySpark does\n\n### What changes were proposed in this pull request?\n\nA follow-up of SPARK-62236 (#941).\n\nPySpark\u0027s `createDataFrame` of local data converts the rows with `LocalDataToArrowConversion`, which reads, as Python reads them:\n- the struct\u0027s fields (`fields`) and its names (`fieldNames()`);\n- each field\u0027s name, type and nullable flag;\n- the types and flags of the types that they hold (array elements, map keys and values, nested structs).\n\nIt then sends the struct\u0027s `json()` as the relation\u0027s schema. So a property of a Python subclass that overrides one of these is part of both the conversion and the schema, and so is a patch of a native class. For example, under a field whose `dataType` reads `StringType()` over `a long`:\n- PySpark\u0027s `createDataFrame([(1,)], schema)` is `struct\u003ca:string\u003e` of `Row(a\u003d\u00271\u0027)`;\n- the drop-in converted the rows by the native types and sent their JSON, which gave `struct\u003ca:bigint\u003e` of `Row(a\u003d1)`;\n- the drop-in raised `ArrowInvalid` for `[(\"x\",)]`.\n\nSo:\n- **Local data under such a struct converts with PySpark\u0027s conversion** (`create_from_local_of_pyspark`, `src/session.rs`). This covers tuples, lists, dicts, Rows, values that are no rows, and iterators. It applies to a struct that holds, at any level, either:\n  - a type of a Python subclass that overrides an attribute that PySpark\u0027s conversion and its `json()` read;\n  - or a type of a native class patched over one (`types::holds_json_reads_otherwise`).\n\n  It needs PyArrow, which PySpark\u0027s conversion needs. As PySpark\u0027s, it:\n  - takes the rows apart (`local_rows`: dicts of sorted keys, a value that is no row as a row of it);\n  - converts them with `LocalDataToArrowConversion` (`convert_local_rows`), with its errors;\n  - checks the number of fields against the columns (`AXIS_LENGTH_MISMATCH`);\n  - sends the `json()` of the struct (`pyspark_schema_json_text`).\n\n  The integer fast path of native structs no longer takes such a struct.\n- **A NumPy array under such a struct** is checked against the number of fields as Python reads them, and sent with the struct\u0027s `json()`, as PySpark\u0027s.\n- **A struct whose `names` and `fields` may not be what PySpark\u0027s `__init__` assigned** keeps the native conversion (`local_fields_as_assigned`). This is a struct of a class that defines `names` or `fields`, whose reads of them raise an `Exception` or are not as many. The native `__init__` does not assign them through the class\u0027s setters (SPARK-62231), so its rows convert by the native types, of the fields that it was given, as PySpark\u0027s rows are of the fields that its setter kept. The check reads what PySpark\u0027s local conversion reads, `names` and `fields`. It takes no length of names that have none, such as a generator, which PySpark\u0027s `fieldNames()` takes as a list.\n- **`types.rs`** changes only by making `holds_json_reads_otherwise` `pub(crate)`.\n- **Docs:**\n  - The KD row of local data now says that it converts with PySpark\u0027s conversion, and what stays different:\n    - the `names` of dict rows under a field whose `name` is a property (SPARK-62231);\n    - the structs above;\n    - properties over a setter\u0027s state, and class attributes (SPARK-62231, SPARK-62251);\n    - read-only patches;\n    - the rows without PyArrow.\n  - The Subclasses row and `docs/compatibility.md` say that any data under such a struct is sent with its `json()`.\n\nChecked on both clients against a Spark 4.3.0 server. Each probe runs from a neutral directory.\n\n| case | pyspark-client 4.3.0 | before (#941, 8fb307a8) | drop-in now |\n|---|---|---|---|\n| fieldstr_int | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_str | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] | raises ArrowInvalid: Could not convert \u0027x\u0027 with type str: tried to convert to int64 | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_bool | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027true\u0027)] columns\u003d[\u0027a\u0027] | raises ArrowTypeError: Expected integer, got bool | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027true\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_dict | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_row | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_none_row | struct\u003ca:string\u003e rows\u003d[Row(a\u003dNone)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003dNone)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003dNone)] columns\u003d[\u0027a\u0027] |\n| fieldstr_gen | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027), Row(a\u003d\u00272\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027), Row(a\u003d\u00272\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_scalar | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027), Row(a\u003d\u00272\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027), Row(a\u003d\u00272\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_ndarray | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027), Row(a\u003d\u00272\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027), Row(a\u003d\u00272\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_ndarray1d | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027), Row(a\u003d\u00272\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027), Row(a\u003d\u00272\u0027)] columns\u003d[\u0027a\u0027] |\n| fieldstr_wide_row | raises PySparkValueError: [AXIS_LENGTH_MISMATCH] Length mismatch: Expected axis has 1 elements,... | raises PySparkValueError: [AXIS_LENGTH_MISMATCH] Length mismatch: Expected axis has 1 elements,... | raises PySparkValueError: [AXIS_LENGTH_MISMATCH] Length mismatch: Expected axis has 1 elements,... |\n| fieldint_ints | struct\u003ca:int\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] | struct\u003ca:int\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] |\n| fieldint_big | raises ArrowInvalid: Value 1099511627776 too large to fit in C integer type | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1099511627776)] columns\u003d[\u0027a\u0027] | raises ArrowInvalid: Value 1099511627776 too large to fit in C integer type |\n| fieldint_two | struct\u003ca:int,b:bigint\u003e rows\u003d[Row(a\u003d1, b\u003d2)] columns\u003d[\u0027a\u0027, \u0027b\u0027] | struct\u003ca:bigint,b:bigint\u003e rows\u003d[Row(a\u003d1, b\u003d2)] columns\u003d[\u0027a\u0027, \u0027b\u0027] | struct\u003ca:int,b:bigint\u003e rows\u003d[Row(a\u003d1, b\u003d2)] columns\u003d[\u0027a\u0027, \u0027b\u0027] |\n| fieldnotnull_none | raises PySparkValueError: input for LongType() must not be None | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003dNone)] columns\u003d[\u0027a\u0027] | raises PySparkValueError: input for LongType() must not be None |\n| fieldnotnull_value | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] |\n| fieldmeta | {\"fields\":[{\"metadata\":{\"own\":1},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{\"own\":1},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} |\n| fieldname_tuple | struct\u003crenamed:bigint\u003e rows\u003d[Row(renamed\u003d1)] columns\u003d[\u0027renamed\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003crenamed:bigint\u003e rows\u003d[Row(renamed\u003d1)] columns\u003d[\u0027renamed\u0027] |\n| fieldname_dict | struct\u003crenamed:bigint\u003e rows\u003d[Row(renamed\u003d2)] columns\u003d[\u0027renamed\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003crenamed:bigint\u003e rows\u003d[Row(renamed\u003d1)] columns\u003d[\u0027renamed\u0027] |\n| structrevr | schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or field `col_1` is... | struct\u003ca:bigint,b:string\u003e rows\u003d[Row(a\u003d1, b\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027, \u0027b\u0027] | schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or field `col_1` is... |\n| structflds | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] |\n| nested_struct | struct\u003cs:struct\u003ca:string\u003e\u003e rows\u003d[Row(s\u003dRow(a\u003d\u00271\u0027))] columns\u003d[\u0027s\u0027] | struct\u003cs:struct\u003ca:bigint\u003e\u003e rows\u003d[Row(s\u003dRow(a\u003d1))] columns\u003d[\u0027s\u0027] | struct\u003cs:struct\u003ca:string\u003e\u003e rows\u003d[Row(s\u003dRow(a\u003d\u00271\u0027))] columns\u003d[\u0027s\u0027] |\n| array_of_struct | struct\u003cl:array\u003cstruct\u003ca:string\u003e\u003e\u003e rows\u003d[Row(l\u003d[Row(a\u003d\u00271\u0027)])] columns\u003d[\u0027l\u0027] | struct\u003cl:array\u003cstruct\u003ca:bigint\u003e\u003e\u003e rows\u003d[Row(l\u003d[Row(a\u003d1)])] columns\u003d[\u0027l\u0027] | struct\u003cl:array\u003cstruct\u003ca:string\u003e\u003e\u003e rows\u003d[Row(l\u003d[Row(a\u003d\u00271\u0027)])] columns\u003d[\u0027l\u0027] |\n| map_of_struct | struct\u003cm:map\u003cstring,struct\u003ca:string\u003e\u003e\u003e rows\u003d[Row(m\u003d{\u0027k\u0027: Row(a\u003d\u00271\u0027)})] columns\u003d[\u0027m\u0027] | struct\u003cm:map\u003cstring,struct\u003ca:bigint\u003e\u003e\u003e rows\u003d[Row(m\u003d{\u0027k\u0027: Row(a\u003d1)})] columns\u003d[\u0027m\u0027] | struct\u003cm:map\u003cstring,struct\u003ca:string\u003e\u003e\u003e rows\u003d[Row(m\u003d{\u0027k\u0027: Row(a\u003d\u00271\u0027)})] columns\u003d[\u0027m\u0027] |\n| arrstr | schema raises ParseException:  [PARSE_SYNTAX_ERROR] Syntax error at or near \u0027{\u0027. | struct\u003cl:array\u003cbigint\u003e\u003e rows\u003d[Row(l\u003d[1, 2])] columns\u003d[\u0027l\u0027] | schema raises ParseException:  [PARSE_SYNTAX_ERROR] Syntax error at or near \u0027{\u0027. |\n| plain_ints | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1), Row(a\u003d2)] columns\u003d[\u0027a\u0027] |\n| StructGenr_fieldstr_tuple | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] |\n| StructGenr_fieldstr_dict | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] |\n\n- local: 4/26 before, 25/26 now;\n- guard: 2/16 before, 4/16 now;\n\nThe case that still differs:\n- `fieldname_dict` is a dict `{\"a\": 1, \"renamed\": 2}` under a field `a` whose `name` reads `renamed`.\n- PySpark\u0027s `fieldNames()` are the names that PySpark\u0027s `StructType.__init__` read from each field\u0027s `name` property, so it takes `renamed` (`Row(renamed\u003d2)`).\n- The drop-in\u0027s are the names that the native `__init__` was given (`a`), so it gives `Row(renamed\u003d1)`. That is SPARK-62231.\n\nLocal rows under patched native classes now give PySpark\u0027s results too:\n- with `StringType.isUTF8BinaryCollation` patched to return False, `[(\"x\", 1)]` under `a string, b long` raises the server\u0027s `PARSE_SYNTAX_ERROR` of the `json()` with `\"string collate UTF8_BINARY\"`, as PySpark\u0027s; #941 gave the rows;\n- with `StructType.__iter__` patched to reverse the fields, it raises PySpark\u0027s `ArrowInvalid: Could not convert \u0027x\u0027 with type str: tried to convert to int64`; #941 gave the rows of a reversed schema.\n\nThe guard cases are structs whose `names` or `fields` property raises, returns a generator, or reads the state that its setter keeps:\n- `StructGenr` now converts as PySpark\u0027s.\n- The others keep their earlier outcomes.\n- A `names` property that always raises (`StructRais`) converts on the native path, where PySpark\u0027s conversion raises its error. It is documented.\n\nThe probes of SPARK-62236 and SPARK-62221, run again:\n- local rows of `p_rows2` are 7/7 (4/7 before), and `p_reads` is 24/25 (23/25; the one left is `simpleString()`, SPARK-62251);\n- `p_priv` is 11/30 (12/30): `rows_fieldprivtype`, a field whose `dataType` property returns the `self._dt` that its setter writes, now raises its `AttributeError` in PySpark\u0027s conversion, as the pandas conversion and `json()` already do (the SPARK-62231 shape documented in #941);\n- p6_iterated is 6/8 (5/8): `iterated_rows_equal`, local rows under a struct of an iteration of its own, now raises PySpark\u0027s `PARSE_SYNTAX_ERROR` of the `json()` of the subclass, as PySpark\u0027s;\n- the 301 pandas scenarios, p10, p11, p12, p13, p14, p16 and p17 are unchanged.\n\nA benchmark of `createDataFrame` of 10 rows of 2 and of 100 fields against the mock server gives the same times on both builds, about 440 us and 720 us, most of which is the settings request.\n\n### Why are the changes needed?\n\nSo that `createDataFrame` of local data under a type subclass that overrides what PySpark\u0027s conversion reads gives PySpark\u0027s result. This also covers a patch of a native class.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. Local data under such types converts with PySpark\u0027s conversion and is sent with the struct\u0027s `json()`. An int under a field whose `dataType` reads `StringType()` is now its str, where it stayed an int of a bigint column.\n\n### How was this patch tested?\n\n- **New offline test** in `python/tests/test_dropin_offline.py`: `test_create_dataframe_of_local_data_under_a_subclass_converts_it_as_pyspark`. It reads the relation that the mock server receives, for:\n  - tuples, strs, bools, dicts, Rows, `None`, values that are no rows, and iterators;\n  - a NumPy array;\n  - a field that reads `IntegerType()`, and a struct in an array;\n  - PySpark\u0027s errors of a field that reads not nullable, of an int past an int field, and of a row of more values;\n  - the native conversion of a struct of the native classes, of a SPARK-62231 struct, and of local data without PyArrow.\n\n  `test_create_dataframe_of_a_pandas_frame_sends_the_json_of_its_struct_as_pyspark` of #941 now expects local rows to convert with PySpark\u0027s conversion.\n- **New e2e test** in `python/tests/test_dropin_e2e.py`: `test_create_dataframe_of_local_data_under_a_subclass_that_overrides_its_reads`. It runs against a Spark 4.3.0 server, with pyspark-client 4.3.0\u0027s values. It passes on both clients, as do the e2e tests of #941 and `test_create_dataframe_of_a_struct_of_another_width`.\n- **The Rust and Python gates** (`gates.sh build rust py`):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps`;\n  - `cargo test -p pyspark-rs --lib`: 37 passed;\n  - ruff 0.14.0, `test_ruff_excludes.py`, `scripts/audit_no_stubs.sh`, the stub and dispatch generators, the test-list guards and the license checks;\n  - `test_type_stubs_offline.py`: 15 passed, 4 skipped;\n  - the offline suite of `coverage.yml`: 7,308 passed, 121 skipped, 235 xfailed.\n- **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 357 passed.\n- `scripts/check_vendored_upstream.sh` was not run, as no vendored path is touched.\n\n- **Rebased onto master 30d257d0**, after #943 (SPARK-62216), which reads the session of the `_client` of a session at each request. The new path takes that session (`this.get()?`), as the other paths of `createDataFrame` do. That one call is the only changed line that differs from 49a2435c, the commit the gates above ran on. `cargo fmt --check` and clippy 1.100.0 with `-D warnings` pass on the rebased tree.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #946 from HyukjinKwon/SPARK-62258-local-data-subclass-reads.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "b6126ae5311ef23cb38842bb1996b60915adec64",
      "tree": "7d7742a257316c77709328f5ae034c2b6f0da9ba",
      "parents": [
        "30d257d0097a9da78ae8e3f718964db31f1d3623"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 07:07:12 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 07:07:14 2026 +0000"
      },
      "message": "[SPARK-62254][CONNECT][PYTHON] Read the DNS search list and options of the system as c-ares does on macOS (dnsinfo) and Windows (the registry), for a dns://\u003cserver\u003e/ target\n\n### What changes were proposed in this pull request?\n\nA follow-up of SPARK-62232 (#937): the configuration of the system that a lookup through the DNS server of a `dns://\u003cserver\u003e/` target takes on macOS and Windows, which the KD row \"Custom gRPC channels\" listed \"until SPARK-62254\".\n\nc-ares, which gRPC\u0027s resolver asks the DNS server of such a target through, reads the search list and the options of the system of a source of each platform (`ares_sysconfig.c` of c-ares 1.34.5):\n- on macOS, the resolvers of dnsinfo\u0027s configuration, and never `/etc/resolv.conf` (`ares_sysconfig_mac.c`, `read_resolvers`): of each resolver of no domain, reachable and of a name server, its search list, joined of no domain twice, and its options;\n- on Windows, the search list of the registry (`ares_sysconfig_win.c`, `get_SuffixList_Windows`): the `SearchList` and the `Domain` of TCP/IP\u0027s parameters, the `SearchList` of the policies of Windows NT\u0027s DNS client, the `PrimaryDNSSuffix` of those of the system\u0027s, and the `SearchList`, the `Domain` and the `DhcpDomain` of each interface of TCP/IP, joined of `,` and split of `,` and spaces.\n\nThe transport read `/etc/resolv.conf` on every system. So:\n- `dns::system` (every system): the `resolv.conf` of macOS\u0027s resolvers and of Windows\u0027s search list, as c-ares takes them, which `dns::config` reads as it reads that file, of `LOCALDOMAIN` and `RES_OPTIONS` on top, as before.\n- `dns::macos` (macOS): `dns_configuration_copy` and `dns_configuration_free` of libSystem or of SystemConfiguration, of `dlopen`, as c-ares\u0027s `dnsinfo_init`, of dnsinfo.h\u0027s structures packed of 4 bytes, read unaligned, as c-ares reads them of `memcpy`.\n- `dns::windows` (Windows): the registry of windows-sys, each value as c-ares\u0027s `get_REG_SZ` reads it.\n- Of no configuration to read, `/etc/resolv.conf`, as before.\n- The core depends on windows-sys 0.61 on Windows, which the lock had already for tokio and socket2.\n\n### Why are the changes needed?\n\nSo that a single-label name, or one of fewer dots than `ndots`, of a `dns://\u003cserver\u003e/` target is searched in the domains that PySpark\u0027s resolver searches on macOS (with several active network services or a VPN, whose resolvers `/etc/resolv.conf` does not list) and on Windows (whose DNS suffixes are only in the registry).\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, on macOS and Windows only, and of a `dns://\u003cserver\u003e/` target only: its lookup takes the search list and the options of the system\u0027s own configuration, as grpcio does.\n\n### How was this patch tested?\n\n- **The readers cannot run here** (a Linux machine). Each module was compiled alone with `cargo check` and `cargo +1.100.0 clippy -- -D warnings` of `#![deny(warnings)]`: `dns/macos.rs` with libc only for `x86_64-apple-darwin` and `aarch64-apple-darwin`, and `dns/windows.rs` with windows-sys only for `x86_64-pc-windows-gnu` (the crate itself does not compile for those targets here, as ring needs their C toolchains). CI\u0027s macOS wheel build (`wheel-build-checks.yml`, `macos-latest`) compiles the macOS one in the crate.\n- **New Rust tests** of what the readers give, on every system: `dns::system::the_resolvers_of_macos_are_read_as_c_ares_reads_them` (the resolvers that are skipped, the joined search list, the options of each, read as a `resolv.conf`) and `dns::system::the_search_list_of_windows_is_read_as_c_ares_reads_it`.\n- `scripts/gen_native_binary_licenses.py` re-records the hash of `Cargo.lock`; `LICENSE-binary` and `NOTICE-binary` are unchanged.\n- **`cargo test -p apache-spark-connect -p apache-spark-connect-core --release`**: 1,940 passed, 0 failed, 18 ignored, over 121 test binaries.\n- **The Rust and Python gates** (`gates.sh build rust py`), all passing: `cargo fmt --all --check`; clippy 1.100.0 of `-D warnings`; `cargo doc` of `-D warnings`; `cargo test -p pyspark-rs --lib`, 37 passed; ruff 0.14.0, `test_ruff_excludes.py`, `scripts/audit_no_stubs.sh`, the stub and dispatch generators, the test-list guards and the license checks; `test_type_stubs_offline.py`, 15 passed, 4 skipped; the offline suite of `coverage.yml`, 7,301 passed, 121 skipped, 235 xfailed.\n- **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 354 passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #945 from HyukjinKwon/SPARK-62254-platform-dns-config.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "30d257d0097a9da78ae8e3f718964db31f1d3623",
      "tree": "25bd0afb64626086650c70de567e21f436e740d7",
      "parents": [
        "50c3aa98230d44daddeffd4fe410596ab0e9e6c2"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 06:17:08 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 06:17:11 2026 +0000"
      },
      "message": "[SPARK-62216][CONNECT][PYTHON] Keep the state of the SparkSession of Spark Connect in its `__dict__` as PySpark\u0027s, with its cached catalog, streams and version, and raise PySpark\u0027s errors of a session whose `__init__` never ran\n\n### What changes were proposed in this pull request?\n\nThis is the ninth sub-task of SPARK-62207, which closes the rows \"The `__dict__` of the objects of a session\" and \"Subclasses\" of `dev/parity/known-differences.md`. It covers the `SparkSession` of `pyspark.sql.connect.session` and is stacked on #932 (SPARK-62215, the builder).\n\nIn PySpark the session is a plain Python class:\n- `__init__(connection, userId\u003dNone, hook_factories\u003dNone)` sets `self._client \u003d SparkConnectClient(...)`, `self._session_id \u003d self._client._session_id` and `self.release_session_on_close \u003d True`. `newSession()` and `cloneSession()` set the same three on the session that they make.\n- `streams` keeps `StreamingQueryManager(self)` as `self._sqm`, unless `hasattr(self, \"_sqm\")`.\n- `catalog` (`Catalog(self)`) and `version` (`self._client._analyze(method\u003d\"spark_version\").spark_version`) are `functools.cached_property`s.\n- The methods read `self._client`, or `self.client` (the property of `_client`), at the call:\n  - `sql`, `createDataFrame`, `interruptAll`, `interruptTag` and `interruptOperation`, the tags, `addArtifacts`, the progress handlers, `profile`, `_parse_ddl`, `_to_ddl`, `newSession` and `cloneSession`;\n  - `conf`, which is `RuntimeConf(self.client)`;\n  - `is_stopped`, which is `self.client.is_closed`;\n  - `stop`, which also reads `release_session_on_close`;\n  - `client`, which is `self._client`.\n- `session_id` and `__reduce__` read `self._session_id`.\n- The objects of the session (the catalog, the table-valued functions, the streams and a query) read `session.client` at each request.\n\nIn the drop-in, the session held its state natively:\n- `vars(spark)` was empty.\n- `_client`, `session_id` and `release_session_on_close` were getters of the native object.\n- The catalog and the stream manager were cached in native cells, and `version` in a native getter.\n- An assignment of `_client` or `_session_id` had no effect.\n- A session whose `__init__` never ran was a session of no server: its requests raised `NO_ACTIVE_SESSION` and its `is_stopped` was True, where PySpark\u0027s raise `AttributeError: \u0027...\u0027 object has no attribute \u0027_client\u0027`.\n\nThe object-state test file of SPARK-62208 compares the session with goldens captured from PySpark 4.3.0:\n\n| | Passed | Strict xfails |\n|---|---|---|\n| Before, #932 at 027a6c04 | 261 | 169 |\n| After, this PR | 272 | 163 |\n\nThis PR fixes 6 generic cases: the session\u0027s `vars`, `attributes`, `construct` and `uninit` cases, including those of \"SparkSession of streams and catalog\". They are deleted from `_DIFFERS_BY_CHANGE`, along with the group \"the session and its builder\", which is now empty. The other 5 passing tests are new (below).\n\n**The changes:**\n- `crates/pyspark-rs/src/session.rs`:\n  - The native object holds its core session and `own_client`, the `SparkConnectClient` that it set as its `_client`. `__traverse__` and `__clear__` handle that reference, after a `GcReady` check.\n  - `init_state` sets `_client`, `_session_id` and `release_session_on_close` in the `__dict__`, in PySpark\u0027s order, through `state::assign`. It runs in `__init__` (once the hook factories made their hooks) and in `session_object`, which makes the objects of the builder, `newSession()`, `cloneSession()` and the clients.\n  - The methods read `_client`, or `client` where PySpark\u0027s read that, at the call (`PySparkSession::of_client`, `of_client_named`):\n    - The own client is the fast path, of the native session at once.\n    - Another `SparkConnectClient` of the drop-in, such as the client of another session, is of its session (`SessionOfClient::Other`).\n    - A client of another class raises the `TypeError` of `state::foreign_client_error`, as the objects of SPARK-62208 do.\n  - Every method of PySpark\u0027s list above now reads it, after the checks of its arguments, as PySpark\u0027s does. `createDataFrame` reads it at its first request (`LazyClientSession`): of a DDL schema, which `schema_spec` and `pyspark_checked_schema` parse, or of its settings. Data of no rows and of no type raises `CANNOT_INFER_EMPTY_SCHEMA` before the settings are read. `newSession` and `cloneSession` make the new session of the session of that client.\n  - `table` calls `self.read.table(name)`, `emptyDataFrame` calls `self.createDataFrame([], schema)`, and `__exit__` calls `self.stop()`, of a subclass too.\n  - `streams` keeps its manager as `_sqm` and reads it back.\n  - The builder\u0027s `_apply_options` sets the options through `session.client`.\n  - Removed: the `streams` and `catalog` cells and the `release_session_on_close` flag of the native object, the native `catalog` and `version` getters, the `_client` getter, and `PyCatalog::of_session` (`catalog.rs`).\n- `crates/pyspark-rs/src/state.rs`: `session_of_value` reads the `client` of a session of the drop-in too, so the catalog, the table-valued functions, the streams and a query make their requests of the client of their session at the call. The own client is again of the native session at once.\n- `crates/pyspark-rs/src/datasource.rs`: `register` reads `self.sparkSession._client` of a session of the drop-in too.\n- `python/pyspark/sql/connect/session.py`: `catalog` and `version` are `functools.cached_property`s of PySpark\u0027s functions, with the docstrings of the classic session\u0027s.\n- `python/pyspark/sql/connect/client/core.py`:\n  - `_client_of(session, session_id\u003dNone)` takes the ID of a session object that is being made.\n  - `_set_client_state` updates the state of the clients of a session in place. So the client that the session makes at once has the state that `SparkSession(connection, userId)`, `newSession()` and `SparkConnectClient(...)` set after it.\n  - `SparkConnectException` is imported when it is first used (the module\u0027s `__getattr__`, as for the names of the retries). Its module imports `grpc.StatusCode`. A session now makes its client, and imports this module, as it is made: so a session and its queries import no grpc, as before.\n- `python/tests/_mock_connect_server.py`: the server answers `AnalyzePlanRequest.spark_version`, with `\"4.3.0\"` or the `spark_version` that a test sets.\n- **Docs:**\n  - `dev/parity/known-differences.md`:\n    - The `__dict__` row lists the session\u0027s state, and says that the requests of the session and of its objects are of the client of the session.\n    - The Subclasses row lists the session among the objects of `__dict__` state, and leaves the readers alone of the session of no server.\n    - The row \"The exit of a dropped session in a reference cycle\" names the `catalog` and `_sqm` of the `__dict__` (decision 1: the cycles are PySpark\u0027s).\n  - `docs/compatibility.md`: a paragraph on the state of the session, the readers\u0027 paragraph without the session, and the same names in the note on the exit.\n\nWhat still differs, as the rows now say:\n- **Inherent:** the requests are made by the native transport of the client of the drop-in. A client of another class raises a `TypeError`, where PySpark\u0027s calls the methods of that client. Its `conf` calls the client\u0027s `config` and `is_stopped` reads its `is_closed`, as PySpark\u0027s do.\n- **Until SPARK-62218 (the DataFrame):** the DataFrames of `range`, `sql` and `createDataFrame` hold, natively, the session of the client at the call. PySpark\u0027s DataFrame reads the client of its session at each request. So `range(1)` and `createDataFrame([], schema)` of a session whose `__init__` never ran raise the `AttributeError` of `_client` at once, where PySpark\u0027s raise it at the first request of the DataFrame.\n- **Until SPARK-62211 (the readers):** `spark.read` and `spark.readStream` are of the native session, so they are not of a replaced `_client`, and `session::constructor_session` and the session of no server stay, for them. The session still has the session of no server as its native value until its `__init__` runs. Only `read` and `readStream` use it, whose readers are of it, as before; every other method reads `_client` first.\n- **Import:** a session imports `pyspark.sql.connect.proto` as it is made, through its client, as PySpark\u0027s core does (about 27 ms, once per process). So `test_responses_take_upbs_limit_of_set_allow_oversize_protos` no longer has a case of a session of no runtime: it checks that the runtime is imported with the session.\n\n### Why are the changes needed?\n\nIn PySpark, code that reads or writes the state of a session works because the state is in its `__dict__`. Examples: `vars(spark)`, `spark._client` and `spark._session_id`, `spark.release_session_on_close \u003d False` (which PySpark\u0027s tests set to skip the release), a client assigned for a test, `del spark.catalog`, and a subclass whose `__init__` does not call the class\u0027s. Until now none of these worked in the drop-in.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes. The `SparkSession` of `pyspark.sql.connect.session` keeps its state in its `__dict__`, as PySpark\u0027s does:\n- `vars(spark)` is `{\u0027_client\u0027: ..., \u0027_session_id\u0027: ..., \u0027release_session_on_close\u0027: True}`, and then `_sqm`, `catalog` and `version` in the order that they are read;\n- `catalog` and `version` are `functools.cached_property`s: `version` asks the server once, and `del spark.catalog` makes a new catalog at the next access;\n- the session makes its requests of the client that its `__dict__` holds at the call;\n- a session whose `__init__` never ran raises PySpark\u0027s `AttributeError` of `_client`;\n- reading `spark.client` takes 0.11 µs, where it took 4.35 µs, and making a session about 26 µs more, for its client (of the mock server, 50 sessions).\n\n### How was this patch tested?\n\n- **`tests/test_dropin_object_state_offline.py`:** the group \"the session and its builder\" is deleted from `_DIFFERS_BY_CHANGE`. On this branch: 272 passed and 163 xfailed. With PySpark 4.3.0: 435 passed. Five new tests cover what this PR adds, and pass with both clients:\n  - a session reads its client and its session ID of its `__dict__`: `client`, `session_id`, the pickle of an assigned `_session_id`, and `stop` with `release_session_on_close`;\n  - the catalog, the streams and the version are in its `__dict__`: `functools.cached_property`s, one `spark_version` request, assignments and `del`;\n  - a session makes its requests of its client at the call: of the client of another session that is assigned, `sql`, `range`, `createDataFrame`, `interruptAll`, `version`, the catalog and `conf` are of that session, and `is_stopped` of that client; then of its own again;\n  - a session whose catalog or streams was read is freed at a collection, and one of neither, or of `client` or `version` only, is freed when it is dropped;\n  - the methods of a session whose `__init__` never ran check their arguments first, then raise the `AttributeError` of `_client` at their first request (`_session_id` of `session_id` and of a pickle): 29 calls, from `createDataFrame` to `__exit__`.\n- **`tests/test_dropin_offline.py`:**\n  - The `version` of `test_property_not_method` is a `cached_property`.\n  - The session whose `__init__` never ran in `test_sessions_catalogs_and_registrations_subclass_as_pyspark` raises PySpark\u0027s `AttributeError` of `_client` for `is_stopped`, a request, `sql`, `version`, its catalog, `newSession` and `stop`.\n  - `test_responses_take_upbs_limit_of_set_allow_oversize_protos` no longer has its case of no runtime (above).\n  - A new test of a client of another class: its requests raise the `TypeError`, and its `conf` and `is_stopped` read it.\n  - `test_a_session_and_its_queries_import_no_grpc_unless_a_log_needs_it` passes unchanged.\n- **`tests/test_exit_cleanup_offline.py`:** passes unchanged. It runs the exit of a new session dropped after its catalog or its streams was read, before and after a collection, of the cycles that the session\u0027s `__dict__` now holds (decision 1).\n- **`tests/test_dropin_e2e.py`:** a new live test, `test_a_session_keeps_its_state_in_its_dict_and_requests_of_its_client_as_pysparks`. Against a Spark 4.3.0 server:\n  - the session\u0027s `__dict__` holds `_client`, `_session_id`, `release_session_on_close`, `version`, `catalog` and `_sqm`;\n  - with the client of a new session assigned, its `sql`, its catalog and its `conf` see the temporary view and the conf of that session, and with its own client back, its own.\n\n  It passes with both clients.\n- **The gates:**\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps -p apache-spark-connect -p apache-spark-connect-core`;\n  - `cargo test -p pyspark-rs --lib`: 37 passed;\n  - ruff 0.14.0, the no-stub audit, `gen_type_stubs.py --check`, `gen_fn_dispatch.py --check`, the license checks, the guards, and `test_type_stubs_offline.py` (15 passed, 4 skipped);\n  - the offline suite of `coverage.yml`: 7390 passed, 121 skipped, 163 xfailed;\n  - `test_dropin_e2e.py` against a Spark 4.3.0 server: 358 passed.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #943 from HyukjinKwon/SPARK-62216-object-state-session.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "50c3aa98230d44daddeffd4fe410596ab0e9e6c2",
      "tree": "1c10feee0caa884c9f41379f5e3292bcfc61e67c",
      "parents": [
        "4378074d8baba4238375259121f62bf98f9064be"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 06:16:06 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 06:16:08 2026 +0000"
      },
      "message": "[SPARK-62230][CONNECT][PYTHON] Keep the metadata of a StructField that is not a dict, as PySpark\u0027s, and send json.dumps of it in plans\n\n### What changes were proposed in this pull request?\n\nPySpark\u0027s `StructField` keeps any metadata it is given (`metadata or {}`), such as a list, a str or an int:\n- its `jsonValue()`, `json()`, `toNullable()`, copies and pickles keep the object;\n- its plans send `json.dumps` of it when it has a length (`len(field.metadata) \u003e 0`), and the server refuses it.\n\nThe drop-in\u0027s field refused metadata that is not a dict when it was made, with `TypeError: \u0027list\u0027 object is not an instance of \u0027dict\u0027`. And the plans of a struct whose element had such metadata raised a `ValueError` on the client. It follows SPARK-62228, and closes the F8 finding of SPARK-62219\u0027s review.\n\n- **The core.** `Metadata` gets a hidden form for a JSON value that is not an object, made by `Metadata::from_json_value`. It has no keys and is not empty. `json()`, the JSON of a type and the plans write it as it is.\n- **The field.**\n  - `StructField`, its `metadata` setter and `StructType.add` take metadata of any value, as PySpark\u0027s do; false metadata gives a new dict.\n  - The setter now reads its snapshot before it borrows the field, as SPARK-62253\u0027s setters do.\n- **The plans.**\n  - They send the metadata when it has a length, as PySpark\u0027s do, and raise the `TypeError` of the length of a value that has none (`object of type \u0027int\u0027 has no len()`).\n  - The `jsonValue()` of a field of collated strings raises PySpark\u0027s `TypeError` for metadata that is not a mapping (`\u0027list\u0027 object is not a mapping`).\n- **Pickles.** A field whose metadata is not a dict pickles of its `__dict__`. That keeps false metadata that was set after the field was made.\n- **Docs.** The KD row \"The metadata of an element of the fields of a struct that is not a JSON object\" is removed, and the compatibility text describes such metadata.\n\n### Why are the changes needed?\n\nTo match PySpark\u0027s behaviour:\n- a field of a list or a str as its metadata is made, written, copied and pickled;\n- its plans send what PySpark\u0027s send, and fail at the server as PySpark\u0027s do.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes:\n- `StructField` takes metadata that is not a dict;\n- the plans of such metadata send it, or raise PySpark\u0027s error of it.\n\n### How was this patch tested?\n\n**New offline tests** (8 cases), which also pass on pyspark-client 4.3.0:\n- `test_fields_keep_metadata_that_is_not_a_dict_as_pysparks`, of a list, a str, a tuple, nested values, a str of JSON, an int and an object;\n- `test_fields_of_false_metadata_make_a_dict_and_keep_one_that_is_set_as_pysparks`.\n\n**A core unit test:** `from_json_value_keeps_metadata_that_is_not_an_object_as_pyspark_sends_it`.\n\n**A probe against pyspark-client 4.3.0** on a Spark 4.3.0 server: 532/532 outcomes match, where SPARK-62228 has 42/545.\n- It covers 14 kinds of metadata: a list, a str, a tuple, a set, an int, a float, `True`, an object, false values, nested values, a str of JSON and a dict.\n- Its uses include the constructor, `jsonValue()`, `json()`, `\u003d\u003d`, `toNullable()`, copies, pickles, the setter, `add` and `fromJson`.\n- The requests include a cast, `to`, a UDF, `createDataFrame`, `from_json` and `mapInPandas`.\n\n**SPARK-62219\u0027s review probe**, of a duck element of list metadata and three other element kinds: 295/296. The miss differs only in a Spark stage number.\n\n**Gates** at e91a2eb6, on SPARK-62228 and master 86b802c3, all passing:\n- fmt, clippy 1.100.0 and doc, and the `pyspark-rs` lib tests (32 passed);\n- ruff, the stub, dispatch and license generators, and the guards;\n- the type stubs test (15 passed, 4 skipped);\n- the offline suite of `coverage.yml`: 7,309 passed, 121 skipped, 235 xfailed;\n- `test_dropin_e2e.py` against a Spark 4.3.0 server: 354 passed;\n- the core\u0027s metadata tests: 32 passed.\n\nThe first run, at f117bdba, failed clippy (`len_zero`) in the new core test. e91a2eb6 changes only that assertion.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #942 from HyukjinKwon/SPARK-62230-field-metadata.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "4378074d8baba4238375259121f62bf98f9064be",
      "tree": "ea15e389a26da873dc8559a67f610d500bbd97c1",
      "parents": [
        "1d3ee99c12cac0cedb737db653b60907754bf86b"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 06:14:04 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 06:14:07 2026 +0000"
      },
      "message": "[SPARK-62236][CONNECT][PYTHON] Write the schema of createDataFrame of a pandas DataFrame, and the json() of a StructType, of a subclass that overrides the reads of its fields as PySpark\u0027s json() reads them\n\n### What changes were proposed in this pull request?\n\nA follow-up of SPARK-62221 (#923, finding N1 of its second review round) and of SPARK-62237 (#933).\n\nPySpark\u0027s `createDataFrame` of a pandas DataFrame sends the struct\u0027s `json()` as the relation\u0027s schema. PySpark\u0027s `jsonValue` reads the attributes of the types as Python reads them:\n- of a struct, its fields as it iterates itself (`for f in self`, which is `iter(self.fields)`);\n- of a field, its `name`, `dataType`, `nullable` and `metadata`;\n- of an array and a map, their types and flags;\n- of a string, `isUTF8BinaryCollation()` and `collation`, through `simpleString()`.\n\nSo a property of a Python subclass that overrides one of these is part of the JSON. So is an iteration of the subclass\u0027s own, and so is a patch of a native class. PySpark\u0027s conversion of the frame reads them the same way.\n\nSince #923 and #933, the drop-in converts such a frame with PySpark\u0027s conversion, so its table follows the override. The relation\u0027s schema, however, was still written from the native types, and the drop-in\u0027s own `json()` read none of these attributes. For example, a field whose `dataType` reads `StringType()` over `a long`, with a column of strs:\n- PySpark\u0027s DataFrame is `struct\u003ca:string\u003e`;\n- the drop-in\u0027s `df.schema` raised the server\u0027s `INVALID_COLUMN_OR_FIELD_DATA_TYPE`.\n\nSo:\n- **`json()` and `jsonValue()` read the attributes as PySpark\u0027s do** (`src/types.rs`):\n  - `json_reads` lists the native classes and the attributes that PySpark\u0027s `jsonValue` reads.\n  - These objects are written by PySpark\u0027s algorithm of their class, reading through Python, at any depth:\n    - an object of a Python subclass that overrides one of those attributes;\n    - any type while a native class is patched over one of them (`native_attribute`, `json_reads_patched`). A patch is found by comparing each of these attributes with the one that the module kept when it was made (`keep_native_json_reads`), by identity, so the check costs well under a microsecond.\n  - The algorithm is `ForeignFields::json_value_of_native`, which SPARK-62219 (#927) added for structs of foreign elements. The types that the object holds are written by their own `jsonValue`.\n  - A patched native `__iter__` or `jsonValue` is read, as a subclass\u0027s is (`reads_own`). The `json()` of a struct, an array, a map or a field calls a patched `jsonValue`.\n  - A patched `StringType.isUTF8BinaryCollation` or `collation` is read by `repr()`, `simpleString()` and `jsonValue()`, as PySpark\u0027s are. For example, `\"string collate UTF8_BINARY\"`, with the `__COLLATIONS` metadata of its field.\n  - Some structs read their fields otherwise than PySpark\u0027s `__init__` assigned them, because the native `__init__` does not assign through the class\u0027s setters (SPARK-62231). These are structs of a class that defines `names` or `fields`, whose `fields`, as Python reads them:\n    - raise an `Exception`, such as the `AttributeError` of the attribute that the setter sets;\n    - or are not as many as their `names`.\n\n    The JSON of such a struct is made of the fields that its native `__init__` was given (`fields_as_assigned`), as PySpark\u0027s is made of the fields that its `__init__` assigned. This is the same evidence as the guard of SPARK-62221\u0027s R3-1, which sends a pandas frame under such a struct to the native row path.\n- **The relation\u0027s schema of PySpark\u0027s conversion, and of no rows, is PySpark\u0027s `json()`** (`pyspark_schema_json_text`). It covers:\n  - the tables of PySpark\u0027s conversion of a pandas DataFrame (`create_from_pandas_table`, `create_from_pandas_arrow`);\n  - the pandas fast paths that send their tables through the importer;\n  - a pyarrow Table, which is cast to the struct by PySpark\u0027s `to_arrow_schema`;\n  - data of no rows: an empty pandas frame and `raw_schema_json`.\n- **The relations of rows that the native types convert stay of those types** (`schema_json_text`, `of_native_values`). These are local rows and the native pandas row path (the SPARK-62231 structs above, and no PyArrow), so their schema stays that of their rows. A thread-local mode makes the JSON of the native values there, also through the Python `json()` of a subclass. Converting local rows by PySpark\u0027s reads, and sending their `json()`, is SPARK-62258.\n- **Docs:**\n  - `dev/parity/known-differences.md`:\n    - the pandas row of customized and patched types says that the relation is PySpark\u0027s `json()`;\n    - it says what the patches and the SPARK-62231 structs now give;\n    - it says what stays different until SPARK-62231 and SPARK-62251: a field property whose getter reads the state that its setter writes reads it unwritten, and a class attribute over a field\u0027s attribute is read;\n    - a new row covers local data, until SPARK-62258;\n    - the Subclasses row covers what `createDataFrame` sends, and `simpleString()`, `repr()` and `treeString()` of property overrides, until SPARK-62251.\n  - `docs/compatibility.md` (types of subclasses), `docs/architecture.md`, and the docstrings of the shim (`_canonical_struct`, `accepts_pandas_schema`).\n\nChecked on both clients against a Spark 4.3.0 server. Each probe runs from a neutral directory. Before is master 5151494b, built from its tree.\n\n| case | pyspark-client 4.3.0 | before (master 5151494b) | drop-in now |\n|---|---|---|---|\n| json_struct_fieldstr | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"string\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"string\"}],\"type\":\"struct\"} |\n| jsonValue_struct_fieldstr | {\"fields\": [{\"metadata\": {}, \"name\": \"a\", \"nullable\": true, \"type\": \"string\"}], \"type\": \"struct\"} | {\"fields\": [{\"metadata\": {}, \"name\": \"a\", \"nullable\": true, \"type\": \"long\"}], \"type\": \"struct\"} | {\"fields\": [{\"metadata\": {}, \"name\": \"a\", \"nullable\": true, \"type\": \"string\"}], \"type\": \"struct\"} |\n| json_fieldstr | {\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"string\"} | {\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"} | {\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"string\"} |\n| jsonValue_fieldstr | {\"metadata\": {}, \"name\": \"a\", \"nullable\": true, \"type\": \"string\"} | {\"metadata\": {}, \"name\": \"a\", \"nullable\": true, \"type\": \"long\"} | {\"metadata\": {}, \"name\": \"a\", \"nullable\": true, \"type\": \"string\"} |\n| json_struct_fieldint_meta | {\"fields\":[{\"metadata\":{\"k\":1},\"name\":\"a\",\"nullable\":true,\"type\":\"integer\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{\"k\":1},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{\"k\":1},\"name\":\"a\",\"nullable\":true,\"type\":\"integer\"}],\"type\":\"struct\"} |\n| json_structrevr | {\"fields\":[{\"metadata\":{},\"name\":\"b\",\"nullable\":true,\"type\":\"string\"},{\"metadata\":{},\"name\":\"a\",\"nul... | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"},{\"metadata\":{},\"name\":\"b\",\"nulla... | {\"fields\":[{\"metadata\":{},\"name\":\"b\",\"nullable\":true,\"type\":\"string\"},{\"metadata\":{},\"name\":\"a\",\"nul... |\n| json_array_of_struct | {\"containsNull\":true,\"elementType\":{\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"stri... | {\"containsNull\":true,\"elementType\":{\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long... | {\"containsNull\":true,\"elementType\":{\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"stri... |\n| json_map_of_struct | {\"keyType\":\"string\",\"type\":\"map\",\"valueContainsNull\":true,\"valueType\":{\"fields\":[{\"metadata\":{},\"nam... | {\"keyType\":\"string\",\"type\":\"map\",\"valueContainsNull\":true,\"valueType\":{\"fields\":[{\"metadata\":{},\"nam... | {\"keyType\":\"string\",\"type\":\"map\",\"valueContainsNull\":true,\"valueType\":{\"fields\":[{\"metadata\":{},\"nam... |\n| json_nested_struct | {\"fields\":[{\"metadata\":{},\"name\":\"s\",\"nullable\":true,\"type\":{\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nu... | {\"fields\":[{\"metadata\":{},\"name\":\"s\",\"nullable\":true,\"type\":{\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nu... | {\"fields\":[{\"metadata\":{},\"name\":\"s\",\"nullable\":true,\"type\":{\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nu... |\n| json_fieldnotnull | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":false,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":false,\"type\":\"long\"}],\"type\":\"struct\"} |\n| json_fieldmeta | {\"fields\":[{\"metadata\":{\"own\":1},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{\"own\":1},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} |\n| json_fieldownjson | {\"fields\":[{\"metadata\":{},\"name\":\"own\",\"nullable\":true,\"type\":\"string\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"own\",\"nullable\":true,\"type\":\"string\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"own\",\"nullable\":true,\"type\":\"string\"}],\"type\":\"struct\"} |\n| json_structflds | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} |\n| simpleString_struct_fieldstr | struct\u003ca:string\u003e | struct\u003ca:bigint\u003e | struct\u003ca:bigint\u003e |\n| pandas_fieldstr_strings | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] | schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or field `col_0` is of t... | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] |\n| pandas_fieldstr_strings_wider | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] | schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or field `col_0` is of t... | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] |\n| pandas_fieldstr_meta | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] | schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or field `col_0` is of t... | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] |\n| pandas_fieldint_ints | struct\u003ca:int\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:int\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] |\n| pandas_structrevr | schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or field `col_1` is of t... | struct\u003ca:bigint,b:string\u003e rows\u003d[Row(a\u003d1, b\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027, \u0027b\u0027] | schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or field `col_1` is of t... |\n| pandas_fieldnotnull_nullable | [False] | [True] | [False] |\n| pandas_fieldmeta_metadata | [{\u0027own\u0027: 1}] | [{}] | [{\u0027own\u0027: 1}] |\n| pandas_fieldownjson | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] |\n| rows_fieldstr | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] | raises ArrowInvalid: Could not convert \u0027x\u0027 with type str: tried to convert to int64 | raises ArrowInvalid: Could not convert \u0027x\u0027 with type str: tried to convert to int64 |\n| empty_fieldstr | struct\u003ca:string\u003e rows\u003d[] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[] columns\u003d[\u0027a\u0027] | struct\u003ca:string\u003e rows\u003d[] columns\u003d[\u0027a\u0027] |\n| arrow_fieldstr | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] | schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or field `col_0` is of t... | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u0027x\u0027)] columns\u003d[\u0027a\u0027] |\n| rows_fieldstr_ints | struct\u003ca:string\u003e rows\u003d[Row(a\u003d\u00271\u0027)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] |\n| rows_fieldint_ints | struct\u003ca:int\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] |\n| rows_fieldint_ints_meta | struct\u003ca:int\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] |\n| rows_structflds | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] |\n| empty_structflds | struct\u003ca:bigint\u003e rows\u003d[] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[] columns\u003d[\u0027a\u0027] |\n| pandas_structflds | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] | struct\u003ca:bigint\u003e rows\u003d[Row(a\u003d1)] columns\u003d[\u0027a\u0027] |\n| json_structflds | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} |\n| json_fieldclassnullable | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"struct\"} | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":false,\"type\":\"long\"}],\"type\":\"struct\"} |\n| json_structprivfields | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"structprivfi\"} | raises AttributeError: \u0027StructPrivFields\u0027 object has no attribute \u0027_fields\u0027 | {\"fields\":[{\"metadata\":{},\"name\":\"a\",\"nullable\":true,\"type\":\"long\"}],\"type\":\"structprivfi\"} |\n| pandas_empty_structprivfields | schema raises ParseException:  [PARSE_SYNTAX_ERROR] Syntax error at or near \u0027{\u0027. | raises AttributeError: \u0027StructPrivFields\u0027 object has no attribute \u0027_fields\u0027 | schema raises ParseException:  [PARSE_SYNTAX_ERROR] Syntax error at or near \u0027{\u0027. |\n| empty_structprivfields | schema raises ParseException:  [PARSE_SYNTAX_ERROR] Syntax error at or near \u0027{\u0027. | raises AttributeError: \u0027StructPrivFields\u0027 object has no attribute \u0027_fields\u0027 | schema raises ParseException:  [PARSE_SYNTAX_ERROR] Syntax error at or near \u0027{\u0027. |\n\n- the json() and pandas probe: 3/25 before, 23/25 now;\n- the setter-backed struct and local rows probe: 4/7 before, 4/7 now;\n- the SPARK-62231/62251 shapes probe (only its changed cases are listed above): 10/30 before, 12/30 now;\n\nWhat stays different:\n- `simpleString()` is SPARK-62251, and the local rows (`rows_*`) are SPARK-62258.\n- `json_fieldclassnullable` is a SPARK-62251 shape: a class attribute `nullable \u003d False`, which PySpark\u0027s `__init__` shadows with the instance\u0027s own and the native one does not. The drop-in\u0027s `json()` now reads it as Python reads it in the drop-in, as the pandas conversion already did. It is documented exactly.\n- A field property over the `self._dt` that its setter writes (`json_fieldprivtype`) raises the `AttributeError` of `_dt`, before and now, as the native `__init__` does not call the setter (SPARK-62231). It is documented exactly too.\n- The other `priv` cases are unchanged. Their differences come from the plain-subclass `typeName` JSON and from SPARK-62231.\n\nThe probes of the SPARK-62221 reviews, run again on master and now:\n- p11_overrides: 6/12 and 10/12;\n- p12_override_json: 0/4 and 4/4;\n- p6_iterated: 3/8 and 5/8 (`iterated_*` now raise PySpark\u0027s `PARSE_SYNTAX_ERROR` of the subclass\u0027s `typeName`);\n- p16_iter_options 7/7, p10_index_ts 3/3, p13_patched 5/11, p14_rebound 11/11 and p17_names 17/43 are unchanged.\n\nThe 301 scenarios of the pandas fast paths and descriptors give 233/301, against 231/301 on master. The two that changed are the patched `StringType.isUTF8BinaryCollation`.\n\n`test_create_dataframe_of_a_struct_of_another_width` of `test_dropin_e2e.py` asserted the server\u0027s `ASSIGNMENT_ARITY_MISMATCH` for a struct of an iteration of its own (`Iterated`) whose `fields` or `names` list was changed in place. PySpark\u0027s relation of it is its `json()`, whose type is the subclass\u0027s `typeName()` (`iter`), and the server fails to parse that first (`PARSE_SYNTAX_ERROR`). The drop-in now sends that `json()` too, and the test asserts PySpark\u0027s error. pyspark-client 4.3.0 gives `PARSE_SYNTAX_ERROR` for all four changes of `Iterated`, which master did not.\n\n`json()` costs what it did: about 15 us for a struct of two fields, as on master. It checks the native attributes that it reads against those the module kept when it was made, by identity (`keep_native_json_reads`).\n\n### Why are the changes needed?\n\nSo that `createDataFrame` of a pandas DataFrame or a pyarrow Table, and `json()`, give PySpark\u0027s results under a type subclass that overrides what PySpark\u0027s `jsonValue` reads. This also covers a patch of a native class.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes.\n- `json()` and `jsonValue()` of such subclasses, and of patched native classes, are PySpark\u0027s.\n- `createDataFrame` of a pandas DataFrame, a pyarrow Table or data of no rows under them sends PySpark\u0027s `json()` of the struct as the relation\u0027s schema. A field whose `dataType` reads `StringType()` over `a long` is now `struct\u003ca:string\u003e`, where it raised `INVALID_COLUMN_OR_FIELD_DATA_TYPE`.\n\n### How was this patch tested?\n\n- **New offline tests** in `python/tests/test_dropin_types_columns_offline.py`:\n  - `test_python_subclasses_that_override_the_reads_of_json_write_it_as_pysparks`: properties of `dataType`, `nullable` and `metadata`, an iteration of its own, nested arrays, maps and structs, and the SPARK-62231 structs whose `fields` property reads none or raises;\n  - `test_patched_native_type_classes_are_of_their_json_as_pysparks`: a patched `isUTF8BinaryCollation` (`json()`, `repr()`, `simpleString()`, an array) and a patched `StructType.__iter__`.\n\n  The same assertions print the same on pyspark-client 4.3.0.\n- **New offline test** in `python/tests/test_dropin_offline.py`: `test_create_dataframe_of_a_pandas_frame_sends_the_json_of_its_struct_as_pyspark`. It reads the relation that the mock server receives, for:\n  - a pandas frame, of rows and of no rows, a pyarrow Table and an empty list under a field that reads `StringType()`;\n  - a SPARK-62231 struct, of rows and of no rows;\n  - local rows, and the row path without PyArrow, which keep the native types.\n- **New e2e test** in `python/tests/test_dropin_e2e.py`: `test_create_dataframe_of_a_pandas_frame_under_a_subclass_that_overrides_its_reads`. It checks the schemas and the rows of a field that reads `StringType()` (also of no rows), one that reads `IntegerType()` with metadata, and the SPARK-62231 struct (also of no rows). It also checks the server\u0027s `INVALID_COLUMN_OR_FIELD_DATA_TYPE` of a struct that iterates its fields in reverse. Its expected values are pyspark-client 4.3.0\u0027s against the same server. `test_create_dataframe_of_a_struct_of_another_width` now expects PySpark\u0027s `PARSE_SYNTAX_ERROR` of `Iterated` (see above).\n- **`python/tests/test_arrow_handoff.py`**: the known differences of the patched descriptors now expect the relation to follow the patch (`_relation_of`), and the known difference of the patched `isUTF8BinaryCollation` is removed.\n- **The Rust and Python gates** (`gates.sh build rust py`):\n  - `cargo fmt --all --check`;\n  - `cargo +1.100.0 clippy -p apache-spark-connect-core -p apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;\n  - `RUSTDOCFLAGS\u003d\"-D warnings\" cargo doc --no-deps`;\n  - `cargo test -p pyspark-rs --lib`: 37 passed;\n  - ruff 0.14.0, `test_ruff_excludes.py`, `scripts/audit_no_stubs.sh`, the stub and dispatch generators, the test-list guards and the license checks;\n  - `test_type_stubs_offline.py`: 15 passed, 4 skipped;\n  - the offline suite of `coverage.yml`: 7,307 passed, 121 skipped, 235 xfailed.\n- **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 356 passed.\n- `scripts/check_vendored_upstream.sh` was not run, as no vendored path is touched.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #941 from HyukjinKwon/SPARK-62236-subclass-schema-reads.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    },
    {
      "commit": "1d3ee99c12cac0cedb737db653b60907754bf86b",
      "tree": "dea0a4e36839e68e5566eb9daff8760aa839ee9b",
      "parents": [
        "521d1846a5e74f493c9fb7c2f433a1dc3de3a038"
      ],
      "author": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 06:09:27 2026 +0000"
      },
      "committer": {
        "name": "Hyukjin Kwon",
        "email": "hyukjin.kwon@databricks.com",
        "time": "Mon Nov 23 06:09:31 2026 +0000"
      },
      "message": "[SPARK-62234][CONNECT][PYTHON] Resolve the name of the target of each new channel of its own before its first call, as each channel of grpcio does\n\n### What changes were proposed in this pull request?\n\nA follow-up of SPARK-62233 (#940): that a new session of a target that the process is connected to resolved no name, which the KD row \"Custom gRPC channels\" listed \"until SPARK-62234\".\n\nEach grpcio channel has a resolver of its own, which resolves its name before its first call, and shares the subchannels of gRPC\u0027s global pool with the other channels of the process: so each PySpark client, of a new session or of a clone too, resolves the name of its target again, and fails its calls of the error of its own resolution, which it tries again a backoff after its end. The transport shares the connection of a target between the clients of the process, as that pool, but resolved the name only as the shared connection connected, so a new session of a target that the process was connected to asked no DNS server, and worked while the name did not resolve.\n\n- `connector::ChannelResolution`: the resolution of a client\u0027s own channel, in the dialect of grpcio, before its first call: a lookup of its own (`Target::resolve_for_a_new_channel`), whatever another channel resolved before, of whose addresses the connections of the target take then (SPARK-62233\u0027s 30 s); of a failure, the calls of the channel fail of its error at once until a backoff after its end. A Rust client resolves the name as it connects, as tonic\u0027s channel does.\n- Each `ChannelLease` (a client\u0027s channel of a generation of the process) has one, which `metadata::Checked` awaits before a call, after the metadata of the call is read, and which the close of the client ends.\n- The KD row no longer lists that a new session does not resolve. It lists, until SPARK-62257 (a pool of the connections by resolved address, of each channel\u0027s own resolution and `pick_first`, as gRPC\u0027s subchannel pool), that the channels that share a connection resolve again once between them as it fails, where each grpcio channel resolves it again, and that a new channel takes the connection of the process whatever addresses its own resolution gives, where grpcio\u0027s connects to those addresses.\n\nChecked on both clients against a Spark 4.3.0 server, of a program of four sessions of one target (a session, its `newSession()`, its `cloneSession()`, and another session of the same URL or builder), each running `range(2).count()`:\n\n| | pyspark-client 4.3.0 | before (#940) | now |\n|---|---|---|---|\n| queries that the DNS responder got, of `dns://127.0.0.1:18753/a4.probe.test:17841` (3 of each resolution) | 12 | 3 | 12 |\n| connections to the server (a counting relay), of `sc://127.0.0.1:18650` | 1 | 1 | 1 |\n| connections to the server, of `sc://localhost:18650/;token\u003dt` | 4 | 4 | 4 |\n\nThe connections are the same as grpcio\u0027s: its channels share the subchannels of its global pool, of the same address and arguments, so the four sessions of a target share one connection, and those of a token, whose channels have call credentials of their own, one each; the transport\u0027s pool of the channels of the process gives the same.\n\n### Why are the changes needed?\n\nSo that a new session asks the DNS server, or the system\u0027s resolver, as PySpark\u0027s does, and fails of a name that no longer resolves, as PySpark\u0027s does, rather than working of the connection of another session.\n\n### Does this PR introduce _any_ user-facing change?\n\nYes, in the dialect of grpcio (the Python client): the first call of each new session resolves the name of its target, and fails of `UNAVAILABLE` (`errors resolving ...`) of a name that does not resolve, as PySpark\u0027s does, where it used the connection of another session of the process.\n\n### How was this patch tested?\n\n- **New Rust test** `connector::each_new_channel_resolves_its_name_of_its_own_before_its_first_call`: each channel of a connector asks the DNS server once, a connection of the target within 30 s asks nothing, a new channel asks again, and a failure fails the calls of the channel at once until its backoff; a Rust client resolves nothing before its calls.\n- **Probes of both clients**: the table above (`p_dns_sessions2.py`, `p_conn_count.py`).\n- **`cargo test -p apache-spark-connect -p apache-spark-connect-core --release`**: 1,938 passed, 0 failed, 18 ignored, over 121 test binaries.\n- **The Rust and Python gates** (`gates.sh build rust py`), all passing: `cargo fmt --all --check`; clippy 1.100.0 of `-D warnings`; `cargo doc` of `-D warnings`; `cargo test -p pyspark-rs --lib`, 37 passed; ruff 0.14.0, `test_ruff_excludes.py`, `scripts/audit_no_stubs.sh`, the stub and dispatch generators, the test-list guards and the license checks; `test_type_stubs_offline.py`, 15 passed, 4 skipped; the offline suite of `coverage.yml`, 7,301 passed, 121 skipped, 235 xfailed.\n- **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 354 passed.\n- No dependency changes.\n\n### Was this patch authored or co-authored using generative AI tooling?\n\nGenerated-by: Claude Opus 5.5\n\nThis pull request and its description were written by Isaac.\n\nCloses #944 from HyukjinKwon/SPARK-62234-resolve-per-channel.\n\nAuthored-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nSigned-off-by: Hyukjin Kwon \u003chyukjin.kwon@databricks.com\u003e\nCo-authored-by: Isaac \u003cno-reply@databricks.com\u003e\n"
    }
  ],
  "next": "521d1846a5e74f493c9fb7c2f433a1dc3de3a038"
}
