tdcmeehan opened a new pull request, #60452:
URL: https://github.com/apache/spark/pull/60452

   ### What changes were proposed in this pull request?
   
   `LocalDataToArrowConversion._create_converter` in 
`python/pyspark/sql/conversion.py` converts a `TimestampType` value with 
`value.astimezone(datetime.timezone.utc)`. This PR keeps that call and handles 
the naive values it rejects: when `astimezone()` raises for a naive `datetime`, 
the converter keeps the wall clock and attaches the fixed UTC offset that 
`time.mktime` gives for it, which is the local-time interpretation 
`TimestampType.toInternal` uses. PyArrow converts an aware `datetime` by its 
own UTC offset, so the Arrow value equals `TimestampType.toInternal(value)`. 
Aware values that `astimezone()` rejects still raise, and values that convert 
today keep their current result.
   
   The fallback cannot return a UTC `datetime`, because some of these instants 
are outside the range of `datetime` in UTC. Under `America/Los_Angeles`, 
`9999-12-31 23:59:59.999999` is `10000-01-01 07:59:59.999999` UTC. Under 
`Asia/Tokyo`, whose offset on `0001-01-01` is local mean time (UTC+09:18:59), 
`0001-01-01 00:00` is in year 0 in UTC. The Arrow type, `timestamp[us, 
tz=UTC]`, holds both.
   
   The branch is shared with `TimestampLTZNanosType`, whose Arrow type 
`timestamp[ns]` cannot represent these dates. For that type, values on these 
two dates no longer fail in `astimezone()` and instead get what values on 
9999-12-30 already get from PyArrow. For Spark Connect `createDataFrame`, 
Arrow-optimized Python UDTF and Python data source rows, the conversion raises 
`ArrowInvalid` (out of bounds for nanosecond resolution). In Arrow-optimized 
Python UDF results, the existing fallback cast raises `ArrowInvalid` with the 
default `spark.sql.execution.pandas.convertToArrowArraySafely=true`, and wraps 
the value silently when it is `false`.
   
   ### Why are the changes needed?
   
   For a naive `datetime`, `astimezone()` first works out the local UTC offset. 
CPython does this by converting nearby instants, up to a day before and after 
the wall clock, back to `datetime`s, to detect DST folds and gaps. On 
9999-12-31 and 0001-01-01 one of them falls outside the range of `datetime`, so 
the conversion fails at any time of day on those two dates:
   
   ```
   ValueError: year 10000 is out of range
   ValueError: year 0 is out of range
   ```
   
   `9999-12-30 23:59:59` converts. The pickled path (`useArrow=False`) applies 
`TimestampType.toInternal`, which uses `time.mktime` for a naive value, and 
accepts these values.
   
   Besides the results of Arrow-optimized Python UDFs (`useArrow=True`; 
`spark.sql.execution.pythonUDF.arrow.enabled` defaults to `true`), the same 
converter handles the rows of Spark Connect `createDataFrame`, of 
Arrow-optimized Python UDTFs and of Python data source readers, which fail the 
same way.
   
   To reproduce without a JVM:
   
   ```python
   import datetime
   from pyspark.sql.conversion import LocalDataToArrowConversion
   from pyspark.sql.types import TimestampType
   
   convert = LocalDataToArrowConversion._create_converter(TimestampType())
   convert(datetime.datetime(9999, 12, 31))  # ValueError: year 10000 is out of 
range
   convert(datetime.datetime(1, 1, 1))  # ValueError: year 0 is out of range
   ```
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes. A naive `datetime` on 9999-12-31 or 0001-01-01 for a `TIMESTAMP` value, 
returned by an Arrow-optimized Python UDF, an Arrow-optimized Python UDTF or a 
Python data source reader, or passed to Spark Connect `createDataFrame`, used 
to fail with `ValueError: year 10000 is out of range` (or `year 0`). It now 
succeeds with the value `TimestampType.toInternal` gives for it, which is what 
a pickled (`useArrow=False`) Python UDF or UDTF returns. Values that converted 
before keep their results. The same conversion code is in released versions, 
for example 4.1.0 and 4.3.0.
   
   For example, with both `spark.sql.session.timeZone` and the process time 
zone set to `America/Los_Angeles`:
   
   ```python
   import datetime
   from pyspark.sql.functions import udf, unix_micros
   
   for use_arrow in (True, False):
       f = udf(lambda: datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), 
"timestamp", useArrow=use_arrow)
       print(f"useArrow={use_arrow}:", 
spark.range(1).select(unix_micros(f())).first()[0])
   ```
   
   Before, `useArrow=True` raises `PythonException` with `ValueError: year 
10000 is out of range` from the Python worker, while `useArrow=False` prints 
`253402329599999999`. After:
   
   ```
   useArrow=True: 253402329599999999
   useArrow=False: 253402329599999999
   ```
   
   ### How was this patch tested?
   
   Added tests:
   
   - `ConversionTests.test_naive_timestamp_at_datetime_range_ends` in 
`python/pyspark/sql/tests/test_conversion.py`: with `TZ` set to 
`America/Los_Angeles`, `Asia/Tokyo` and `UTC`, converts naive values on 
9999-12-31 (00:00, 12:00:00.000001 and 23:59:59.999999), 0001-01-01 (00:00 and 
23:59:59.999999) and 9999-12-30 23:59:59 with 
`LocalDataToArrowConversion.convert`, and checks that each Arrow value equals 
`TimestampType.toInternal`. Without the fix, the 15 subtests on 9999-12-31 and 
0001-01-01 fail with `ValueError`.
   - `ConversionTests.test_aware_timestamp_overflowing_utc_raises`: an aware 
value whose UTC instant is past `datetime.max` still raises `OverflowError`.
   - `ArrowPythonUDFNonLegacyTests.test_naive_timestamp_at_datetime_range_ends` 
in `python/pyspark/sql/tests/arrow/test_arrow_python_udf.py`: with the driver, 
the Python workers and the session time zone set to `America/Los_Angeles` and 
then `Asia/Tokyo`, an Arrow-optimized and a pickled UDF return the same naive 
values, and `unix_micros` of both results equals `TimestampType.toInternal`. 
Without the fix, it fails with `ValueError: year 10000 is out of range` from 
the Python worker.
   
   Ran:
   
   ```
   python/run-tests --testnames 
'pyspark.sql.tests.test_conversion,pyspark.sql.tests.arrow.test_arrow_python_udf,pyspark.sql.tests.connect.arrow.test_parity_arrow_python_udf'
   ```
   
   It passed: `test_conversion` ran 51 tests, `test_arrow_python_udf` 317 (14 
skipped) and `test_parity_arrow_python_udf` 399 (52 skipped), with no failures. 
The ruff checks in `dev/lint-python` (`ruff check` and `ruff format`) pass. 
`ConversionTests` also passes with PyArrow 18.0.0. Spark Connect 
`createDataFrame`, an Arrow-optimized Python UDTF and a Python data source were 
also checked by hand with these values under `America/Los_Angeles`: they failed 
before and return the `TimestampType.toInternal` values after.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Isaac (Claude Opus 5.5)
   
   This pull request and its description were written by Isaac.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to