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 7df14ee9 [SPARK-61452][CONNECT][PYTHON] Cache Python objects when
collecting rows
7df14ee9 is described below
commit 7df14ee9526dc8fec81ac7086b4834380735e80c
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 07:00:18 2026 +0900
[SPARK-61452][CONNECT][PYTHON] Cache Python objects when collecting rows
## What changed
JIRA: https://issues.apache.org/jira/browse/SPARK-61452
- Cache the Python `datetime` classes and immutable UTC/naive epoch objects
used when collected Spark values are materialized.
- Cache `decimal.Decimal` for collected decimal values.
- Reuse the cached objects through `PyOnceLock` instead of importing
modules and resolving attributes for every field.
## Performance
Release-mode microbenchmark of the actual `row::value_to_py` path on x86_64
with Python 3.13.12. Each result is the median of 200,000 conversions over 7-9
rounds; the comparison was repeated in two fresh Python processes.
| Value type | Before | After | Speedup | Time reduction |
| --- | ---: | ---: | ---: | ---: |
| Date | 526-545 ns/value | 195-196 ns/value | 2.68-2.79x | 62.8-64.2% |
| Decimal | 541-550 ns/value | 195-198 ns/value | 2.78x | 64.0-64.1% |
| Day-time interval | 644-650 ns/value | 295-296 ns/value | 2.18-2.21x |
54.1-54.6% |
| Timestamp | 3,479-3,583 ns/value | 1,965-1,994 ns/value | 1.77-1.80x |
43.5-44.4% |
| Timestamp NTZ | 1,252-1,390 ns/value | 444-462 ns/value | 2.82-3.01x |
64.5-66.8% |
This isolates Python scalar materialization. End-to-end `collect()` also
includes RPC, Arrow decoding, and row construction, so its overall percentage
improvement depends on the returned schema and workload.
## Affected operations
The optimization speeds up actions that materialize Spark results as Python
`Row` objects: `collect()`, `first()`, `head()` / `head(n)`, `take(n)`,
`tail(n)`, and `toLocalIterator()`.
The gain applies to `DateType`, `TimestampType`, `TimestampNTZType`,
`TimeType`, `DayTimeIntervalType`, and `DecimalType`, including those values
nested inside arrays, maps, and structs. Primitive-only rows are unchanged.
It does not materially affect `count()`, `show()`, `toArrow()`, or
`toPandas()`, because those paths either avoid Python scalar row
materialization or do not materialize the affected types. RPC and Arrow
decoding time are also unchanged.
## Tests
- `cargo build -p pyspark-rs --release --locked`
- `cargo fmt --all --check`
- `cargo test -p apache-spark-connect --release --lib`
- `cargo test -p apache-spark-connect --release --no-run`
- `cargo test -p apache-spark-connect --release --features wasm-udf
--no-run`
- Offline Python suite: 3,116 passed, 8 skipped, 14 subtests passed
This pull request and its description were written by Isaac.
Closes #513 from zhengruifeng/optimize-row-python-object-caching.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/row.rs | 61 +++++++++++++++++++++++++++++++-------------
1 file changed, 43 insertions(+), 18 deletions(-)
diff --git a/crates/pyspark-rs/src/row.rs b/crates/pyspark-rs/src/row.rs
index 4970d3f3..8ec592ed 100644
--- a/crates/pyspark-rs/src/row.rs
+++ b/crates/pyspark-rs/src/row.rs
@@ -5,15 +5,48 @@ use std::sync::Arc;
use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
-use pyo3::types::{PyByteArray, PyBytes, PyDict, PyList, PyTuple};
+use pyo3::types::{PyByteArray, PyBytes, PyDict, PyList, PyTuple, PyType};
use spark_connect::row::{StructValue, Value};
/// Functions that deserialize user-defined or spatial values in each result
field.
pub(crate) type FieldConverters = Arc<Vec<Option<Py<PyAny>>>>;
static CREATE_ROW: PyOnceLock<Py<PyAny>> = PyOnceLock::new();
+static DATETIME_OBJECTS: PyOnceLock<DateTimeObjects> = PyOnceLock::new();
+static DECIMAL: PyOnceLock<Py<PyType>> = PyOnceLock::new();
const ROW_SOURCE: &std::ffi::CStr = pyo3::ffi::c_str!(include_str!("row.py"));
+/// Python classes and immutable epoch values used for every collected
date/time value.
+/// Resolving them once avoids repeated imports and module attribute lookups
per field.
+struct DateTimeObjects {
+ date: Py<PyType>,
+ time: Py<PyType>,
+ timedelta: Py<PyType>,
+ naive_epoch: Py<PyAny>,
+ utc_epoch: Py<PyAny>,
+}
+
+fn datetime_objects(py: Python<'_>) -> PyResult<&DateTimeObjects> {
+ DATETIME_OBJECTS.get_or_try_init(py, || {
+ let module = py.import("datetime")?;
+ let class = |name: &str| -> PyResult<Bound<'_, PyType>> {
+ Ok(module.getattr(name)?.cast_into::<PyType>()?)
+ };
+ let datetime = class("datetime")?;
+ let naive_epoch = datetime.call1((1970, 1, 1))?;
+ let kwargs = PyDict::new(py);
+ kwargs.set_item("tzinfo",
module.getattr("timezone")?.getattr("utc")?)?;
+ let utc_epoch = datetime.call((1970, 1, 1), Some(&kwargs))?;
+ Ok(DateTimeObjects {
+ date: class("date")?.unbind(),
+ time: class("time")?.unbind(),
+ timedelta: class("timedelta")?.unbind(),
+ naive_epoch: naive_epoch.unbind(),
+ utc_epoch: utc_epoch.unbind(),
+ })
+ })
+}
+
/// Expose the embedded tuple `Row` as `pyspark._pyspark.Row`, re-exported by
the Python shims.
/// Its source imports PySpark modules only inside methods, avoiding import
cycles
/// while `pyspark.sql.types` is importing this extension.
@@ -176,19 +209,12 @@ pub(crate) fn row_values_to_py(
/// `datetime.datetime(1970, 1, 1)`, the epoch of Spark's timestamps, without
a time zone.
fn naive_epoch(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
- py.import("datetime")?
- .getattr("datetime")?
- .call1((1970, 1, 1))
+ Ok(datetime_objects(py)?.naive_epoch.bind(py).clone())
}
/// `datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)`, the epoch
of the instants.
fn utc_epoch(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
- let datetime = py.import("datetime")?;
- let kwargs = PyDict::new(py);
- kwargs.set_item("tzinfo", datetime.getattr("timezone")?.getattr("utc")?)?;
- datetime
- .getattr("datetime")?
- .call((1970, 1, 1), Some(&kwargs))
+ Ok(datetime_objects(py)?.utc_epoch.bind(py).clone())
}
/// The `datetime.timedelta` of `micros` microseconds, exact over the whole
i64 range: a float
@@ -196,7 +222,7 @@ fn utc_epoch(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
fn micros_timedelta(py: Python<'_>, micros: i64) -> PyResult<Bound<'_, PyAny>>
{
let days = micros.div_euclid(86_400_000_000);
let remainder = micros.rem_euclid(86_400_000_000);
- py.import("datetime")?.getattr("timedelta")?.call1((
+ datetime_objects(py)?.timedelta.bind(py).call1((
days,
remainder / 1_000_000,
remainder % 1_000_000,
@@ -230,8 +256,8 @@ fn value_to_py<'py>(
Value::Binary(b) => PyByteArray::new(py, b).into_any(),
Value::Date(d) => {
// Convert days-since-epoch (i32) to datetime.date
- let date_mod = py.import("datetime")?;
- let date_cls = date_mod.getattr("date")?;
+ let datetime = datetime_objects(py)?;
+ let date_cls = datetime.date.bind(py);
if (-719_162..=2_932_896).contains(d) {
// 719163 is the ordinal of 1970-01-01
let ordinal = (*d as i64) + 719163i64;
@@ -241,7 +267,7 @@ fn value_to_py<'py>(
// `date(1970, 1, 1) + timedelta(days=d)`, which raises its
OverflowError.
let kwargs = PyDict::new(py);
kwargs.set_item("days", *d)?;
- let delta = date_mod.getattr("timedelta")?.call((),
Some(&kwargs))?;
+ let delta = datetime.timedelta.bind(py).call((),
Some(&kwargs))?;
date_cls.call1((1970, 1, 1))?.add(delta)?.into_any()
}
}
@@ -265,7 +291,7 @@ fn value_to_py<'py>(
);
let (minutes, remainder) = (remainder / 60_000_000_000, remainder
% 60_000_000_000);
let (seconds, remainder) = (remainder / 1_000_000_000, remainder %
1_000_000_000);
- py.import("datetime")?.getattr("time")?.call1((
+ datetime_objects(py)?.time.bind(py).call1((
hours,
minutes,
seconds,
@@ -278,7 +304,7 @@ fn value_to_py<'py>(
// The resulting +/-107 million days fit timedelta's +/-999999999
days.
let days = micros.div_euclid(86_400_000_000);
let remainder = micros.rem_euclid(86_400_000_000);
- py.import("datetime")?.getattr("timedelta")?.call1((
+ datetime_objects(py)?.timedelta.bind(py).call1((
days,
remainder / 1_000_000,
remainder % 1_000_000,
@@ -299,8 +325,7 @@ fn value_to_py<'py>(
}
Value::Decimal { value, .. } => {
// Convert to Python decimal.Decimal by instantiating the class
- let decimal_mod = py.import("decimal")?;
- let decimal_cls = decimal_mod.getattr("Decimal")?;
+ let decimal_cls = DECIMAL.import(py, "decimal", "Decimal")?;
decimal_cls.call1((value.as_str(),))?.into_any()
}
Value::List(items) => {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]