This is an automated email from the ASF dual-hosted git repository.

zhengruifeng pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new 53b0d0a2cfc9 [SPARK-48995][PYTHON] Fix intermittent 
NullPointerException in Column.startswith/endswith with None
53b0d0a2cfc9 is described below

commit 53b0d0a2cfc9af54e036f79efa79cbf41678540a
Author: Narendra Singh <[email protected]>
AuthorDate: Wed Nov 11 09:08:54 2026 +0800

    [SPARK-48995][PYTHON] Fix intermittent NullPointerException in 
Column.startswith/endswith with None
    
    ### What changes were proposed in this pull request?
    
    In classic PySpark, `Column.startswith` and `Column.endswith` now convert a 
non-`Column`, non-`str` argument (such as `None`) to a literal `Column` before 
calling the JVM, so the `Column` overload of `startsWith`/`endsWith` is used 
for it. `str` arguments (including str-valued Enums) still go directly to the 
`String` overload, as before.
    
    ### Why are the changes needed?
    
    `df.s.startswith(None)` / `df.s.endswith(None)` intermittently fail with:
    
    ```
    py4j.protocol.Py4JJavaError: An error occurred while calling o51.startsWith.
    : java.lang.NullPointerException: Cannot invoke 
"org.apache.spark.sql.Column.expr()" because "x$1" is null
    ```
    
    `None` is passed to the JVM as `null`, and `Column.startsWith`/`endsWith` 
are overloaded for `Column` and `String`. Py4J cannot tell the overloads apart 
for a `null` argument, and the one it picks varies between JVM runs. When it 
picks the `Column` overload, `Column.fn` dereferences the null. When it picks 
the `String` overload, `lit(null)` is used and the result is `NULL`.
    
    On master, running `df.s.startswith(None)` and `df.s.endswith(None)` in 6 
fresh sessions failed in 5 of them, on different methods each time. Spark 
Connect is not affected because it creates `lit(None)` on the client.
    
    `str` arguments still use the `String` overload directly, so results for 
string literals do not change.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    - `Column.startswith(None)` and `Column.endswith(None)` in classic PySpark 
now consistently return `NULL` (same as Spark Connect and as `contains(None)`), 
instead of sometimes failing with a `NullPointerException`.
    - Classic `Column.startswith`/`endswith` now also accept non-string 
literals such as `int`, `float` or `Decimal`, which are cast to string as in 
SQL and Spark Connect (for example, `df.s.startswith(1)` is true for values 
starting with `'1'`). Before, these failed with a Py4J error such as `Method 
startsWith([class java.lang.Integer]) does not exist`.
    
    ### How was this patch tested?
    
    Added `test_startswith_endswith_with_none` and 
`test_startswith_endswith_with_non_string_literal` to `ColumnTestsMixin`, so 
they run for both classic (`test_column`) and Spark Connect 
(`test_parity_column`). The second one fails deterministically without this 
change.
    
    Also checked manually by repeating the following in 6 fresh sessions: 
before this change 5 of 6 failed, after it all return `[None, None]`.
    
    ```python
    df = spark.createDataFrame([("abc",), (None,)], "s string")
    df.select(df.s.startswith(None)).collect()
    df.select(df.s.endswith(None)).collect()
    ```
    
    Also checked that `col("s").startswith("a")` still builds a `Column` 
without an active `SparkContext`.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    Generated-by: Claude Code (Claude Opus 5.5)
    
    Closes #60222 from CODERNSINGH/SPARK-48995-startswith-none.
    
    Authored-by: Narendra Singh <[email protected]>
    Signed-off-by: Ruifeng Zheng <[email protected]>
    
    (cherry picked from commit 078972b9c18f2e78e97200c14ef892f1ba5d9ec3)
    Signed-off-by: Ruifeng Zheng <[email protected]>
    
    
    skip-checks: true
---
 python/pyspark/sql/classic/column.py    | 10 ++++++++++
 python/pyspark/sql/tests/test_column.py | 16 ++++++++++++++++
 2 files changed, 26 insertions(+)

diff --git a/python/pyspark/sql/classic/column.py 
b/python/pyspark/sql/classic/column.py
index 4a3ac86968ff..46c042b8a113 100644
--- a/python/pyspark/sql/classic/column.py
+++ b/python/pyspark/sql/classic/column.py
@@ -445,11 +445,21 @@ class Column(ParentColumn):
     def startswith(
         self, other: Union[ParentColumn, "LiteralType", "DecimalLiteral", 
"DateTimeLiteral"]
     ) -> ParentColumn:
+        # The JVM `startsWith` is overloaded for `Column` and `String`. A 
`str` can only bind the
+        # `String` overload, but for `None` (a JVM null) Py4J may pick the 
`Column` overload and
+        # fail with a NullPointerException, so pass other literals as a 
`Column`.
+        other = enum_to_value(other)
+        if not isinstance(other, (ParentColumn, str)):
+            other = Column(_create_column_from_literal(other))
         return _bin_op("startsWith", self, other)
 
     def endswith(
         self, other: Union[ParentColumn, "LiteralType", "DecimalLiteral", 
"DateTimeLiteral"]
     ) -> ParentColumn:
+        # See the comment in `startswith`.
+        other = enum_to_value(other)
+        if not isinstance(other, (ParentColumn, str)):
+            other = Column(_create_column_from_literal(other))
         return _bin_op("endsWith", self, other)
 
     def like(self: ParentColumn, other: str) -> ParentColumn:
diff --git a/python/pyspark/sql/tests/test_column.py 
b/python/pyspark/sql/tests/test_column.py
index a3c1d680cbd7..c6503991a79f 100644
--- a/python/pyspark/sql/tests/test_column.py
+++ b/python/pyspark/sql/tests/test_column.py
@@ -123,6 +123,22 @@ class ColumnTestsMixin:
             ValueError, "Cannot apply 'in' operator against a column", lambda: 
1 in cs
         )
 
+    def test_startswith_endswith_with_none(self):
+        # SPARK-48995: startswith/endswith with None should return null 
instead of failing
+        df = self.spark.createDataFrame([("abc",), (None,)], "s string")
+        for name in ["startswith", "endswith"]:
+            with self.subTest(name=name):
+                result = df.select(getattr(df.s, 
name)(None).alias("r")).collect()
+                self.assertEqual(result, [Row(r=None), Row(r=None)])
+
+    def test_startswith_endswith_with_non_string_literal(self):
+        # SPARK-48995: non-string literals are cast to string, as in SQL and 
Spark Connect
+        df = self.spark.createDataFrame([("1abc1",), ("abc",), (None,)], "s 
string")
+        for name in ["startswith", "endswith"]:
+            with self.subTest(name=name):
+                result = df.select(getattr(df.s, name)(1).alias("r")).collect()
+                self.assertEqual(result, [Row(r=True), Row(r=False), 
Row(r=None)])
+
     def test_column_date_time_op(self):
         query = """
             SELECT * FROM VALUES


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

Reply via email to