spark-test commented on code in PR #60222:
URL: https://github.com/apache/spark/pull/60222#discussion_r4524026386


##########
python/pyspark/sql/classic/column.py:
##########
@@ -445,11 +445,18 @@ def contains(
     def startswith(
         self, other: Union[ParentColumn, "LiteralType", "DecimalLiteral", 
"DateTimeLiteral"]
     ) -> ParentColumn:
+        # The JVM `startsWith` is overloaded for `Column` and `String`. Always 
pass a `Column` so
+        # that Py4J does not pick the `Column` overload with a null argument 
for `None`.
+        if not isinstance(other, ParentColumn):

Review Comment:
   **Blocking (P1):** In classic PySpark this guard also converts a `str` (and 
a str-valued Enum), not just `None`. `_create_column_from_literal` first calls 
`get_active_spark_context()`, so building a predicate from a string now needs 
an active SparkContext. On the base branch, `_bin_op` passed the string 
straight to the JVM `startsWith(String)`/`endsWith(String)` overload, which 
already wraps it in `lit` and needs no session. Spark Connect builds its 
literal on the client and is unaffected.
   
   For example, tracing the code for a Column kept from a stopped session:
   
   ```python
   c = sf.col("s")
   spark.stop()
   c.startswith("a")  # base branch: a Column; this PR: 
SESSION_OR_CONTEXT_NOT_EXISTS
   ```
   
   `SparkContext.stop()` stops the JVM context and clears 
`_active_spark_context` but leaves the Py4J gateway running 
(`SparkSession.stop()` itself keeps calling into the JVM right after it), so 
the base-branch call still works in that state. With an active session the 
result is unchanged, but every string call now makes three more synchronous 
Py4J round trips (looking up `functions` and `lit`, then calling `lit`) plus a 
queued release of the temporary proxy, only to build the literal that the 
`String` overload already builds.
   
   A Python `str` can only bind the `String` overload, so it has no ambiguity 
to fix. Unwrapping an Enum first and converting only values that are neither a 
Column nor a `str` keeps strings on the old path, while `None` and other 
literals still get a literal Column:
   
   ```python
   other = enum_to_value(other)
   if not isinstance(other, (ParentColumn, str)):
       other = Column(_create_column_from_literal(other))
   ```
   
   Then the code comment above the guard can explain why strings are skipped, 
and `endswith` below needs the same change.
   
   **Verification:**
   - **Regression:** Check that classic startswith and endswith, with a str 
argument and with a str-valued Enum argument, build a Column while no 
SparkContext is active. This is the case that raised 
SESSION_OR_CONTEXT_NOT_EXISTS with the PR's version.
   - **Inspection:** Check that a str argument reaches the JVM String overload 
directly, without a literal built in Python, so the call adds no Py4J round 
trips over the base branch.
   - **Behavior:** Check that startswith(None) and endswith(None) still return 
NULL for every row, and that a non-string literal argument such as 1 still 
gives the implicit-cast result, in both classic and Spark Connect.
   - **Compatibility:** Check that string and StrEnum arguments return the same 
rows as on the base branch when a SparkContext is active.



##########
python/pyspark/sql/tests/test_column.py:
##########
@@ -123,6 +123,14 @@ def test_column_operators(self):
             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)])

Review Comment:
   **Nit (P3):** This assertion catches a revert only in some runs. If either 
conversion in `classic/column.py` is reverted, `_bin_op` passes `None` to the 
JVM again, and in a run where Py4J binds the `String` overload, 
`startsWith(lit(null))` returns the same `[Row(r=None), Row(r=None)]`, so the 
test still passes. The PR description itself reports that this binding varies 
between JVM runs, and the Spark Connect parity run builds the null literal on 
the client, so it never reaches the classic code. In addition, no test 
exercises the non-string literals that classic `startswith`/`endswith` now 
accept, such as `1`, a `Decimal`, or a date, so a later narrowing of the 
conversion would go unnoticed.
   
   A classic-only check that the JVM method receives a Column for `None` (for 
example through a recording stand-in for the Column's JVM object, or 
`unittest.mock` around `_bin_op`) fails on every run after a revert. A mixin 
case such as `df.s.startswith(1)`, which classic and Spark Connect now both 
accept, pins the new literal support.
   
   **Verification:**
   - **Regression:** Check that in classic mode startswith(None) and 
endswith(None) pass a Column, not None, to the JVM method, so that reverting 
either conversion fails deterministically.
   - **Behavior:** Check that startswith and endswith with a non-string literal 
such as 1 return the implicit-cast result in both classic and Spark Connect.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to