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 255186f2 [SPARK-61393][CONNECT][PYTHON] Accept the values that PySpark
accepts in the list arguments of the Column methods, and raise RecursionError
for a deep list, in the Python client
255186f2 is described below
commit 255186f28fe3e7e21d71566ffa95cd8d8b7e9834
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 08:56:34 2026 +0900
[SPARK-61393][CONNECT][PYTHON] Accept the values that PySpark accepts in
the list arguments of the Column methods, and raise RecursionError for a deep
list, in the Python client
### What changes were proposed in this pull request?
[SPARK-61393](https://issues.apache.org/jira/browse/SPARK-61393): a
follow-up of #454 (SPARK-61290), and of #463 (SPARK-61340), from a review of
them.
- The list arguments of `Column.when`/`otherwise`, `getItem` and `isin`
convert each element by the element type, as `LiteralExpression(value,
element_type)` of PySpark does, with the same class checks
(`crates/pyspark-rs/src/functions.rs`, `literal_as`):
- a Python int or a NumPy int of the width for the integral types, in
range;
- a float or `np.float32` for float, and a float, `np.float32` or
`np.float64` for double;
- any `datetime.date`, including a datetime (its date), for date;
- a datetime of a timestamp element by the already-chosen timestamp type,
without reading the timestamp conf again per element.
Values that PySpark rejects still raise `AssertionError`.
- The conversion converts each element once, so it is linear in the size of
the list. A list nested deeper than 988 levels raises `RecursionError`, as
PySpark's does, on a grown stack, instead of taking seconds and growing the
native stack.
- `scalar_literal`'s doc comment is back above it, and the wall clock of a
TIMESTAMP_NTZ literal is one function in `infer.rs`.
### Why are the changes needed?
`literal_as` accepted only an exact literal type (plus int to long and bool
to int or long), so lists that PySpark sends failed with a bare
`AssertionError`:
```python
F.when(F.lit(False),
F.array(F.lit(0.0).cast("float"))).otherwise([np.float32(1.5), 2.0])
# before: AssertionError after: array<float> [1.5, 2.0], as PySpark
F.when(F.lit(False), F.array(F.lit(0.0))).otherwise([1.5, np.float32(2.0)])
# before: AssertionError after: array<double> [1.5, 2.0], as PySpark
F.when(F.lit(False), F.array(F.lit(datetime.date(2000, 1, 1)))).otherwise(
[datetime.date(2020, 1, 1), datetime.datetime(2020, 1, 2, 3)])
# before: AssertionError after: array<date> [2020-01-01, 2020-01-02],
as PySpark
```
It also accepted a few that PySpark rejects (`[1, np.bool_(True)]`). The
first element of each nested list was converted twice at each level, so a list
nested 2000 levels deep took about 52 seconds, and 5000 levels did not finish.
PySpark raises `RecursionError` there.
### Does this PR introduce _any_ user-facing change?
Yes. List values that PySpark accepts in `when`, `otherwise`, `getItem` and
`isin` work in the Python client, the ones it rejects raise as it does, and a
list nested deeper than 988 levels raises `RecursionError` promptly.
### How was this patch tested?
- Offline tests in `python/tests/test_dropin_offline.py` compare the built
literal protos with those of PySpark 4.3.0 for the accepted cases, check the
rejected cases, check the depth bound and that a 900-level list builds in under
a second (it took 4.8 s before), and that a TIMESTAMP_NTZ `pd.Timestamp`
literal of nanoseconds gives no warning. 12 of the new cases fail without the
change.
- A live-server test in `python/tests/test_dropin_e2e.py` checks that the
server evaluates the arrays.
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--release --lib`, the `--no-run` builds, `cargo fmt --check`, and the offline
and e2e drop-in suites against a Spark 4.3.0 server.
### 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 #481 from HyukjinKwon/SPARK-61393-column-list-literals.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
Cargo.lock | 1 +
crates/pyspark-rs/Cargo.toml | 1 +
crates/pyspark-rs/src/functions.rs | 274 +++++++++++++++++++++++++++++-------
crates/pyspark-rs/src/infer.rs | 21 ++-
python/tests/test_dropin_e2e.py | 17 +++
python/tests/test_dropin_offline.py | 136 ++++++++++++++++++
6 files changed, 394 insertions(+), 56 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 4bc2ce2e..a79073d3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3421,6 +3421,7 @@ dependencies = [
"prost-types",
"pyo3",
"serde_json",
+ "stacker",
"tokio",
"tonic",
]
diff --git a/crates/pyspark-rs/Cargo.toml b/crates/pyspark-rs/Cargo.toml
index 3b9192cf..041d0f4b 100644
--- a/crates/pyspark-rs/Cargo.toml
+++ b/crates/pyspark-rs/Cargo.toml
@@ -30,3 +30,4 @@ prost.workspace = true
prost-types.workspace = true
tonic.workspace = true
serde_json = "1.0"
+stacker = "0.1"
diff --git a/crates/pyspark-rs/src/functions.rs
b/crates/pyspark-rs/src/functions.rs
index b7a33511..82293333 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -360,10 +360,63 @@ pub(crate) fn to_value_column(obj: &Bound<'_, PyAny>) ->
PyResult<Column> {
to_column(obj)
}
+/// How deep the lists of a Column method may nest. PySpark's
`LiteralExpression` recurses in
+/// Python for each level, so under Python's default recursion limit it raises
`RecursionError`
+/// for a list nested about 990 levels deep (a little less below a deeper
caller). A deeper list
+/// is a `RecursionError` here too, rather than a native stack overflow.
+const MAX_LIST_DEPTH: usize = 988;
+
+/// The stack that a level of nested lists keeps free before it goes down a
level, and the size of
+/// a stack segment that it adds when less is left, as for the levels of an
expression or a plan:
+/// a thread's stack may be smaller than the depth of a list needs, so a level
grows it.
+const LIST_RED_ZONE: usize = if cfg!(debug_assertions) {
+ 1 << 20
+} else {
+ 128 << 10
+};
+const LIST_STACK_SEGMENT: usize = if cfg!(debug_assertions) {
+ 16 << 20
+} else {
+ 4 << 20
+};
+
+/// Run `f`, which goes down a level of nested lists, with at least
[`LIST_RED_ZONE`] of stack left.
+fn with_stack_for_a_list_level<T>(f: impl FnOnce() -> T) -> T {
+ stacker::maybe_grow(LIST_RED_ZONE, LIST_STACK_SEGMENT, f)
+}
+
+thread_local! {
+ static LIST_DEPTH: std::cell::Cell<usize> = const {
std::cell::Cell::new(0) };
+}
+
+/// One more level of nested lists for as long as it lives.
+struct ListLevel;
+
+impl ListLevel {
+ fn enter() -> PyResult<ListLevel> {
+ LIST_DEPTH.with(|depth| {
+ if depth.get() >= MAX_LIST_DEPTH {
+ return Err(pyo3::exceptions::PyRecursionError::new_err(
+ "maximum recursion depth exceeded while converting a list
to a literal",
+ ));
+ }
+ depth.set(depth.get() + 1);
+ Ok(ListLevel)
+ })
+ }
+}
+
+impl Drop for ListLevel {
+ fn drop(&mut self) {
+ LIST_DEPTH.with(|depth| depth.set(depth.get() - 1));
+ }
+}
+
/// The array literal of a list, of the type of its first element, as PySpark's
-/// `LiteralExpression` infers it. Each element is then a literal of that
type, as
-/// `literal_as` makes it.
+/// `LiteralExpression` infers it. The first element's literal gives that
type, and each other
+/// element is converted to it once, by `literal_as`.
fn typed_array_literal(list: &Bound<'_, pyo3::types::PyList>) ->
PyResult<LiteralExpression> {
+ let _level = ListLevel::enter()?;
let Some(first) = list.iter().next().filter(|first| !first.is_none()) else
{
return Err(crate::column::raise_pyspark(
list.py(),
@@ -373,14 +426,14 @@ fn typed_array_literal(list: &Bound<'_,
pyo3::types::PyList>) -> PyResult<Litera
));
};
let first = match first.cast::<pyo3::types::PyList>() {
- Ok(inner) => typed_array_literal(inner)?,
+ Ok(inner) => with_stack_for_a_list_level(||
typed_array_literal(inner))?,
Err(_) => scalar_literal_of(&first)?,
};
let element_type = literal_data_type(&first);
- let elements = list
- .iter()
- .map(|item| literal_as(&item, &element_type))
- .collect::<PyResult<Vec<_>>>()?;
+ let mut elements = vec![first];
+ for item in list.iter().skip(1) {
+ elements.push(literal_as(&item, &element_type)?);
+ }
Ok(LiteralExpression::Array {
element_type: Box::new(element_type),
elements,
@@ -388,47 +441,184 @@ fn typed_array_literal(list: &Bound<'_,
pyo3::types::PyList>) -> PyResult<Litera
}
/// The literal of `obj` as a value of `data_type`, as PySpark's
`LiteralExpression(obj, type)`:
-/// None is a null, a list is an array of the element type, and another value
must be of the
-/// type, else a bare AssertionError, as PySpark's asserts raise. As in
Python, an int is a long
-/// and a bool is an int.
+/// None is a null, a list is an array of the element type, and another value
must be accepted
+/// for the type, by the Python or NumPy classes that PySpark's asserts take,
else it is a bare
+/// AssertionError. So an int is a byte, a short, an integer or a long only
within its range,
+/// and a bool is an int, but a float is none of them.
fn literal_as(
obj: &Bound<'_, PyAny>,
data_type: &spark_connect::types::DataType,
) -> PyResult<LiteralExpression> {
use spark_connect::types::DataType;
+ let obj = &enum_to_value(obj)?;
if obj.is_none() {
return Ok(LiteralExpression::Null(data_type.clone()));
}
let assertion = || pyo3::exceptions::PyAssertionError::new_err(());
- if let DataType::Array { element_type, .. } = data_type {
- let list = obj.cast::<pyo3::types::PyList>().map_err(|_| assertion())?;
- let elements = list
- .iter()
- .map(|item| literal_as(&item, element_type))
- .collect::<PyResult<Vec<_>>>()?;
- return Ok(LiteralExpression::Array {
- element_type: element_type.clone(),
- elements,
- });
- }
- if obj.is_instance_of::<pyo3::types::PyList>() {
- return Err(assertion());
- }
- match (scalar_literal_of(obj)?, data_type) {
- (LiteralExpression::Integer(value), DataType::Long) => {
- Ok(LiteralExpression::Long(i64::from(value)))
+ let literal = match data_type {
+ DataType::Array { element_type, .. } => {
+ let list = obj.cast::<pyo3::types::PyList>().map_err(|_|
assertion())?;
+ let _level = ListLevel::enter()?;
+ let elements = with_stack_for_a_list_level(|| {
+ list.iter()
+ .map(|item| literal_as(&item, element_type))
+ .collect::<PyResult<Vec<_>>>()
+ })?;
+ LiteralExpression::Array {
+ element_type: element_type.clone(),
+ elements,
+ }
+ }
+ DataType::Boolean => {
+ if !(obj.is_instance_of::<pyo3::types::PyBool>() ||
is_numpy_scalar(obj, &["bool_"])?) {
+ return Err(assertion());
+ }
+ LiteralExpression::Boolean(obj.is_truthy()?)
+ }
+ DataType::Byte => {
+ LiteralExpression::Byte(
+ integral_value(obj, &["int8"], i8::MIN.into(),
i8::MAX.into())? as i32,
+ )
+ }
+ DataType::Short => LiteralExpression::Short(integral_value(
+ obj,
+ &["int8", "int16"],
+ i16::MIN.into(),
+ i16::MAX.into(),
+ )? as i32),
+ DataType::Integer => LiteralExpression::Integer(integral_value(
+ obj,
+ &["int8", "int16", "int32"],
+ i32::MIN.into(),
+ i32::MAX.into(),
+ )? as i32),
+ DataType::Long => LiteralExpression::Long(integral_value(
+ obj,
+ &["int8", "int16", "int32", "int64"],
+ i64::MIN,
+ i64::MAX,
+ )?),
+ DataType::Float => {
+ if !(obj.is_instance_of::<pyo3::types::PyFloat>()
+ || is_numpy_scalar(obj, &["float32"])?)
+ {
+ return Err(assertion());
+ }
+ LiteralExpression::Float(obj.extract::<f64>()? as f32)
}
- (LiteralExpression::Boolean(value), DataType::Integer) => {
- Ok(LiteralExpression::Integer(i32::from(value)))
+ DataType::Double => {
+ if !(obj.is_instance_of::<pyo3::types::PyFloat>()
+ || is_numpy_scalar(obj, &["float32", "float64"])?)
+ {
+ return Err(assertion());
+ }
+ LiteralExpression::Double(obj.extract::<f64>()?)
}
- (LiteralExpression::Boolean(value), DataType::Long) => {
- Ok(LiteralExpression::Long(i64::from(value)))
+ DataType::Decimal { precision, scale } => {
+ if !is_instance_of_class(obj, "decimal", "Decimal")? {
+ return Err(assertion());
+ }
+ LiteralExpression::Decimal {
+ value: obj.str()?.extract()?,
+ precision: *precision,
+ scale: *scale,
+ }
+ }
+ DataType::String { .. } => {
+ if !obj.is_instance_of::<pyo3::types::PyString>() {
+ return Err(assertion());
+ }
+ match obj.extract::<String>() {
+ Ok(s) => LiteralExpression::String(s),
+ // A str that UTF-8 cannot encode, as in `to_column`.
+ Err(_) => return Err(not_utf8_string(obj)),
+ }
}
- (literal, data_type) if literal_data_type(&literal) == *data_type =>
Ok(literal),
+ DataType::Binary => {
+ if !(obj.is_instance_of::<pyo3::types::PyBytes>()
+ || obj.is_instance_of::<pyo3::types::PyByteArray>())
+ {
+ return Err(assertion());
+ }
+ LiteralExpression::Binary(obj.extract::<Vec<u8>>()?)
+ }
+ DataType::Date => {
+ // A datetime is a date too, and its date is the one of the
literal.
+ if !is_instance_of_class(obj, "datetime", "date")? {
+ return Err(assertion());
+ }
+ let ordinal: i64 = obj.call_method0("toordinal")?.extract()?;
+ // 719163 is the ordinal of 1970-01-01.
+ LiteralExpression::Date((ordinal - 719163i64) as i32)
+ }
+ DataType::Time { precision } => {
+ if !is_instance_of_class(obj, "datetime", "time")? {
+ return Err(assertion());
+ }
+ LiteralExpression::Time {
+ nano: crate::infer::time_nanos(obj)?,
+ precision: *precision,
+ }
+ }
+ DataType::Timestamp => {
+ if !is_instance_of_class(obj, "datetime", "datetime")? {
+ return Err(assertion());
+ }
+
LiteralExpression::Timestamp(crate::session::datetime_to_micros(obj)?)
+ }
+ DataType::TimestampNtz => {
+ if !is_instance_of_class(obj, "datetime", "datetime")? {
+ return Err(assertion());
+ }
+
LiteralExpression::TimestampNtz(crate::infer::wall_clock_micros(obj)?)
+ }
+ DataType::DayTimeInterval { .. } => {
+ if !is_instance_of_class(obj, "datetime", "timedelta")? {
+ return Err(assertion());
+ }
+
LiteralExpression::DayTimeInterval(crate::infer::timedelta_micros(obj)?)
+ }
+ // Another type is not a value of a list's elements, as PySpark's
asserts take it.
+ _ => return Err(assertion()),
+ };
+ Ok(literal)
+}
+
+/// The value of `obj` as an integer within `min..=max`, for an integer type
of PySpark's
+/// `LiteralExpression`: a Python int (a bool included), or a NumPy int of one
of `numpy`.
+fn integral_value(obj: &Bound<'_, PyAny>, numpy: &[&str], min: i64, max: i64)
-> PyResult<i64> {
+ let assertion = || pyo3::exceptions::PyAssertionError::new_err(());
+ if !(obj.is_instance_of::<pyo3::types::PyInt>() || is_numpy_scalar(obj,
numpy)?) {
+ return Err(assertion());
+ }
+ match obj.extract::<i64>() {
+ Ok(value) if (min..=max).contains(&value) => Ok(value),
_ => Err(assertion()),
}
}
+/// Whether `obj` is an instance of the class `name` of the module `module`.
+fn is_instance_of_class(obj: &Bound<'_, PyAny>, module: &str, name: &str) ->
PyResult<bool> {
+ let class = obj.py().import(module)?.getattr(name)?;
+ obj.is_instance(&class)
+}
+
+/// Whether `obj` is an instance of one of the NumPy scalar classes `classes`,
such as `int8`.
+/// NumPy is looked up in `sys.modules`, as a NumPy scalar exists only when
NumPy is imported.
+fn is_numpy_scalar(obj: &Bound<'_, PyAny>, classes: &[&str]) -> PyResult<bool>
{
+ let modules = obj.py().import("sys")?.getattr("modules")?;
+ let numpy = match
modules.cast::<pyo3::types::PyDict>()?.get_item("numpy")? {
+ Some(numpy) if !numpy.is_none() => numpy,
+ _ => return Ok(false),
+ };
+ for class in classes {
+ if obj.is_instance(&numpy.getattr(*class)?)? {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+}
+
/// The literal of a value that is not a list, as `to_column` builds it.
fn scalar_literal_of(obj: &Bound<'_, PyAny>) -> PyResult<LiteralExpression> {
match to_column(obj)?.expression().node() {
@@ -587,20 +777,6 @@ fn numpy_scalar_literal(obj: &Bound<'_, PyAny>) ->
PyResult<Option<LiteralExpres
/// `decimal.Decimal`, `bytes`/`bytearray`). Returns `None` if `obj` is not
one of them,
/// so the caller falls through to the primitive int/float/str/bool checks.
Kept in sync
/// with `session::py_to_value` so `lit(..)` and `createDataFrame(..)` encode
identically.
-/// The microseconds of the wall clock of a datetime, naive or aware, as
PySpark's
-/// `TimestampNTZType.toInternal` takes them: `calendar.timegm` of its own
time tuple, whatever
-/// its zone. A pandas Timestamp's fields are read from it, as PySpark's, so
its nanoseconds are
-/// dropped silently, as for a TIMESTAMP.
-fn wall_clock_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
- let py = obj.py();
- let seconds: i64 = py
- .import("calendar")?
- .call_method1("timegm", (obj.call_method0("timetuple")?,))?
- .extract()?;
- let micros: i64 = obj.getattr("microsecond")?.extract()?;
- Ok(seconds * 1_000_000 + micros)
-}
-
fn scalar_literal(obj: &Bound<'_, PyAny>) ->
PyResult<Option<LiteralExpression>> {
let py = obj.py();
@@ -632,9 +808,9 @@ fn scalar_literal(obj: &Bound<'_, PyAny>) ->
PyResult<Option<LiteralExpression>>
.call_method0("is_timestamp_ntz_preferred")?
.is_truthy()?
{
- return
Ok(Some(LiteralExpression::TimestampNtz(wall_clock_micros(
- obj,
- )?)));
+ return Ok(Some(LiteralExpression::TimestampNtz(
+ crate::infer::wall_clock_micros(obj)?,
+ )));
}
// Shared with session::py_to_value so lit() and createDataFrame()
agree (a pandas
// Timestamp's .timestamp() treats a naive value as UTC; normalize
it first).
diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index 4e4c23d6..a0a05eac 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -1137,14 +1137,21 @@ fn instant_micros(obj: &Bound<'_, PyAny>) ->
PyResult<i64> {
delta_micros(&aware.sub(epoch)?)
}
-/// Microseconds since 1970-01-01 00:00 of the wall-clock time of a naive
datetime, as
-/// PyArrow takes a TIMESTAMP_NTZ value.
-fn wall_clock_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
+/// The microseconds of the wall clock of a datetime, naive or aware, as
PySpark's
+/// `TimestampNTZType.toInternal` takes them: `calendar.timegm` of its own
time tuple, whatever
+/// its zone. The fields of a pandas Timestamp are read from it, as PySpark's,
so its nanoseconds
+/// are dropped silently. The naive values are those of a TIMESTAMP_NTZ, as
PyArrow takes them.
+pub(crate) fn wall_clock_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
let py = obj.py();
- let epoch = DATETIME
- .import(py, "datetime", "datetime")?
- .call1((1970, 1, 1))?;
- delta_micros(&obj.sub(epoch)?)
+ let seconds: i64 = py
+ .import(intern!(py, "calendar"))?
+ .call_method1(
+ intern!(py, "timegm"),
+ (obj.call_method0(intern!(py, "timetuple"))?,),
+ )?
+ .extract()?;
+ let micros: i64 = obj.getattr(intern!(py, "microsecond"))?.extract()?;
+ Ok(seconds * 1_000_000 + micros)
}
/// A field value of `dt` from `obj`, as PySpark's converters and then PyArrow
convert it.
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 29d385d5..c7d48dd4 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -104,6 +104,23 @@ def
test_udtfs_of_ddl_return_types_are_unparsed_as_pyspark(session):
+def
test_list_values_of_column_methods_are_evaluated_by_the_server_as_pyspark(session):
+ # As PySpark's LiteralExpression of a list: each element is of the type
that the first one
+ # gives the list, when the type accepts it, so the server evaluates the
array of the value.
+ import numpy as np
+
+ df = session.range(1)
+ when = F.when(F.lit(False), F.array(F.lit(0.0).cast("float")))
+ assert df.select(when.otherwise([np.float32(1.5),
2.0]).alias("r")).collect() == [
+ Row(r=[1.5, 2.0])]
+ when = F.when(F.lit(False), F.array(F.lit(0.0)))
+ assert df.select(when.otherwise([1.5,
np.float32(2.0)]).alias("r")).collect() == [
+ Row(r=[1.5, 2.0])]
+ when = F.when(F.lit(False), F.array(F.lit(date(2000, 1, 1))))
+ assert df.select(when.otherwise([date(2020, 1, 1), datetime(2020, 1, 2,
3)]).alias("r")
+ ).collect() == [Row(r=[date(2020, 1, 1), date(2020, 1,
2)])]
+
+
def test_udf_and_udtf_calls_take_named_arguments_as_pyspark(session):
# As PySpark's: the keyword arguments of a UDF or UDTF call are its named
arguments, and
# a bare string is a column name.
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 236bcf70..c53cbc79 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -21,6 +21,7 @@ from concurrent.futures import ThreadPoolExecutor
from fractions import Fraction
from threading import Barrier
+import numpy as np
import pytest
from _mock_connect_server import (
@@ -2200,6 +2201,141 @@ def
test_functions_lit_of_a_list_stays_an_array_as_pyspark():
assert when.arguments[1].unresolved_function.function_name == "array"
[email protected]("base, value, expected", [
+ # A NumPy float32 or a float in a float array, a float in a double array,
and a datetime in a
+ # date array, which is its date.
+ (lambda F: F.array(F.lit(0.0).cast("float")), [np.float32(1.5), 2.0],
+ {"array": {"elementType": {"float": {}},
+ "elements": [{"float": 1.5}, {"float": 2.0}]}}),
+ (lambda F: F.array(F.lit(0.0)), [1.5, np.float32(2.0)],
+ {"array": {"elementType": {"double": {}},
+ "elements": [{"double": 1.5}, {"double": 2.0}]}}),
+ (lambda F: F.array(F.lit(datetime.date(2000, 1, 1))),
+ [datetime.date(2020, 1, 1), datetime.datetime(2020, 1, 2, 3)],
+ {"array": {"elementType": {"date": {}},
+ "elements": [{"date": 18262}, {"date": 18263}]}}),
+])
+def test_when_otherwise_takes_a_list_of_the_values_that_pyspark_accepts(base,
value, expected):
+ # As PySpark's LiteralExpression of the list: its element type is that of
the first element,
+ # and each other element must be accepted for that type, as the type says.
+ from google.protobuf.json_format import MessageToDict
+ from pyspark.sql import functions as F
+
+ when = F.when(F.lit(False),
base(F)).otherwise(value)._expr.to_plan(None).unresolved_function
+ assert MessageToDict(when.arguments[2].literal) == expected
+
+
[email protected]("value, expected", [
+ # Each element is of the element type of the first, as PySpark's
LiteralExpression makes it:
+ # a Python int is a byte, a short, an integer or a long that is in its
range, a bool is an
+ # int, and a NumPy int is accepted for its own width and the wider ones.
+ ([np.int8(1), 2], {"elementType": {"byte": {}},
+ "elements": [{"byte": 1}, {"byte": 2}]}),
+ ([np.int16(1), np.int8(2)], {"elementType": {"short": {}},
+ "elements": [{"short": 1}, {"short": 2}]}),
+ ([np.int32(1), np.int8(2)], {"elementType": {"integer": {}},
+ "elements": [{"integer": 1}, {"integer":
2}]}),
+ ([1, np.int8(2)], {"elementType": {"integer": {}},
+ "elements": [{"integer": 1}, {"integer": 2}]}),
+ ([np.int64(1), 2], {"elementType": {"long": {}},
+ "elements": [{"long": "1"}, {"long": "2"}]}),
+ ([np.float32(1.5), 2.0], {"elementType": {"float": {}},
+ "elements": [{"float": 1.5}, {"float": 2.0}]}),
+ ([1.5, np.float64(2.0)], {"elementType": {"double": {}},
+ "elements": [{"double": 1.5}, {"double": 2.0}]}),
+ ([datetime.date(2020, 1, 1), datetime.datetime(2020, 1, 2, 3)],
+ {"elementType": {"date": {}}, "elements": [{"date": 18262}, {"date":
18263}]}),
+ ([[datetime.date(2020, 1, 1)], [datetime.datetime(2020, 1, 2, 3)]], {
+ "elementType": {"array": {"elementType": {"date": {}}, "containsNull":
True}},
+ "elements": [{"array": {"elementType": {"date": {}}, "elements":
[{"date": 18262}]}},
+ {"array": {"elementType": {"date": {}}, "elements":
[{"date": 18263}]}}]}),
+ (["a", np.str_("b")], {"elementType": {"string": {"collation":
"UTF8_BINARY"}},
+ "elements": [{"string": "a"}, {"string": "b"}]}),
+ ([b"a", bytearray(b"b")], {"elementType": {"binary": {}},
+ "elements": [{"binary": "YQ=="}, {"binary":
"Yg=="}]}),
+ ([datetime.timedelta(1), datetime.timedelta(seconds=2)], {
+ "elementType": {"dayTimeInterval": {"startField": 0, "endField": 3}},
+ "elements": [{"dayTimeInterval": "86400000000"}, {"dayTimeInterval":
"2000000"}]}),
+ ([datetime.time(1, 2, 3), datetime.time(4, 5, 6, 7)], {
+ "elementType": {"time": {"precision": 6}},
+ "elements": [{"time": {"nano": "3723000000000", "precision": 6}},
+ {"time": {"nano": "14706000007000", "precision": 6}}]}),
+])
+def test_column_methods_take_the_list_of_values_that_pyspark_accepts(value,
expected):
+ from google.protobuf.json_format import MessageToDict
+ from pyspark.sql import functions as F
+
+ extraction =
F.col("a").getItem(value)._expr.to_plan(None).unresolved_extract_value.extraction
+ assert MessageToDict(extraction.literal) == {"array": expected}
+
+
[email protected]("value", [
+ [np.int8(1), 300],
+ [np.int8(1), 2 ** 40],
+ [np.int8(1), np.int16(2)],
+ [np.int8(1), np.int32(2)],
+ [np.int32(1), np.int64(2)],
+ [1, np.int64(2)],
+ [1, np.bool_(True)],
+ [1, 1.5],
+ [1.5, 2],
+ [datetime.datetime(2020, 1, 2, 3), datetime.date(2020, 1, 1)],
+ [decimal.Decimal("1.5"), 2],
+])
+def test_column_methods_reject_a_list_value_that_pyspark_rejects(value):
+ # As PySpark's asserts: another type than the element type's, or an int
out of its range.
+ from pyspark.sql import functions as F
+
+ with pytest.raises(AssertionError):
+ F.col("a").getItem(value)._expr.to_plan(None)
+
+
+def _nested_list(depth):
+ value = 1.5
+ for _ in range(depth):
+ value = [value]
+ return value
+
+
+def
test_column_methods_build_a_deep_list_and_raise_recursion_error_past_the_bound():
+ # As PySpark's LiteralExpression, which recurses for each level of a list,
so a list nested
+ # about 1000 levels deep raises RecursionError. A list of 900 levels is
built at once, as each
+ # level converts its elements once, where converting the first element
twice took many seconds.
+ from pyspark.sql import functions as F
+
+ start = time.time()
+ F.col("a").getItem(_nested_list(900))
+ assert time.time() - start < 1.0
+ deep = _nested_list(2000)
+ for build in (
+ lambda: F.col("a").getItem(deep),
+ lambda: F.col("a").isin(deep),
+ lambda: F.when(F.lit(False), F.lit(0.0)).otherwise(deep),
+ ):
+ with pytest.raises(RecursionError):
+ build()
+
+
+def
test_lit_of_a_timestamp_under_ntz_is_its_wall_clock_without_a_warning(mock_connect):
+ # As PySpark's TimestampNTZType.toInternal, which reads the fields of the
value: the
+ # nanoseconds of a pandas Timestamp are dropped silently, where its
to_pydatetime() warns,
+ # and an aware datetime is the wall clock that it shows.
+ import pandas as pd
+ import warnings
+ from pyspark.sql import functions as F
+
+ _, service = mock_connect
+ service.confs = {"spark.sql.timestampType": "TIMESTAMP_NTZ"}
+ aware = datetime.datetime(
+ 2020, 1, 2, 3, 4, 5,
tzinfo=datetime.timezone(datetime.timedelta(hours=5)))
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ column = F.lit(pd.Timestamp("2020-06-01 12:00:00.000000123"))
+ aware_column = F.lit(aware)
+ assert column._expr.to_plan(None).literal.timestamp_ntz == 1591012800000000
+ assert aware_column._expr.to_plan(None).literal.timestamp_ntz ==
1577934245000000
+
+
def test_map_functions_send_their_resource_profile_as_pyspark(mock_connect):
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]