This is an automated email from the ASF dual-hosted git repository.
HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git
The following commit(s) were added to refs/heads/master by this push:
new 8a1de74e [SPARK-61418][CONNECT][PYTHON] Make VariantVal, Geometry and
Geography PySpark's plain classes in the Python client, whose attributes are
instance attributes as given and which are freed with their values
8a1de74e is described below
commit 8a1de74e813230504b3d2c23a091d29850027fc7
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 10:27:41 2026 +0900
[SPARK-61418][CONNECT][PYTHON] Make VariantVal, Geometry and Geography
PySpark's plain classes in the Python client, whose attributes are instance
attributes as given and which are freed with their values
### What changes were proposed in this pull request?
[SPARK-61418](https://issues.apache.org/jira/browse/SPARK-61418). This
builds on [SPARK-61402](https://issues.apache.org/jira/browse/SPARK-61402)
(#476), which pickles `VariantVal`, `Geometry` and `Geography` as PySpark's
plain classes.
`VariantVal`, `Geometry` and `Geography` of the Python client are now
PySpark 4.3.0's own plain classes, embedded in the extension as `Row` is:
- `crates/pyspark-rs/src/values.py` (new) is the source of the three
classes in `python/pyspark/sql/types.py` at v4.3.0. It differs from it only as
`row.py` does: `__module__ = "pyspark.sql.types"`, and `VariantUtils` is
imported inside the methods, so that the extension does not import the
partially initialized types shim while it loads.
- `crates/pyspark-rs/src/values.rs` loads the module once, as
`pyspark._values`, and exports the classes as `pyspark._pyspark.VariantVal`,
`Geography` and `Geometry`. `pyspark.sql.types` re-exports them, as before.
`variant_val` builds the `VariantVal` of a collected VARIANT (`row.rs`). It
makes the instance with the class's `__new__` and sets its two attributes, so
that the Python `__init__` does not run for every value.
- `infer.rs` and `session.rs` check values with `isinstance` of these
classes. `_infer_type` checks the exact type, as PySpark's `_type_mappings`
does. `convert` reads the `value`/`metadata` and `srid`/`wkb` attributes, as
PySpark's `toInternal` does, and converts them as PyArrow converts the fields
of their structs:
- The new `arrow_binary` takes a bytes, a bytearray, a memoryview or a
str (as UTF-8). Anything else raises PyArrow's `ArrowTypeError: Expected bytes,
got a '<type>' object`.
- The SRID is converted as an int32 column value is (`convert_integral`).
- With the attributes in a plain `__dict__`, a value pickles as any plain
class does. So the `__reduce__`, `__setstate__`, `reduce_as_a_plain_class` and
`restore_plain_class_state` of SPARK-61402 are removed.
- `pyproject.toml`, `.github/workflows/lint.yml` and `python/.coveragerc`
handle `values.py` as they handle the embedded `row.py`: Ruff checks it, with
UP031 ignored for PySpark's `%` reprs, and coverage omits its synthetic path.
### Why are the changes needed?
PySpark's classes are plain classes. `__init__(self, value, metadata)` and
`__init__(self, wkb, srid)` store the arguments, of any type, as instance
attributes. The client kept them in Rust `Vec<u8>`/`i32` fields behind
read-only getters. Probes of official PySpark 4.3.0 and of a build of
SPARK-61402:
| Probe | PySpark 4.3.0 | Before |
|---|---|---|
| `vars(VariantVal(b"\x0c\x01", b"\x01\x00\x00"))` | `{'value':
b'\x0c\x01', 'metadata': b'\x01\x00\x00'}` | `{}` |
| `v.value = b"\x0c\x02"`, `del v.value` | set, deleted | `AttributeError:
attribute 'value' of 'pyspark.sql.types.VariantVal' objects is not writable` |
| a subclass whose `__init__` sets `self.value` and `self.metadata` | works
| the same `AttributeError` |
| `VariantVal("x", None).value` | `'x'` | ``TypeError: argument 'value':
Can't extract `str` to `Vec` `` |
| `Geometry(wkb=1, srid=2)` | `{'wkb': 1, 'srid': 2}` | `TypeError:
argument 'wkb': 'int' object is not an instance of 'Sequence'` |
| `repr(Geometry(b"a", 4326.7))` | `"Geometry(b'a', 4326)"` | `TypeError:
argument 'srid': 'float' object cannot be interpreted as an integer` |
| `VariantVal.parseJson(b"1")` | `VariantVal(b'\x0c\x01', b'\x01\x00\x00')`
| `TypeError: argument 'json_str': 'bytes' object is not an instance of 'str'` |
| `Geometry.__new__(Geometry) == Geometry(wkb, 1)` | `AttributeError:
'Geometry' object has no attribute 'wkb'` | `False` |
The attributes cannot simply move to the `__dict__` of the
`#[pyclass(dict)]` types either. When such an instance is freed, PyO3 0.28
clears its `__dict__` but does not release it. `PyClassObjectContents::dealloc`
calls `clear_dict`, which is `PyDict_Clear`; PyO3 0.29 adds `release_dict`.
Already on the build of SPARK-61402, `tracemalloc` keeps 25,600,032 bytes after
100k `VariantVal` and 100k `Geometry` values, each with one attribute set, are
freed. PySpark keeps 32 bytes, and so do [...]
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client, matching PySpark:
- The attributes of `VariantVal`, `Geometry` and `Geography` are instance
attributes of any value. They are writable, deletable and listed by `vars()`,
and a subclass may set them itself.
- `repr`, `str`, `==`, `toJson`, `toPython`, `getSrid`, `getBytes`,
`fromWKB` and `parseJson` are PySpark's. They raise PySpark's errors for values
they cannot use, and the constructor no longer raises for them. Error messages
name the class as PySpark does, e.g. `'VariantVal' object has no attribute
'value'`.
- `createDataFrame` converts the attributes as PySpark and PyArrow do. A
value of a subclass of `Geometry` or `Geography` is inferred by its `__dict__`,
as `struct<srid:bigint,wkb:binary>`.
- Values whose `__dict__` was created no longer leak it.
### How was this patch tested?
- New offline tests in `python/tests/test_dropin_offline.py`, placed after
`test_spatial_values_copy_pickle_and_are_subclassed_as_pyspark`:
-
`test_variant_and_spatial_values_keep_their_attributes_as_given_as_pyspark`
covers `vars()`, writing and deleting the attributes, values of any type,
`repr`/`str`/`==`/`hash`, `fromWKB` and `parseJson`. Its body also passes
against official PySpark 4.3.0.
-
`test_variant_and_spatial_values_are_sent_and_collected_by_their_attributes_as_pyspark`
runs against the mock server:
- subclasses that set their own attributes, and their pickles;
- `createDataFrame` sends the same Arrow data for those subclasses and
for bytearray, memoryview and str attributes as for the class's bytes;
- PyArrow's errors for an int WKB, an int metadata and a str SRID, and
the `AttributeError` of a missing attribute, at conversion;
- the inferred type of a `Geometry` subclass;
- collected VARIANT and GEOMETRY values have their attributes in
`__dict__`.
- Without the fix (the source change reverted by hand and rebuilt; the
build is byte-identical to one of SPARK-61402), both tests fail:
- the first with `assert {} == {'metadata': ..., 'value': ...}` on
`vars()`;
- the second with `AttributeError: attribute 'value' of
'pyspark.sql.types.VariantVal' objects is not writable`.
- A probe of 113 cases ran on both clients: attributes, construction,
`repr`/`str`, `==`/`hash`, `fromWKB`/`parseJson`, pickles at every protocol,
copies and subclasses. It prints the same as official PySpark 4.3.0, except for
memory addresses.
- A probe of 93 `createDataFrame` and `collect` cases ran against a local
Spark 4.3.0 server. It covers bytes-like, str, int, None and missing
attributes, subclasses, and explicit and inferred schemas. It gives PySpark's
results and errors, except for a None attribute:
- PySpark sends the None as a null field, and the server rejects it
(`NullPointerException`, or `IllegalStateException: Value at index is null`).
- The client's Arrow batches have no null fields for these types. So it
raises PyArrow's error for the value when it converts it, e.g. `ArrowTypeError:
Expected bytes, got a 'NoneType' object`.
- `collect()` of 100k rows, best of 12 runs:
| Run | VARIANT before | VARIANT after | GEOMETRY before | GEOMETRY after
|
|---|---|---|---|---|
| local Spark 4.3.0 server, best of three interleaved rounds | 194 ms |
217 ms | 380 ms | 340 ms |
| mock server, client CPU time, three rounds | 152 to 154 ms | 165 to 189
ms | 338 to 347 ms | 278 to 316 ms |
On the server, the times of both builds overlap across rounds because the
machine was loaded. GEOMETRY is faster because the old `fromWKB` extracted the
WKB into a `Vec<u8>`. Official PySpark took 376 ms (VARIANT) and 407 ms
(GEOMETRY) on the same server.
- Tests run:
- offline `-k "variant or spatial or geometry or geography or Geometry or
Geography"`: 57 passed;
- live, on the same filter plus the `createDataFrame` and collected-row
tests: 47 passed;
- offline `createDataFrame`, inference, `Row`, pickle, collect and type
tests: 686 passed, 8 skipped.
- Checks:
- `ruff check` and `ruff format --check` of `values.py` and `row.py`, and
`cargo fmt --all --check`;
- `cargo clippy -p pyspark-rs --release --all-targets`, which reports
nothing in the changed files;
- `cargo test -p apache-spark-connect --release --no-run`, with and
without `--features wasm-udf`, with no warnings.
### 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.
Closes #493 from HyukjinKwon/SPARK-61418-value-classes-plain.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
.github/workflows/lint.yml | 4 +-
AGENTS.md | 12 +-
crates/pyspark-rs/src/infer.rs | 135 +++++++-----
crates/pyspark-rs/src/lib.rs | 4 +-
crates/pyspark-rs/src/row.rs | 7 +-
crates/pyspark-rs/src/session.rs | 4 +-
crates/pyspark-rs/src/values.py | 257 +++++++++++++++++++++++
crates/pyspark-rs/src/values.rs | 405 ++++++------------------------------
pyproject.toml | 6 +-
python/.coveragerc | 10 +-
python/tests/test_dropin_offline.py | 140 +++++++++++++
11 files changed, 574 insertions(+), 410 deletions(-)
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index c1473891..f7bb52eb 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -76,6 +76,6 @@ jobs:
- name: Install ruff
run: python -m pip install "ruff==0.14.0"
- name: ruff check - blocking
- run: ruff check scripts/ crates/pyspark-rs/src/row.py
+ run: ruff check scripts/ crates/pyspark-rs/src/row.py
crates/pyspark-rs/src/values.py
- name: ruff format (check) - blocking
- run: ruff format --check scripts/ crates/pyspark-rs/src/row.py
+ run: ruff format --check scripts/ crates/pyspark-rs/src/row.py
crates/pyspark-rs/src/values.py
diff --git a/AGENTS.md b/AGENTS.md
index 9e8f63c2..db75de3c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -243,9 +243,10 @@ Vendor the ones we don't have a Rust implementation for.
(the gRPC channel connects lazily, so proto/plan construction needs no
server)
and server-gated `tests/e2e_*.rs` (they check
`std::env::var("SPARK_REMOTE")`).
- **Python drop-in**: `python/.coveragerc` scopes to the hand-written shim
- (omits vendored/generated/Rust-only). The embedded
`crates/pyspark-rs/src/row.py`
- runs as `pyspark/_row.py` without a file at that path and is explicitly
omitted;
- Row tests exercise its behavior and Ruff checks its source. Run:
+ (omits vendored/generated/Rust-only). The embedded
`crates/pyspark-rs/src/row.py` and
+ `values.py` run as `pyspark/_row.py` and `pyspark/_values.py` without files
at those paths
+ and are explicitly omitted; their tests exercise their behavior and Ruff
checks their source.
+ Run:
```
cd python && PYTHONPATH=$(pwd) python -m coverage run --rcfile=.coveragerc \
-m pytest tests/test_dropin_offline.py && python -m coverage report
--rcfile=.coveragerc
@@ -425,6 +426,11 @@ For every method matching a pyspark name:
record batch. Nested names are shared by schema path across the execution,
including
iterator batches, while distinct sibling paths keep separate lists.
Nested local-input Rows follow the tuple inference paths; named Rows expose
`__fields__`.
+- **Value classes:** `crates/pyspark-rs/src/values.py` embeds PySpark's plain
classes
+ `VariantVal`, `Geometry` and `Geography` the same way, exported by
`pyspark._pyspark`, so
+ their attributes are the instance attributes of PySpark's, as given, and
they pickle as plain
+ classes into the server's Python workers. Do not make them
`#[pyclass(dict)]` types: PyO3 0.28
+ clears but never releases the `__dict__` of such an instance, so each value
would keep a dict.
- **Streaming listeners and progress holders:** Keep progress holders
(`StreamingQueryProgress`,
`StateOperatorProgress`, etc.) as faithful pure-Python implementations
parsed from server
JSON, not Rust-backed. The listener bus (subscribe/dispatch) is genuinely
Rust-backed;
diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index a0a05eac..a0512236 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -14,8 +14,8 @@ use pyo3::intern;
use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
use pyo3::types::{
- IntoPyDict, PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyInt, PyList,
PyString, PyTuple,
- PyType,
+ IntoPyDict, PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyInt, PyList,
PyMemoryView,
+ PyString, PyTuple, PyType,
};
use spark_connect::conf::RuntimeConf;
use spark_connect::row::{StructValue, Value};
@@ -23,7 +23,7 @@ use spark_connect::types::{DataType, GeographyType,
GeometryType, StructField};
use crate::column::raise_pyspark;
use crate::errors::ResultExt;
-use crate::values::{PyGeography, PyGeometry, PyVariantVal};
+use crate::values::{geography_class, geometry_class, variant_val_class};
static DECIMAL: PyOnceLock<Py<PyType>> = PyOnceLock::new();
static C_DECIMAL: PyOnceLock<Option<Py<PyType>>> = PyOnceLock::new();
@@ -461,12 +461,12 @@ pub(crate) fn infer_type(obj: &Bound<'_, PyAny>, o:
Options<'_>) -> PyResult<Dat
// As PySpark's `_infer_type`, the type of a value is `GeometryType(srid)`
or
// `GeographyType(srid)`, which raises `ST_INVALID_SRID_VALUE` for an SRID
that the type does
// not take (the explicit schema is not checked here, the server checks
the values of it).
- if obj.is_exact_instance_of::<PyGeometry>() {
+ if obj.get_type().is(geometry_class(py)?) {
let srid = obj.call_method0(intern!(py, "getSrid"))?;
let srid = crate::types::spatial_type_srid(&srid, false)?;
return Ok(DataType::Geometry { srid });
}
- if obj.is_exact_instance_of::<PyGeography>() {
+ if obj.get_type().is(geography_class(py)?) {
let srid = obj.call_method0(intern!(py, "getSrid"))?;
let srid = crate::types::spatial_type_srid(&srid, true)?;
return Ok(DataType::Geography { srid });
@@ -495,7 +495,7 @@ pub(crate) fn infer_type(obj: &Bound<'_, PyAny>, o:
Options<'_>) -> PyResult<Dat
)),
};
}
- if obj.is_instance_of::<PyVariantVal>() {
+ if obj.is_instance(variant_val_class(py)?)? {
return Ok(DataType::Variant);
}
match infer_schema(obj, None, o.for_nested_rows()) {
@@ -1340,47 +1340,50 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt:
&DataType, nullable: bool) ->
)?))
}
}
- // As PySpark's converters of these types: the value and metadata of a
VariantVal, and
- // the srid and WKB of a Geometry or a Geography, the structs of their
Arrow types.
- DataType::Variant => match obj.cast::<PyVariantVal>() {
- Ok(variant) => {
- let variant = variant.borrow();
+ // As PySpark's converters of these types, their `toInternal`: the
`value` and
+ // `metadata` attributes of a VariantVal, and the `srid` and `wkb` of
a Geometry or a
+ // Geography, which PyArrow converts as the fields of the structs of
their Arrow types.
+ DataType::Variant => {
+ if obj.is_instance(variant_val_class(py)?)? {
+ let value = obj.getattr(intern!(py, "value"))?;
+ let metadata = obj.getattr(intern!(py, "metadata"))?;
Ok(Value::Variant {
- value: variant.value.clone(),
- metadata: variant.metadata.clone(),
+ value: arrow_binary(&value)?,
+ metadata: arrow_binary(&metadata)?,
})
+ } else {
+ Err(raise_pyspark(
+ py,
+ "PySparkValueError",
+ "MALFORMED_VARIANT",
+ &[],
+ ))
}
- Err(_) => Err(raise_pyspark(
- py,
- "PySparkValueError",
- "MALFORMED_VARIANT",
- &[],
- )),
- },
- DataType::Geometry { .. } => match obj.cast::<PyGeometry>() {
- Ok(geometry) => {
- let geometry = geometry.borrow();
- Ok(spatial_value(geometry.srid, &geometry.wkb))
+ }
+ DataType::Geometry { .. } => {
+ if obj.is_instance(geometry_class(py)?)? {
+ spatial_value(obj)
+ } else {
+ Err(raise_pyspark(
+ py,
+ "PySparkValueError",
+ "MALFORMED_GEOMETRY",
+ &[],
+ ))
}
- Err(_) => Err(raise_pyspark(
- py,
- "PySparkValueError",
- "MALFORMED_GEOMETRY",
- &[],
- )),
- },
- DataType::Geography { .. } => match obj.cast::<PyGeography>() {
- Ok(geography) => {
- let geography = geography.borrow();
- Ok(spatial_value(geography.srid, &geography.wkb))
+ }
+ DataType::Geography { .. } => {
+ if obj.is_instance(geography_class(py)?)? {
+ spatial_value(obj)
+ } else {
+ Err(raise_pyspark(
+ py,
+ "PySparkValueError",
+ "MALFORMED_GEOGRAPHY",
+ &[],
+ ))
}
- Err(_) => Err(raise_pyspark(
- py,
- "PySparkValueError",
- "MALFORMED_GEOGRAPHY",
- &[],
- )),
- },
+ }
// As PySpark's converter of a user-defined type: the value serialized
by the UDT, and
// converted as its SQL type.
DataType::Udt {
@@ -1515,15 +1518,51 @@ pub(crate) fn time_nanos(obj: &Bound<'_, PyAny>) ->
PyResult<i64> {
Ok(seconds * 1_000_000_000 + field(intern!(py, "microsecond"))? * 1_000)
}
-/// The value of a GEOMETRY or a GEOGRAPHY, as their `toInternal`: its srid
and WKB.
-fn spatial_value(srid: i32, wkb: &[u8]) -> Value {
- Value::Struct(
+/// The value of a Geometry or a Geography `obj`, as their `toInternal`, the
dict of its `srid`
+/// and `wkb` attributes, which PyArrow converts to the int32 and the binary
of their struct.
+fn spatial_value(obj: &Bound<'_, PyAny>) -> PyResult<Value> {
+ let py = obj.py();
+ let srid = obj.getattr(intern!(py, "srid"))?;
+ let wkb = obj.getattr(intern!(py, "wkb"))?;
+ Ok(Value::Struct(
spark_connect::row::Row::new(
vec!["srid".to_string(), "wkb".to_string()],
- vec![Value::Integer(srid), Value::Binary(wkb.to_vec())],
+ vec![
+ convert_integral(&srid, &DataType::Integer)?,
+ Value::Binary(arrow_binary(&wkb)?),
+ ],
)
.into(),
- )
+ ))
+}
+
+/// The bytes of `obj` as PyArrow converts a value to binary: of a bytes, a
bytearray or a
+/// memoryview, or the UTF-8 of a str; else the `ArrowTypeError` "Expected
bytes, got a 'T'
+/// object". So are the attributes of a VariantVal, a Geometry and a
Geography, which PySpark
+/// stores as they are given, converted. A None, which PyArrow takes as a null
that the server
+/// then rejects, is no value here either, as these structs have no null
fields here.
+fn arrow_binary(obj: &Bound<'_, PyAny>) -> PyResult<Vec<u8>> {
+ let py = obj.py();
+ if let Ok(bytes) = obj.cast::<PyBytes>() {
+ Ok(bytes.as_bytes().to_vec())
+ } else if let Ok(text) = obj.cast::<PyString>() {
+ Ok(text.to_cow()?.as_bytes().to_vec())
+ } else if let Ok(bytes) = obj.cast::<PyByteArray>() {
+ Ok(bytes.to_vec())
+ } else if obj.is_instance_of::<PyMemoryView>() {
+ // Its bytes in C order, as PyArrow takes them, also of a view that is
not contiguous.
+ Ok(obj
+ .call_method0(intern!(py, "tobytes"))?
+ .cast_into::<PyBytes>()?
+ .as_bytes()
+ .to_vec())
+ } else {
+ Err(pyarrow_error(
+ py,
+ "ArrowTypeError",
+ format!("Expected bytes, got a '{}' object",
arrow_type_name(obj)?),
+ )?)
+ }
}
/// The user-defined type of a column whose class is `python_class`, to
serialize `obj`: that of
@@ -1751,7 +1790,7 @@ pub(crate) fn row_values<'py>(
if item.is_instance_of::<PyDict>() {
return values_by_name(item, fields);
}
- if item.is_instance_of::<PyVariantVal>() {
+ if item.is_instance(variant_val_class(py)?)? {
return Err(variant_row(py));
}
if item.hasattr(intern!(py, "__dict__"))? {
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 2740654e..47520fb8 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -211,9 +211,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<PyYearMonthIntervalType>()?;
m.add_class::<PyDayTimeIntervalType>()?;
m.add_class::<PyVariantType>()?;
- m.add_class::<values::PyVariantVal>()?;
- m.add_class::<values::PyGeography>()?;
- m.add_class::<values::PyGeometry>()?;
+ values::register(m)?;
// Register Window classes
m.add_class::<PyWindow>()?;
diff --git a/crates/pyspark-rs/src/row.rs b/crates/pyspark-rs/src/row.rs
index 07c517d9..4970d3f3 100644
--- a/crates/pyspark-rs/src/row.rs
+++ b/crates/pyspark-rs/src/row.rs
@@ -356,12 +356,7 @@ fn value_to_py<'py>(
Value::Variant { value, metadata } => {
// A VARIANT materializes as a VariantVal (toJson/toPython decode
lazily),
// matching pyspark, rather than a raw {value, metadata} dict.
- Py::new(
- py,
- crate::values::PyVariantVal::from_parts(value.clone(),
metadata.clone()),
- )?
- .into_bound(py)
- .into_any()
+ crate::values::variant_val(py, value, metadata)?
}
})
}
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 1268dbe4..964874e5 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -944,7 +944,7 @@ impl PySparkSession {
// PySpark's `to_row` rejects, as `row_values` does.
!(first.is_instance_of::<pyo3::types::PyTuple>()
|| first.is_instance_of::<PyList>()
- || first.is_instance_of::<crate::values::PyVariantVal>()
+ || first.is_instance(crate::values::variant_val_class(py)?)?
|| first.hasattr("__dict__")?)
};
@@ -959,7 +959,7 @@ impl PySparkSession {
let row_type = if single {
let items = infer::positional(py, vec![item.clone()],
cols.as_mut());
infer::infer_fields(py, items, options)?
- } else if
item.is_instance_of::<crate::values::PyVariantVal>() {
+ } else if
item.is_instance(crate::values::variant_val_class(py)?)? {
// PySpark infers the type of its `__dict__`, then
rejects the row.
return Err(infer::variant_row(py));
} else {
diff --git a/crates/pyspark-rs/src/values.py b/crates/pyspark-rs/src/values.py
new file mode 100644
index 00000000..837a853f
--- /dev/null
+++ b/crates/pyspark-rs/src/values.py
@@ -0,0 +1,257 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""The plain value classes of PySpark's ``pyspark.sql.types``: ``VariantVal``,
``Geography``
+and ``Geometry``.
+
+Mirrors these classes in apache/spark v4.3.0, ``python/pyspark/sql/types.py``,
whose
+``__init__`` stores its arguments, as they are given, as instance attributes,
which pickle as
+those of any plain class, also into the server's Python workers. Embedded by
the extension so
+``pyspark._pyspark`` and the public imports refer to the same classes, which
the client builds
+when it collects values, without importing the partially initialized types
shim.
+"""
+
+from typing import Any
+
+
+class VariantVal:
+ """
+ A class to represent a Variant value in Python.
+
+ .. versionadded:: 4.0.0
+
+ Parameters
+ ----------
+ value : bytes
+ The bytes representing the value component of the Variant.
+ metadata : bytes
+ The bytes representing the metadata component of the Variant.
+
+ Methods
+ -------
+ toPython()
+ Convert the VariantVal to a Python data structure.
+
+ Examples
+ --------
+ >>> from pyspark.sql import functions as sf
+ >>> df = spark.createDataFrame([ {'json': '''{ "a" : 1 }'''} ])
+ >>> v = df.select(sf.parse_json(df.json).alias("var")).head().var
+ >>> v.toPython()
+ {'a': 1}
+ >>> v.toJson()
+ '{"a":1}'
+ """
+
+ __module__ = "pyspark.sql.types"
+
+ def __init__(self, value: bytes, metadata: bytes):
+ self.value = value
+ self.metadata = metadata
+
+ def __str__(self) -> str:
+ from pyspark.sql.variant_utils import VariantUtils
+
+ return VariantUtils.to_json(self.value, self.metadata)
+
+ def __repr__(self) -> str:
+ return "VariantVal(%r, %r)" % (self.value, self.metadata)
+
+ def toPython(self) -> Any:
+ """
+ Convert the VariantVal to a Python data structure.
+
+ Returns
+ -------
+ Any
+ A Python object that represents the Variant.
+ """
+ from pyspark.sql.variant_utils import VariantUtils
+
+ return VariantUtils.to_python(self.value, self.metadata)
+
+ def toJson(self, zone_id: str = "UTC") -> str:
+ """
+ Convert the VariantVal to a JSON string. The zone ID represents the
time zone that the
+ timestamp should be printed in. It is defaulted to UTC. The list of
valid zone IDs can be
+ found by importing the `zoneinfo` module and running
:code:`zoneinfo.available_timezones()`.
+
+ Returns
+ -------
+ str
+ A JSON string that represents the Variant.
+ """
+ from pyspark.sql.variant_utils import VariantUtils
+
+ return VariantUtils.to_json(self.value, self.metadata, zone_id)
+
+ @classmethod
+ def parseJson(cls, json_str: str) -> "VariantVal":
+ """
+ Parse a JSON string and construct a VariantVal.
+
+ Returns
+ -------
+ VariantVal
+ A VariantVal representing the parsed Variant value.
+ """
+ from pyspark.sql.variant_utils import VariantUtils
+
+ value, metadata = VariantUtils.parse_json(json_str)
+ return VariantVal(value, metadata)
+
+
+class Geography:
+ """
+ A class to represent a Geography value in Python.
+
+ .. versionadded:: 4.1.0
+
+ Parameters
+ ----------
+ wkb : bytes
+ The bytes representing the WKB of Geography.
+
+ srid : integer
+ The integer value representing SRID of Geography.
+
+ Methods
+ -------
+ getBytes()
+ Returns the WKB of Geography.
+
+ getSrid()
+ Returns the SRID of Geography.
+
+ Examples
+ --------
+ >>> g =
Geography.fromWKB(bytes.fromhex('010100000000000000000031400000000000001c40'),
4326)
+ >>> g.getBytes().hex()
+ '010100000000000000000031400000000000001c40'
+ >>> g.getSrid()
+ 4326
+ """
+
+ __module__ = "pyspark.sql.types"
+
+ def __init__(self, wkb: bytes, srid: int):
+ self.wkb = wkb
+ self.srid = srid
+
+ def __str__(self) -> str:
+ return "Geography(%r, %d)" % (self.wkb, self.srid)
+
+ def __repr__(self) -> str:
+ return "Geography(%r, %d)" % (self.wkb, self.srid)
+
+ def getSrid(self) -> int:
+ """
+ Returns the SRID of Geography.
+ """
+ return self.srid
+
+ def getBytes(self) -> bytes:
+ """
+ Returns the WKB of Geography.
+ """
+ return self.wkb
+
+ def __eq__(self, other: Any) -> bool:
+ if not isinstance(other, Geography):
+ # Don't attempt to compare against unrelated types.
+ return NotImplemented
+
+ return self.wkb == other.wkb and self.srid == other.srid
+
+ @classmethod
+ def fromWKB(cls, wkb: bytes, srid: int) -> "Geography":
+ """
+ Construct Python Geography object from WKB.
+ :return: Python representation of the Geography type value.
+ """
+ return Geography(wkb, srid)
+
+
+class Geometry:
+ """
+ A class to represent a Geometry value in Python.
+
+ .. versionadded:: 4.1.0
+
+ Parameters
+ ----------
+ wkb : bytes
+ The bytes representing the WKB of Geometry.
+
+ srid : integer
+ The integer value representing SRID of Geometry.
+
+ Methods
+ -------
+ getBytes()
+ Returns the WKB of Geometry.
+
+ getSrid()
+ Returns the SRID of Geometry.
+
+ Examples
+ --------
+ >>> g =
Geometry.fromWKB(bytes.fromhex('010100000000000000000031400000000000001c40'), 0)
+ >>> g.getBytes().hex()
+ '010100000000000000000031400000000000001c40'
+ >>> g.getSrid()
+ 0
+ """
+
+ __module__ = "pyspark.sql.types"
+
+ def __init__(self, wkb: bytes, srid: int):
+ self.wkb = wkb
+ self.srid = srid
+
+ def __str__(self) -> str:
+ return "Geometry(%r, %d)" % (self.wkb, self.srid)
+
+ def __repr__(self) -> str:
+ return "Geometry(%r, %d)" % (self.wkb, self.srid)
+
+ def getSrid(self) -> int:
+ """
+ Returns the SRID of Geometry.
+ """
+ return self.srid
+
+ def getBytes(self) -> bytes:
+ """
+ Returns the WKB of Geometry.
+ """
+ return self.wkb
+
+ def __eq__(self, other: Any) -> bool:
+ if not isinstance(other, Geometry):
+ # Don't attempt to compare against unrelated types.
+ return NotImplemented
+
+ return self.wkb == other.wkb and self.srid == other.srid
+
+ @classmethod
+ def fromWKB(cls, wkb: bytes, srid: int) -> "Geometry":
+ """
+ Construct Python Geometry object from WKB.
+ :return: Python representation of the Geometry type value.
+ """
+ return Geometry(wkb, srid)
diff --git a/crates/pyspark-rs/src/values.rs b/crates/pyspark-rs/src/values.rs
index 752f9ed1..398e9aa3 100644
--- a/crates/pyspark-rs/src/values.rs
+++ b/crates/pyspark-rs/src/values.rs
@@ -1,356 +1,81 @@
-//! PyO3-backed value holders returned/consumed by the client for the newer
types,
-//! mirroring `pyspark.sql.types.{VariantVal, Geometry, Geography}`.
+//! The value classes of the newer types, `pyspark.sql.types.{VariantVal,
Geometry, Geography}`:
+//! PySpark's plain Python classes, embedded from `values.py`.
+//!
+//! PySpark's `__init__` stores its arguments, as they are given, as the
instance attributes
+//! `value` and `metadata`, or `wkb` and `srid`, which are writable, deletable
and in the
+//! instance `__dict__`, and a subclass's `__init__` may set them itself. A
value pickles as any
+//! plain class does, which the server's Python workers, of PySpark, unpickle.
The classes are
+//! not `#[pyclass(dict)]` types, as PyO3 0.28 clears but does not release the
`__dict__` of
+//! such an instance when it is freed, so that every value would keep a dict
alive.
+use pyo3::intern;
use pyo3::prelude::*;
-use pyo3::types::{PyBytes, PyDict, PyString, PyTuple};
+use pyo3::sync::PyOnceLock;
+use pyo3::types::{PyBytes, PyType};
-/// Pickle `slf` as PySpark pickles its plain class: rebuilt by
`copyreg.__newobj__`, without
-/// `__init__`, with the state `object.__reduce_ex__` gives, the dict of its
instance attributes
-/// and `fields`, or that dict and the values of its slots, `(dict, slots)`,
for a subclass of
-/// slots. PySpark's class, which has no `__setstate__`, takes this state as
its attributes, so
-/// a value pickled here loads in PySpark, as in the server's Python workers.
-fn reduce_as_a_plain_class<'py>(
- slf: &Bound<'py, PyAny>,
- fields: [(&str, Bound<'py, PyAny>); 2],
-) -> PyResult<Bound<'py, PyTuple>> {
- let py = slf.py();
- let copyreg = py.import("copyreg")?;
- let attributes = slf.getattr("__dict__")?.cast::<PyDict>()?.copy()?;
- for (name, value) in fields {
- attributes.set_item(name, value)?;
- }
- let slots = PyDict::new(py);
- for name in copyreg
- .call_method1("_slotnames", (slf.get_type(),))?
- .try_iter()?
- {
- let name = name?.cast_into::<PyString>()?;
- // As `object.__getstate__`: the slots that have a value.
- if let Ok(value) = slf.getattr(&name) {
- slots.set_item(name, value)?;
- }
- }
- let state = if slots.is_empty() {
- attributes.into_any()
- } else {
- PyTuple::new(py, [attributes.into_any(), slots.into_any()])?.into_any()
- };
- let args = PyTuple::new(py, [slf.get_type().into_any()])?;
- PyTuple::new(py, [copyreg.getattr("__newobj__")?, args.into_any(), state])
-}
+static CLASSES: PyOnceLock<ValueClasses> = PyOnceLock::new();
+const VALUES_SOURCE: &std::ffi::CStr =
pyo3::ffi::c_str!(include_str!("values.py"));
-/// Restore on `slf` a state of [`reduce_as_a_plain_class`], or of PySpark's
pickle of its plain
-/// class, as pickle's BUILD restores a plain class: its instance attributes,
and its slots of a
-/// `(dict, slots)`. The values of `fields`, which are not instance attributes
here, are returned.
-fn restore_plain_class_state<'py>(
- slf: &Bound<'py, PyAny>,
- state: &Bound<'py, PyAny>,
- fields: [&str; 2],
-) -> PyResult<[Option<Bound<'py, PyAny>>; 2]> {
- let (attributes, slots) = match state.cast::<PyTuple>() {
- Ok(pair) if pair.len() == 2 => (pair.get_item(0)?,
Some(pair.get_item(1)?)),
- _ => (state.clone(), None),
- };
- let mut values = [None, None];
- if !attributes.is_none() {
- let attributes = attributes.cast::<PyDict>()?.copy()?;
- for (value, name) in values.iter_mut().zip(fields) {
- if let Some(field) = attributes.get_item(name)? {
- attributes.del_item(name)?;
- *value = Some(field);
- }
- }
- slf.getattr("__dict__")?
- .call_method1("update", (attributes,))?;
- }
- if let Some(slots) = slots.filter(|slots| !slots.is_none()) {
- for (name, value) in slots.cast::<PyDict>()?.iter() {
- slf.setattr(name.cast_into::<PyString>()?, value)?;
- }
- }
- Ok(values)
+struct ValueClasses {
+ variant_val: Py<PyType>,
+ geography: Py<PyType>,
+ geometry: Py<PyType>,
}
-/// A Variant value (the `value`/`metadata` binary components). Mirrors
-/// `pyspark.sql.types.VariantVal`.
-#[pyclass(
- name = "VariantVal",
- module = "pyspark.sql.types",
- weakref,
- dict,
- subclass
-)]
-pub struct PyVariantVal {
- pub(crate) value: Vec<u8>,
- pub(crate) metadata: Vec<u8>,
+/// The classes of the embedded module, which is loaded once. Its source
imports PySpark modules
+/// only inside methods, avoiding import cycles while `pyspark.sql.types` is
importing this
+/// extension. The synthetic filename avoids embedding a build-machine path in
wheels.
+fn classes(py: Python<'_>) -> PyResult<&ValueClasses> {
+ CLASSES.get_or_try_init(py, || {
+ let module =
+ PyModule::from_code(py, VALUES_SOURCE, c"pyspark/_values.py",
c"pyspark._values")?;
+ let class = |name: &str| -> PyResult<Py<PyType>> {
+ Ok(module.getattr(name)?.cast_into::<PyType>()?.unbind())
+ };
+ Ok(ValueClasses {
+ variant_val: class("VariantVal")?,
+ geography: class("Geography")?,
+ geometry: class("Geometry")?,
+ })
+ })
}
-impl PyVariantVal {
- /// Build from raw (value, metadata) bytes (used when materializing a
VARIANT column).
- pub(crate) fn from_parts(value: Vec<u8>, metadata: Vec<u8>) -> Self {
- PyVariantVal { value, metadata }
- }
+/// Expose the classes as `pyspark._pyspark.{VariantVal, Geography,
Geometry}`, which
+/// `pyspark.sql.types` re-exports.
+pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> {
+ let py = module.py();
+ let classes = classes(py)?;
+ module.add("VariantVal", classes.variant_val.bind(py))?;
+ module.add("Geography", classes.geography.bind(py))?;
+ module.add("Geometry", classes.geometry.bind(py))
}
-#[pymethods]
-impl PyVariantVal {
- /// Accepts any arguments, so that a subclass's `__init__` may take
others; `__init__` sets
- /// the value and metadata.
- #[new]
- #[pyo3(signature = (*_args, **_kwargs))]
- fn new(_args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>) ->
Self {
- PyVariantVal {
- value: Vec::new(),
- metadata: Vec::new(),
- }
- }
- #[pyo3(signature = (value, metadata))]
- fn __init__(&mut self, value: Vec<u8>, metadata: Vec<u8>) {
- self.value = value;
- self.metadata = metadata;
- }
- /// Pickled as PySpark's plain class is, with its value and metadata as
attributes, so that
- /// PySpark loads it, as PySpark's pickles of it load here.
- fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py,
PyTuple>> {
- let py = slf.py();
- let fields = {
- let this = slf.borrow();
- [
- ("value", PyBytes::new(py, &this.value).into_any()),
- ("metadata", PyBytes::new(py, &this.metadata).into_any()),
- ]
- };
- reduce_as_a_plain_class(slf.as_any(), fields)
- }
- fn __setstate__(slf: &Bound<'_, Self>, state: &Bound<'_, PyAny>) ->
PyResult<()> {
- let [value, metadata] =
- restore_plain_class_state(slf.as_any(), state, ["value",
"metadata"])?;
- let value: Option<Vec<u8>> = value.map(|v| v.extract()).transpose()?;
- let metadata: Option<Vec<u8>> = metadata.map(|m|
m.extract()).transpose()?;
- let mut this = slf.borrow_mut();
- if let Some(value) = value {
- this.value = value;
- }
- if let Some(metadata) = metadata {
- this.metadata = metadata;
- }
- Ok(())
- }
- #[getter]
- fn value<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
- PyBytes::new(py, &self.value)
- }
- #[getter]
- fn metadata<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
- PyBytes::new(py, &self.metadata)
- }
- /// Decode to a Python value. Mirrors `VariantVal.toPython` — delegates to
the shared
- /// `VariantUtils.to_python` (kept in Python since the full binary codec
lives there).
- fn toPython<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
- py.import("pyspark.sql.variant_utils")?
- .getattr("VariantUtils")?
- .getattr("to_python")?
- .call1((self.value(py), self.metadata(py)))
- }
- /// Encode to a JSON string. Mirrors `VariantVal.toJson`.
- #[pyo3(signature = (zone_id="UTC"))]
- fn toJson(&self, py: Python<'_>, zone_id: &str) -> PyResult<String> {
- py.import("pyspark.sql.variant_utils")?
- .getattr("VariantUtils")?
- .getattr("to_json")?
- .call1((self.value(py), self.metadata(py), zone_id))?
- .extract()
- }
- #[classmethod]
- fn parseJson(
- _cls: &Bound<'_, pyo3::types::PyType>,
- py: Python<'_>,
- json_str: &str,
- ) -> PyResult<PyVariantVal> {
- let t = py
- .import("pyspark.sql.variant_utils")?
- .getattr("VariantUtils")?
- .getattr("parse_json")?
- .call1((json_str,))?;
- let (value, metadata): (Vec<u8>, Vec<u8>) = t.extract()?;
- Ok(PyVariantVal { value, metadata })
- }
- fn __repr__(&self, py: Python<'_>) -> String {
- format!("VariantVal({:?}, {:?})", self.value(py), self.metadata(py))
- }
- /// The JSON of the value, as PySpark's `VariantVal.__str__`:
`VariantUtils.to_json` of it,
- /// in UTC, as `toJson()`.
- fn __str__(&self, py: Python<'_>) -> PyResult<String> {
- self.toJson(py, "UTC")
- }
+/// The `VariantVal` class, to check the values of PySpark's checks of it.
+pub(crate) fn variant_val_class(py: Python<'_>) -> PyResult<&Bound<'_,
PyType>> {
+ Ok(classes(py)?.variant_val.bind(py))
}
-/// A Geography value (WKB bytes + SRID). Mirrors
`pyspark.sql.types.Geography`.
-#[pyclass(
- name = "Geography",
- module = "pyspark.sql.types",
- weakref,
- dict,
- subclass
-)]
-pub struct PyGeography {
- pub(crate) wkb: Vec<u8>,
- pub(crate) srid: i32,
-}
-#[pymethods]
-impl PyGeography {
- /// Accepts any arguments, so that a subclass's `__init__` may take
others, as of PySpark's
- /// plain class; `__init__` sets the WKB and the SRID.
- #[new]
- #[pyo3(signature = (*_args, **_kwargs))]
- fn new(_args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>) ->
Self {
- PyGeography {
- wkb: Vec::new(),
- srid: 0,
- }
- }
- #[pyo3(signature = (wkb, srid))]
- fn __init__(&mut self, wkb: Vec<u8>, srid: i32) {
- self.wkb = wkb;
- self.srid = srid;
- }
- /// Pickled as PySpark's plain class is, with its WKB and SRID as
attributes, so that PySpark
- /// loads it, as PySpark's pickles of it load here.
- fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py,
PyTuple>> {
- let py = slf.py();
- let fields = {
- let this = slf.borrow();
- [
- ("wkb", PyBytes::new(py, &this.wkb).into_any()),
- ("srid", this.srid.into_pyobject(py)?.into_any()),
- ]
- };
- reduce_as_a_plain_class(slf.as_any(), fields)
- }
- fn __setstate__(slf: &Bound<'_, Self>, state: &Bound<'_, PyAny>) ->
PyResult<()> {
- let [wkb, srid] = restore_plain_class_state(slf.as_any(), state,
["wkb", "srid"])?;
- let wkb: Option<Vec<u8>> = wkb.map(|w| w.extract()).transpose()?;
- let srid: Option<i32> = srid.map(|s| s.extract()).transpose()?;
- let mut this = slf.borrow_mut();
- if let Some(wkb) = wkb {
- this.wkb = wkb;
- }
- if let Some(srid) = srid {
- this.srid = srid;
- }
- Ok(())
- }
- fn getSrid(&self) -> i32 {
- self.srid
- }
- fn getBytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
- PyBytes::new(py, &self.wkb)
- }
- /// The spatial reference identifier, as PySpark's attribute.
- #[getter]
- fn srid(&self) -> i32 {
- self.srid
- }
- /// The well-known binary, as PySpark's attribute.
- #[getter]
- fn wkb<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
- PyBytes::new(py, &self.wkb)
- }
- #[classmethod]
- fn fromWKB(_cls: &Bound<'_, pyo3::types::PyType>, wkb: Vec<u8>, srid: i32)
-> PyGeography {
- PyGeography { wkb, srid }
- }
- fn __eq__(&self, other: &PyGeography) -> bool {
- self.wkb == other.wkb && self.srid == other.srid
- }
- fn __repr__(&self, py: Python<'_>) -> String {
- format!(
- "Geography({:?}, {})",
- PyBytes::new(py, &self.wkb),
- self.srid
- )
- }
+/// The `Geography` class, to check the values of PySpark's checks of it.
+pub(crate) fn geography_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
+ Ok(classes(py)?.geography.bind(py))
}
-/// A Geometry value (WKB bytes + SRID). Mirrors `pyspark.sql.types.Geometry`.
-#[pyclass(
- name = "Geometry",
- module = "pyspark.sql.types",
- weakref,
- dict,
- subclass
-)]
-pub struct PyGeometry {
- pub(crate) wkb: Vec<u8>,
- pub(crate) srid: i32,
+/// The `Geometry` class, to check the values of PySpark's checks of it.
+pub(crate) fn geometry_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
+ Ok(classes(py)?.geometry.bind(py))
}
-#[pymethods]
-impl PyGeometry {
- /// Accepts any arguments, so that a subclass's `__init__` may take
others, as of PySpark's
- /// plain class; `__init__` sets the WKB and the SRID.
- #[new]
- #[pyo3(signature = (*_args, **_kwargs))]
- fn new(_args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>) ->
Self {
- PyGeometry {
- wkb: Vec::new(),
- srid: 0,
- }
- }
- #[pyo3(signature = (wkb, srid))]
- fn __init__(&mut self, wkb: Vec<u8>, srid: i32) {
- self.wkb = wkb;
- self.srid = srid;
- }
- /// Pickled as PySpark's plain class is, with its WKB and SRID as
attributes, so that PySpark
- /// loads it, as PySpark's pickles of it load here.
- fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py,
PyTuple>> {
- let py = slf.py();
- let fields = {
- let this = slf.borrow();
- [
- ("wkb", PyBytes::new(py, &this.wkb).into_any()),
- ("srid", this.srid.into_pyobject(py)?.into_any()),
- ]
- };
- reduce_as_a_plain_class(slf.as_any(), fields)
- }
- fn __setstate__(slf: &Bound<'_, Self>, state: &Bound<'_, PyAny>) ->
PyResult<()> {
- let [wkb, srid] = restore_plain_class_state(slf.as_any(), state,
["wkb", "srid"])?;
- let wkb: Option<Vec<u8>> = wkb.map(|w| w.extract()).transpose()?;
- let srid: Option<i32> = srid.map(|s| s.extract()).transpose()?;
- let mut this = slf.borrow_mut();
- if let Some(wkb) = wkb {
- this.wkb = wkb;
- }
- if let Some(srid) = srid {
- this.srid = srid;
- }
- Ok(())
- }
- fn getSrid(&self) -> i32 {
- self.srid
- }
- fn getBytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
- PyBytes::new(py, &self.wkb)
- }
- /// The spatial reference identifier, as PySpark's attribute.
- #[getter]
- fn srid(&self) -> i32 {
- self.srid
- }
- /// The well-known binary, as PySpark's attribute.
- #[getter]
- fn wkb<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
- PyBytes::new(py, &self.wkb)
- }
- #[classmethod]
- fn fromWKB(_cls: &Bound<'_, pyo3::types::PyType>, wkb: Vec<u8>, srid: i32)
-> PyGeometry {
- PyGeometry { wkb, srid }
- }
- fn __eq__(&self, other: &PyGeometry) -> bool {
- self.wkb == other.wkb && self.srid == other.srid
- }
- fn __repr__(&self, py: Python<'_>) -> String {
- format!("Geometry({:?}, {})", PyBytes::new(py, &self.wkb), self.srid)
- }
+
+/// The VariantVal of the bytes `value` and `metadata`, as PySpark's
`VariantVal(value,
+/// metadata)` of a collected VARIANT: an instance of the class, made by its
`__new__`, with
+/// its two attributes, but without running the Python `__init__` for every
value.
+pub(crate) fn variant_val<'py>(
+ py: Python<'py>,
+ value: &[u8],
+ metadata: &[u8],
+) -> PyResult<Bound<'py, PyAny>> {
+ let class = variant_val_class(py)?;
+ let variant = class.call_method1(intern!(py, "__new__"), (class,))?;
+ variant.setattr(intern!(py, "value"), PyBytes::new(py, value))?;
+ variant.setattr(intern!(py, "metadata"), PyBytes::new(py, metadata))?;
+ Ok(variant)
}
diff --git a/pyproject.toml b/pyproject.toml
index 0fb7b92f..89d657f2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -44,14 +44,14 @@ Repository = "https://github.com/apache/spark-connect-rust"
"Bug Tracker" = "https://issues.apache.org/jira/browse/SPARK"
[tool.ruff]
-# Lint our authored tooling/scripts and the embedded Row implementation.
+# Lint our authored tooling/scripts and the embedded Row and value classes.
# The python/pyspark tree is largely vendored from Apache Spark
(pandas-on-Spark
# and the drop-in skin). It must stay byte-compatible with upstream and is
excluded
# from this linter.
line-length = 100
target-version = "py39"
extend-exclude = ["python/pyspark", "target", ".claude"]
-include = ["scripts/**/*.py", "crates/pyspark-rs/src/row.py"]
+include = ["scripts/**/*.py", "crates/pyspark-rs/src/row.py",
"crates/pyspark-rs/src/values.py"]
[tool.ruff.lint]
select = ["E", "F", "W", "I", "UP", "B"]
@@ -61,6 +61,8 @@ ignore = ["E501"] # line length handled by the formatter,
not enforced hard
# Keep the upstream Row implementation's implicit exception context and percent
# formatting so error behavior and source comparisons stay faithful to PySpark
4.3.0.
"crates/pyspark-rs/src/row.py" = ["B904", "UP031"]
+# The upstream value classes format their reprs with percent formatting, as
PySpark 4.3.0.
+"crates/pyspark-rs/src/values.py" = ["UP031"]
[tool.maturin]
# Mixed Python/Rust layout: the pure-Python drop-in skin lives under
python/pyspark,
diff --git a/python/.coveragerc b/python/.coveragerc
index 699ead7c..0952cc99 100644
--- a/python/.coveragerc
+++ b/python/.coveragerc
@@ -3,9 +3,9 @@
# the Python glue only, excluding vendored third-party code (cloudpickle), the
# test-support utilities, pandas-on-spark, generated wrappers, and the compiled
# extension itself.
-# The embedded crates/pyspark-rs/src/row.py runs as pyspark/_row.py.
-# That path has no file and is explicitly omitted. Row tests exercise its
behavior;
-# Ruff checks the embedded source.
+# The embedded crates/pyspark-rs/src/row.py runs as pyspark/_row.py, and
values.py as
+# pyspark/_values.py. Those paths have no file and are explicitly omitted. The
Row and
+# value tests exercise their behavior; Ruff checks the embedded sources.
[run]
source = pyspark
branch = True
@@ -74,9 +74,11 @@ omit =
*/pyspark/sql/sql_formatter.py
*/pyspark/sql/connect/profiler.py
*/pyspark/sql/connect/shell/progress.py
- # The native extension and its embedded Row source, which has a synthetic
filename.
+ # The native extension and its embedded Row and value sources, which have
synthetic
+ # filenames.
*/pyspark/_pyspark*
*/pyspark/_row.py
+ */pyspark/_values.py
# Test helpers.
*/tests/*
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index cdbdd157..6858a93f 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7064,6 +7064,146 @@ def
test_spatial_values_copy_pickle_and_are_subclassed_as_pyspark():
assert (restored.value, restored.metadata) == (b"\x0c\x01",
b"\x01\x00\x00")
+def
test_variant_and_spatial_values_keep_their_attributes_as_given_as_pyspark():
+ # As PySpark's VariantVal, Geometry and Geography, plain classes whose
__init__ stores its
+ # arguments, of any type, as instance attributes: they are in vars(),
writable and
+ # deletable, and the methods, repr, str and == read them, which raise for
a value they
+ # cannot use, not the constructor. A VariantVal compares by identity; the
spatial values
+ # compare their attributes, with the values of their own class only, and
are not hashable.
+ import pickle
+
+ v = T.VariantVal(b"\x0c\x01", b"\x01\x00\x00")
+ assert vars(v) == {"value": b"\x0c\x01", "metadata": b"\x01\x00\x00"}
+ v.value, v.tag = bytearray(b"\x0c\x02"), "kept"
+ assert vars(v) == {"value": bytearray(b"\x0c\x02"), "metadata":
b"\x01\x00\x00", "tag": "kept"}
+ assert (v.toJson(), str(v), v.toPython()) == ("2", "2", 2)
+ assert repr(v) == "VariantVal(bytearray(b'\\x0c\\x02'),
b'\\x01\\x00\\x00')"
+ assert vars(pickle.loads(pickle.dumps(v))) == vars(v)
+ del v.metadata
+ assert vars(v) == {"value": bytearray(b"\x0c\x02"), "tag": "kept"}
+ with pytest.raises(AttributeError, match="metadata"):
+ repr(v)
+ odd = T.VariantVal("x", None)
+ assert (odd.value, odd.metadata, repr(odd)) == ("x", None,
"VariantVal('x', None)")
+ with pytest.raises(TypeError):
+ odd.toJson()
+ assert vars(T.VariantVal(metadata=2, value=1)) == {"value": 1, "metadata":
2}
+ assert vars(T.VariantVal.parseJson(b"1")) == {"value": b"\x0c\x01",
"metadata": b"\x01\x00\x00"}
+ assert T.VariantVal(b"\x0c\x01", b"\x01\x00\x00") !=
T.VariantVal(b"\x0c\x01", b"\x01\x00\x00")
+ assert hash(v) == hash(v)
+
+ wkb = bytes.fromhex("0101000000000000000000F03F0000000000000040")
+ for cls, other in ((T.Geometry, T.Geography), (T.Geography, T.Geometry)):
+ name = cls.__name__
+ g = cls.fromWKB("x", "4326")
+ assert type(g) is cls and vars(g) == {"wkb": "x", "srid": "4326"}
+ assert (g.getBytes(), g.getSrid()) == ("x", "4326")
+ with pytest.raises(TypeError, match="%d format: a real number is
required, not str"):
+ repr(g)
+ g.srid = 3857.9
+ assert repr(g) == str(g) == f"{name}('x', 3857)"
+ del g.wkb
+ assert vars(g) == {"srid": 3857.9}
+ assert cls(wkb, 4326) == cls(bytearray(wkb), 4326.0) and cls(wkb,
4326) != cls(wkb, 3857)
+ assert cls(wkb, 4326).__eq__(other(wkb, 4326)) is NotImplemented
+ assert cls(wkb, 4326) != other(wkb, 4326) and cls.__hash__ is None
+
+
+class _AssignedVariant(T.VariantVal):
+ # Sets the attributes itself, without the __init__ of VariantVal.
+ def __init__(self, value, metadata):
+ self.value, self.metadata = value, metadata
+
+
+class _AssignedGeometry(T.Geometry):
+ def __init__(self, wkb, srid):
+ self.wkb, self.srid = wkb, srid
+
+
+class _AssignedGeography(T.Geography):
+ def __init__(self, wkb, srid):
+ self.wkb, self.srid = wkb, srid
+
+
+def
test_variant_and_spatial_values_are_sent_and_collected_by_their_attributes_as_pyspark(
+ mock_connect):
+ # As PySpark's: createDataFrame sends the attributes of a VariantVal, a
Geometry and a
+ # Geography, also of a subclass whose __init__ sets them itself, as
PyArrow converts them to
+ # the fields of their structs: a bytearray, a memoryview or a str (its
UTF-8) as binary,
+ # else its ArrowTypeError, raised when the value is converted. A value of
a subclass of
+ # Geometry is inferred by its __dict__, as it is not of the class. And the
values that
+ # collect builds have their attributes in their __dict__.
+ import pickle
+
+ import pyarrow as pa
+ from _mock_connect_server import data_type_proto
+
+ spark, service = mock_connect
+
+ def local_table(df):
+ df.toArrow()
+ request = parse_message(service.execute_requests[-1])
+ relation = parse_message(parse_message(request[3][0])[1][0])
+ while 18 in relation: # Relation.to_df -> ToDF.input.
+ relation = parse_message(parse_message(relation[18][0])[1][0])
+ # Relation.local_relation=11 -> LocalRelation.data=1.
+ local = parse_message(relation[11][0])
+ return pa.ipc.open_stream(local[1][0]).read_all()
+
+ value, metadata = b"\x0c\x01", b"\x01\x00\x00"
+ assigned = _AssignedVariant(value, metadata)
+ assert vars(assigned) == {"value": value, "metadata": metadata}
+ assert (assigned.toJson(), repr(assigned)) == ("1",
repr(T.VariantVal(value, metadata)))
+ restored = pickle.loads(pickle.dumps(assigned))
+ assert type(restored) is _AssignedVariant and vars(restored) ==
vars(assigned)
+ sent = local_table(spark.createDataFrame([(T.VariantVal(value,
metadata),)], "v variant"))
+ for variant in (assigned, T.VariantVal(bytearray(value),
memoryview(metadata)),
+ _AssignedVariant("\x0c\x01", "\x01\x00\x00")):
+ assert local_table(spark.createDataFrame([(variant,)], "v
variant")).equals(sent)
+ with pytest.raises(pa.ArrowTypeError, match="Expected bytes, got a 'int'
object"):
+ spark.createDataFrame([(T.VariantVal(value, 1),)], "v variant")
+ with pytest.raises(AttributeError, match="no attribute 'value'"):
+ spark.createDataFrame([(_AssignedVariant.__new__(_AssignedVariant),)],
"v variant")
+
+ wkb = bytes.fromhex("0101000000000000000000F03F0000000000000040")
+ for cls, assigned_cls, schema in ((T.Geometry, _AssignedGeometry, "g
geometry(4326)"),
+ (T.Geography, _AssignedGeography, "g
geography(4326)")):
+ g = assigned_cls(wkb, 4326)
+ assert vars(g) == {"wkb": wkb, "srid": 4326} and g == cls(wkb, 4326)
+ assert repr(g) == repr(cls(wkb, 4326))
+ sent = local_table(spark.createDataFrame([(cls(wkb, 4326),)], schema))
+ for spatial in (g, cls(bytearray(wkb), 4326.0)):
+ assert local_table(spark.createDataFrame([(spatial,)],
schema)).equals(sent)
+ with pytest.raises(pa.ArrowInvalid, match="Could not convert '4326'
with type str"):
+ spark.createDataFrame([(cls(wkb, "4326"),)], schema)
+ with pytest.raises(pa.ArrowTypeError, match="Expected bytes, got a
'int' object"):
+ spark.createDataFrame([(cls(1, 4326),)], schema)
+ inferred = local_table(spark.createDataFrame([(_AssignedGeometry(wkb,
4326),)]))
+ assert inferred.schema.field("_1").type == pa.struct(
+ [("srid", pa.int64()), ("wkb", pa.binary())])
+
+ def respond(schema, table):
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, table.schema) as writer:
+ writer.write_table(table)
+ # ExecutePlanResponse.schema=7 and arrow_batch=2:
ArrowBatch.row_count=1, data=2.
+ service.execute_payload = message_field(7, schema) + message_field(
+ 2, varint_field(1, table.num_rows) + message_field(2,
sink.getvalue().to_pybytes()))
+
+ variant_type = pa.struct([pa.field("value", pa.binary(), False),
+ pa.field("metadata", pa.binary(), False,
{"variant": "true"})])
+ geometry_type = pa.struct([pa.field("srid", pa.int32(), False),
+ pa.field("wkb", pa.binary(), False)])
+ respond(data_type_proto({"type": "struct", "fields": [
+ {"name": "v", "type": "variant", "nullable": True, "metadata": {}},
+ {"name": "g", "type": "geometry(SRID:0)", "nullable": True,
"metadata": {}}]}),
+ pa.table({"v": pa.array([{"value": value, "metadata": metadata}],
variant_type),
+ "g": pa.array([{"srid": 0, "wkb": wkb}], geometry_type)}))
+ row = spark.range(1).collect()[0]
+ assert type(row.v) is T.VariantVal and vars(row.v) == {"value": value,
"metadata": metadata}
+ assert type(row.g) is T.Geometry and vars(row.g) == {"wkb": wkb, "srid": 0}
+
+
def test_str_of_variant_values_is_their_json_and_they_are_no_rows_as_pyspark():
# As PySpark's VariantVal: str is its JSON, in UTC, as toJson(); repr is
of its bytes. And
# as PySpark's createDataFrame, whose VariantVal has a __dict__, so that
it is a row, which
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]