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 c31f6bda [SPARK-61249][CONNECT][PYTHON] Raise for out-of-range 
createDataFrame integers and nanosecond timestamps in collect, as PySpark does
c31f6bda is described below

commit c31f6bdafeda7f3728b8b050db6c655f78c97726
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 21:01:46 2026 +0900

    [SPARK-61249][CONNECT][PYTHON] Raise for out-of-range createDataFrame 
integers and nanosecond timestamps in collect, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61249](https://issues.apache.org/jira/browse/SPARK-61249): Raise for 
out-of-range integers in `createDataFrame` and collect nanosecond timestamps in 
microseconds, raising in the Python client for them as PySpark does.
    
    - `createDataFrame` (`crates/spark-connect/src/session.rs`): an integer 
value that does not fit its declared integer type is an error naming the value 
and the type, instead of an `as` cast that wraps it. In-range narrowing and 
widening are unchanged. The float encoder is unchanged: a finite double beyond 
the float range becomes infinity, as official PySpark 4.3.0 gives (`inf` for 
1e300 into FLOAT, with no error).
    - Collect of `TIMESTAMP_NTZ(p)` and `TIMESTAMP_LTZ(p)` with p > 6 
(`crates/spark-connect/src/dataframe.rs`): the nanoseconds are floored to 
microseconds (`div_euclid`) instead of truncated toward zero. The collecting 
API and the `Value` variants document that collect gives microseconds, while 
`to_arrow` keeps nanoseconds.
    - Python drop-in (`crates/pyspark-rs/src/dataframe.rs`): `collect`, 
`first`, `head`, `take`, `tail`, `toLocalIterator`, `toPandas` and `toArrow` 
raise `PySparkValueError` `UNSUPPORTED_OPERATION` for a result whose schema 
holds a nanosecond timestamp, nested or not, with the message PySpark gives 
(`data type timestamp_ntz_nanos {\n  precision: 9\n}\n is not supported.`). 
`count` and `show` keep working, as in PySpark. Every other type is unchanged.
    
    ### Why are the changes needed?
    
    - `spark.createDataFrame([(300,)], "b TINYINT").collect()` returned 
`Row(b=44)` on master, and `4294967297` into an `INT` column returned `1`. 
PySpark 4.3.0 raises `ArrowInvalid` ("Value 300 too large to fit in C integer 
type") for these, and so does the Python drop-in, which checks first.
    - `spark.sql("SELECT CAST('1969-12-31 23:59:59.1234567' AS 
TIMESTAMP_NTZ(7))").collect()` returned the microsecond value -876543 for the 
correct floor -876544, and the sub-microsecond digits were dropped silently. 
PySpark 4.3.0 refuses to collect these types with `PySparkValueError` 
`UNSUPPORTED_OPERATION`, from `collect`, `first`, `head`, `take`, `tail`, 
`toLocalIterator`, `toPandas` and `toArrow`, and the drop-in returned the 
values.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    - An out-of-range integer in `createDataFrame` through the Rust API is an 
error, not a wrapped value.
    - Collecting a `TIMESTAMP_NTZ(p)` or `TIMESTAMP_LTZ(p)` value with p > 6 
raises in the Python client as in PySpark. The Rust API returns microseconds, 
floored.
    - Not changed: the drop-in's `schema` property. PySpark 4.3.0 raises for 
these types in `df.schema` too (checked; `columns` not checked); this PR leaves 
`schema` unchanged.
    
    ### How was this patch tested?
    
    - Rust unit tests in `crates/spark-connect/src/session.rs` (`mod tests`): 
`integers_that_do_not_fit_the_declared_type_are_errors_not_wrapped` (7 
out-of-range cases for TINYINT, SMALLINT, INT and BIGINT, for the value and the 
batch path), `integers_that_fit_the_declared_type_still_narrow_and_widen`, and 
`a_double_beyond_the_float_range_is_infinite_as_in_pyspark`.
    - Rust unit test in `crates/spark-connect/src/dataframe.rs` (`mod 
arrow_value_tests`): 
`nanosecond_timestamps_floor_to_micros_at_top_level_and_nested`, at top level, 
in a struct and in an array. The existing 
`typed_scalar_layouts_preserve_exact_values_and_normalization` expectation for 
-1999 ns changes from -1 to -2 us, which is the floored value.
    - Python live test 
`test_nanosecond_timestamps_are_not_collected_as_pyspark` in 
`python/tests/test_dropin_e2e.py`: five queries (NTZ(9), LTZ(7), a struct, an 
array, a map) through the nine APIs, and `count`, `show` and an NTZ(6) collect 
that still work.
    - Python offline test 
`test_nanosecond_timestamps_are_not_collected_as_pyspark` in 
`python/tests/test_dropin_offline.py`, with a mock server: top level, array and 
struct nesting through the collecting APIs and `toArrow`.
    - The new Python tests fail without the guard (21 offline, 1 live). The new 
Rust tests fail with the wrapping cast and the truncating division restored.
    - The same cases give the same results with official PySpark 4.3.0 on the 
same server: the integer cases raise `ArrowInvalid`, 1e300 into FLOAT gives 
`inf`, and the nanosecond timestamps raise `PySparkValueError` 
`UNSUPPORTED_OPERATION` in each API above (`count` and `show` work).
    - The live Rust tests `e2e_dataframe` (4 passed), `e2e_coverage` (25 
passed) and `e2e_integration` (17 passed) against a local Spark 4.3.0 server.
    - The lib tests of both crates (668 passed), the build of all tests, also 
with `wasm-udf`, the offline Python suites (2840 passed, 8 skipped), and the 
live drop-in and Arrow suites (234 passed) and live cases (13 passed) against a 
local Spark 4.3.0 server. Clippy reports no 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 #427 from HyukjinKwon/SPARK-61249-numeric-range-and-nanos.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs    |  51 ++++++++++++++++
 crates/spark-connect/src/dataframe.rs |  59 +++++++++++++++++-
 crates/spark-connect/src/row.rs       |   6 +-
 crates/spark-connect/src/session.rs   | 109 ++++++++++++++++++++++++++++++----
 python/tests/test_dropin_e2e.py       |  47 +++++++++++++++
 python/tests/test_dropin_offline.py   |  55 +++++++++++++++++
 6 files changed, 312 insertions(+), 15 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 426538a5..d023a04a 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -108,6 +108,7 @@ impl PyDataFrame {
         let (batches, schema) = py
             .detach(|| self.dataframe.collect_record_batches_with_schema())
             .to_pyerr()?;
+        check_nanosecond_timestamps(py, schema.as_ref())?;
         let table = crate::pyarrow_export::record_batches_to_pyarrow(py, 
batches)?;
         let schema = match &schema {
             Some(schema) => crate::types::data_type_to_py(py, schema)?,
@@ -2246,6 +2247,7 @@ impl PyDataFrame {
                     .map_err(Box::new)
             })
             .to_pyerr()?;
+        check_nanosecond_timestamps(py, schema.as_ref())?;
         let table = crate::pyarrow_export::record_batches_to_pyarrow(py, 
batches)?;
         let Some(schema) = schema else {
             return Ok(table);
@@ -4267,6 +4269,53 @@ fn check_arrow_schema(
     Ok(())
 }
 
+/// The proto text of the first nanosecond-precision timestamp of `data_type`, 
`TIMESTAMP_NTZ(p)`
+/// or `TIMESTAMP_LTZ(p)` with p > 6, in the order of PySpark's conversion of 
a schema from its
+/// proto: the message that PySpark's `proto_schema_to_pyspark_data_type` 
names when it fails.
+fn nanosecond_timestamp_text(data_type: &spark_connect::types::DataType) -> 
Option<String> {
+    use spark_connect::types::DataType;
+    match data_type {
+        DataType::TimestampNtzNanos { precision } => Some(format!(
+            "timestamp_ntz_nanos {{\n  precision: {precision}\n}}\n"
+        )),
+        DataType::TimestampLtzNanos { precision } => Some(format!(
+            "timestamp_ltz_nanos {{\n  precision: {precision}\n}}\n"
+        )),
+        DataType::Struct { fields } => fields
+            .iter()
+            .find_map(|field| nanosecond_timestamp_text(&field.data_type)),
+        DataType::Array { element_type, .. } => 
nanosecond_timestamp_text(element_type),
+        DataType::Map {
+            key_type,
+            value_type,
+            ..
+        } => nanosecond_timestamp_text(key_type).or_else(|| 
nanosecond_timestamp_text(value_type)),
+        DataType::Udt {
+            sql_type: Some(sql_type),
+            ..
+        } => nanosecond_timestamp_text(sql_type),
+        _ => None,
+    }
+}
+
+/// 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(
+    py: Python<'_>,
+    schema: Option<&spark_connect::types::DataType>,
+) -> PyResult<()> {
+    if let Some(text) = schema.and_then(nanosecond_timestamp_text) {
+        return Err(crate::column::raise_pyspark(
+            py,
+            "PySparkValueError",
+            "UNSUPPORTED_OPERATION",
+            &[("operation", &format!("data type {text}"))],
+        ));
+    }
+    Ok(())
+}
+
 /// Raises as PySpark's Arrow conversion of the rows does for a result of 
`schema` with a
 /// year-month interval, which Spark Connect cannot collect: the error is 
raised even when the
 /// result has no rows.
@@ -4311,6 +4360,7 @@ fn rows_to_py(
     rows: &[spark_connect::row::Row],
     schema: Option<&spark_connect::types::DataType>,
 ) -> PyResult<Vec<Py<PyAny>>> {
+    check_nanosecond_timestamps(py, schema)?;
     check_arrow_schema(py, schema)?;
     let binary_as_bytes = read_binary_as_bytes(py, dataframe)?;
     check_collectable(py, schema)?;
@@ -4398,6 +4448,7 @@ impl PyLocalRowIterator {
         if self.converters.is_none() {
             if let Some(schema) = 
self.iterator.as_ref().and_then(LocalRowIterator::schema) {
                 // The result is known once its first message arrives, 
possibly with no rows.
+                check_nanosecond_timestamps(py, Some(&schema))?;
                 check_collectable(py, Some(&schema))?;
                 self.converters = Some(udt_field_converters(py, 
Some(&schema))?);
                 self.nested_fields.note_udt_key_maps(&schema);
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 346bb6dc..0d496cdd 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -910,7 +910,9 @@ impl DataFrame {
         crate::group::GroupedData::new(self.clone(), group_cols, 
AggregateGroupType::GroupBy)
     }
 
-    /// Collect all rows into memory.
+    /// Collect all rows into memory. A `TIMESTAMP(p)` or `TIMESTAMP_NTZ(p)` 
value with p > 6
+    /// is collected in microseconds, its sub-microsecond digits rounded down 
(`to_arrow` keeps
+    /// them); the Python client refuses to collect these types, as PySpark 
does.
     pub fn collect(&self) -> Result<Vec<Row>> {
         self.collect_with_schema().map(|(rows, _)| rows)
     }
@@ -3042,8 +3044,10 @@ impl<'a> ArrowValueLayout<'a> {
                 arr.value(index) * 1_000,
                 arr.timezone().is_some(),
             )),
+            // Collect gives microseconds: floor, so a pre-1970 value keeps 
its sign and its
+            // sub-microsecond digits round down as Spark's micros do 
(`to_arrow` keeps nanos).
             ArrowValueDecoder::TimestampNanosecond(arr) => Ok(timestamp_value(
-                arr.value(index) / 1_000,
+                arr.value(index).div_euclid(1_000),
                 arr.timezone().is_some(),
             )),
             ArrowValueDecoder::Date64(arr) => {
@@ -5264,8 +5268,9 @@ mod arrow_value_tests {
                 Value::Timestamp(-1_000),
             ),
             (
+                // Collect floors nanoseconds to microseconds: -1.999 us is -2 
us.
                 
Arc::new(TimestampNanosecondArray::from(vec![-1999]).with_timezone_utc()),
-                Value::Timestamp(-1),
+                Value::Timestamp(-2),
             ),
             // Without a time zone, as TIMESTAMP_NTZ is declared.
             (
@@ -5489,6 +5494,54 @@ mod arrow_value_tests {
         ));
     }
 
+    #[test]
+    fn nanosecond_timestamps_floor_to_micros_at_top_level_and_nested() {
+        use arrow::buffer::OffsetBuffer;
+        use arrow::datatypes::TimeUnit;
+
+        // Division toward zero put a pre-1970 value with sub-microsecond 
digits one microsecond
+        // too high; collect floors to micros instead, and keeps post-1970 
values.
+        let times = [-876_543_300i64, -1, -1_000, 1_577_836_800_123_456_789];
+        let expected = [-876_544i64, -1, -1, 1_577_836_800_123_456];
+        for (index, micros) in expected.into_iter().enumerate() {
+            let array = TimestampNanosecondArray::from(times.to_vec());
+            assert_eq!(
+                arrow_value_at(&array, index).unwrap(),
+                Value::TimestampNtz(micros)
+            );
+            let zoned = 
TimestampNanosecondArray::from(times.to_vec()).with_timezone_utc();
+            assert_eq!(
+                arrow_value_at(&zoned, index).unwrap(),
+                Value::Timestamp(micros)
+            );
+        }
+
+        let nanos_type = ArrowDataType::Timestamp(TimeUnit::Nanosecond, None);
+        let field = Arc::new(Field::new("t", nanos_type.clone(), false));
+        let col: ArrayRef = 
Arc::new(TimestampNanosecondArray::from(vec![-876_543_300i64]));
+        let s = StructArray::from(vec![(field, col)]);
+        match arrow_value_at(&s, 0).unwrap() {
+            Value::Struct(row) => assert_eq!(row.values()[0], 
Value::TimestampNtz(-876_544)),
+            other => panic!("expected a struct, got {other:?}"),
+        }
+
+        let item = Arc::new(Field::new("item", nanos_type, true));
+        let values = TimestampNanosecondArray::from(vec![-1i64, 1_000_001]);
+        let list = ListArray::new(
+            item,
+            OffsetBuffer::from_lengths([2]),
+            Arc::new(values),
+            None,
+        );
+        match arrow_value_at(&list, 0).unwrap() {
+            Value::List(items) => assert_eq!(
+                items,
+                vec![Value::TimestampNtz(-1), Value::TimestampNtz(1_000)]
+            ),
+            other => panic!("expected a list, got {other:?}"),
+        }
+    }
+
     #[test]
     fn time_types_decode_as_nanoseconds_since_midnight() {
         // As PySpark's internal value of TimeType, whatever the unit of the 
Arrow time.
diff --git a/crates/spark-connect/src/row.rs b/crates/spark-connect/src/row.rs
index ec9f22c8..a1e99985 100644
--- a/crates/spark-connect/src/row.rs
+++ b/crates/spark-connect/src/row.rs
@@ -31,10 +31,12 @@ pub enum Value {
     Binary(Vec<u8>),
     /// Date (days since epoch)
     Date(i32),
-    /// Timestamp with local time zone (`TimestampType`), in microseconds 
since the epoch.
+    /// Timestamp with local time zone (`TimestampType`), in microseconds 
since the epoch. Collect
+    /// floors a nanosecond-precision value (p > 6) to microseconds.
     Timestamp(i64),
     /// Timestamp without time zone (`TimestampNTZType`), in microseconds of 
its wall clock
-    /// since 1970-01-01 00:00:00, which the time zone of the client does not 
shift.
+    /// since 1970-01-01 00:00:00, which the time zone of the client does not 
shift. Collect
+    /// floors a nanosecond-precision value (p > 6) to microseconds.
     TimestampNtz(i64),
     /// TIME, in nanoseconds since midnight, as PySpark's internal value of 
`TimeType`.
     Time(i64),
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index d8d87e7a..30006804 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -1580,17 +1580,28 @@ fn values_to_arrow(values: &[&Value], dt: &DataType) -> 
Result<Arc<dyn arrow::ar
 
     // Numeric encoders coerce across integer/float widths, so a value the 
schema-unaware
     // Python->Value conversion produced as a wider/narrower numeric (e.g. a 
nested-struct
-    // int arriving as Long) still matches its declared field type.
+    // int arriving as Long) still matches its declared field type. An integer 
that does
+    // not fit the declared type is an error, as PySpark's Arrow conversion 
raises for it.
     macro_rules! int_prim {
-        ($arr:ty, $t:ty) => {{
+        ($arr:ty, $t:ty, $sql:expr) => {{
+            let narrow = |x: i64| {
+                <$t>::try_from(x).map(Some).map_err(|_| {
+                    SparkError::value_msg(format!(
+                        "Value {x} does not fit the {} type of its column, 
whose range is {}..={}",
+                        $sql,
+                        <$t>::MIN,
+                        <$t>::MAX
+                    ))
+                })
+            };
             let vals: Result<Vec<_>> = values
                 .iter()
                 .map(|v| match *v {
                     Value::Null => Ok(None),
-                    Value::Byte(x) => Ok(Some(*x as $t)),
-                    Value::Short(x) => Ok(Some(*x as $t)),
-                    Value::Integer(x) => Ok(Some(*x as $t)),
-                    Value::Long(x) => Ok(Some(*x as $t)),
+                    Value::Byte(x) => narrow(*x as i64),
+                    Value::Short(x) => narrow(*x as i64),
+                    Value::Integer(x) => narrow(*x as i64),
+                    Value::Long(x) => narrow(*x),
                     _ => Err(SparkError::connect_msg("Type mismatch in row 
data")),
                 })
                 .collect();
@@ -1619,10 +1630,10 @@ fn values_to_arrow(values: &[&Value], dt: &DataType) -> 
Result<Arc<dyn arrow::ar
     match dt {
         DataType::Null => Ok(Arc::new(NullArray::new(values.len()))),
         DataType::Boolean => prim!(BooleanArray, Value::Bool),
-        DataType::Byte => int_prim!(Int8Array, i8),
-        DataType::Short => int_prim!(Int16Array, i16),
-        DataType::Integer => int_prim!(Int32Array, i32),
-        DataType::Long => int_prim!(Int64Array, i64),
+        DataType::Byte => int_prim!(Int8Array, i8, "TINYINT"),
+        DataType::Short => int_prim!(Int16Array, i16, "SMALLINT"),
+        DataType::Integer => int_prim!(Int32Array, i32, "INT"),
+        DataType::Long => int_prim!(Int64Array, i64, "BIGINT"),
         DataType::Float => float_prim!(Float32Array, f32),
         DataType::Double => float_prim!(Float64Array, f64),
         DataType::String { .. } | DataType::Char { .. } | DataType::Varchar { 
.. } => {
@@ -3057,6 +3068,84 @@ mod tests {
         assert_eq!(ids(&spark), vec![main, late]);
     }
 
+    #[test]
+    fn integers_that_do_not_fit_the_declared_type_are_errors_not_wrapped() {
+        // PySpark's Arrow conversion raises for an integer outside the 
declared type's
+        // range, so the encoder must not wrap it with an `as` cast.
+        for (value, dt, sql_type) in [
+            (Value::Long(4_294_967_297), DataType::Integer, "INT"),
+            (Value::Long(-2_147_483_649), DataType::Integer, "INT"),
+            (Value::Long(300), DataType::Byte, "TINYINT"),
+            (Value::Integer(200), DataType::Byte, "TINYINT"),
+            (Value::Short(-129), DataType::Byte, "TINYINT"),
+            (Value::Integer(70_000), DataType::Short, "SMALLINT"),
+        ] {
+            let error = values_to_arrow(&[&value], &dt)
+                .map(|_| ())
+                .unwrap_err()
+                .to_string();
+            let number = match &value {
+                Value::Long(x) => x.to_string(),
+                Value::Integer(x) => x.to_string(),
+                Value::Short(x) => x.to_string(),
+                _ => unreachable!(),
+            };
+            assert!(error.contains(&number), "{error}");
+            assert!(error.contains(sql_type), "{error}");
+            // The batch-level path reports the same error.
+            let rows = [row(vec![value.clone()])];
+            assert!(rows_to_arrow_batch(&rows, &schema(vec![dt])).is_err());
+        }
+    }
+
+    #[test]
+    fn integers_that_fit_the_declared_type_still_narrow_and_widen() {
+        use arrow::array::{Int16Array, Int32Array, Int64Array, Int8Array};
+
+        let bytes = values_to_arrow(
+            &[&Value::Long(127), &Value::Integer(-128), &Value::Null],
+            &DataType::Byte,
+        )
+        .unwrap();
+        assert_eq!(
+            bytes.as_any().downcast_ref::<Int8Array>().unwrap(),
+            &Int8Array::from(vec![Some(127), Some(-128), None])
+        );
+        let shorts =
+            values_to_arrow(&[&Value::Byte(-5), &Value::Long(32_767)], 
&DataType::Short).unwrap();
+        assert_eq!(
+            shorts.as_any().downcast_ref::<Int16Array>().unwrap(),
+            &Int16Array::from(vec![-5, 32_767])
+        );
+        let ints = values_to_arrow(
+            &[&Value::Long(i32::MIN as i64), &Value::Long(i32::MAX as i64)],
+            &DataType::Integer,
+        )
+        .unwrap();
+        assert_eq!(
+            ints.as_any().downcast_ref::<Int32Array>().unwrap(),
+            &Int32Array::from(vec![i32::MIN, i32::MAX])
+        );
+        let longs = values_to_arrow(
+            &[&Value::Integer(-7), &Value::Long(i64::MAX)],
+            &DataType::Long,
+        )
+        .unwrap();
+        assert_eq!(
+            longs.as_any().downcast_ref::<Int64Array>().unwrap(),
+            &Int64Array::from(vec![-7, i64::MAX])
+        );
+    }
+
+    #[test]
+    fn a_double_beyond_the_float_range_is_infinite_as_in_pyspark() {
+        // PySpark's Arrow conversion does not reject a finite double beyond 
the float range
+        // (it becomes infinity), so the float encoder keeps that behavior.
+        let array = values_to_arrow(&[&Value::Double(1e300)], 
&DataType::Float).unwrap();
+        let floats = array.as_any().downcast_ref::<Float32Array>().unwrap();
+        assert!(floats.value(0).is_infinite());
+    }
+
     #[test]
     fn session_tags_add_and_remove() {
         let spark = session();
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 35c37b18..3883736d 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -453,6 +453,53 @@ def _run_in_time_zone(code, zone):
     return result.stdout
 
 
+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.
+    import datetime
+    import re
+
+    from pyspark.errors import PySparkValueError
+
+    def message(proto_text):
+        return r"\[UNSUPPORTED_OPERATION\] data type " + re.escape(proto_text) 
+ r" is not supported\."
+
+    ntz9 = "timestamp_ntz_nanos {\n  precision: 9\n}\n"
+    ltz7 = "timestamp_ltz_nanos {\n  precision: 7\n}\n"
+    ltz9 = "timestamp_ltz_nanos {\n  precision: 9\n}\n"
+    cases = [
+        ("SELECT CAST('2020-01-01 00:00:00.123456789' AS TIMESTAMP_NTZ(9)) c", 
ntz9),
+        ("SELECT CAST('2020-01-01 00:00:00.1234567' AS TIMESTAMP_LTZ(7)) c", 
ltz7),
+        ("SELECT named_struct('a', CAST('2020-01-01 00:00:00.123456789' AS 
TIMESTAMP_NTZ(9))) c",
+         ntz9),
+        ("SELECT array(CAST('2020-01-01 00:00:00.123456789' AS 
TIMESTAMP_LTZ(9))) c", ltz9),
+        ("SELECT map('k', CAST('2020-01-01 00:00:00.123456789' AS 
TIMESTAMP_NTZ(9))) c", ntz9),
+    ]
+    for query, proto_text in cases:
+        df = session.sql(query)
+        for collect in (
+            lambda d: d.collect(),
+            lambda d: d.first(),
+            lambda d: d.head(),
+            lambda d: d.head(1),
+            lambda d: d.take(1),
+            lambda d: d.tail(1),
+            lambda d: list(d.toLocalIterator()),
+            lambda d: d.toPandas(),
+            lambda d: d.toArrow(),
+        ):
+            with pytest.raises(PySparkValueError, match=message(proto_text)):
+                collect(df)
+    # 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
+    df.show()
+    # Microsecond timestamps still collect.
+    micros = session.sql("SELECT CAST('2020-01-01 00:00:00.123456' AS 
TIMESTAMP_NTZ(6)) c")
+    assert micros.collect()[0].c == datetime.datetime(2020, 1, 1, 0, 0, 0, 
123456)
+
+
 def test_ntz_collect_is_the_wall_clock_in_the_client_time_zone_as_pyspark():
     # As PySpark's Arrow conversion: a TIMESTAMP_NTZ is the wall clock, 
whatever the time zone of
     # the client, from year 1 to year 9999 and inside arrays, maps and 
structs, while a TIMESTAMP
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index c742d855..d21ef289 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7324,6 +7324,61 @@ def test_udf_string_arg_is_column_name_not_literal():
     assert repr(c) == repr(u(col("id")))
 
 
[email protected]("collect", [
+    lambda df: df.collect(),
+    lambda df: df.first(),
+    lambda df: df.head(1),
+    lambda df: df.take(1),
+    lambda df: df.tail(1),
+    lambda df: list(df.toLocalIterator()),
+    lambda df: df.toArrow(),
+])
[email protected]("nesting, proto_text", [
+    (None, "timestamp_ntz_nanos {\n  precision: 9\n}\n"),
+    ("array", "timestamp_ltz_nanos {\n  precision: 7\n}\n"),
+    ("struct", "timestamp_ntz_nanos {\n  precision: 9\n}\n"),
+])
+def test_nanosecond_timestamps_are_not_collected_as_pyspark(
+        mock_connect, collect, nesting, proto_text):
+    # As PySpark's conversion of the schema from its proto: TIMESTAMP_NTZ(p) 
and TIMESTAMP_LTZ(p)
+    # with p > 6 raise UNSUPPORTED_OPERATION, also nested, from the collecting 
APIs, as the message
+    # of the proto of the first such type. The Arrow data is empty; toPandas 
is checked live.
+    import re
+
+    import pyarrow as pa
+    from pyspark.errors import PySparkValueError
+
+    # DataType.timestamp_ntz_nanos=29, timestamp_ltz_nanos=30; precision=1 of 
both messages.
+    is_ltz = "ltz" in proto_text
+    leaf = message_field(30 if is_ltz else 29, varint_field(1, 7 if is_ltz 
else 9))
+    arrow_type = pa.timestamp("ns", tz="UTC" if is_ltz else None)
+    if nesting == "array":
+        # Array.element_type=1, contains_null=2; DataType.array=20.
+        field_type = message_field(20, message_field(1, leaf) + 
varint_field(2, 1))
+        arrow_type = pa.list_(arrow_type)
+    elif nesting == "struct":
+        # Struct.fields=1; StructField: name=1, data_type=2, nullable=3; 
DataType.struct=21.
+        field_type = message_field(21, message_field(1, message_field(1, "s")
+                                                     + message_field(2, leaf) 
+ b"\x18\x01"))
+        arrow_type = pa.struct([("s", arrow_type)])
+    else:
+        field_type = leaf
+    struct = message_field(21, message_field(1, message_field(1, "c")
+                                             + message_field(2, field_type) + 
b"\x18\x01"))
+
+    spark, service = mock_connect
+    table = pa.table({"c": pa.array([], arrow_type)})
+    sink = pa.BufferOutputStream()
+    with pa.ipc.new_stream(sink, table.schema) as writer:
+        writer.write_table(table)
+    batch = varint_field(1, table.num_rows) + message_field(2, 
sink.getvalue().to_pybytes())
+    service.execute_payload = message_field(7, struct) + message_field(2, 
batch)
+    df = spark.range(1)
+    with pytest.raises(PySparkValueError, match=(
+            r"\[UNSUPPORTED_OPERATION\] data type " + re.escape(proto_text) + 
r" is not supported\.")):
+        collect(df)
+
+
 def test_udf_and_pandas_udf_decorator_forms(mock_connect):
     # @udf(returnType) / @pandas_udf(returnType) return a decorator that wraps 
a function.
     from pyspark.sql.functions import udf, pandas_udf


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to