HyukjinKwon opened a new pull request, #933:
URL: https://github.com/apache/spark-connect-rust/pull/933
### What changes were proposed in this pull request?
A follow-up of SPARK-62221 (#923). It also covers the findings of
SPARK-62221's third review round (R3-1, R3-2 and R3-3).
SPARK-62221 sent a pandas DataFrame under a struct through PySpark's
conversion (`prepare_pandas_table`) on the row path. It kept the old row path,
which converts by the native types, in two cases:
- frames under patched native classes, such as a `StructField.dataType`
property;
- frames under rebound type names, such as `pyspark.sql.types.BooleanType`
rebound to `LongType`, or a name rebound in `pyspark.sql.pandas.types`.
The independent review measured that PySpark's conversion honours these
patches. Of 21 probes, PySpark raises in 19, and with a public `BooleanType`
rebound over ints it gives `[1, 0, 1]` where the drop-in gave `[1, 0, 2]`. The
KD's reason, "the conversion would read the patch, and the relation's schema
the native type", describes PySpark too, so the difference is not inherent.
So:
- **The converters are bound as PySpark Connect's module of the session
binds them.** `pyspark.sql.connect.session` now imports, when it is imported
with the first session, what PySpark's session module imports:
- `create_arrow_table_from_pandas`;
- `to_arrow_schema`, `_deduplicate_field_names` and `from_arrow_type`;
- the types that the conversion makes: `StructType`, `MapType`,
`StringType`, `TimestampType` and `DayTimeIntervalType`.
`prepare_pandas_table` and `prepare_inferred_pandas_table` call them by
their names there at each call, as PySpark's `createDataFrame` reads its
globals. They do so in PySpark's order:
- `_deduplicate_field_names` is called twice, as PySpark calls it;
- the field types are read before `to_arrow_schema`;
- `schema.fieldNames()` is read before the table is converted, and the
names it gives are the ones `toDF` applies.
The conversion of each column still imports `to_arrow_type` from the
converter module of `sys.modules` when it is called (the vendored
`create_arrow_array_from_pandas`). As a result, a name rebound after the first
session affects exactly what it affects in PySpark. The last mismatch of the
review, from the import timing of `to_arrow_schema`, is closed.
- **Frames under patched classes and rebound names take PySpark's
conversion.**
- `converts_row_path_frames()` is gone. With PyArrow, the row path
converts every frame under a struct with `create_from_pandas_table`.
- `create_from_pandas_inferred` no longer declines a frame without a
schema, or of names, under rebound names.
- The row path converts the frame's rows only:
- without PyArrow;
- for the SPARK-62231 shape below;
- for an empty frame;
- for an atomic schema.
- **The schema check of `createDataFrame`.** PySpark checks its schema with
`isinstance(schema, (AtomicType, StructType))`, against the names of its
session module. It does this for any data, after it parses a DDL string, and
before it reads any setting. The session module now has PySpark's check,
`_check_schema`, which reads those names at each call. The native
`createDataFrame` calls it only when `AtomicType` or `StructType` of that
module is not the native class; its own checks are the same otherwise. With
such a name rebound:
- an `AtomicType` of None raises PySpark's `TypeError: isinstance() arg 2
must be a type, a tuple of types, or a union`;
- a struct that a rebound `StructType` does not take raises
`[NOT_EXPECTED_TYPE] ... got StructType.`;
- a deleted name raises PySpark's `NameError: name 'StructType' is not
defined`.
A DDL string is parsed first, in one request, and the parsed type is then
the schema, as in PySpark.
- **The fast paths decline what PySpark's conversion would read
differently.** `_converter_namespaces_intact` checks:
- the type names and the converters of `pyspark.sql.types` and of the
converter module, including the module's own functions that the conversion
calls by name (`to_arrow_type`, `_create_converter_from_pandas`, ...);
- the session module's bindings, and the modules whose globals those
functions hold;
- the importer.
Every fast path now calls it. The float64 and object-string paths did not
check the converter module before, so a converter-module `BooleanType` rebound
to `DoubleType` took the double fast path, where PySpark makes bools.
- **R3-1 (a regression of SPARK-62221's round 2).**
- `names_as_many_as_fields` compares the counts only for a class that
defines `names` or `fields` itself (`_reads_as(type(schema), StructType,
("names", "fields"))`).
- A struct whose native `fields` or `names` list was changed in place, of
a class that defines neither, takes PySpark's conversion again:
- a field appended, or a name removed, raises `IndexError`;
- a field removed, or a name appended, raises the server's
`ASSIGNMENT_ARITY_MISMATCH`.
- This is the review's prototype.
- **R3-2 and R3-3.**
- The KD clause on this guard now says exactly what it does: the `fields`
setter, `names` that PySpark reads as fewer or more, and the setter case. The
nits are fixed too.
- The doc comments of `create_from_pandas` and `accepts_pandas_schema` are
rewritten.
- **Docs.**
- The KD rows are split. A new row, "pandas DataFrames under customized or
patched types, or rebound type names", covers the parts tracked for a fix:
SPARK-62231, SPARK-62236 and SPARK-62251.
- Another new row, marked intentional, covers the other modules of PySpark
Connect that bind the type names with the session, as decided.
- `docs/compatibility.md`, `docs/architecture.md` and
`dev/design/architecture.md` say how the conversion binds the names.
What still differs, as the KD states:
- **A property with no setter patched over an attribute that PySpark's
`__init__` assigns** (a field's `name`, `dataType`, `nullable` or `metadata`,
or a struct's `fields` or `names`).
- PySpark's `_deduplicate_field_names` raises `AttributeError: property of
'StructField' object has no setter`, because its constructors assign through
the property.
- The native constructors do not (SPARK-62231), and the native types have
no `__dict__` (SPARK-62251). So the drop-in's conversion goes on and reads the
patch where PySpark would.
- **The relation's schema of the native types.** PySpark writes the `json()`
of the struct, which reads the overrides and the patches, such as a patched
`StringType.isUTF8BinaryCollation` (SPARK-62236, the next PR).
- **Intentional:**
- PySpark Connect's client and its parsing of types use the names that
they bound with the session.
- PySpark's types read the names of `pyspark.sql.types` in their methods.
- An `AtomicType` or `StructType` rebound to a class such as `object`
makes PySpark take any object as its schema.
Checked on both clients. The guard scenarios of `test_arrow_handoff.py` were
run on the same mock service:
| case (mock service) | pyspark-client 4.3.0 | before (8ecb3e62) | now |
|---|---|---|---|
| ints, public `BooleanType` rebound to `LongType` | table of renamed: bool
[True, True, True, False] | table of renamed: int64 [9007199254740993,
-9223372036854775808, 9223372 | table of renamed: bool [True, True, True,
False] |
| ints, converter `LongType` rebound to `BooleanType` | raises
PySparkTypeError: [UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION] LongType() is
not supported in conversion to Arrow. | table of renamed: int64
[9007199254740993, -9223372036854775808, 9223372 | raises PySparkTypeError:
[UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION] LongType() is not supported in
conversion to Arrow. |
| ints, public `ByteType` rebound to `LongType` | raises PySparkValueError:
Exception thrown when converting pandas.Series (int64) with name 'renamed' to
Arrow Array (int8). It can be caused by overflows or other unsafe conver... |
table of renamed: int64 [9007199254740993, -9223372036854775808, 9223372 |
raises PySparkValueError: Exception thrown when converting pandas.Series
(int64) with name 'renamed' to Arrow Array (int8). It can be caused by
overflows or other unsafe conver... |
| timestamps, public `BooleanType` rebound to `TimestampType` | raises
ArrowNotImplementedError: Unsupported cast from timestamp[ns] to bool using
function cast_boolean | table of renamed: timestamp[us, tz=UTC]
[datetime.datetime(1970, 1, 1, 0, 0, tzinfo=zone | raises
ArrowNotImplementedError: Unsupported cast from timestamp[ns] to bool using
function cast_boolean |
| timestamps, converter `DateType` rebound to `TimestampType` | table of
renamed: date32[day] [datetime.date(1970, 1, 1), datetime.date(1970, | table
of renamed: timestamp[us, tz=UTC] [datetime.datetime(1970, 1, 1, 0, 0,
tzinfo=zone | table of renamed: date32[day] [datetime.date(1970, 1, 1),
datetime.date(1970, |
| timestamps, public `BinaryType` rebound to `TimestampType` | table of
renamed: binary [b'', b'@B\x0f', None, b'\xc0\xbd\xf0\xff\xff\xf | table of
renamed: timestamp[us, tz=UTC] [datetime.datetime(1970, 1, 1, 0, 0, tzinfo=zone
| table of renamed: binary [b'', b'@B\x0f', None, b'\xc0\xbd\xf0\xff\xff\xf |
| 100,000 doubles, converter `BooleanType` rebound to `DoubleType` | table
of x: bool [True, False, True, True] | table of x: double [1.5, -0.0, inf,
-inf] | table of x: bool [True, False, True, True] |
| 100,000 doubles, public `FloatType` rebound to `DoubleType` | table of x:
float [1.5, -0.0, inf, -inf] | table of x: double [1.5, -0.0, inf, -inf] |
table of x: float [1.5, -0.0, inf, -inf] |
| dates, public `StructField` rebound to `DateType` | raises TypeError:
DataTypeSingleton.__call__() got an unexpected keyword argument 'nullable' |
table of renamed: date32[day] [datetime.date(1, 1, 1), datetime.date(9999, 12,
| raises TypeError: DataTypeSingleton.__call__() got an unexpected keyword
argument 'nullable' |
| dates, public `StructType` rebound to `DateType` | raises
PySparkTypeError: [NOT_EXPECTED_TYPE] Argument `schema` should be list, None or
StructType, got StructType. (before any setting is read) | table of renamed:
date32[day] [datetime.date(1, 1, 1), datetime.date(9999, 12, | raises
PySparkTypeError: [NOT_EXPECTED_TYPE] Argument `schema` should be list, None or
StructType, got StructType. (before any setting is read) |
| Arrow strings, converter `StructType` rebound to `StringType` | raises
AttributeError: 'StringType' object has no attribute 'names' | table of v:
string ['original', None, 'original', None] | raises AttributeError:
'StringType' object has no attribute 'names' |
| ints, public `AtomicType` rebound to None | raises TypeError: isinstance()
arg 2 must be a type, a tuple of types, or a union (before any setting is read)
| table of renamed: int64 [9007199254740993, -9223372036854775808, 9223372 |
raises TypeError: isinstance() arg 2 must be a type, a tuple of types, or a
union (before any setting is read) |
| ints, patched `StructType.__iter__` | raises ValueError: Target schema's
field names are not matching the table's field names: ['renamed'], ['changed']
| table of renamed: int64 [9007199254740993, -9223372036854775808, 9223372 |
raises ValueError: Target schema's field names are not matching the table's
field names: ['renamed'], ['changed'] |
| ints, patched `StructField.dataType` (a property of no setter;
SPARK-62231, SPARK-62251) | raises AttributeError: property of 'StructField'
object has no setter | table of renamed: int64 [9007199254740993,
-9223372036854775808, 9223372 | table of renamed: bool [True, True, True,
False] |
| ints, patched `StructType.fields` (a property of no setter; SPARK-62231,
SPARK-62251) | raises AttributeError: property of 'StructType' object has no
setter | table of renamed: int64 [9007199254740993, -9223372036854775808,
9223372 | table of no column |
| ints, public `StructType` rebound to `object` (intentional: PySpark's
client) | table of renamed: int64 [9007199254740993, -9223372036854775808,
9223372; `_to_table` raises AssertionError | table of renamed: int64
[9007199254740993, -9223372036854775808, 9223372 | table of renamed: int64
[9007199254740993, -9223372036854775808, 9223372 |
Against a Spark 4.3.0 server (the review's p14 and p13, and probes of the
inferred path and of the schema check):
| case (server) | pyspark-client 4.3.0 | before (8ecb3e62) | now |
|---|---|---|---|
| ints [1, 0, 2] under `renamed long`, public `BooleanType` rebound to
`LongType` after the session | struct<renamed:bigint> rows=[Row(renamed=1),
Row(renamed=0), Row(renamed=1)]; columns=['renamed'] | struct<renamed:bigint>
rows=[Row(renamed=1), Row(renamed=0), Row(renamed=2)]; columns=['renamed'] |
struct<renamed:bigint> rows=[Row(renamed=1), Row(renamed=0), Row(renamed=1)];
columns=['renamed'] |
| the same, converter `LongType` rebound to `BooleanType` | raises
PySparkTypeError: [UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION] LongType() is
not supported in conversion to Arrow. | struct<renamed:bigint>
rows=[Row(renamed=1), Row(renamed=0), Row(renamed=2)]; columns=['renamed'] |
raises PySparkTypeError: [UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION]
LongType() is not supported in conversion to Arrow. |
| the same, public `StructType` rebound to `LongType` | raises
AttributeError: 'LongType' object has no attribute 'names' |
struct<renamed:bigint> rows=[Row(renamed=1), Row(renamed=0), Row(renamed=2)];
columns=['renamed'] | raises AttributeError: 'LongType' object has no attribute
'names' |
| aware timestamps, public `BooleanType` rebound to `TimestampType` | raises
ArrowNotImplementedError: Unsupported cast from timestamp[ns] to bool using
function cast_boolean | struct<renamed:timestamp>
rows=[Row(renamed=datetime.datetime(1970, 1, 1, 0, 0)),
Row(renamed=datetime.datetime(1970, 1, 1, 0, 0, 0, 1000)), Row(renamed=None),
Row(rename... | raises ArrowNotImplementedError: Unsupported cast from
timestamp[ns] to bool using function cast_boolean |
| dates, converter `DateType` rebound to `BooleanType` | raises
PySparkTypeError: [UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION] DateType() is
not supported in conversion to Arrow. | struct<renamed:date>
rows=[Row(renamed=datetime.date(2020, 1, 1)), Row(renamed=None)];
columns=['renamed'] | raises PySparkTypeError:
[UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION] DateType() is not supported in
conversion to Arrow. |
| ints, patched `StructType.__iter__` (p13) | raises ValueError: Target
schema's field names are not matching the table's field names: ['renamed'],
['changed'] | struct<renamed:bigint> rows=[Row(renamed=1), Row(renamed=0),
Row(renamed=2)]; columns=['renamed'] | raises ValueError: Target schema's field
names are not matching the table's field names: ['renamed'], ['changed'] |
| ints, patched `StructField.dataType` of `BooleanType()`, of no setter
(p13; SPARK-62231, SPARK-62251) | raises AttributeError: property of
'StructField' object has no setter | struct<renamed:bigint>
rows=[Row(renamed=1), Row(renamed=0), Row(renamed=2)]; columns=['renamed'] |
schema raises AnalysisException: [INVALID_COLUMN_OR_FIELD_DATA_TYPE] Column or
field `col_0` is of type "BOOLEAN" while it's required to be "BIGINT"... |
| datetimes, no schema, public `TimestampType` rebound to `LongType` after
the session | raises PySparkTypeError:
[UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION] TimestampType() is not supported
in conversion to Arrow. | struct<t:timestamp>
rows=[Row(t=datetime.datetime(1970, 1, 1, 0, 0)), Row(t=datetime.datetime(1970,
1, 1, 0, 0, 1))]; columns=['t'] | raises PySparkTypeError:
[UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION] TimestampType() is not supported
in conversion to Arrow. |
| dicts, no schema, inferPandasDictAsMap, `MapType` of the session's module
rebound to `ArrayType` | struct<m:array<string>> rows=[Row(m=['k']),
Row(m=['j'])]; columns=['m'] | struct<m:map<string,bigint>> rows=[Row(m={'k':
1}), Row(m={'j': 2})]; columns=['m'] | struct<m:array<string>>
rows=[Row(m=['k']), Row(m=['j'])]; columns=['m'] |
| datetimes, no schema, public `TimestampType` rebound before the session,
collected (intentional: PySpark's client) | struct<t:bigint> collect raises
AssertionError: | struct<t:timestamp> rows=[Row(t=datetime.datetime(1970, 1,
1, 0, 0)), Row(t=datetime.datetime(1970, 1, 1, 0, 0, 1))]; columns=['t'] |
struct<t:bigint> rows=[Row(t=0), Row(t=1000000000)]; columns=['t'] |
| local rows under `a long`, public `AtomicType` rebound to None before the
session | raises TypeError: isinstance() arg 2 must be a type, a tuple of
types, or a union | struct<a:bigint> rows=[Row(a=1)]; columns=['a'] | raises
TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union |
| a pandas frame, no schema, the same | raises TypeError: isinstance() arg 2
must be a type, a tuple of types, or a union | struct<a:bigint>
rows=[Row(a=1)]; columns=['a'] | raises TypeError: isinstance() arg 2 must be a
type, a tuple of types, or a union |
| local rows under `"a long"`, the session module's `StructType` rebound to
a subclass | raises PySparkTypeError: [NOT_EXPECTED_TYPE] Argument `schema`
should be list, None or StructType, got StructType. | struct<a:bigint>
rows=[Row(a=1)]; columns=['a'] | raises PySparkTypeError: [NOT_EXPECTED_TYPE]
Argument `schema` should be list, None or StructType, got StructType. |
| local rows under `a long`, public `StructType` rebound to `object` before
the session (intentional: PySpark's conversion of local rows) | raises
AttributeError: 'LongType' object has no attribute 'fieldNames' |
struct<a:bigint> rows=[Row(a=1)]; columns=['a'] | struct<a:bigint>
rows=[Row(a=1)]; columns=['a'] |
Totals, against the reference client:
| probe | cases | before (8ecb3e62) | now | what still differs |
|---|---|---|---|---|
| the guard scenarios of `test_arrow_handoff.py`, at the mock service | 301
| 133 | 231 | 60 property patches with no setter (SPARK-62231, SPARK-62251); 8
of a `StructType` of `object`, whose `_to_table` PySpark's client fails
(intentional); 2 of a patched `isUTF8BinaryCollation` (SPARK-62236) |
| p14, rebound names (server) | 11 | 1 | 11 | |
| p13, patched classes (server) | 11 | 1 | 5 | the property patches with no
setter (SPARK-62231, SPARK-62251) |
| rebound names on the inferred path (server) | 21 | 3 | 17 | PySpark's
client and types: its `collect` and its parsing of the server's types by the
rebound names, and `DayTimeIntervalType()` reading `DayTimeIntervalType.DAY`
(intentional) |
| the schema check, of several kinds of data (server) | 112 | 43 | 93 |
PySpark's client and types: its parsing of types and its conversion of local
rows by the rebound names, and an `AtomicType` or `StructType` of `object`
(intentional); the `typeName()` JSON of a struct of a subclass (documented
already) |
The rewritten tests were also run on the reference client, against the same
mock service. A plugin compares each outcome with the PySpark expectation, not
with the known difference:
- Of the 316 tests selected, 300 pass.
- The 12 date cases of property patches with no setter cannot load the test
module on the reference. PySpark's own constructors of its module-level schemas
raise there, under the patch. The harness that does not construct schemas at
import gives PySpark's `AttributeError` for them, as the tests expect.
- The 4 other failures are older tests that the `-k` pattern also selected,
which use drop-in internals.
### Why are the changes needed?
So that `createDataFrame` of a pandas DataFrame under a patched type class
or a rebound type name gives PySpark's result, with PySpark's values and errors.
### Does this PR introduce _any_ user-facing change?
Yes, for programs that patch the type classes or rebind the type names:
- A pandas DataFrame converts with PySpark's conversion, which reads the
patch or the rebound name. It gives PySpark's values (`[1, 0, 1]` of a public
`BooleanType` rebound over ints) and PySpark's errors, where the drop-in
converted by the native types.
- `createDataFrame` raises PySpark's `TypeError` or `NOT_EXPECTED_TYPE` when
the session module's `AtomicType` or `StructType` rejects the schema.
- A struct whose `fields` or `names` list was changed in place takes
PySpark's conversion, with its `IndexError` or `ASSIGNMENT_ARITY_MISMATCH`, as
before round 3 of SPARK-62221.
### How was this patch tested?
- **The guard tests of `python/tests/test_arrow_handoff.py`.** The integer,
timestamp, float64, string, date and Arrow-string groups are rewritten:
- The 118 tests that asserted the old row path are now
`*_take(s)_pyspark_conversion`, along with the other tests of those groups.
- Each patches or rebinds in a process of its own, sends the plan at the
mock service, and prints the outcome as JSON: the error and the call that
raised it, the settings read, the Arrow table and the relation's schema
(`_GUARD_OUTCOME`).
- `_assert_guard` compares the outcome with PySpark's, as the reference
client gives it, or with the drop-in's outcome for a KD difference, and names
PySpark's in its message.
- Every PySpark expectation was checked on the reference client at the
same mock service, as above.
- The mock's Config response now carries the server-side session ID, as a
server's does, which PySpark's client checks.
- **New test of the schema check**,
`test_create_dataframe_checks_its_schema_against_the_names_of_the_session_module`.
It covers an `AtomicType` of None, a subclass `StructType` and a deleted
`StructType`, of local rows, a DDL string (parsed in one request), empty data,
a pandas frame, a pyarrow Table and an ndarray of bad dimensions. It passes on
both clients.
- **`test_dropin_offline.py`**:
`test_create_dataframe_of_a_pandas_frame_of_another_width_zips_it_as_pyspark`
adds the R3-1 cases, `fields.append` and `names.pop` (`IndexError`), and
`names.append` (the three names of `toDF`), of a plain struct and of `Iterated`.
- **`test_dropin_e2e.py`**:
- `test_create_dataframe_of_a_struct_of_another_width` adds the four
in-place changes, of both classes and two widths, with the server's
`ASSIGNMENT_ARITY_MISMATCH` and `IndexError`.
- The new
`test_create_dataframe_of_a_pandas_frame_under_a_rebound_type_name` checks the
import-timing case `[1, 0, 1]` in a process of its own.
- **Probes of both clients**: the tables above. The review's probes give the
same results as before: p1 48/48, p2 53/53, p3 59/59, p5 26/26, p7 10/10, p8
4/4, p9 6/6, p10 3/3 and p16 7/7. p17 and p18 are identical to round 3's
prototype (p18 16/16); p6 3/8, p11 6/12 and p12 0/4 are the documented
`typeName` and SPARK-62236 cases.
- **The Rust and Python gates** (`gates.sh build rust py`):
- `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`: 32 passed;
- ruff 0.14.0, `test_ruff_excludes.py`, `scripts/audit_no_stubs.sh`, the
stub and dispatch generators (`session.pyi` is regenerated: the module now has
PySpark's names), the test-list guards and the license checks;
- `test_type_stubs_offline.py`: 15 passed, 4 skipped;
- the offline suite of `coverage.yml`: 7,100 passed, 121 skipped.
- **`test_dropin_e2e.py`** against a Spark 4.3.0 server: 353 passed.
- `scripts/check_vendored_upstream.sh` was not run, as asked: no vendored
path changed.
### 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]