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 e5b0911c [SPARK-61317][CONNECT][PYTHON] Raise for nanosecond
timestamps on every schema surface, as PySpark does
e5b0911c is described below
commit e5b0911cbd032c4e131d63322e938bd57b4a199f
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 09:40:57 2026 +0900
[SPARK-61317][CONNECT][PYTHON] Raise for nanosecond timestamps on every
schema surface, as PySpark does
### What changes were proposed in this pull request?
[SPARK-61317](https://issues.apache.org/jira/browse/SPARK-61317): Raise for
nanosecond timestamps on every schema surface, as PySpark does.
PySpark 4.3.0 cannot convert a nanosecond-precision timestamp
(`TIMESTAMP_NTZ(p)` or `TIMESTAMP_LTZ(p)` with p > 6) from the proto of a
schema, so every schema surface raises `PySparkValueError` with
`UNSUPPORTED_OPERATION` (`data type timestamp_ntz_nanos {precision: 9} is not
supported.`). The collecting APIs already raised it (SPARK-61249). This change
raises the same error from:
- the schema of a DataFrame (`df.schema`, and `df.schema.json()`),
`df.columns`, `df.dtypes`, `df.printSchema()` and `repr(df)`;
- a DDL string of a schema: `DataType.fromDDL`, `StructType.fromDDL`,
`createDataFrame(data, "a timestamp_ntz(9)")`, the return type of a UDF, and
the schema of `from_json` with such a DDL string (its result schema raises at
the schema surface, as in PySpark);
- `StructType.add("t", "timestamp_ntz(9)")`, which raises
`CANNOT_PARSE_DATATYPE` as PySpark does, since a name of a type takes only the
JSON names of PySpark's types.
The check runs on the schema from the server, before the Python types are
built, so the Rust types and the picklable nanosecond classes are unchanged.
`count`, `show`, `describe` and `isEmpty` keep working, as in PySpark.
### Why are the changes needed?
A user could still read the schema of such a frame: `spark.sql("SELECT
CAST('2020-01-01 00:00:00.123456789' AS TIMESTAMP_NTZ(9)) c").schema` returned
`struct<c:timestamp_ntz(7)>`, and `spark.createDataFrame([(1,)], "a
timestamp_ntz(9)")` raised a bare `AssertionError`. Official PySpark raises
`UNSUPPORTED_OPERATION` for each of these.
### Does this PR introduce _any_ user-facing change?
Yes. The schema surfaces listed above raise `PySparkValueError`
(`UNSUPPORTED_OPERATION`, or `CANNOT_PARSE_DATATYPE` for `StructType.add`) for
nanosecond timestamps, as PySpark does, instead of returning a schema or
failing with an `AssertionError`.
### How was this patch tested?
- `test_nanosecond_timestamps_are_not_collected_as_pyspark` (offline,
`test_dropin_offline.py`, extended with the schema surfaces, the DDL strings
and `StructType.add`; the mock returns the schema of the type) and the live
test of the same name (`test_dropin_e2e.py`, extended the same way, the
`spark.sql.timestampNanosTypes.enabled` conf set and unset as before).
- Checked against official PySpark 4.3.0 on the same server: for
`TIMESTAMP_NTZ(9)` and `TIMESTAMP_LTZ(7)` results, `schema`, `columns`,
`dtypes`, `printSchema`, `repr`, `schema.json()`, `createDataFrame` with a DDL
schema, `DataType.fromDDL`, `StructType.fromDDL` (a struct field too),
`from_json` with a DDL schema, `udf` with a DDL return type and
`StructType.add` raise the same error class, condition and message parameters.
`count`, `show`, `describe` and `isEmpty` give the same results.
- The offline test fails without this change (the schema surfaces return
the schema) and passes with it.
- The build of all tests, the offline Python suites (2927 passed, 8
skipped) with the rebuilt extension, the extended tests also under pytest 9.2,
and the live drop-in tests `-k "timestamp or ntz or lit"` (10 passed) against a
local Spark 4.3.0 server. Clippy reports no new diagnostics in the changed
lines.
### 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 #438 from HyukjinKwon/SPARK-61317-nanos-schema-surfaces.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 20 +++++++++++++-------
crates/pyspark-rs/src/session.rs | 1 +
crates/pyspark-rs/src/types.rs | 23 +++++++++++++++++++++--
python/tests/test_dropin_e2e.py | 28 +++++++++++++++++++++++++++-
python/tests/test_dropin_offline.py | 27 +++++++++++++++++++++++++++
5 files changed, 89 insertions(+), 10 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 6f59fe02..4799811d 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -2409,6 +2409,7 @@ impl PyDataFrame {
#[getter]
fn schema(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
let schema = py.detach(|| self.dataframe.schema()).to_pyerr()?;
+ check_nanosecond_timestamps(py, Some(&schema))?;
crate::types::data_type_to_py(py, &schema)
}
@@ -2448,6 +2449,9 @@ impl PyDataFrame {
/// Column names (a property, mirroring `DataFrame.columns`).
#[getter]
fn columns(&self, py: Python<'_>) -> PyResult<Vec<String>> {
+ // The schema is cached, so the names come from it without another
request.
+ let schema = py.detach(|| self.dataframe.schema()).to_pyerr()?;
+ check_nanosecond_timestamps(py, Some(&schema))?;
py.detach(|| self.dataframe.columns().to_pyerr())
}
@@ -2536,6 +2540,7 @@ impl PyDataFrame {
_ => None,
};
let schema = py.detach(|| self.dataframe.schema().to_pyerr())?;
+ check_nanosecond_timestamps(py, Some(&schema))?;
let depth = level
.map(crate::types::normalize_tree_depth)
.transpose()?
@@ -2548,9 +2553,9 @@ impl PyDataFrame {
/// Get the schema as a list of (name, type) tuples.
#[getter]
fn dtypes(&self, py: Python<'_>) -> PyResult<Vec<(String, String)>> {
- let spark_connect::types::DataType::Struct { fields } =
- py.detach(|| self.dataframe.schema().to_pyerr())?
- else {
+ let schema = py.detach(|| self.dataframe.schema().to_pyerr())?;
+ check_nanosecond_timestamps(py, Some(&schema))?;
+ let spark_connect::types::DataType::Struct { fields } = schema else {
unreachable!("schema() validates struct responses")
};
// As PySpark, a user-defined type is named by its simpleString(),
such as `vector`,
@@ -4295,10 +4300,11 @@ fn nanosecond_timestamp_text(data_type:
&spark_connect::types::DataType) -> Opti
}
}
-/// Raises as PySpark does for a result of `schema` with a
nanosecond-precision timestamp, which
-/// PySpark cannot convert from the proto of the schema: the collecting APIs
raise, though the
-/// Rust core collects these values in microseconds.
-fn check_nanosecond_timestamps(
+/// Raises as PySpark does for a schema with a nanosecond-precision timestamp,
which PySpark cannot
+/// convert from the proto of the schema: the collecting APIs and every schema
surface raise (the
+/// schema, columns, dtypes, printSchema, a DDL string of a schema), though
the Rust core keeps
+/// these values, and count, show and describe work.
+pub(crate) fn check_nanosecond_timestamps(
py: Python<'_>,
schema: Option<&spark_connect::types::DataType>,
) -> PyResult<()> {
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 3d503b5e..dfca928a 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -2918,6 +2918,7 @@ impl PySparkSession {
let data_type = py
.detach(|| self.session.parse_ddl(ddl).map_err(Box::new))
.to_pyerr()?;
+ crate::dataframe::check_nanosecond_timestamps(py, Some(&data_type))?;
crate::types::data_type_to_py(py, &data_type)
}
diff --git a/crates/pyspark-rs/src/types.rs b/crates/pyspark-rs/src/types.rs
index 669a1c91..0b9609af 100644
--- a/crates/pyspark-rs/src/types.rs
+++ b/crates/pyspark-rs/src/types.rs
@@ -2509,6 +2509,22 @@ impl PyStructType {
data_type.clone()
};
let dt = py_to_data_type(&type_object)?;
+ // As PySpark's `_parse_datatype_json_value`, a name of a type
that has no JSON name in
+ // PySpark (a nanosecond timestamp) is not a data type.
+ if data_type.is_instance_of::<pyo3::types::PyString>()
+ && matches!(
+ dt,
+ DataType::TimestampNtzNanos { .. } |
DataType::TimestampLtzNanos { .. }
+ )
+ {
+ let name: String = data_type.extract()?;
+ return Err(crate::column::raise_pyspark(
+ py,
+ "PySparkValueError",
+ "CANNOT_PARSE_DATATYPE",
+ &[("msg", &name)],
+ ));
+ }
let md = match metadata {
Some(d) => py_metadata_to_map(py, d)?,
None => BTreeMap::new(),
@@ -3880,9 +3896,12 @@ pub(crate) fn schema_data_type(
) -> PyResult<DataType> {
if schema.is_instance_of::<pyo3::types::PyString>() {
let ddl: String = schema.extract()?;
- return crate::errors::ResultExt::to_pyerr(
+ let parsed = crate::errors::ResultExt::to_pyerr(
py.detach(|| session.parse_ddl(&ddl).map_err(Box::new)),
- );
+ )?;
+ // As PySpark converts the parsed type from its proto, which fails for
a nanosecond timestamp.
+ crate::dataframe::check_nanosecond_timestamps(py, Some(&parsed))?;
+ return Ok(parsed);
}
py_to_data_type(schema)
}
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 56e9b684..17f527ba 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -484,12 +484,17 @@ def _run_in_time_zone(code, zone):
def test_nanosecond_timestamps_are_not_collected_as_pyspark(session):
# As PySpark's conversion of the schema from its proto: a TIMESTAMP_NTZ(p)
or TIMESTAMP_LTZ(p)
# with p > 6, also nested, raises UNSUPPORTED_OPERATION from every
collecting API, toPandas
- # and toArrow, while count, show and the microsecond timestamps keep
working.
+ # and toArrow, and from every schema surface (the schema, columns, dtypes,
printSchema, repr
+ # and json, and the DDL strings of the types), while count, show and the
microsecond
+ # timestamps keep working.
import datetime
import re
from pyspark.errors import PySparkValueError
+ from pyspark.sql.functions import from_json, lit
+ from pyspark.sql.types import DataType, StructType
+
def message(proto_text):
return r"\[UNSUPPORTED_OPERATION\] data type " + re.escape(proto_text)
+ r" is not supported\."
@@ -524,6 +529,27 @@ def
test_nanosecond_timestamps_are_not_collected_as_pyspark(session):
):
with pytest.raises(PySparkValueError,
match=message(proto_text)):
collect(df)
+ # The schema surfaces raise too: PySpark converts a schema from
its proto, so the
+ # schema of the frame, its columns and types, and the schema of a
DDL string do not.
+ for surface in (
+ lambda d: d.schema,
+ lambda d: d.columns,
+ lambda d: d.dtypes,
+ lambda d: d.printSchema(),
+ lambda d: repr(d),
+ lambda d: d.schema.json(),
+ ):
+ with pytest.raises(PySparkValueError,
match=message(proto_text)):
+ surface(df)
+ # The DDL strings of the types, as the server parses them.
+ for surface in (
+ lambda: session.createDataFrame([(1,)], "a timestamp_ntz(9)"),
+ lambda: DataType.fromDDL("timestamp_ntz(9)"),
+ lambda: StructType.fromDDL("a struct<x: timestamp_ntz(9)>"),
+ lambda: session.range(1).select(from_json(lit('{"a": 1}'), "a
timestamp_ntz(9)")).schema,
+ ):
+ with pytest.raises(PySparkValueError, match=message(ntz9)):
+ surface()
# Spark Connect and PySpark both count and show these results.
df = session.sql("SELECT CAST('2020-01-01 00:00:00.123456789' AS
TIMESTAMP_NTZ(9)) c")
assert df.count() == 1
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 21f84ced..ed520ade 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7580,6 +7580,33 @@ def
test_nanosecond_timestamps_are_not_collected_as_pyspark(
with pytest.raises(PySparkValueError, match=(
r"\[UNSUPPORTED_OPERATION\] data type " + re.escape(proto_text) +
r" is not supported\.")):
collect(df)
+ # The schema surfaces raise as well, as PySpark's, which converts a schema
from its proto: the
+ # analyzed schema of the frame and of a DDL string (the mock answers any
DDL it does not parse
+ # with its data type) are the struct, and CANNOT_PARSE_DATATYPE for a name
of the type.
+ from pyspark.sql import functions as F
+
+ service.data_type = struct
+ # repr reads the settings of the eager evaluation of the session, which
the server has.
+ service.confs = {"spark.sql.repl.eagerEval.enabled": "false",
+ "spark.sql.repl.eagerEval.maxNumRows": "20",
+ "spark.sql.repl.eagerEval.truncate": "20"}
+ message = (r"\[UNSUPPORTED_OPERATION\] data type " + re.escape(proto_text)
+ r" is not supported\.")
+ for surface in (
+ lambda: df.schema,
+ lambda: df.columns,
+ lambda: df.dtypes,
+ lambda: df.printSchema(),
+ lambda: repr(df),
+ lambda: df.schema.json(),
+ lambda: spark.createDataFrame([(1,)], "a timestamp_ntz(9)"),
+ lambda: T.DataType.fromDDL("timestamp_ntz(9)"),
+ lambda: T.StructType.fromDDL("a timestamp_ntz(9)"),
+ lambda: spark.range(1).select(F.from_json(F.lit("{}"), "a
timestamp_ntz(9)")).schema,
+ ):
+ with pytest.raises(PySparkValueError, match=message):
+ surface()
+ with pytest.raises(PySparkValueError,
match=r"CANNOT_PARSE_DATATYPE.*timestamp_ntz\(9\)"):
+ T.StructType().add("t", "timestamp_ntz(9)")
def test_udf_and_pandas_udf_decorator_forms(mock_connect):
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]