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 5dd419ef [SPARK-61269][CONNECT] Fast-path exact integer literals in 
Spark Connect Rust
5dd419ef is described below

commit 5dd419ef4dc383acd518d2a4b7d9d20e6575da36
Author: DB Tsai <[email protected]>
AuthorDate: Tue Nov 10 07:19:51 2026 +0900

    [SPARK-61269][CONNECT] Fast-path exact integer literals in Spark Connect 
Rust
    
    ### What changes were proposed in this pull request?
    
    Jira: [SPARK-61269](https://issues.apache.org/jira/browse/SPARK-61269).
    
    Add an exact built-in `int` branch to the Rust scalar-to-Column conversion 
used by expressions such as `F.col("id") == 5`. Values within the signed 64-bit 
range directly produce integer or long literals, using the existing signed 
32-bit boundary. Consolidate that literal classification in one helper.
    
    Boolean values, integer subclasses, `IntEnum`, NumPy scalars and 
out-of-range integers retain the generic conversion path. Add wire-boundary, 
boolean and probe-sentinel regression tests.
    
    ### Why are the changes needed?
    
    Exact integer operands currently repeat generic enum, NumPy and 
nonprimitive scalar checks during expression construction. Their exact Python 
type and integer value provide the information needed to construct the literal 
directly.
    
    Two preplanned local fake-server runs compared the same patch with Rust 
master at `0ac7a0f4e8c98a2d13157175b20c9ebb3c536c28`. Each run used 45 
fresh-process samples per client and case across 12 cases; the runs were 
evaluated separately.
    
    | Expression construction target | Run A, master → patch | Run B, master → 
patch |
    | --- | --- | --- |
    | Wall time per operation | 0.580084 → 0.505625 ms (−12.84%) | 0.573583 → 
0.516083 ms (−10.02%) |
    | CPU time per operation | 0.313 → 0.262 ms (−16.29%) | 0.318 → 0.265 ms 
(−16.67%) |
    
    All measured regression guards passed in both runs. These are exploratory 
local measurements: the original same-binary control remained noise-uncertain, 
the full benchmark catalog was not completed, and they establish no general or 
separately accepted memory improvement. The comparison is with the pinned 
master revision above; it has not been repeated against the current target 
branch.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Expressions with exact built-in integer operands avoid repeated 
scalar-type probes. Literal wire types and overflow behavior are preserved.
    
    ### How was this patch tested?
    
    - Added tests for signed 32-bit/64-bit wire boundaries, integer subclasses, 
`IntEnum`, boolean literal types and exact-integer probe avoidance. The 
probe-sentinel test passed on the patch and failed at the intended 
plain-integer comparison on the pinned master.
    - `test_dropin_offline.py` and `test_arrow_handoff.py`: 2,589 passed, eight 
`SPARK_REMOTE`-dependent tests skipped, zero failures/errors. The separate 
unchanged `test_ml_offline.py` module passed all 72 tests.
    - Release Rust library tests: 495 passed. Integration and WebAssembly 
targets compiled with `--no-run`; formatting checks passed.
    - Four selected native live tests passed for the candidate and the same 
four passed for the official reference on Spark 4.3.0. Full native/API/official 
parity, full benchmark holdout and required CI coverage remain incomplete.
    - Workspace Clippy exited 101 with 140 errors and 297 warnings. The 38 
diagnosed files matched the pinned master source; master Clippy was not 
separately executed. This is a non-green result.
    
    The local tests and measurements above apply to the unchanged patch on 
pinned base `0ac7a0f4e8c98a2d13157175b20c9ebb3c536c28`. Current upstream master 
`8768cc4f780c7fb144e0b7a72ed5d5be14005023` is 35 commits ahead. The production 
conversion file is unchanged upstream and this two-file patch applies cleanly; 
a merged-base build/test and upstream CI have not been run.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: OpenAI Codex
    
    This pull request and its description were written by OpenAI Codex.
    
    Closes #430 from dbtsai/codex/expression-exact-integer-fast-path.
    
    Authored-by: DB Tsai <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/functions.rs  | 24 +++++++++----
 python/tests/test_dropin_offline.py | 70 +++++++++++++++++++++++++++++++++++++
 2 files changed, 87 insertions(+), 7 deletions(-)

diff --git a/crates/pyspark-rs/src/functions.rs 
b/crates/pyspark-rs/src/functions.rs
index 14ac379f..3aa22b96 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -220,12 +220,28 @@ pub(crate) fn value_not_between(py: Python<'_>) -> PyErr {
     )
 }
 
+/// An int32 literal within its range, otherwise a long, as PySpark's 
`_infer_type`.
+fn integer_literal(value: i64) -> LiteralExpression {
+    if let Ok(value) = i32::try_from(value) {
+        LiteralExpression::int(value)
+    } else {
+        LiteralExpression::long(value)
+    }
+}
+
 /// 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 ints need no Enum, NumPy or non-primitive scalar probing.
+    // Subclasses and out-of-range ints retain the generic conversion order 
below.
+    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))));
+        }
+    }
     // An Enum is the literal of its value, as PySpark's.
     let obj = &enum_to_value(obj)?;
 
@@ -278,13 +294,7 @@ pub fn to_column(obj: &Bound<'_, PyAny>) -> 
PyResult<Column> {
     }
 
     if let Ok(i) = obj.extract::<i64>() {
-        return Ok(Column::new(Expression::literal(
-            if i32::try_from(i).is_ok() {
-                LiteralExpression::int(i as i32)
-            } else {
-                LiteralExpression::long(i)
-            },
-        )));
+        return Ok(Column::new(Expression::literal(integer_literal(i))));
     }
     // An int beyond a long is not a double, as PySpark's literal of it: it is 
an error.
     if obj.is_instance_of::<pyo3::types::PyInt>() {
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index ad20a874..ca6d4ce1 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -12717,6 +12717,76 @@ def completion_analyzed():
         child.close()
 
 
[email protected]("value, wire_type", [
+    (-(2**63), "long"),
+    (-(2**31) - 1, "long"),
+    (-(2**31), "integer"),
+    (-1, "integer"),
+    (0, "integer"),
+    (2**31 - 1, "integer"),
+    (2**31, "long"),
+    (2**63 - 1, "long"),
+])
+def test_integer_literal_wire_boundaries(value, wire_type):
+    from enum import IntEnum
+
+    from pyspark.sql import functions as F
+    from pyspark.sql.connect import proto
+
+    class IntegerSubclass(int):
+        pass
+
+    class IntegerEnum(IntEnum):
+        VALUE = value
+
+    expected = proto.Expression.Literal()
+    setattr(expected, wire_type, value)
+    for scalar in (value, IntegerSubclass(value), IntegerEnum.VALUE):
+        literal = F.lit(scalar)._expr.to_plan(None).literal
+        compared = (F.col("id") == scalar)._expr.to_plan(None)
+        assert literal == expected
+        assert compared.unresolved_function.arguments[1].literal == expected
+
+
+def test_exact_integer_operators_skip_numpy_probes(monkeypatch):
+    import sys
+    from enum import IntEnum
+
+    from pyspark.sql import functions as F
+    from pyspark.sql.connect import proto
+
+    class IntegerSubclass(int):
+        pass
+
+    class IntegerEnum(IntEnum):
+        VALUE = 5
+
+    class ProbeSentinel:
+        @property
+        def ndarray(self):
+            raise RuntimeError("NumPy probe reached")
+
+    column = F.col("id")
+    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):
+            with pytest.raises(RuntimeError, match="NumPy probe reached"):
+                column == value
+
+
+def test_boolean_literals_keep_their_wire_type():
+    from pyspark.sql import functions as F
+    from pyspark.sql.connect import proto
+
+    for value in (False, True):
+        expected = proto.Expression.Literal(boolean=value)
+        assert F.lit(value)._expr.to_plan(None).literal == expected
+        compared = (F.col("flag") == value)._expr.to_plan(None)
+        assert compared.unresolved_function.arguments[1].literal == expected
+
+
 def test_int_literals_beyond_a_long_raise_value_not_between_as_pyspark():
     # As PySpark's LiteralExpression._infer_type: an int beyond the range of a 
long is an error,
     # not a double, which would make `col == 2**63` match the rows of the 
longs next to it. The


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

Reply via email to