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 d7bcfd90 [SPARK-61533][CONNECT][PYTHON] Fast-path exact primitive 
literals
d7bcfd90 is described below

commit d7bcfd90c0611f9bcbcda2b15d1bf6bbad65062f
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 20:25:27 2026 +0900

    [SPARK-61533][CONNECT][PYTHON] Fast-path exact primitive literals
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61533](https://issues.apache.org/jira/browse/SPARK-61533): fast-path 
exact built-in `bool`, `float`, `str`, `bytes`, and `bytearray` values when the 
Python client converts them to Spark literals.
    
    These exact types now produce their Rust `LiteralExpression` directly, 
before the generic Enum, NumPy, Decimal, and datetime probes. Subclasses, 
`IntEnum`, NumPy scalars, pandas values, out-of-range integers, and other 
objects retain the existing generic conversion order and behavior.
    
    The regression test verifies both sides of that boundary: exact built-ins 
skip a sentinel NumPy probe, while subclasses and `IntEnum` still reach it.
    
    ### Why are the changes needed?
    
    Common literal values currently perform several Python module, attribute, 
and instance checks whose results cannot affect an exact built-in primitive. 
This overhead occurs in `lit(...)`, Column operators, and other APIs that route 
values through the same conversion.
    
    Release-mode Python 3.13 microbenchmarks compared this patch with master 
`cdf38e8`. Each process measured 150,000 `F.lit` calls per case, took the 
median of nine `timeit` repeats, and used fresh processes. Two runs produced:
    
    | Exact value | Master | This patch | Reduction |
    | --- | ---: | ---: | ---: |
    | `True` | 2.28–2.40 µs | 0.32–0.40 µs | 82.5–86.6% |
    | `1.0` | 2.45–2.57 µs | 0.33–0.41 µs | 83.1–87.1% |
    | `"x"` | 2.46–2.53 µs | 0.36–0.44 µs | 82.2–85.6% |
    | `b"x"` | 2.28–2.38 µs | 0.36–0.45 µs | 80.3–84.7% |
    | `bytearray(b"x")` | 2.43–2.48 µs | 0.53–0.54 µs | 77.9–78.6% |
    
    The already-fast-pathed exact integer was the unchanged control. It was 
within 1% in one comparison and 19% faster in the other, showing process-level 
timing variation; every targeted case remained at least 77.9% faster.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Expression construction with these exact built-in literal types is 
faster. Literal values, wire types, errors, and subclass behavior are unchanged.
    
    ### How was this patch tested?
    
    - The new regression test fails on the pinned master at the intended NumPy 
probe and passes with this patch.
    - Offline Python suites: 3,204 passed, 8 skipped, and 14 subtests passed.
    - `cargo build -p pyspark-rs --release`.
    - `cargo test -p apache-spark-connect --release --lib`: 622 passed.
    - `cargo test -p apache-spark-connect --release --no-run`.
    - `cargo test -p apache-spark-connect --release --features wasm-udf 
--no-run`.
    - `cargo fmt --all --check`.
    - `ruff check python/tests/test_dropin_offline.py`.
    - Full-workspace clippy still exits on the repository's existing `-D 
warnings` backlog; it reports no finding in the changed code.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Codex (GPT-5)
    
    This pull request and its description were written by Isaac.
    
    Closes #565 from zhengruifeng/optimize-primitive-literal-fastpaths.
    
    Authored-by: Ruifeng Zheng <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/functions.rs  | 27 +++++++++++++++++++++-
 python/tests/test_dropin_offline.py | 45 ++++++++++++++++++++++++++++++++-----
 2 files changed, 65 insertions(+), 7 deletions(-)

diff --git a/crates/pyspark-rs/src/functions.rs 
b/crates/pyspark-rs/src/functions.rs
index f57b7830..d8186191 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -249,13 +249,38 @@ pub fn to_column(obj: &Bound<'_, PyAny>) -> 
PyResult<Column> {
     if let Ok(col) = obj.extract::<Bound<'_, PyColumn>>() {
         return Ok(col.borrow().column.clone());
     }
-    // Exact built-in ints need no Enum, NumPy or non-primitive scalar probing.
+    // 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.
+    if let Ok(boolean) = obj.cast_exact::<pyo3::types::PyBool>() {
+        return Ok(Column::new(Expression::literal(
+            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))));
         }
     }
+    if let Ok(float) = obj.cast_exact::<pyo3::types::PyFloat>() {
+        return Ok(Column::new(Expression::literal(LiteralExpression::double(
+            float.extract()?,
+        ))));
+    }
+    if let Ok(string) = obj.cast_exact::<pyo3::types::PyString>() {
+        return match string.extract::<String>() {
+            Ok(string) => 
Ok(Column::new(Expression::literal(LiteralExpression::string(
+                string,
+            )))),
+            Err(_) => Err(not_utf8_string(obj)),
+        };
+    }
+    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()?,
+        ))));
+    }
     // An Enum is the literal of its value, as PySpark's.
     let obj = &enum_to_value(obj)?;
 
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 305d5b50..00c83baa 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -16249,16 +16249,29 @@ def test_integer_literal_wire_boundaries(value, 
wire_type):
         assert compared.unresolved_function.arguments[1].literal == expected
 
 
-def test_exact_integer_operators_skip_numpy_probes(monkeypatch):
+def test_exact_primitive_literals_skip_numpy_probes(monkeypatch):
     import sys
     from enum import IntEnum
 
+    from pyspark import _pyspark
     from pyspark.sql import functions as F
     from pyspark.sql.connect import proto
 
     class IntegerSubclass(int):
         pass
 
+    class FloatSubclass(float):
+        pass
+
+    class StringSubclass(str):
+        pass
+
+    class BytesSubclass(bytes):
+        pass
+
+    class ByteArraySubclass(bytearray):
+        pass
+
     class IntegerEnum(IntEnum):
         VALUE = 5
 
@@ -16267,14 +16280,34 @@ def 
test_exact_integer_operators_skip_numpy_probes(monkeypatch):
         def ndarray(self):
             raise RuntimeError("NumPy probe reached")
 
-    column = F.col("id")
+    exact = [
+        (None, 
proto.Expression.Literal(null=proto.DataType(null=proto.DataType.NULL()))),
+        (True, proto.Expression.Literal(boolean=True)),
+        (5, proto.Expression.Literal(integer=5)),
+        (1.25, proto.Expression.Literal(double=1.25)),
+        ("x", proto.Expression.Literal(string="x")),
+        (b"x", proto.Expression.Literal(binary=b"x")),
+        (bytearray(b"x"), proto.Expression.Literal(binary=b"x")),
+    ]
+    for value, expected in exact:
+        assert F.lit(value)._expr.to_plan(None).literal == expected
+
     with monkeypatch.context() as patch:
         patch.setitem(sys.modules, "numpy", ProbeSentinel())
-        compared = (column == 5)._expr.to_plan(None)
-        assert compared.unresolved_function.arguments[1].literal == 
proto.Expression.Literal(integer=5)
-        for value in (IntegerSubclass(5), IntegerEnum.VALUE, True, 2**63):
+        for value, expected in exact:
+            literal = 
_pyspark.functions.pyfunc_lit(value)._expr.to_plan(None).literal
+            assert literal == expected
+        for value in (
+            IntegerSubclass(5),
+            FloatSubclass(1.25),
+            StringSubclass("x"),
+            BytesSubclass(b"x"),
+            ByteArraySubclass(b"x"),
+            IntegerEnum.VALUE,
+            2**63,
+        ):
             with pytest.raises(RuntimeError, match="NumPy probe reached"):
-                column == value
+                _pyspark.functions.pyfunc_lit(value)
 
 
 def test_boolean_literals_keep_their_wire_type():


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

Reply via email to