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 61d04190 [SPARK-61316][CONNECT][PYTHON] Encode datetime literals
exactly, as PySpark's TimestampType does
61d04190 is described below
commit 61d04190b2c97f672f52a15141409a70c09cd0e4
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 09:05:53 2026 +0900
[SPARK-61316][CONNECT][PYTHON] Encode datetime literals exactly, as
PySpark's TimestampType does
### What changes were proposed in this pull request?
[SPARK-61316](https://issues.apache.org/jira/browse/SPARK-61316): Encode
datetime literals exactly, as PySpark's TimestampType does.
The drop-in converted a Python `datetime` to microseconds (for `lit()` and
for the values of `createDataFrame`) with `datetime.timestamp() * 1e6`,
rounded. The float of seconds loses the microseconds once the value is past
2^53 microseconds (about the year 2255), and a naive datetime near the year
9999 overflows in `timestamp()`. `datetime_to_micros` now computes the value in
integers, as `TimestampType.toInternal` does in PySpark:
- an aware datetime: `calendar.timegm(dt.utctimetuple()) * 1_000_000 +
dt.microsecond`;
- a naive datetime, in the local time zone of the client:
`time.mktime(dt.timetuple())` truncated to whole seconds, then the same sum.
Both callers (`functions.lit` and `session::py_to_value`) use it, so
`lit()` and `createDataFrame` keep agreeing. The pandas `Timestamp`
normalization is unchanged.
The values are the same as official PySpark 4.3.0 for years 1969, 2300 and
9999, aware and naive. A naive datetime of year 1 raises `OverflowError` from
`time.mktime` in official PySpark on macOS (the limit of the platform C
library); the drop-in uses the same call, so it behaves the same there.
### Why are the changes needed?
`F.lit(datetime(2300, 1, 1, 0, 0, 0, 123457, tzinfo=timezone.utc))`
collected as `.123456`, and `F.lit(datetime(9999, 12, 31, 23, 59, 59, 999999))`
raised `OverflowError: date value out of range`. Official PySpark gives
`.123457` and `9999-12-31 23:59:59.999999` for both.
### Does this PR introduce _any_ user-facing change?
Yes. Datetime literals and the values of `createDataFrame` past 2255 keep
their microseconds, and the largest datetimes no longer raise `OverflowError`.
Values before 2255 do not change.
### How was this patch tested?
- `test_datetime_literals_are_exact_micros_as_pyspark` (offline,
`test_dropin_offline.py`, before `test_lit_errors_as_pyspark`): the
`Literal.timestamp` micros in the plan for years 1, 1969, 2300 and 9999
(aware), and for naive 1969, 2300 and 9999 in a zone nine hours east of UTC.
The expected values are those of official PySpark 4.3.0
(`TimestampType().toInternal`).
- `test_datetime_literals_collect_the_exact_values_of_pyspark` (live,
`test_dropin_e2e.py`, before `test_window_frames_return_the_rows_of_pyspark`,
client time zone Asia/Seoul): the collected values of the same literals equal
those of official PySpark 4.3.0 in the same zone, including `OverflowError` on
collect of the aware 9999 value (which is past the year 9999 in that zone).
- Both tests fail on the base conversion (the float path) and pass with
this change.
- The build of all tests, the offline Python suites (2928 passed, 8
skipped) with the rebuilt extension, the new tests also under pytest 9.2, and
the live drop-in tests `-k "timestamp or ntz or lit"` (11 passed) against a
local Spark 4.3.0 server. Clippy reports no new diagnostics in the changed
lines.
Closes #437 from HyukjinKwon/SPARK-61316-exact-datetime-literals.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/session.rs | 24 ++++++++++++++++++--
python/tests/test_dropin_e2e.py | 39 ++++++++++++++++++++++++++++++++
python/tests/test_dropin_offline.py | 45 +++++++++++++++++++++++++++++++++++++
3 files changed, 106 insertions(+), 2 deletions(-)
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 489c3515..3d503b5e 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -3843,14 +3843,34 @@ pub(crate) fn py_to_value(obj: &Bound<'_, PyAny>) ->
PyResult<Value> {
/// make `createDataFrame(pandas_df)` disagree with `lit(..)` by the local
offset. To keep the
/// two paths identical we first downcast a pandas Timestamp to a plain
`datetime` via
/// `to_pydatetime()`. Timezone-aware values are unaffected (both encode the
same instant).
+///
+/// The seconds and the microseconds are integers, as
`TimestampType.toInternal` takes them
+/// (`calendar.timegm` of the UTC tuple of an aware value, `time.mktime` of
the local tuple of a
+/// naive one): a float of seconds loses the microseconds of the values far
from the epoch, and
+/// `timestamp()` overflows for the latest datetimes of the year 9999.
pub(crate) fn datetime_to_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
+ let py = obj.py();
let normalized = if obj.hasattr("to_pydatetime").unwrap_or(false) {
obj.call_method0("to_pydatetime")?
} else {
obj.clone()
};
- let timestamp_f64: f64 = normalized.call_method0("timestamp")?.extract()?;
- Ok((timestamp_f64 * 1_000_000.0).round() as i64)
+ let seconds: i64 = if normalized.getattr("tzinfo")?.is_none() {
+ // time.mktime returns a float of whole seconds; int() truncates it as
`as` does.
+ let local = normalized.call_method0("timetuple")?;
+ let secs: f64 = py
+ .import("time")?
+ .call_method1("mktime", (local,))?
+ .extract()?;
+ secs as i64
+ } else {
+ let utc = normalized.call_method0("utctimetuple")?;
+ py.import("calendar")?
+ .call_method1("timegm", (utc,))?
+ .extract()?
+ };
+ let micros: i64 = normalized.getattr("microsecond")?.extract()?;
+ Ok(seconds * 1_000_000 + micros)
}
/// If `obj` is an instance of the cached Decimal class (C `_decimal.Decimal`,
else the
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 58ee4eb3..56e9b684 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3182,6 +3182,45 @@ def
test_functions_send_their_optional_arguments_as_pyspark(session):
assert nulls.groupBy("g").agg(F.first("v", ignorenulls=True)).first()[1]
== 5
+def test_datetime_literals_collect_the_exact_values_of_pyspark():
+ # As PySpark's TimestampType: a datetime literal is the instant of its
micros, exact from year
+ # 1 to year 9999 (a float of seconds lost the micros after the year 2255),
and a naive one is
+ # in the client's time zone. A TIMESTAMP that is past the year 9999 in the
zone of the client
+ # (here nine hours ahead of UTC) raises OverflowError on collect, as
PySpark does.
+ remote = os.environ.get("SPARK_REMOTE")
+ if not remote:
+ pytest.skip("SPARK_REMOTE is required for live-server tests")
+ out = _run_in_time_zone("""
+import datetime
+from pyspark.sql import SparkSession, functions as F
+spark = SparkSession.builder.remote(%r).getOrCreate()
+utc = datetime.timezone.utc
+values = [
+ ("aware_1", datetime.datetime(1, 1, 1, 0, 0, 0, 1, tzinfo=utc)),
+ ("aware_1969", datetime.datetime(1969, 12, 31, 23, 59, 59, 999999,
tzinfo=utc)),
+ ("aware_2300", datetime.datetime(2300, 1, 1, 0, 0, 0, 123457, tzinfo=utc)),
+ ("aware_9999", datetime.datetime(9999, 12, 31, 23, 59, 59, 999999,
tzinfo=utc)),
+ ("naive_1969", datetime.datetime(1969, 12, 31, 23, 59, 59, 999999)),
+ ("naive_2300", datetime.datetime(2300, 1, 1, 0, 0, 0, 123457)),
+ ("naive_9999", datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)),
+]
+for name, value in values:
+ try:
+ print(name,
repr(spark.range(1).select(F.lit(value).alias("v")).collect()[0][0]))
+ except Exception as error:
+ print(name, type(error).__name__)
+""" % remote, "Asia/Seoul")
+ assert out.splitlines() == [
+ "aware_1 datetime.datetime(1, 1, 1, 8, 27, 52, 1)",
+ "aware_1969 datetime.datetime(1970, 1, 1, 8, 59, 59, 999999)",
+ "aware_2300 datetime.datetime(2300, 1, 1, 9, 0, 0, 123457)",
+ "aware_9999 OverflowError",
+ "naive_1969 datetime.datetime(1969, 12, 31, 23, 59, 59, 999999)",
+ "naive_2300 datetime.datetime(2300, 1, 1, 0, 0, 0, 123457)",
+ "naive_9999 datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)",
+ ]
+
+
def test_window_frames_return_the_rows_of_pyspark(session):
# As PySpark's: a range frame of a boundary out of the range of an int,
which was
# truncated, and the frames of the bounds of -sys.maxsize and sys.maxsize,
unbounded.
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 1422ba4c..21f84ced 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -14377,6 +14377,51 @@ def
test_lit_of_a_numpy_array_is_an_array_of_its_type_as_pyspark():
assert repr(F.lit(value)).lower() == f"column<'{expected}'>"
+def test_datetime_literals_are_exact_micros_as_pyspark(mock_connect,
monkeypatch):
+ # As PySpark's TimestampType.toInternal: the microseconds of a datetime
are exact over the
+ # whole range (a float of seconds loses them after the year 2255), and a
naive datetime is
+ # in the local time zone (the micros of year 1 of a naive datetime are
platform-dependent).
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+
+ def micros(column):
+ spark.range(1).select(column).collect()
+ # Project.expressions=3; Expression.literal=1, Literal.timestamp=17
(an int64).
+ plan =
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+ expression =
parse_message(parse_message(parse_message(plan)[3][0])[3][0])
+ value = parse_message(expression[1][0])[17][0]
+ return value - (1 << 64) if value >= 1 << 63 else value
+
+ utc = datetime.timezone.utc
+ cases = [
+ (datetime.datetime(1, 1, 1, 0, 0, 0, 1, tzinfo=utc),
-62135596799999999),
+ (datetime.datetime(1969, 12, 31, 23, 59, 59, 999999, tzinfo=utc), -1),
+ (datetime.datetime(2300, 1, 1, 0, 0, 0, 123457, tzinfo=utc),
10413792000123457),
+ (datetime.datetime(9999, 12, 31, 23, 59, 59, 999999, tzinfo=utc),
253402300799999999),
+ ]
+ for value, expected in cases:
+ assert micros(F.lit(value)) == expected
+ # The naive values of the same instants in a zone nine hours east of UTC,
which has no DST.
+ if not hasattr(time, "tzset"):
+ pytest.skip("time.tzset is not available")
+ zone, offset = os.environ.get("TZ"), 9 * 3600 * 1_000_000
+ os.environ["TZ"] = "Etc/GMT-9"
+ time.tzset()
+ try:
+ assert micros(F.lit(datetime.datetime(1969, 12, 31, 23, 59, 59,
999999))) == -1 - offset
+ assert micros(F.lit(datetime.datetime(2300, 1, 1, 0, 0, 0, 123457)))
== (
+ 10413792000123457 - offset)
+ assert micros(F.lit(datetime.datetime(9999, 12, 31, 23, 59, 59,
999999))) == (
+ 253402300799999999 - offset)
+ finally:
+ if zone is None:
+ del os.environ["TZ"]
+ else:
+ os.environ["TZ"] = zone
+ time.tzset()
+
+
def test_lit_errors_as_pyspark():
np = pytest.importorskip("numpy")
from pyspark.errors import PySparkTypeError, PySparkValueError
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]