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 f610967a [SPARK-61547][CONNECT][PYTHON] Cache the UTC epoch for local 
timestamp conversion
f610967a is described below

commit f610967a496b70cc652d0d547ee1df9e9183970a
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 23:14:33 2026 +0900

    [SPARK-61547][CONNECT][PYTHON] Cache the UTC epoch for local timestamp 
conversion
    
    ### What changes were proposed in this pull request?
    
    Cache the UTC timezone and `datetime(1970, 1, 1, tzinfo=UTC)` together in a 
`PyOnceLock` in `infer.rs`. `instant_micros()` currently imports `datetime`, 
looks up `timezone.utc`, and constructs the epoch and its keyword dictionary 
for every timestamp value.
    
    The cache removes that repeated work from local `createDataFrame()` 
timestamp conversion, including timestamps nested in arrays, maps, and structs. 
Each input still goes through its own `astimezone()` and subtraction, 
preserving local-timezone/DST behavior, datetime subclass hooks, and exact 
integer microseconds. Initialization remains fallible through 
`get_or_try_init()`.
    
    ### Why are the changes needed?
    
    The UTC epoch and timezone are immutable constants. Constructing and 
resolving them for every timestamp adds substantial overhead when converting 
local data to Arrow.
    
    Release-build benchmark against base commit `79e62fc`, on CPython 3.13.12, 
PyO3 0.28.3 (`abi3-py39`), Linux x86_64, Intel Xeon Platinum 8375C. Inputs and 
schemas were prepared outside timing. Each build ran in five fresh processes, 
alternating baseline/candidate order and reversing it on alternate pairs, 
pinned to CPU 0. Times are the median of each process's median of five `timeit` 
samples, in milliseconds per `createDataFrame()` call.
    
    | Local input | Before (ms) | After (ms) | Speedup |
    |---|---:|---:|---:|
    | 1,000 UTC timestamps, explicit schema | 1.216 | 0.366 | 3.32× |
    | 10,000 UTC timestamps, explicit schema | 12.116 | 4.322 | 2.80× |
    | 1,000 fixed-offset timestamps, explicit schema | 1.502 | 0.623 | 2.41× |
    | 1,000 naive timestamps, explicit schema, local TZ=UTC | 2.188 | 1.330 | 
1.64× |
    | 1,000 rows, each with an array of 4 UTC timestamps | 4.556 | 1.240 | 
3.68× |
    | 1,000 UTC timestamps, inferred schema | 2.664 | 1.910 | 1.40× |
    | Control: 1,000 `TimestampNTZ` values | 1.709 | 1.696 | 1.01× |
    | Control: 1,000 integers | 0.039 | 0.039 | 0.99× |
    
    These measure local DataFrame construction, including conversion and Arrow 
serialization. A mock Connect server answers metadata requests; no Spark query 
is executed. They do not represent server-side execution or `collect()` 
speedups. The controls are effectively unchanged.
    
    <details>
    <summary>Reproduce the 1,000-UTC-timestamp case</summary>
    
    Build `pyspark-rs` with `cargo build -p pyspark-rs --release` at the base 
and PR commits. Save each release library and install the selected one as 
`python/pyspark/_pyspark.so`. Run this with `TZ=UTC PYTHONHASHSEED=0 
PYTHONPATH=python:python/tests`, alternating the two builds in fresh processes 
for five pairs as described above. No builds or tests ran concurrently with the 
measurements.
    
    ```python
    import os
    import statistics
    import timeit
    from datetime import datetime, timedelta, timezone
    from pyspark.sql import types as T
    from _mock_connect_server import mock_connect_session
    
    os.sched_setaffinity(0, {0})
    
    def benchmark():
        start = datetime(2020, 1, 2, 3, 4, 5, 123456, tzinfo=timezone.utc)
        data = [(start + timedelta(microseconds=i),) for i in range(1000)]
        schema = T.StructType().add("value", T.TimestampType())
        with mock_connect_session() as (spark, _):
            timer = timeit.Timer(lambda: spark.createDataFrame(data, schema))
            timer.timeit(number=5)
            samples = timer.repeat(repeat=5, number=100)
            print(statistics.median(samples) / 100 * 1000, "ms/call")
    
    if __name__ == "__main__":
        benchmark()
    ```
    
    </details>
    
    ### Does this PR introduce _any_ user-facing change?
    
    Faster local timestamp conversion in `createDataFrame()`. No API or 
timestamp-value changes.
    
    ### How was this patch tested?
    
    - Added a cache-reuse regression covering repeated calls and nested 
timestamp fields; it fails on the baseline and passes with this change. 
Subclass `astimezone()` and subtraction are still called for every value.
    - Added coverage for changing the local timezone after cache 
initialization, DST folds, pre-epoch values, year 1/year 9999, microsecond 
precision, and subclass exceptions.
    - Focused timestamp tests: 15 passed. Python Ruff passed.
    - Official Spark 4.3.0 creation/type parity suites against the drop-in and 
a local Connect server: 88 passed, 22 skipped (UTC, 
`spark.sql.timeType.enabled=true`).
    - Rust core unit tests: 634 passed; all integration tests compiled, 
including with `wasm-udf` enabled. `cargo fmt --all --check` passed.
    - Public callable/property introspection across 12 reference Connect 
classes: zero missing members.
    - `cargo clippy --workspace --all-targets` encounters existing lints. 
Comparing `cargo clippy -p pyspark-rs --lib` on the unchanged base and this 
branch found the same 62 errors, matching diagnostic codes, messages, and files.
    - Full offline Python suites: 3,257 passed, 8 skipped, and 14 subtests 
passed.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Codex (GPT-6)
    
    This pull request and its description were written by Isaac.
    
    Closes #575 from zhengruifeng/cache-utc-epoch.
    
    Authored-by: Ruifeng Zheng <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/infer.rs      | 32 +++++++++----
 python/tests/test_dropin_offline.py | 94 +++++++++++++++++++++++++++++++++++++
 2 files changed, 117 insertions(+), 9 deletions(-)

diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index b98171cc..ebe121a4 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -28,6 +28,7 @@ static DECIMAL: PyOnceLock<Py<PyType>> = PyOnceLock::new();
 static C_DECIMAL: PyOnceLock<Option<Py<PyType>>> = PyOnceLock::new();
 static DATE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
 static DATETIME: PyOnceLock<Py<PyType>> = PyOnceLock::new();
+static UTC_EPOCH: PyOnceLock<UtcEpoch> = PyOnceLock::new();
 static TIME: PyOnceLock<Py<PyType>> = PyOnceLock::new();
 static TIMEDELTA: PyOnceLock<Py<PyType>> = PyOnceLock::new();
 static ARRAY: PyOnceLock<Py<PyType>> = PyOnceLock::new();
@@ -1143,19 +1144,32 @@ fn delta_micros(delta: &Bound<'_, PyAny>) -> 
PyResult<i64> {
     Ok(days * 86_400_000_000 + seconds * 1_000_000 + micros)
 }
 
+/// Immutable arguments shared by local timestamp conversions. The input's 
local timezone
+/// and datetime subclass hooks are still resolved for every value.
+struct UtcEpoch {
+    timezone: Py<PyAny>,
+    datetime: Py<PyAny>,
+}
+
 /// Microseconds since the epoch of the instant of a datetime, which PySpark 
takes with
 /// `astimezone(timezone.utc)`: a naive datetime is in the local time zone.
 fn instant_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
     let py = obj.py();
-    let datetime = py.import(intern!(py, "datetime"))?;
-    let utc = datetime
-        .getattr(intern!(py, "timezone"))?
-        .getattr(intern!(py, "utc"))?;
-    let aware = obj.call_method1(intern!(py, "astimezone"), (&utc,))?;
-    let epoch = DATETIME
-        .import(py, "datetime", "datetime")?
-        .call((1970, 1, 1), Some(&[("tzinfo", &utc)].into_py_dict(py)?))?;
-    delta_micros(&aware.sub(epoch)?)
+    let epoch = UTC_EPOCH.get_or_try_init(py, || -> PyResult<_> {
+        let utc = py
+            .import(intern!(py, "datetime"))?
+            .getattr(intern!(py, "timezone"))?
+            .getattr(intern!(py, "utc"))?;
+        let datetime = DATETIME
+            .import(py, "datetime", "datetime")?
+            .call((1970, 1, 1), Some(&[("tzinfo", &utc)].into_py_dict(py)?))?;
+        Ok(UtcEpoch {
+            timezone: utc.unbind(),
+            datetime: datetime.unbind(),
+        })
+    })?;
+    let aware = obj.call_method1(intern!(py, "astimezone"), 
(epoch.timezone.bind(py),))?;
+    delta_micros(&aware.sub(epoch.datetime.bind(py))?)
 }
 
 /// The microseconds of the wall clock of a datetime, naive or aware, as 
PySpark's
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 34ca3b17..82d2f726 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -18030,6 +18030,100 @@ def 
test_duplicate_struct_field_names_keep_int64_columns_as_pyspark(mock_connect
     assert table.column(1).to_pylist() == list(range(1000, 2000))
 
 
+def 
test_local_timestamp_conversion_reuses_utc_epoch_and_calls_subclass_hooks(mock_connect):
+    from datetime import datetime, timezone
+
+    epochs, zones = [], []
+
+    class TracedDatetime(datetime):
+        def astimezone(self, tz=None):
+            zones.append(tz)
+            return self
+
+        def __sub__(self, other):
+            epochs.append(other)
+            return super().__sub__(other)
+
+    value = TracedDatetime(1969, 12, 31, 23, 59, 59, 999999, 
tzinfo=timezone.utc)
+    schema = T.StructType().add("value", T.TimestampType()) \
+        .add("items", T.ArrayType(T.TimestampType())) \
+        .add("mapping", T.MapType(T.StringType(), T.TimestampType())) \
+        .add("nested", T.StructType().add("value", T.TimestampType()))
+    for _ in range(2):
+        table = _native_number_input_table(
+            mock_connect, [(value, [value, None], {"key": value}, (value,))], 
schema)
+        assert table["value"].cast("int64").to_pylist() == [-1]
+        assert table["items"][0].as_py() == [value, None]
+        assert table["mapping"][0].as_py() == [("key", value)]
+        assert table["nested"][0].as_py() == {"value": value}
+    assert len(epochs) == len(zones) == 8
+    assert all(zone is timezone.utc for zone in zones)
+    assert epochs[0] == datetime(1970, 1, 1, tzinfo=timezone.utc)
+    assert all(epoch is epochs[0] for epoch in epochs)
+
+
+def 
test_local_timestamp_cached_epoch_preserves_timezone_and_precision(mock_connect,
 monkeypatch):
+    import time
+    from datetime import datetime, timedelta, timezone
+    from zoneinfo import ZoneInfo
+
+    if not hasattr(time, "tzset"):
+        pytest.skip("requires time.tzset")
+    utc = timezone.utc
+    eastern = ZoneInfo("America/New_York")
+    values = [
+        None, datetime.min.replace(tzinfo=utc), 
datetime.max.replace(tzinfo=utc),
+        datetime(1969, 12, 31, 23, 59, 59, 999999, tzinfo=utc),
+        datetime(2500, 1, 2, 3, 4, 5, 123456, tzinfo=utc),
+        datetime(2020, 1, 2, 3, 4, 5, 123456, 
tzinfo=timezone(timedelta(hours=5, minutes=30))),
+        datetime(2021, 11, 7, 1, 30, 0, 123456, tzinfo=eastern, fold=0),
+        datetime(2021, 11, 7, 1, 30, 0, 123456, tzinfo=eastern, fold=1),
+        datetime(2021, 11, 7, 1, 30, 0, 123456, fold=0),
+        datetime(2021, 11, 7, 1, 30, 0, 123456, fold=1),
+    ]
+    schema = T.StructType().add("value", T.TimestampType())
+    epoch = datetime(1970, 1, 1, tzinfo=utc)
+    try:
+        # A warmed cache must still observe changes to the local timezone of 
naive values.
+        with monkeypatch.context() as patch:
+            for zone in ("UTC", "America/New_York", "UTC"):
+                patch.setenv("TZ", zone)
+                time.tzset()
+                expected = []
+                for value in values:
+                    if value is None:
+                        expected.append(None)
+                    else:
+                        delta = value.astimezone(utc) - epoch
+                        expected.append((delta.days * 86400 + delta.seconds) * 
1000000
+                                        + delta.microseconds)
+                table = _native_number_input_table(mock_connect, [(v,) for v 
in values], schema)
+                assert table["value"].cast("int64").to_pylist() == expected
+    finally:
+        time.tzset()
+
+
[email protected]("method", ["astimezone", "__sub__"])
+def test_local_timestamp_cached_epoch_preserves_subclass_errors(mock_connect, 
method):
+    from datetime import datetime, timezone
+
+    error = RuntimeError("timestamp hook failed")
+
+    def fail(*args):
+        raise error
+
+    class BrokenDatetime(datetime):
+        def astimezone(self, tz=None):
+            return self
+
+    setattr(BrokenDatetime, method, fail)
+    value = BrokenDatetime(2020, 1, 1, tzinfo=timezone.utc)
+    spark, _ = mock_connect
+    with pytest.raises(RuntimeError, match="timestamp hook failed") as raised:
+        spark.createDataFrame([(value,)], T.StructType().add("value", 
T.TimestampType()))
+    assert raised.value is error
+
+
 def test_null_timestamps_in_non_nullable_fields_raise_as_pyspark(mock_connect):
     pd = pytest.importorskip("pandas")
     from pyspark.sql import types as T


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

Reply via email to