HyukjinKwon opened a new pull request, #924:
URL: https://github.com/apache/spark-connect-rust/pull/924

   ### What changes were proposed in this pull request?
   
   A type can hold itself:
   - a struct whose `fields` hold a field of it 
(`s.fields.append(StructField("b", s))`, or `s.add("b", s)`);
   - an array or a map set to be its own element or value (`a.elementType = a`);
   - a field set to the type of the struct that holds it.
   
   No walk of its levels ends. PySpark's methods walk the levels in Python, so 
each use that reads them raises `RecursionError`, and the others work.
   
   The drop-in's native walks grow their stacks per level (`pbmsg::grow`, since 
SPARK-62130), so they recursed until the memory for the stacks ran out 
(`PanicException: mmap failed to allocate stack`). Some overflowed the stack 
and ended the process (`treeString`, and the constructors of types that hold 
one). The setters that make such a type panicked (`Already mutably borrowed`).
   
   - **A bound on every walk of the type objects.** Each walk counts its levels 
in a thread-local (`type_level`) and raises `RecursionError` past Python's 
recursion limit (`Py_GetRecursionLimit`), as PySpark's walks do with at least 
one Python frame per level. This covers the lowering, the JSON, `==`, the 
simple string, `needConversion`, `toNullable`, the flag and subclass checks, 
and the foreign fields of SPARK-62189. A type of more levels than the limit 
raises it too, and a higher limit takes it.
   - **Constructors and setters.** A type whose lowering raises 
`RecursionError` stands as the null type for the constructors and setters that 
keep it (`lenient_type`), as a type that does not lower now does, so they make 
it as PySpark's do. The walk of the types that stand for a type is bounded too 
(`stand_in_type`). The setters lower the new type before they borrow the type 
that they set, and drop the type that they replace after.
   - **`==`, the foreign fields and pickles.**
     - `==` of the same object is true without a walk, as Python's comparison 
of PySpark's `__dict__`s is.
     - The memo of the foreign fields marks the objects that it is looking at, 
so a type that holds itself adds nothing to its answer.
     - A struct, an array, a map or a field-as-type of more levels than the 
limit pickles and copies as its class and PySpark's `__dict__` of it. Pickle 
and copy keep the object before its children, so the copies hold themselves, as 
PySpark's do.
   - **`treeString`.** It reads such a type to the levels that the string 
holds, as PySpark's walk of the objects does: `treeString(2)` prints two levels 
(`tree_stand_in`). It raises `RecursionError` for more levels than the limit.
   - **A cast and `DataFrame.to`.** They return their Column and DataFrame, as 
PySpark's do, and their repr and requests raise the `RecursionError`. 
`PlanArgs::raised` takes it, and the cast's repr is unrenderable with the error 
of `simpleString()`.
   - **`spark.udf.register`** converts the return type before it pickles the 
function, as PySpark's `PythonUDF.to_plan` does. A type past the limit now 
raises its `RecursionError`, not cloudpickle's `PicklingError`.
   - **Construction cost.** The lowering of a field builds the core field from 
its name and flag, without copying its snapshot of the type. Making a type of 
many levels one level at a time is now quadratic in the levels, not cubic: 
1,000 nested structs took 102 s, and now take 0.7 s.
   - **Docs.**
     - `docs/compatibility.md` says what each use of such a type does.
     - The KD row of deep types gives the new levels of the `RecursionError`.
     - A new KD row covers the text of the error, which is inherent (below).
   
   Checked on both clients against a Spark 4.3.0 server, with `s = 
StructType([StructField("a", LongType())]); s.fields.append(StructField("b", 
s))`. Each use runs in a process of its own under a 4 GiB cap:
   
   | use | pyspark-client 4.3.0 | before (5516cbf3) | now |
   |---|---|---|---|
   | json | RecursionError | PanicException: mmap failed to allocate stack | 
RecursionError |
   | jsonValue | RecursionError | PanicException: mmap failed to allocate stack 
| RecursionError |
   | simpleString | RecursionError | RecursionError | RecursionError |
   | repr | RecursionError | RecursionError | RecursionError |
   | treeString | RecursionError | PanicException: mmap failed to allocate 
stack | RecursionError |
   | `==` of another struct | False | False | False |
   | `==` of itself | True | PanicException: mmap failed to allocate stack | 
True |
   | hash | RecursionError | RecursionError | RecursionError |
   | needConversion | True | True | True |
   | toInternal | tuple | tuple | tuple |
   | fromInternal | Row | Row | Row |
   | pickle | 250 bytes | 263 bytes | 263 bytes |
   | deepcopy | StructType | StructType | StructType |
   | copy | StructType | StructType | StructType |
   | fieldNames | ['a', 'b'] | ['a', 'b'] | ['a', 'b'] |
   | add | StructType | StructType | StructType |
   | `s["b"]` | b | b | b |
   | toNullable | RecursionError | PanicException: mmap failed to allocate 
stack | RecursionError |
   | `StructField("x", s).simpleString()` | RecursionError | PanicException: 
mmap failed to allocate stack | RecursionError |
   | `ArrayType(s).simpleString()` | RecursionError | PanicException: mmap 
failed to allocate stack | RecursionError |
   | createDataFrame, no rows | RecursionError | PanicException: mmap failed to 
allocate stack | RecursionError |
   | createDataFrame, rows | RecursionError | PanicException: mmap failed to 
allocate stack | RecursionError |
   | createDataFrame, pyarrow | RecursionError | RecursionError | 
RecursionError |
   | createDataFrame, pandas | RecursionError | PanicException: mmap failed to 
allocate stack | RecursionError |
   | `spark.range(1).to(s)` | DataFrame | PanicException: mmap failed to 
allocate stack | DataFrame |
   | `F.col("x").cast(s)` | Column | PanicException: mmap failed to allocate 
stack | Column |
   | from_json | RecursionError | PanicException: mmap failed to allocate stack 
| RecursionError |
   | read.schema | RecursionError | PanicException: mmap failed to allocate 
stack | RecursionError |
   | udf | RecursionError | RecursionError | RecursionError |
   
   28 of 29 match PySpark now; 14 did before. The pickle of a struct is 13 
bytes longer than PySpark's, as it was before; it loads the same in both 
clients.
   
   A wider probe (`p_62224_more.py`) covers 62 uses of 8 forms: the struct 
above, `add`, an array, a map, a field, two structs that hold each other, a 
struct that also holds a `UserDefinedType` whose `module()` is not implemented, 
and 3,000 nested arrays. The uses add, to the above:
   - `treeString(1)` and `treeString(2)`;
   - the constructors of `StructField`, `ArrayType`, `MapType` and 
`StructType`, and the setters;
   - try_cast, astype, the repr, the select and the collect of a cast;
   - the schema, the columns and the collect of `to`;
   - udtf, mapInPandas, mapInArrow, applyInPandas, cogroup.applyInPandas, 
pandas_udf, udf.register, readStream.schema and catalog.createTable.
   
   Every outcome matches PySpark's: 496 of 496, against 296 after the bound 
alone and many crashes before. 355 of 496 match in their text; the rest differ 
only in the suffix of the `RecursionError` message (below).
   
   The levels at which a type of many levels that does not hold itself raises 
`RecursionError`, on the main thread of Python 3.11 (`p_62224_depth.py`):
   
   | nested | operation | pyspark-client 4.3.0 | drop-in now |
   |---|---|---|---|
   | structs | `==` | 143 | 500 |
   | structs | hash, repr | 166 | 498 |
   | structs | json, jsonValue | 249 | 331 |
   | structs | simpleString | 250 | 997 |
   | structs | treeString | 332 | 500 |
   | structs | toNullable | 992 | 999 |
   | structs | pickle | 125 | 500 |
   | structs | unpickle, deepcopy | 125, 100 | 248 |
   | structs | needConversion, StructField(t) | never | never |
   | arrays | `==` | 333 | 999 |
   | arrays | hash, repr | 497 | 996 |
   | arrays | json, simpleString, needConversion | 992 to 997 | 993 to 999 |
   | arrays | treeString | 497 | 998 |
   | arrays | pickle | 332 | 1000 |
   | arrays | unpickle, deepcopy | 332, 249 | 497, 496 |
   
   Before this change, `==`, pickling, simpleString and treeString took 600 
nested structs and more, without a bound.
   
   The bound costs one access to a thread-local per level. The limit is read 
only past 32 levels. Ordinary types, in microseconds, as the minimum of 4 
interleaved rounds against master's types (46b2dc93's build, whose types are 
master's), of the review's `p_bench.py` of SPARK-62219:
   
   | path | master | now | now/master |
   |---|---|---|---|
   | json, 1,000 fields | 3,764.6 | 3,731.9 | 0.99 |
   | simpleString, 1,000 fields | 290.3 | 298.3 | 1.03 |
   | treeString, 1,000 fields | 593.0 | 639.4 | 1.08 |
   | `pyspark_types_to_proto_types`, 1,000 fields | 1,170.0 | 1,150.4 | 0.98 |
   | cast, 1,000 fields | 419.0 | 446.5 | 1.07 |
   | pickle, 1,000 fields | 1,293.9 | 1,367.5 | 1.06 |
   | json, 40 nested levels | 2,010.8 | 1,588.8 | 0.79 |
   | `pyspark_types_to_proto_types`, 40 nested levels | 865.2 | 579.2 | 0.67 |
   | cast, 40 nested levels | 349.4 | 109.8 | 0.31 |
   | json, cast and proto, 8 fields | 39.7, 12.1, 13.1 | 39.5, 12.2, 12.9 | 
0.98 to 1.01 |
   
   The nested types are faster because the lowering no longer copies the 
snapshots of the levels below each field.
   
   **The text of the error is inherent.** The drop-in's message is `maximum 
recursion depth exceeded`, from the bound of the native walk. When a call to 
Python code in the walk crosses the limit first, Python's own check adds its 
suffix (` while calling a Python object`, ` while getting the str of an 
object`). PySpark's message comes from the operation of its Python code that 
crosses the limit: ` in comparison` for `treeString()`, ` in __instancecheck__` 
for `udf()`, and none for `json()`. CPython's check (`_Py_CheckRecursiveCall`) 
adds the `where` of the C call that enters the frame past the limit, and the 
native walks enter no such frame. The new KD row covers this.
   
   ### Why are the changes needed?
   
   A type that holds itself crashed the process, or ran it out of memory, where 
PySpark raises `RecursionError`. The fix bounds the walks as PySpark's Python 
walks are bounded, without giving up the deep types that SPARK-62130 supports 
within the limit.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes:
   - A type that holds itself raises `RecursionError` where PySpark does, and 
works where PySpark does, instead of crashing.
   - A type of more levels than Python's recursion limit raises 
`RecursionError` for the uses that walk it. Before, they took any depth; now 
they take more levels with a higher limit (`sys.setrecursionlimit`).
   - `spark.udf.register` of a return type past the limit raises 
`RecursionError`, not `PicklingError`.
   - Nested types of many levels are much faster to make.
   
   ### How was this patch tested?
   
   - **New offline test** in `python/tests/test_dropin_offline.py`: 
`test_a_type_that_holds_itself_raises_pysparks_recursion_error`. It runs in a 
process of its own under a 4 GiB cap and covers:
     - 13 uses of each of 5 forms of such a type;
     - `treeString` of 1, 2 and 5,000 levels;
     - the cycles that pickle and deepcopy keep;
     - a thread of a 256 KiB stack;
     - 1,500 nested arrays under the default and a higher recursion limit;
     - a cast, `to`, createDataFrame, from_json and udf of such a type, which 
send no request.
   
     It fails on master, at the `Already mutably borrowed` panic of the setter. 
`test_udf_defaults_and_registration`'s stub of `_registerPythonUdf` takes the 
command as a function that pickles it, as the registration now passes it.
   - **Probes of both clients** against a Spark 4.3.0 server: the tables above.
   - **The Rust and Python gates** (`gates.sh build rust py`), all passing:
     - `cargo fmt --all --check`;
     - `cargo +1.100.0 clippy -p apache-spark-connect-core -p 
apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;
     - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps`;
     - `cargo test -p pyspark-rs --lib`: 18 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,055 passed, 114 skipped.
   - **`scripts/check_vendored_upstream.sh`**: every vendored file matches 
Apache Spark v4.3.0.
   - **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 352 passed.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Claude Opus 5.5
   
   This pull request and its description were written by Isaac.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to