HyukjinKwon opened a new pull request, #928:
URL: https://github.com/apache/spark-connect-rust/pull/928
### What changes were proposed in this pull request?
A follow-up of SPARK-62063 (#876), which reports the option keys and values
that are objects to Python's garbage collector, and of SPARK-62235 (#921,
gc-shared), whose rules keep each collection's passes consistent.
The readers, the writers and the session builder keep the options that
PySpark keeps in a dict and that the core does not take: keys that are not
strs, and values that are objects (`UnencodableOptions`). Their shallow copies
share these options, and one Python object reports them for all copies
(`_SharedObjects`, `SharedObjects::visit`). It reports an object only while the
options alone hold it (`Arc::strong_count == 1`), so that a copy of the state
does not count one reference twice. It reads the state with `try_lock()`, so
that a traverse never waits.
CPython's collector traverses each object several times in one collection:
in `subtract_refs`, in `move_unreachable`, and again for its resurrection
checks. A report that differs between those passes can make a live object look
unreachable. Its weak references are then cleared, its finalizer runs, and it
can be cleared under a live holder. A report could differ in two ways: a thread
without the GIL clones an option object between passes, or a thread without the
GIL takes or releases the state's lock between them. An audit found that
neither happens today: every clone and every lock holds the GIL, and the
closures that run without the GIL carry only the core's reader or writer. This
PR makes both impossible by construction, following gc-shared's rules:
- **Option objects are cloned only with the GIL.** An option object is an
`OptionObject` with no `Clone`, only `clone_ref(py)`. `OptionKey` and
`UnencodableOptions` have no `Clone` either, only `clone_ref(py)`. A `Python`
token cannot enter a call without the GIL, so the count that `visit_objects`
reads changes only while no collection runs. A drop without the GIL only lowers
the count, which makes an object reported, and that is safe.
- **The states of options are locked only with the GIL.** They use a new
`crate::gc::GilMutex`, whose `lock` takes a `Python` token. The traverse takes
the lock without waiting, given its `PyVisit`, and `__clear__` takes it with
the GIL. Its guard cannot be moved into a call without the GIL. This covers the
readers' kept options, the session builder's options, the V1 writer's kept
arguments (options, format, mode, and the partitioning, sorting, bucketing and
clustering columns), and the V2 writer's kept options and table properties.
- **No Python code runs under these locks, and no lock is held while the GIL
is released.** A thread that wants a lock waits for it with the GIL held. So:
- **Keys are compared outside the locks.** The kept keys are compared with
their `==`, which is Python code, on a copy of the options. Neither a lock nor
a borrow of the reader is held meanwhile (`change_options`). The copy then
replaces the options, unless another call changed them meanwhile. In that case
the comparisons run again on the options as they are, as a dict looks a key up
again when a comparison changes the dict.
- **Writers convert their arguments first.** They convert their format,
mode and columns, which is Python code, before they take the lock. They drop
the values that they replace after it is released, as a drop can run a
finalizer.
- **Reduces make Python objects from a copy of the options**, outside the
lock.
- **The test-time check of gc-shared covers the locks.** While a thread
holds a `GilMutex`, it logs any release of the GIL by the binding
(`crate::gc::detach*`), the Python code of options (`==` and the making of
their Python objects), and a lock found already held. The violations go through
`_take_part_clone_violations`, so the `conftest.py` hook of the offline suite
fails such a test.
- **Docs:** `AGENTS.md` states the rule for the states of options.
**Real hazards found by the audit, and fixed** (probes in
`p_writer_lock_deadlock.py` and `p_compare_calls.py`, on master bdf82090 and on
PySpark 4.3.0):
- **A deadlock of the V1 and V2 writers.** Their `option` and
`tableProperty` compared the kept keys while holding the lock of the kept
arguments and the lock of the writer's state. A key whose `__eq__` releases the
GIL, such as one that sleeps or does I/O (and any Python function may, at the
interpreter's switch interval), let another thread's call of the same writer,
or of a shallow copy, block on those locks with the GIL held. The first thread
then never got the GIL back. A comparison that set an option of the same writer
again deadlocked on its own lock.
| case: another thread's call while a kept key's `__eq__` sleeps |
pyspark-client 4.3.0 | master | now |
|---|---|---|---|
| `df.write`: `format("parquet")` | returns, 0.40 s | deadlock | returns,
0.40 s |
| `df.write`: `mode("overwrite")` | returns, 0.40 s | deadlock | returns,
0.40 s |
| `df.write`: `option("k", "v")` | returns, 0.40 s | deadlock | returns,
0.40 s |
| `df.writeTo("t")`: `using("parquet")` | returns, 0.40 s | deadlock |
returns, 0.40 s |
| `df.writeTo("t")`: `option("k", "v")` | returns, 0.40 s | deadlock |
returns, 0.40 s |
| `df.writeTo("t")`: `tableProperty("p", "q")` | returns, 0.40 s |
deadlock | returns, 0.40 s |
(0.40 s is the time until the sleeping comparison returns. The other call
itself returns at once.)
- **"RuntimeError: Already borrowed" from the readers.**
`DataFrameReader.option` and `DataStreamReader.option` compared the kept keys
while holding a mutable borrow of the reader. So another thread's call of the
same reader raised `RuntimeError: Already borrowed` during a comparison that
released the GIL. A comparison that set an option of the same reader again
failed inside `__eq__`, where the error was swallowed, and that option was
lost. Now `option` and `options` convert, compare and set with no borrow held.
Like PySpark's `options`, they set each option in turn, so a value whose
`str()` raises keeps the options before it, where master kept none
(`spark.read.options(a="1", b=Bad())`: PySpark and now `{'a': '1'}`, master
`{}`).
`p_compare_calls.py` (27 cases: another thread's call during a comparison,
and a comparison that sets an object key or a str key of the same object again,
on both readers, both writers and the builder; each must return with no error
and keep every option):
| | pyspark-client 4.3.0 | master | now |
|---|---|---|---|
| `spark.read`, `spark.readStream` (10) | 10/10 | 2/10: 6 `RuntimeError:
Already borrowed`, 2 options lost | 10/10 |
| `df.write`, `df.writeTo("t")` (16) | 16/16 | deadlock at the first case
| 16/16 |
| `SparkSession.builder` (1) | 1/1 | 1/1 | 1/1 |
**Nothing else changes in what is collected.** `p_collected_shapes.py` gives
the same 75 results on master and with this PR, and PySpark gives them too. It
covers reference cycles through the keys and values of options:
- of the 13 holder shapes, alone and with a shallow copy;
- after a reduce, and after a failed read or write;
- with a copy that stays and then goes;
- with a key replaced by an equal one.
### Why are the changes needed?
To make the reports of option objects to Python's garbage collector
consistent across a collection's passes by construction, as gc-shared made
those of the parts of plans and expressions. Also to fix the deadlock of the
writers, and the readers' `Already borrowed` and lost options, which PySpark's
dicts do not have.
### Does this PR introduce _any_ user-facing change?
Yes, in the cases above:
- A writer's call no longer deadlocks while another thread compares an
option key whose `__eq__` releases the GIL.
- A reader's call no longer raises `RuntimeError: Already borrowed` in that
case.
- An option that a key's `__eq__` sets on the same object is kept.
- A reader's `options(**kw)` keeps the options before one whose value fails
to convert.
What the garbage collector frees is unchanged.
### How was this patch tested?
- **New offline tests** in `python/tests/test_dropin_offline.py`:
-
`test_option_keys_compared_as_python_code_stop_no_call_and_lose_no_option_as_pyspark`:
the 27 cases of `p_compare_calls.py`, with PySpark's outcome as the
expectation. It runs in a process of its own, which a deadlock would hang, with
the check of the clones on.
-
`test_collections_while_option_keys_are_compared_free_and_clear_nothing_kept_as_pyspark`:
a collection that runs inside a key's comparison frees and clears nothing that
the options keep. The holders are in reference cycles, and some have shallow
copies. Once the holders go, every cycle is collected.
-
`test_holders_of_option_objects_are_used_on_threads_as_the_collector_runs`, a
stress test modelled on gc-shared's:
- three threads set object keys and values in reference cycles, copy the
holders, set options on other threads' holders, reduce them and fail their
reads and writes;
- another thread runs requests without the GIL, and another one the
collector;
- no key that a live holder keeps is freed or cleared, and every cycle
is collected at the end.
- The three tests above also pass with PySpark 4.3.0 run as the reference.
The subprocess test's code was run on PySpark as a script, as its `-c`
subprocess needs a SPARK_HOME for PySpark in this environment, as the existing
subprocess tests do.
- **New Rust tests:**
-
`gc::tests::the_check_logs_a_release_of_the_gil_and_python_code_while_a_gil_mutex_is_held`;
-
`gc::tests::a_gil_mutex_found_held_is_logged_and_waited_for_with_the_gil_released`;
-
`options::tests::the_objects_of_options_are_reported_while_the_options_of_a_state_alone_hold_them`;
-
`options::tests::keys_are_compared_with_no_lock_held_and_again_once_the_options_changed`;
-
`options::tests::a_key_that_is_a_str_is_set_with_no_comparison_of_python_code`.
- **Probes** of master bdf82090, this PR and PySpark 4.3.0: the tables above.
- **The Rust and Python gates** (`gates.sh build rust py`): see the results
that follow.
- **`test_dropin_e2e.py`** against a Spark 4.3.0 server (`-k "read or write
or option"`): see the results that follow.
### 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]