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


##########
python/pyspark/pandas/data_type_ops/num_ops.py:
##########
@@ -100,6 +100,27 @@ def _cast_back_float(
     return expr
 
 
+def _python_mod(left: Any, right: Any) -> PySparkColumn:
+    """
+    Python and NumPy style modulo, whose result takes the sign of the divisor, 
as in NumPy.
+
+    Spark's remainder takes the sign of the dividend, so add the divisor only 
when the two
+    signs differ. ``((left % right) + right) % right`` returns NaN for an 
infinite divisor,
+    loses a small remainder next to a large divisor and can overflow for 
integers.
+    """
+    remainder = F.lit(left) % right
+    right_is_negative = F.lit(right) < 0
+    return (
+        # NumPy returns a zero with the sign of the divisor.
+        F.when(
+            remainder == 0,

Review Comment:
   **Blocking (P1):** `remainder` is used in six places of a short-circuiting 
CASE WHEN, and each place becomes its own expression occurrence. For a stateful 
nondeterministic operand kept inline, for example 
`F.monotonically_increasing_id()` or `F.randn(seed)` applied through 
`Series.spark.transform`, each occurrence carries its own state, subexpression 
elimination never merges nondeterministic expressions, and occurrences in arms 
a row doesn't take don't advance. Tracing the generated code, 
`ps.Series(range(6)).spark.transform(lambda c: F.monotonically_increasing_id()) 
% 3` in one partition gives `[0, 0, 1, 1, 2, 0]` instead of `[0, 1, 2, 0, 1, 
2]`, and a `randn` dividend modulo `0.5` can come back negative or above `0.5`. 
The same happens when such an operand is the divisor of `%` or `rmod`. The base 
formula read the dividend once, so these results were consistent. A 
nondeterministic column read by attribute, for example from `sdf.pandas_api()`, 
is not affected, because Spark never
  inlines it.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/pandas/data_type_ops/num_ops.py:
##########
@@ -100,6 +100,27 @@ def _cast_back_float(
     return expr
 
 
+def _python_mod(left: Any, right: Any) -> PySparkColumn:
+    """
+    Python and NumPy style modulo, whose result takes the sign of the divisor, 
as in NumPy.
+
+    Spark's remainder takes the sign of the dividend, so add the divisor only 
when the two
+    signs differ. ``((left % right) + right) % right`` returns NaN for an 
infinite divisor,
+    loses a small remainder next to a large divisor and can overflow for 
integers.
+    """
+    remainder = F.lit(left) % right
+    right_is_negative = F.lit(right) < 0
+    return (
+        # NumPy returns a zero with the sign of the divisor.
+        F.when(
+            remainder == 0,
+            F.when(right_is_negative, 
-F.abs(remainder)).otherwise(F.abs(remainder)),
+        )
+        .when((remainder < 0) != right_is_negative, remainder + right)

Review Comment:
   **Blocking (P1):** `remainder` and `remainder + right` have different 
decimal types, so Spark's CASE WHEN coercion casts every branch, the plain 
remainder included, to their wider type, which the base formula `((a % b) + b) 
% b` never produced. With a `decimal(38, s)` divisor and `s >= 7`, for example 
the `decimal(38,18)` that `spark.createDataFrame` infers for Python `Decimal` 
values, that common type has one fraction digit fewer than the remainder 
(`decimal(38,17)` for two `decimal(38,18)` columns), so the cast rounds 
same-sign remainders half-up with no error. Following Spark's type rules, 
`0.100000000000000001 % 0.300000000000000009` on two such columns now returns 
`0.10000000000000000`, where the base branch returned `0.100000000000000001` 
exactly, and `1.000000000000000001 % 1.000000000000000000` still returns zero, 
so the small-remainder fix doesn't reach decimals. Most other decimal pairs 
keep their values but gain an integral digit in the result type: `decimal(18,2) 
% dec
 imal(18,2)` becomes `decimal(19,2)`, which leaves Spark's compact 8-byte 
decimal storage and switches Parquet output from INT64 to FIXED_LEN_BYTE_ARRAY. 
With the internal 
`spark.sql.legacy.decimal.retainFractionDigitsOnTruncate=true`, a 
sign-differing row such as `-1.5 % Decimal(10**21)` on a `decimal(38,18)` 
Series overflows the branch cast to null, or to `NUMERIC_VALUE_OUT_OF_RANGE` 
under ANSI, where the base branch returned `999999999999999999998.5`. No test 
covers decimal operands here.
   
   **Recommended change:** For decimal operands, give the Python-style modulo 
the decimal type the base formula ((left % right) + right) % right had, derived 
from the operand types with Remainder's and Add's result-type rules under the 
session's decimal settings, and produce every result in that type directly: the 
exact Python-style remainder is changed to it once, with half-up rounding only 
where its scale is smaller than the remainder's. Integral and floating operands 
keep Remainder's type. Add pandas-on-Spark modulo cases for decimal(38,18), 
decimal(18,2) and mixed-precision operands that check spark.data_type as well 
as values, and Catalyst expression tests for the decimal result types.
   
   **Why this works:** With the result type declared once by the expression and 
no branches left for CaseWhenTypeCoercion to merge, a result never gains or 
loses digits relative to the base branch, and a remainder whose digits fit that 
type comes back exactly. Every result is at most the divisor's magnitude, so 
one overflows only on a sign-differing row whose divisor has 33 or more 
integral digits, where that type holds fewer integral digits than the divisor 
and the base branch's intermediate sum overflowed on the same row.
   
   **Scope:** The decimal result-type rule of the Python-style modulo 
expression, with decimal type and value tests in Catalyst and pandas-on-Spark.
   
   **Compatibility:** Decimal result types and every value the base branch 
already returned exactly.
   
   **Risks:** For a decimal(38, s>=7) divisor, zero and same-sign results that 
the base formula's rounded intermediate sum got wrong now come back exact, and 
for a divisor with 33 or more integral digits, same-sign results whose 
intermediate sum overflowed on the base branch, returning null or raising under 
ANSI, now come back, as they do with this PR; both correct values but change 
them relative to the base branch, as the PR does for doubles.
   
   **Constraints:** The rule must hold under both values of 
spark.sql.decimalOperations.allowPrecisionLoss and 
spark.sql.legacy.decimal.retainFractionDigitsOnTruncate.
   
   **Exclusions:**
   - pandas applies Python Decimal's remainder, which takes the dividend's 
sign, so negative decimal operands differ from pandas on the base branch and 
after this repair; changing that convention is outside this repair.
   
   **Success:** Every decimal modulo returns the decimal type ((left % right) + 
right) % right returned on the base branch: decimal(38,18) for two 
decimal(38,18) Series, decimal(10,2) for two decimal(10,2) Series and 
decimal(18,2) for two decimal(18,2) Series. 0.100000000000000001 % 
0.300000000000000009 on decimal(38,18) Series returns 0.100000000000000001, and 
1.000000000000000001 % 1.000000000000000000 returns 0.000000000000000001. With 
spark.sql.legacy.decimal.retainFractionDigitsOnTruncate=true, -1.5 % 
Decimal(10**21) on a decimal(38,18) Series returns 999999999999999999998.5 with 
ANSI on and off.
   
   **Verification:**
   - **Regression:** For decimal(38,18) and other decimal(38, s) divisors with 
s >= 7, decimal(18,2), decimal(10,2) and mixed-precision operands, as Series % 
Series, Series % Decimal scalar and scalar % Series, the result's 
spark.data_type equals the base formula's type and values equal the exact 
Python-style result rounded half-up to that type, including last-digit 
remainders.
   - **Regression:** With the legacy fraction-first setting enabled, a 
sign-differing decimal(38,18) modulo by a 22-digit divisor returns its value 
instead of null or NUMERIC_VALUE_OUT_OF_RANGE, with ANSI on and off.
   - **Compatibility:** Results stay in Spark's compact decimal representation 
whenever the base formula's type had precision 18 or less.



##########
python/pyspark/pandas/tests/data_type_ops/test_num_mod.py:
##########
@@ -65,6 +65,45 @@ def test_mod(self):
                 else:
                     self.assertRaises(TypeError, lambda: psser % psdf[n_col])
 
+    def test_mod_sign_of_divisor(self):
+        # SPARK-60655: the result takes the sign of the divisor, as in NumPy, 
including for an
+        # infinite divisor.
+        pdf = pd.DataFrame(
+            {
+                "x": [1.0, -1.0, 0.0, 2.5, -2.5, np.inf],
+                "y": [np.inf, np.inf, -np.inf, -np.inf, 2.0, 2.0],
+            }
+        )
+        psdf = ps.from_pandas(pdf)
+        pser, psser = pdf["x"], psdf["x"]
+
+        for divisor in [np.inf, -np.inf, 2.0, -2.0]:
+            with self.subTest(divisor=divisor):
+                self.assert_eq(pser % divisor, psser % divisor)
+                self.assert_eq(np.mod(pser, divisor), np.mod(psser, divisor))
+                self.assert_eq(divisor % pser, divisor % psser)
+        self.assert_eq(pdf["x"] % pdf["y"], psdf["x"] % psdf["y"])
+        self.assert_eq(1.0 % pdf["y"], 1.0 % psdf["y"])
+
+        # A zero result takes the sign of the divisor.
+        for divisor in [2.0, -2.0]:

Review Comment:
   **Nit (P3):** The only zero result this `np.signbit` loop sees comes from `x 
= 0.0`, whose Spark remainder is already `+0.0`. So with these inputs, 
replacing `F.abs(remainder)` with `remainder` in the positive-divisor zero 
branch would still pass every assertion, even though `-2.0 % 2.0` and `-0.0 % 
2.0` would then return `-0.0` where pandas returns `0.0`. The reflected `-2.0 % 
psser` at `x = 1.0` does produce Spark's `-0.0`, but `assert_eq` treats `-0.0` 
and `0.0` as equal. The loop also compares the sign bit of the NaN from `inf % 
2.0`, which IEEE 754 and the JLS leave unspecified, so it depends on the JVM 
and NumPy producing the same NaN bit pattern. Adding exact negative multiples 
such as `-2.0` and `-0.0`, checking signbit for the reflected and Series % 
Series forms too, and comparing it only where the pandas result is zero would 
cover both halves of the contract.
   
   **Verification:**
   - **Regression:** When the positive-divisor zero result keeps the raw -0.0 
remainder, the sign test fails for the forward, reflected and Series % Series 
forms; with the intended behavior it passes in the classic and Connect suites 
with ANSI on and off.



##########
python/pyspark/pandas/data_type_ops/num_ops.py:
##########
@@ -153,10 +174,10 @@ def mod(self, left: IndexOpsLike, right: Any) -> 
SeriesOrIndex:
         def mod(left_op: PySparkColumn, right_op: Any) -> PySparkColumn:
             if is_ansi_mode_enabled(spark_session):
                 expr = F.when(F.lit(right_op == 0), F.lit(None)).otherwise(
-                    ((left_op % right_op) + right_op) % right_op
+                    _python_mod(left_op, right_op)

Review Comment:
   **Non-blocking (P2):** With ANSI on (the default) and a Series divisor, 
`F.lit(right_op == 0)` is a column predicate, so this guard never folds away. 
Spark's subexpression elimination enters a CASE WHEN only through its first 
condition and through subexpressions shared by every branch, and here the other 
branch is a null literal, so none of the remainder's occurrences inside 
`_python_mod` is shared. Reading the generated code, a row with a nonzero 
remainder computes it three times (first condition, second condition and the 
chosen value), against twice for the base formula and once when `_python_mod` 
is the top-level expression, as with a scalar divisor or ANSI off. Every Series 
% Series, including DataFrame % DataFrame, and every reflected modulo pays 
this, and for decimals each extra evaluation is a BigDecimal remainder. The 
extra work isn't needed: a guard on the divisor alone, such as 
`_python_mod(left_op, F.when(right_op != 0, right_op))`, gives the same null 
for a zero or nul
 l divisor, because Spark's remainder returns null for a null divisor before 
its zero check.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/pandas/data_type_ops/num_ops.py:
##########
@@ -100,6 +100,27 @@ def _cast_back_float(
     return expr
 
 
+def _python_mod(left: Any, right: Any) -> PySparkColumn:
+    """
+    Python and NumPy style modulo, whose result takes the sign of the divisor, 
as in NumPy.
+
+    Spark's remainder takes the sign of the dividend, so add the divisor only 
when the two
+    signs differ. ``((left % right) + right) % right`` returns NaN for an 
infinite divisor,
+    loses a small remainder next to a large divisor and can overflow for 
integers.
+    """
+    remainder = F.lit(left) % right

Review Comment:
   **Blocking (P1):** `remainder` contains the dividend's whole expression and 
appears six times in the result, and pandas-on-Spark keeps Series expressions 
unmaterialized: `column_op` passes the previous result's expression as the 
dividend, and both the classic column converter and the Spark Connect client 
expand each shared reference separately. So `k` chained modulo operations, as 
in a loop `s = (s * 1103515245 + 12345) % 2**31` or a rolling hash `h = (h * 31 
+ psdf[c]) % M`, expand to about `6**k` copies of the base expression, and 
`column_op` analyzes the whole tree at every step. By this review's count that 
is about 2 million nodes at depth 7, 12 million at depth 8 and over 400 million 
at depth 10, against a few dozen on the base branch, where the dividend 
appeared once. Depths 1 and 2 stay cheap, but loops of seven or more steps that 
worked before become slow and then run out of driver memory or exceed the Spark 
Connect message limit; the exact depth at which a given driver fa
 ils wasn't measured. This applies to every numeric dtype in both ANSI modes, 
and no test chains more than one modulo.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/pandas/data_type_ops/num_ops.py:
##########
@@ -100,6 +100,27 @@ def _cast_back_float(
     return expr
 
 
+def _python_mod(left: Any, right: Any) -> PySparkColumn:
+    """
+    Python and NumPy style modulo, whose result takes the sign of the divisor, 
as in NumPy.
+
+    Spark's remainder takes the sign of the dividend, so add the divisor only 
when the two
+    signs differ. ``((left % right) + right) % right`` returns NaN for an 
infinite divisor,
+    loses a small remainder next to a large divisor and can overflow for 
integers.
+    """
+    remainder = F.lit(left) % right
+    right_is_negative = F.lit(right) < 0

Review Comment:
   **Non-blocking (P2):** `F.lit(right)`, and `F.lit(left)` for the reflected 
form, raises `UNSUPPORTED_NUMPY_ARRAY_SCALAR` for NumPy scalars whose dtype 
`_from_numpy_type` doesn't map, namely `uint8`, `uint16`, `uint32`, `uint64` 
and `float16`, and casts other NumPy scalars back to their own type. The 
operand check accepts all of them as `numbers.Number`, and the base formula 
used only Column operators, which convert the scalar to a Python number. 
Reading the code, `ps.Series([5, 7]) % np.uint8(3)` in classic PySpark, which 
the base branch computed as `[2, 1]` like pandas, now raises in both ANSI 
modes, as do `mod` and `np.mod` with such divisors. With ANSI off, `np.uint8(7) 
% psser` now raises too, and `np.float32(2.5) % psser` on an int64 Series 
returns float32 instead of the float64 that the base branch and pandas return. 
Spark Connect already rejected these scalars before this change, and no test 
uses a NumPy scalar operand. Computing a scalar divisor's sign in Python, and 
build
 ing the reflected dividend's literal from its Python value as the base 
branch's Column operators did, would keep these working.
   
   **Verification:**
   - **Regression:** Modulo of an integral and a float Series by 
unsigned-integer, float16, float32 and int64 NumPy scalars, as divisor and as 
reflected dividend, matches pandas' values and the base branch's dtypes in 
classic PySpark with ANSI on and off.



-- 
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