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 4626c3ae [SPARK-61541][CONNECT][PYTHON] Fast-path exact primitive
values in Column methods
4626c3ae is described below
commit 4626c3aed7c7172c1e74f24645529a849fed2913
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 22:03:56 2026 +0900
[SPARK-61541][CONNECT][PYTHON] Fast-path exact primitive values in Column
methods
### What changes were proposed in this pull request?
Use the existing exact-primitive literal fast paths at the start of
`to_value_column()`, before its Enum and NumPy probes. Share the converter with
`to_column()` so both entry points use the same encoding rules for exact
`bool`, signed-64-bit `int`, `float`, `str`, `bytes`, and `bytearray` values.
This speeds up `Column.isin()` (once per candidate value), `getItem()`,
indexing, chained `Column.when()`, and `otherwise()`. Field access such as
`col.field` also delegates to indexing. Subclasses, Enum values, oversized
integers, lists, NumPy inputs, and other scalar types retain their existing
fallback handling.
### Why are the changes needed?
The earlier primitive optimization in `to_column()` is reached only after
`to_value_column()` has already performed its Enum and NumPy checks. For a
large `isin()` expression, those redundant checks repeat for every argument.
Release-build microbenchmark against base commit `87e9a09`, using CPython
3.13.12, PyO3 0.28.3 (`abi3-py39`), Linux x86_64, and an Intel Xeon Platinum
8375C. Inputs and base columns 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. Numbers are the median of each process's
median of five `timeit` samples, in microseconds per expression construction.
| Expression | Before (µs) | After (µs) | Speedup |
|---|---:|---:|---:|
| `col.isin(10 integers)` | 6.500 | 1.975 | 3.29× |
| `col.isin(1,000 integers)` | 519.841 | 86.081 | 6.04× |
| `col.isin(10 strings)` | 7.225 | 2.442 | 2.96× |
| `col.isin(1,000 strings)` | 607.928 | 135.885 | 4.47× |
| `col.getItem("key")` | 1.132 | 0.661 | 1.71× |
| `col[1]` | 0.951 | 0.432 | 2.20× |
| `when_col.when(condition, True)` | 1.240 | 0.729 | 1.70× |
| `when_col.otherwise(1.25)` | 1.118 | 0.665 | 1.68× |
| `when_col.otherwise(b"x")` | 1.185 | 0.683 | 1.73× |
These are client-side expression-construction timings, not Spark query
execution speedups. Controls: `F.lit(1)` measured 0.343→0.348 µs and
`F.lit("x")` 0.377→0.387 µs. List, Decimal, integer-subclass, and IntEnum
fallback controls ranged from unchanged to 4% slower (at most 0.124 µs/call);
fallback inputs now pass the additional exact-type checks.
<details>
<summary>Benchmark reproduction</summary>
Build `pyspark-rs` with `cargo build -p pyspark-rs --release` at the base
and PR commits. Save each release library, install the selected library as
`python/pyspark/_pyspark.so`, and run the following with `PYTHONPATH=python` in
a fresh Python process. Alternate builds for five process pairs, reverse their
order on alternate pairs, and take the median of the five process medians. No
builds or tests ran concurrently with the benchmark.
```python
import os
import statistics
import timeit
from decimal import Decimal
from enum import IntEnum
from pyspark.sql import functions as F
os.sched_setaffinity(0, {0})
class IntegerSubclass(int):
pass
class IntegerEnum(IntEnum):
VALUE = 5
col = F.col("a")
condition = col > 0
when_col = F.when(condition, 0)
ints10, ints1000 = list(range(10)), list(range(1000))
strs10 = [f"key{i}" for i in range(10)]
strs1000 = [f"key{i}" for i in range(1000)]
array, decimal = [1, 2, 3], Decimal("1.25")
subclass, enum = IntegerSubclass(5), IntegerEnum.VALUE
cases = [
("isin_10_ints", lambda: col.isin(ints10), 10000),
("isin_1000_ints", lambda: col.isin(ints1000), 300),
("isin_10_strings", lambda: col.isin(strs10), 10000),
("isin_1000_strings", lambda: col.isin(strs1000), 300),
("getItem", lambda: col.getItem("key"), 20000),
("index", lambda: col[1], 20000),
("when", lambda: when_col.when(condition, True), 20000),
("otherwise_float", lambda: when_col.otherwise(1.25), 20000),
("otherwise_bytes", lambda: when_col.otherwise(b"x"), 20000),
("control_lit_int", lambda: F.lit(1), 20000),
("control_lit_str", lambda: F.lit("x"), 20000),
("control_list", lambda: when_col.otherwise(array), 10000),
("control_decimal", lambda: when_col.otherwise(decimal), 10000),
("control_subclass", lambda: when_col.otherwise(subclass), 10000),
("control_enum", lambda: when_col.otherwise(enum), 10000),
]
for name, call, number in cases:
timer = timeit.Timer(call)
timer.timeit(number=1000)
samples = timer.repeat(repeat=5, number=number)
print(name, statistics.median(samples) / number * 1e6)
```
</details>
### Does this PR introduce _any_ user-facing change?
Faster construction of Column expressions using exact primitive values. No
API or literal-encoding changes.
### How was this patch tested?
- Added regression tests for all five affected entry points. They verify
wire encoding, integer boundaries, signed zero, NaN/infinity, Unicode and
binary values, and unchanged fallback probing for subclasses, IntEnum and
oversized integers. All five cases fail on the baseline and pass with this
change.
- Offline Python suites: 3,236 passed, 8 skipped, and 14 subtests passed.
- Official Spark 4.3.0 Column parity suite against the drop-in and a local
Connect server: 137 passed, 2 skipped (`spark.sql.timeType.enabled=true`, UTC).
- Rust core unit tests: 626 passed; all integration tests compiled,
including with `wasm-udf` enabled.
- `cargo fmt --all --check`, Python Ruff, and the public callable/property
introspection comparison across 12 reference Connect classes passed (zero
missing members).
- `cargo clippy --workspace --all-targets` fails on existing lints on both
the base and this branch. A separate comparison of `cargo clippy -p pyspark-rs
--lib` found the same 59 errors on both, matching diagnostic codes, messages,
and files.
### 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 #572 from zhengruifeng/optimize-value-column-fastpaths.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/functions.rs | 44 ++++++++++++++++---------------
python/tests/test_dropin_offline.py | 52 +++++++++++++++++++++++++++++++++++++
2 files changed, 75 insertions(+), 21 deletions(-)
diff --git a/crates/pyspark-rs/src/functions.rs
b/crates/pyspark-rs/src/functions.rs
index ad4faefe..dd62dd56 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -229,42 +229,41 @@ fn integer_literal(value: i64) -> LiteralExpression {
}
}
-/// Convert a Python object to a Rust Column (handles Column or scalars that
become literals).
-pub fn to_column(obj: &Bound<'_, PyAny>) -> PyResult<Column> {
- // Try to get as PyColumn first
- if let Ok(col) = obj.extract::<Bound<'_, PyColumn>>() {
- return Ok(col.borrow().column.clone());
- }
- // Exact built-in primitives need no Enum, NumPy or non-primitive scalar
probing.
- // Subclasses and out-of-range ints retain the generic conversion order
below.
+/// Exact built-in primitives need no Enum, NumPy or non-primitive scalar
probing.
+/// Subclasses and out-of-range ints retain the generic conversion order in
the callers.
+fn exact_primitive_literal(obj: &Bound<'_, PyAny>) ->
PyResult<Option<LiteralExpression>> {
if let Ok(boolean) = obj.cast_exact::<pyo3::types::PyBool>() {
- return Ok(Column::new(Expression::literal(
- LiteralExpression::boolean(boolean.extract()?),
- )));
+ return Ok(Some(LiteralExpression::boolean(boolean.extract()?)));
}
if let Ok(integer) = obj.cast_exact::<pyo3::types::PyInt>() {
if let Ok(value) = integer.extract::<i64>() {
- return
Ok(Column::new(Expression::literal(integer_literal(value))));
+ return Ok(Some(integer_literal(value)));
}
}
if let Ok(float) = obj.cast_exact::<pyo3::types::PyFloat>() {
- return Ok(Column::new(Expression::literal(LiteralExpression::double(
- float.extract()?,
- ))));
+ return Ok(Some(LiteralExpression::double(float.extract()?)));
}
if let Ok(string) = obj.cast_exact::<pyo3::types::PyString>() {
// A str that UTF-8 cannot encode raises the `UnicodeEncodeError` of
its encoding, as
// the str of a subclass below.
- return Ok(Column::new(Expression::literal(LiteralExpression::string(
- string.extract::<String>()?,
- ))));
+ return
Ok(Some(LiteralExpression::string(string.extract::<String>()?)));
}
if obj.is_exact_instance_of::<pyo3::types::PyBytes>()
|| obj.is_exact_instance_of::<pyo3::types::PyByteArray>()
{
- return Ok(Column::new(Expression::literal(LiteralExpression::Binary(
- obj.extract()?,
- ))));
+ return Ok(Some(LiteralExpression::Binary(obj.extract()?)));
+ }
+ Ok(None)
+}
+
+/// Convert a Python object to a Rust Column (handles Column or scalars that
become literals).
+pub fn to_column(obj: &Bound<'_, PyAny>) -> PyResult<Column> {
+ // Try to get as PyColumn first
+ if let Ok(col) = obj.extract::<Bound<'_, PyColumn>>() {
+ return Ok(col.borrow().column.clone());
+ }
+ if let Some(lit) = exact_primitive_literal(obj)? {
+ return Ok(Column::new(Expression::literal(lit)));
}
// An Enum is the literal of its value, as PySpark's.
let obj = &enum_to_value(obj)?;
@@ -361,6 +360,9 @@ pub fn to_column(obj: &Bound<'_, PyAny>) ->
PyResult<Column> {
/// CANNOT_INFER_ARRAY_ELEMENT_TYPE. `to_column` builds a list as `lit` does,
for the functions.
/// A NumPy array is not a value, as PySpark's `_from_value` does not take it,
though `lit` does.
pub(crate) fn to_value_column(obj: &Bound<'_, PyAny>) -> PyResult<Column> {
+ if let Some(lit) = exact_primitive_literal(obj)? {
+ return Ok(Column::new(Expression::literal(lit)));
+ }
let obj = &enum_to_value(obj)?;
if let Ok(list) = obj.cast::<pyo3::types::PyList>() {
return
Ok(Column::new(Expression::literal(typed_array_literal(list)?)));
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 7cfe1d97..34ca3b17 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -16946,6 +16946,58 @@ def
test_exact_primitive_literals_skip_numpy_probes(monkeypatch):
_pyspark.functions.pyfunc_lit(value)
[email protected]("method", ["isin", "getItem", "__getitem__", "when",
"otherwise"])
+def test_column_value_primitives_skip_numpy_probes(monkeypatch, method):
+ import sys
+ from enum import IntEnum
+
+ from pyspark.sql import functions as F
+
+ class IntegerEnum(IntEnum):
+ VALUE = 5
+
+ class ProbeSentinel:
+ @property
+ def ndarray(self):
+ raise RuntimeError("NumPy probe reached")
+
+ column = F.col("a")
+ condition = column > 0
+ when = F.when(condition, 0)
+ if method == "when":
+ build = lambda value: when.when(condition, value)
+ elif method == "otherwise":
+ build = when.otherwise
+ else:
+ build = getattr(column, method)
+
+ def literal(value):
+ plan = build(value)._expr.to_plan(None)
+ if method in ("getItem", "__getitem__"):
+ return plan.unresolved_extract_value.extraction.literal
+ index = {"isin": 1, "when": 3, "otherwise": 2}[method]
+ return plan.unresolved_function.arguments[index].literal
+
+ values = [
+ False, True, -(2**63), -(2**31) - 1, -(2**31), 0, 2**31 - 1, 2**31,
2**63 - 1,
+ -0.0, 1.25, float("inf"), float("nan"), "", "雪", b"", b"\x00\xff",
+ bytearray(), bytearray(b"\x00\xff"),
+ ]
+ expected = [F.lit(value)._expr.to_plan(None).literal.SerializeToString()
for value in values]
+ subclasses = [type(f"{type(value).__name__}Subclass", (type(value),),
{})(value)
+ for value in (5, 1.25, "x", b"x", bytearray(b"x"))]
+ with monkeypatch.context() as patch:
+ patch.setitem(sys.modules, "numpy", ProbeSentinel())
+ for value, wire in zip(values, expected):
+ # Serialized literals also distinguish signed zero and compare NaN
reliably.
+ assert literal(value).SerializeToString() == wire
+ with pytest.raises(UnicodeEncodeError):
+ build("\ud800")
+ for value in [*subclasses, IntegerEnum.VALUE, 2**63, -(2**63) - 1]:
+ with pytest.raises(RuntimeError, match="NumPy probe reached"):
+ build(value)
+
+
def test_boolean_literals_keep_their_wire_type():
from pyspark.sql import functions as F
from pyspark.sql.connect import proto
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]