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 647e4d0615e4 [SPARK-60655][PS][SQL] Fix modulo with an infinite 
divisor in pandas API on Spark
647e4d0615e4 is described below

commit 647e4d0615e4a77d3ed697979c1c2d4b9ff089dc
Author: RonakkGovani <[email protected]>
AuthorDate: Thu Nov 12 16:57:55 2026 +0800

    [SPARK-60655][PS][SQL] Fix modulo with an infinite divisor in pandas API on 
Spark
    
    ### What changes were proposed in this pull request?
    
    Compute Python-style modulo in pandas API on Spark with a new internal 
Catalyst expression, `pandas_mod` (`PandasMod`), modeled on `Pmod`. It is used 
by numeric `%`, `rmod` and `np.mod` / `np.remainder`, and replaces `((a % b) + 
b) % b`.
    
    Python and NumPy give the result the sign of the divisor, while Spark's 
remainder takes the sign of the dividend. `PandasMod` computes the remainder 
once and adds the divisor only when a nonzero remainder's sign differs from the 
divisor's, which is CPython's algorithm. A floating zero result takes the sign 
of the divisor.
    
    - Each operand is evaluated once per row.
    - A zero or null divisor gives null in both ANSI modes, as the 
pandas-on-Spark zero-divisor guards did, so those guards are removed.
    - A decimal result keeps the type that `((a % b) + b) % b` had, is computed 
exactly, and is rounded half-up to that type once. Integral and floating 
results keep the type of `%`.
    - A NumPy scalar operand is taken as the Python number it holds, as the 
Column operators did.
    
    ### Why are the changes needed?
    
    `((a % b) + b) % b` gives wrong results:
    
    - For an infinite divisor, `a + inf` is `inf` and `inf % inf` is NaN, so 
`np.mod(1.0, inf)` returns NaN instead of `1.0`.
    - A small remainder next to a large divisor is lost: `1e-20 % 1e20` returns 
`0.0` instead of `1e-20`.
    - For integers, the intermediate `(a % b) + b` can overflow. 
`ps.Series([1]) % (2**63 - 1)` fails with `ARITHMETIC_OVERFLOW` under ANSI mode 
and returns `-1` instead of `1` otherwise.
    
    ```python
    >>> import numpy as np
    >>> import pyspark.pandas as ps
    >>> np.mod(ps.Series([1.0]), float("inf"))
    0   NaN
    dtype: float64
    ```
    
    Fixing this with a `CASE WHEN` in Python, as the first version of this PR 
did, repeats the remainder in every branch. That makes chained modulo plans 
grow exponentially, gives wrong results for nondeterministic operands, and 
changes decimal result types. A single expression avoids all three.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. The results now match pandas for infinite divisors, small remainders 
and integral divisors near the int64 bounds:
    
    ```python
    >>> np.mod(ps.Series([1.0]), float("inf"))
    0    1.0
    dtype: float64
    ```
    
    Decimal results keep their types, and come back exact where the rounded 
intermediate sum of `((a % b) + b) % b` was wrong before, for example for a 
`decimal(38, s)` divisor with `s >= 7`. Negative decimal operands still follow 
Python's integer convention rather than Python `Decimal`'s, as before.
    
    ### How was this patch tested?
    
    - `ArithmeticExpressionSuite`: new tests for `PandasMod` over every numeric 
type, with ANSI on and off, interpreted and generated code, signed zeros, 
infinities and NaN, integral bounds, and decimal result types and values, with 
both values of `spark.sql.decimalOperations.allowPrecisionLoss` and 
`spark.sql.legacy.decimal.retainFractionDigitsOnTruncate`.
    - `pyspark.pandas.tests.data_type_ops.test_num_mod`, which the Spark 
Connect parity suite also runs: infinite divisors, zero signs in the forward, 
reflected and Series % Series forms, a nondeterministic operand, the plan size 
of chained modulo, decimal types and values, and NumPy scalar operands with 
ANSI on and off. The new tests fail without this change.
    - Also ran `test_num_reverse`, `test_num_mul_div`, `test_num_arithmetic`, 
`test_num_ops` and `test_numpy_compat` locally.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Isaac (Claude Opus 5.5)
    
    This pull request and its description were written by Isaac.
    
    Closes #60249 from RonakkGovani/SPARK-60655-mod-sign-of-divisor.
    
    Authored-by: RonakkGovani <[email protected]>
    Signed-off-by: Ruifeng Zheng <[email protected]>
    
    (cherry picked from commit d6bbb24b5be3c3c4371756adc7c6ba05d8411295)
    Signed-off-by: Ruifeng Zheng <[email protected]>
    
    
    skip-checks: true
---
 python/pyspark/pandas/data_type_ops/num_ops.py     |  39 +++---
 .../pandas/tests/data_type_ops/test_num_mod.py     | 137 +++++++++++++++++++++
 python/pyspark/sql/internal.py                     |   4 +
 .../apache/spark/sql/catalyst/util/MathUtils.scala |  36 ++++++
 .../sql/catalyst/analysis/FunctionRegistry.scala   |   1 +
 .../sql/catalyst/expressions/arithmetic.scala      | 110 +++++++++++++++++
 .../expressions/ArithmeticExpressionSuite.scala    | 114 +++++++++++++++++
 7 files changed, 424 insertions(+), 17 deletions(-)

diff --git a/python/pyspark/pandas/data_type_ops/num_ops.py 
b/python/pyspark/pandas/data_type_ops/num_ops.py
index c1926d4d6878..52f2e1d22f93 100644
--- a/python/pyspark/pandas/data_type_ops/num_ops.py
+++ b/python/pyspark/pandas/data_type_ops/num_ops.py
@@ -55,6 +55,7 @@ from pyspark.pandas.typedef.typehints import (
 from pyspark.pandas.utils import _floor_divide_func, is_ansi_mode_enabled
 from pyspark.sql import Column as PySparkColumn
 from pyspark.sql import functions as F
+from pyspark.sql.internal import InternalFunction as SF
 from pyspark.sql.types import (
     BooleanType,
     DataType,
@@ -100,6 +101,25 @@ 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.
+
+    A zero or null divisor gives null. The internal ``pandas_mod`` function 
evaluates each operand
+    once, and keeps the decimal result type of ``((left % right) + right) % 
right``.
+    """
+
+    def to_column(operand: Any) -> PySparkColumn:
+        if isinstance(operand, PySparkColumn):
+            return operand
+        # Like the Column operators, take a NumPy scalar as the Python number 
it holds.
+        if isinstance(operand, np.generic):
+            operand = operand.item()
+        return F.lit(operand)
+
+    return SF.mod(to_column(left), to_column(right))
+
+
 def _is_decimal_float_mixed(left: IndexOpsLike, right: Any) -> bool:
     left_is_decimal = isinstance(left.spark.data_type, DecimalType)
     left_is_float = is_float_dtype(left.dtype)
@@ -148,16 +168,9 @@ class NumericOps(DataTypeOps):
         _sanitize_list_like(right)
         if not is_valid_operand_for_numeric_arithmetic(right):
             raise TypeError("Modulo can not be applied to given types.")
-        spark_session = left._internal.spark_frame.sparkSession
 
         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
-                )
-            else:
-                expr = ((left_op % right_op) + right_op) % right_op
-            return _cast_back_float(expr, left.dtype, right)
+            return _cast_back_float(_python_mod(left_op, right_op), 
left.dtype, right)
 
         new_right = transform_boolean_operand_to_numeric(right, 
spark_type=left.spark.data_type)
 
@@ -226,19 +239,11 @@ class NumericOps(DataTypeOps):
         _sanitize_list_like(right)
         if not isinstance(right, numbers.Number):
             raise TypeError("Modulo can not be applied to given types.")
-        spark_session = left._internal.spark_frame.sparkSession
 
         new_right = transform_boolean_operand_to_numeric(right)
 
         def safe_rmod(left_op: PySparkColumn, right_op: Any) -> PySparkColumn:
-            if is_ansi_mode_enabled(spark_session):
-                # Java-style modulo -> Python-style modulo
-                result = F.when(
-                    left_op != 0, ((F.lit(right_op) % left_op) + left_op) % 
left_op
-                ).otherwise(F.lit(None))
-            else:
-                result = ((right_op % left_op) + left_op) % left_op
-            return _cast_back_float(result, left.dtype, right)
+            return _cast_back_float(_python_mod(right_op, left_op), 
left.dtype, right)
 
         return column_op(safe_rmod)(left, new_right)
 
diff --git a/python/pyspark/pandas/tests/data_type_ops/test_num_mod.py 
b/python/pyspark/pandas/tests/data_type_ops/test_num_mod.py
index 0f2d799bfb7c..6e52416f4ed4 100644
--- a/python/pyspark/pandas/tests/data_type_ops/test_num_mod.py
+++ b/python/pyspark/pandas/tests/data_type_ops/test_num_mod.py
@@ -16,11 +16,17 @@
 #
 
 
+import contextlib
+import decimal
+import io
+from decimal import Decimal
+
 import numpy as np
 import pandas as pd
 
 from pyspark import pandas as ps
 from pyspark.pandas.tests.data_type_ops.testing_utils import OpsTestBase
+from pyspark.sql import functions as F
 from pyspark.testing.pandasutils import PandasOnSparkTestCase
 
 
@@ -65,6 +71,137 @@ class NumModTestsMixin:
                 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, as in pandas.
+        pdf = pd.DataFrame({"x": [2.0, -2.0, 0.0, -0.0, 4.0], "y": [-2.0, 2.0, 
-2.0, 2.0, 2.0]})
+        psdf = ps.from_pandas(pdf)
+        for expected, actual in [
+            (pdf["x"] % 2.0, psdf["x"] % 2.0),
+            (pdf["x"] % -2.0, psdf["x"] % -2.0),
+            (4.0 % pdf["y"], 4.0 % psdf["y"]),
+            (-4.0 % pdf["y"], -4.0 % psdf["y"]),
+            (pdf["x"] % pdf["y"], psdf["x"] % psdf["y"]),
+        ]:
+            expected, actual = expected.to_numpy(), 
actual.to_pandas().to_numpy()
+            zero = expected == 0
+            self.assertTrue(zero.any())
+            self.assertEqual(np.signbit(actual[zero]).tolist(), 
np.signbit(expected[zero]).tolist())
+
+        # A small remainder is kept next to a large divisor.
+        pser = pd.Series([1e-20, -1e-20])
+        self.assert_eq(pser % 1e20, ps.from_pandas(pser) % 1e20)
+
+        # Integral operands near the bounds do not overflow.
+        pser = pd.Series([1, -1, 0], dtype="int64")
+        psser = ps.from_pandas(pser)
+        for divisor in [np.iinfo(np.int64).max, np.iinfo(np.int64).min]:
+            with self.subTest(divisor=divisor):
+                self.assert_eq(pser % divisor, psser % divisor)
+
+    def test_mod_nondeterministic_operand(self):
+        # SPARK-60655: each operand is evaluated once per row.
+        psser = ps.Series(range(6)).spark.transform(lambda c: 
F.monotonically_increasing_id())
+        pdf = ps.concat(
+            [psser.rename("id"), (psser % 3).rename("mod"), (100 % (psser + 
1)).rename("rmod")],
+            axis=1,
+        ).to_pandas()
+        self.assert_eq(pdf["mod"], (pdf["id"] % 3).rename("mod"))
+        self.assert_eq(pdf["rmod"], (100 % (pdf["id"] + 1)).rename("rmod"))
+
+    def test_mod_chained(self):
+        # SPARK-60655: the plan of chained modulo operations grows linearly.
+        def plan_size(psser):
+            with contextlib.redirect_stdout(io.StringIO()) as out:
+                psser.to_frame().to_spark().explain(extended=True)
+            return len(out.getvalue())
+
+        pser = pd.Series([7, -7, 3, 10])
+        psser = ps.from_pandas(pser)
+        sizes = []
+        for divisor in [11, 7, 5, 3, 2]:
+            pser, psser = pser % divisor, psser % divisor
+            sizes.append(plan_size(psser))
+        self.assert_eq(pser, psser)
+        self.assertLess(sizes[-1], 2 * len(sizes) * sizes[0])
+
+    def test_mod_decimal(self):
+        # SPARK-60655: a decimal result is exact and has the type of
+        # ((left % right) + right) % right.
+        def python_mod(a, b):
+            with decimal.localcontext() as ctx:
+                ctx.prec = 100
+                r = a % b  # takes the sign of the dividend
+                return r + b if r and (r < 0) != (b < 0) else r
+
+        for ltype, rtype, rows in [
+            (
+                "decimal(38,18)",
+                "decimal(38,18)",
+                [("0.100000000000000001", "0.300000000000000009"), 
("1.000000000000000001", "1")]
+                + [("-1.5", "4"), ("7.25", "-2")],
+            ),
+            ("decimal(18,2)", "decimal(18,2)", [("7.25", "-2"), ("-1.5", "4"), 
("6", "-3")]),
+            ("decimal(10,2)", "decimal(20,5)", [("7.25", "-2.12345"), ("-1.5", 
"0.00004")]),
+        ]:
+            with self.subTest(ltype=ltype, rtype=rtype):
+                rows = [(Decimal(a), Decimal(b)) for a, b in rows]
+                sdf = self.spark.createDataFrame(rows, f"a {ltype}, b {rtype}")
+                expected_type = sdf.select(((sdf.a % sdf.b) + sdf.b) % 
sdf.b).schema[0].dataType
+                psdf = sdf.pandas_api()
+                result = psdf["a"] % psdf["b"]
+                self.assertEqual(result.spark.data_type, expected_type)
+                self.assertEqual(result.to_list(), [python_mod(a, b) for a, b 
in rows])
+
+        psser = ps.Series([Decimal("-1.5")])
+        with 
self.sql_conf({"spark.sql.legacy.decimal.retainFractionDigitsOnTruncate": 
True}):
+            for ansi in [True, False]:
+                with self.subTest(ansi=ansi), 
self.sql_conf({"spark.sql.ansi.enabled": ansi}):
+                    self.assertEqual(
+                        (psser % Decimal(10**21)).to_list(), 
[Decimal("999999999999999999998.5")]
+                    )
+
+    def test_mod_numpy_scalar(self):
+        # SPARK-60655: a NumPy scalar operand is taken as the Python number it 
holds.
+        pser = pd.Series([5, 7, -7])
+        psser = ps.from_pandas(pser)
+        for ansi in [True, False]:
+            with self.sql_conf({"spark.sql.ansi.enabled": ansi}):
+                for scalar, dtype in [
+                    (np.uint8(3), np.int64),
+                    (np.uint16(3), np.int64),
+                    (np.uint32(3), np.int64),
+                    (np.uint64(3), np.int64),
+                    (np.int64(3), np.int64),
+                    (np.float16(2.5), np.float64),
+                    (np.float32(2.5), np.float64),
+                ]:
+                    with self.subTest(ansi=ansi, scalar=repr(scalar)):
+                        for expected, actual in [
+                            (pser % scalar, psser % scalar),
+                            (scalar % pser, scalar % psser),
+                        ]:
+                            self.assertEqual(actual.dtype, dtype)
+                            self.assert_eq(expected.astype(float), 
actual.astype(float))
+
 
 class NumModTests(
     NumModTestsMixin,
diff --git a/python/pyspark/sql/internal.py b/python/pyspark/sql/internal.py
index f9605875c34b..033c915fed35 100644
--- a/python/pyspark/sql/internal.py
+++ b/python/pyspark/sql/internal.py
@@ -58,6 +58,10 @@ class InternalFunction:
             "pandas_product", col, F.lit(dropna)
         )
 
+    @staticmethod
+    def mod(left: Column, right: Column) -> Column:
+        return 
InternalFunction._invoke_internal_function_over_columns("pandas_mod", left, 
right)
+
     @staticmethod
     def stddev(col: Column, ddof: int) -> Column:
         return InternalFunction._invoke_internal_function_over_columns(
diff --git 
a/sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/MathUtils.scala 
b/sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/MathUtils.scala
index d22aad62597e..a53f3e6cf543 100644
--- a/sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/MathUtils.scala
+++ b/sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/MathUtils.scala
@@ -19,6 +19,7 @@ package org.apache.spark.sql.catalyst.util
 
 import org.apache.spark.QueryContext
 import org.apache.spark.sql.errors.ExecutionErrors
+import org.apache.spark.sql.types.Decimal
 
 /**
  * Helper functions for arithmetic operations with overflow.
@@ -137,6 +138,41 @@ object MathUtils {
     if (r < 0) (r + n) % n else r
   }
 
+  // Python-style modulo, used by `pandas_mod` for pandas API on Spark: the 
result takes the sign
+  // of the divisor `n`, as Python's and NumPy's `%` do, and a floating zero 
result is a zero with
+  // the sign of `n`. This is CPython's algorithm: add `n` to a nonzero 
remainder whose sign
+  // differs from `n`'s. That cannot overflow, because the remainder is 
smaller than `n` in
+  // magnitude. `n` must not be zero. Shared by `PandasMod`'s eval and codegen.
+
+  def pythonMod(a: Int, n: Int): Int = {
+    val r = a % n
+    if (r != 0 && (r ^ n) < 0) r + n else r
+  }
+
+  def pythonMod(a: Long, n: Long): Long = {
+    val r = a % n
+    if (r != 0 && (r ^ n) < 0) r + n else r
+  }
+
+  def pythonMod(a: Byte, n: Byte): Byte = pythonMod(a.toInt, n.toInt).toByte
+
+  def pythonMod(a: Short, n: Short): Short = pythonMod(a.toInt, 
n.toInt).toShort
+
+  def pythonMod(a: Float, n: Float): Float = {
+    val r = a % n
+    if (r == 0) Math.copySign(0.0f, n) else if ((r < 0) != (n < 0)) r + n else 
r
+  }
+
+  def pythonMod(a: Double, n: Double): Double = {
+    val r = a % n
+    if (r == 0) Math.copySign(0.0, n) else if ((r < 0) != (n < 0)) r + n else r
+  }
+
+  def pythonMod(a: Decimal, n: Decimal): Decimal = {
+    val r = a % n
+    if (!r.isZero && (r.compare(Decimal.ZERO) < 0) != (n.compare(Decimal.ZERO) 
< 0)) r + n else r
+  }
+
   // Casts a rounded double (the result of Math.ceil/Math.floor) to long, 
throwing an arithmetic
   // overflow error when the value cannot be represented as a long. NaN is 
passed through to the
   // JVM cast (which yields 0), matching the previous behavior. Shared by the 
eval and codegen
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
index ace2b0cf277b..6256aea1bc62 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
@@ -1243,6 +1243,7 @@ object FunctionRegistry {
     registerInternalExpression[MonotonicallyIncreasingID]("distributed_id", 
setAlias = true)
     
registerInternalExpression[DistributedSequenceID]("distributed_sequence_id")
     registerInternalExpression[PandasProduct]("pandas_product")
+    registerInternalExpression[PandasMod]("pandas_mod")
     registerInternalExpression[PandasStddev]("pandas_stddev")
     registerInternalExpression[PandasVariance]("pandas_var")
     registerInternalExpression[PandasSkewness]("pandas_skew")
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala
index cd632295944e..3ac8a2596376 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala
@@ -1340,6 +1340,116 @@ object Pmod {
     new Pmod(left, right, NumericEvalContext(evalMode))
 }
 
+/**
+ * Python-style modulo for pandas API on Spark, registered as the internal 
function `pandas_mod`.
+ * The result takes the sign of the divisor, as Python's and NumPy's `%` do, 
and a zero or null
+ * divisor gives null in every evaluation mode. Each operand is evaluated once 
per row.
+ *
+ * A decimal result has the type that `((left % right) + right) % right` has, 
and is computed
+ * exactly before it is rounded half-up to that type once. Other results have 
the type of `%`.
+ */
+case class PandasMod(
+    left: Expression,
+    right: Expression,
+    evalContext: NumericEvalContext = 
NumericEvalContext.fromSQLConf(SQLConf.get))
+  extends BinaryArithmetic {
+
+  def this(left: Expression, right: Expression) =
+    this(left, right, NumericEvalContext.fromSQLConf(SQLConf.get))
+
+  override def inputType: AbstractDataType = NumericType
+
+  override def symbol: String = "pandas_mod"
+
+  override def prettyName: String = "pandas_mod"
+
+  override def nullable: Boolean = true
+
+  // A zero divisor gives null in every mode, so only a decimal overflow can 
fail, under ANSI.
+  protected override def failOnError: Boolean = evalMode == EvalMode.ANSI
+
+  override def resultDecimalType(p1: Int, s1: Int, p2: Int, s2: Int): 
DecimalType = {
+    val l = Literal(null, DecimalType(p1, s1))
+    val r = Literal(null, DecimalType(p2, s2))
+    Remainder(Add(Remainder(l, r, evalContext), r, evalContext), r, 
evalContext)
+      .dataType.asInstanceOf[DecimalType]
+  }
+
+  private lazy val isZero: Any => Boolean = right.dataType match {
+    case _: DecimalType => x => x.asInstanceOf[Decimal].isZero
+    case _ => x => x == 0
+  }
+
+  private lazy val modFunc: (Any, Any) => Any = dataType match {
+    case IntegerType => (l, r) => MathUtils.pythonMod(l.asInstanceOf[Int], 
r.asInstanceOf[Int])
+    case LongType => (l, r) => MathUtils.pythonMod(l.asInstanceOf[Long], 
r.asInstanceOf[Long])
+    case ShortType => (l, r) => MathUtils.pythonMod(l.asInstanceOf[Short], 
r.asInstanceOf[Short])
+    case ByteType => (l, r) => MathUtils.pythonMod(l.asInstanceOf[Byte], 
r.asInstanceOf[Byte])
+    case FloatType => (l, r) => MathUtils.pythonMod(l.asInstanceOf[Float], 
r.asInstanceOf[Float])
+    case DoubleType =>
+      (l, r) => MathUtils.pythonMod(l.asInstanceOf[Double], 
r.asInstanceOf[Double])
+    case DecimalType.Fixed(precision, scale) => (l, r) => checkDecimalOverflow(
+      MathUtils.pythonMod(l.asInstanceOf[Decimal], r.asInstanceOf[Decimal]), 
precision, scale)
+  }
+
+  final override def eval(input: InternalRow): Any = {
+    // Evaluate the divisor first, to skip the dividend for a zero or null 
divisor.
+    val input2 = right.eval(input)
+    if (input2 == null || isZero(input2)) {
+      null
+    } else {
+      val input1 = left.eval(input)
+      if (input1 == null) null else modFunc(input1, input2)
+    }
+  }
+
+  override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+    val eval1 = left.genCode(ctx)
+    val eval2 = right.genCode(ctx)
+    val isZero = if (right.dataType.isInstanceOf[DecimalType]) {
+      s"${eval2.value}.isZero()"
+    } else {
+      s"${eval2.value} == 0"
+    }
+    val javaType = CodeGenerator.javaType(dataType)
+    val mathUtils = MathUtils.getClass.getCanonicalName.stripSuffix("$")
+    val result = dataType match {
+      case DecimalType.Fixed(precision, scale) =>
+        val errorContext = getContextOrNullCode(ctx, failOnError)
+        s"""
+           |${ev.value} = $mathUtils.pythonMod(${eval1.value}, 
${eval2.value}).toPrecision(
+           |  $precision, $scale, Decimal.ROUND_HALF_UP(), ${!failOnError}, 
$errorContext);
+           |${ev.isNull} = ${ev.value} == null;
+           |""".stripMargin
+      case _ =>
+        s"${ev.value} = $mathUtils.pythonMod(${eval1.value}, ${eval2.value});"
+    }
+    // Evaluate the divisor first, to skip the dividend for a zero or null 
divisor.
+    ev.copy(code = code"""
+      ${eval2.code}
+      boolean ${ev.isNull} = false;
+      $javaType ${ev.value} = ${CodeGenerator.defaultValue(dataType)};
+      if (${eval2.isNull} || $isZero) {
+        ${ev.isNull} = true;
+      } else {
+        ${eval1.code}
+        if (${eval1.isNull}) {
+          ${ev.isNull} = true;
+        } else {
+          $result
+        }
+      }""")
+  }
+
+  override def toString: String = s"$prettyName($left, $right)"
+
+  override def sql: String = s"$prettyName(${left.sql}, ${right.sql})"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): PandasMod =
+    copy(left = newLeft, right = newRight)
+}
+
 /**
  * A function that returns the least value of all parameters, skipping null 
values.
  * It takes at least 2 parameters, and returns null iff all parameters are 
null.
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
index 0dc349659448..a9ea36272b36 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
@@ -631,6 +631,120 @@ class ArithmeticExpressionSuite extends SparkFunSuite 
with ExpressionEvalHelper
     }
   }
 
+  test("SPARK-60655: pandas_mod takes the sign of the divisor") {
+    testNumericDataTypes { convert =>
+      // A zero with a negative divisor is -0.0 for floating types, so it is 
checked below.
+      Seq((7, 3, 1), (-7, 3, 2), (7, -3, -2), (-7, -3, -1), (-6, 3, 
0)).foreach {
+        case (a, n, expected) =>
+          checkEvaluation(PandasMod(Literal(convert(a)), Literal(convert(n))), 
convert(expected))
+      }
+      val operand = Literal(convert(7))
+      Seq("true", "false").foreach { ansi =>
+        withSQLConf(SQLConf.ANSI_ENABLED.key -> ansi) {
+          // A zero or null divisor gives null in every mode.
+          checkEvaluation(PandasMod(operand, Literal(convert(0))), null)
+          checkEvaluation(PandasMod(operand, Literal.create(null, 
operand.dataType)), null)
+          checkEvaluation(PandasMod(Literal.create(null, operand.dataType), 
operand), null)
+        }
+      }
+    }
+
+    // Adding the divisor to the remainder does not overflow.
+    checkEvaluation(PandasMod(Literal(-1.toByte), Literal(Byte.MaxValue)), 
126.toByte)
+    checkEvaluation(PandasMod(Literal(1.toShort), Literal(Short.MinValue)), 
(-32767).toShort)
+    checkEvaluation(PandasMod(Literal(-1), Literal(Int.MaxValue)), 
Int.MaxValue - 1)
+    checkEvaluation(PandasMod(Literal(1), Literal(Int.MinValue)), Int.MinValue 
+ 1)
+    checkEvaluation(PandasMod(Literal(-1L), Literal(Long.MaxValue)), 
Long.MaxValue - 1)
+    checkEvaluation(PandasMod(Literal(1L), Literal(Long.MinValue)), 
Long.MinValue + 1)
+    checkEvaluation(PandasMod(Literal(Long.MinValue), Literal(-1L)), 0L)
+
+    val inf = Double.PositiveInfinity
+    checkEvaluation(PandasMod(Literal(1.0), Literal(inf)), 1.0)
+    checkEvaluation(PandasMod(Literal(-1.0), Literal(inf)), inf)
+    checkEvaluation(PandasMod(Literal(1.0), Literal(-inf)), -inf)
+    checkEvaluation(PandasMod(Literal(-1.0), Literal(-inf)), -1.0)
+    checkEvaluation(PandasMod(Literal(-1.0f), Literal(Float.PositiveInfinity)),
+      Float.PositiveInfinity)
+    checkEvaluation(PandasMod(Literal(1e-20), Literal(1e20)), 1e-20)
+    // The bit pattern of a NaN result is not specified, so only check that it 
is NaN.
+    Seq(PandasMod(Literal(inf), Literal(2.0)), PandasMod(Literal(1.0), 
Literal(Double.NaN)))
+      .foreach { expr =>
+        Seq(evaluateWithoutCodegen(expr), 
evaluateWithMutableProjection(expr)).foreach { result =>
+          assert(result.asInstanceOf[Double].isNaN, s"$expr returned $result")
+        }
+      }
+
+    // A zero result takes the sign of the divisor.
+    Seq(
+      PandasMod(Literal(2.0), Literal(-2.0)) -> -0.0,
+      PandasMod(Literal(-2.0), Literal(2.0)) -> 0.0,
+      PandasMod(Literal(-0.0), Literal(2.0)) -> 0.0,
+      PandasMod(Literal(0.0), Literal(-2.0)) -> -0.0,
+      PandasMod(Literal(2.0f), Literal(-2.0f)) -> -0.0f,
+      PandasMod(Literal(-2.0f), Literal(2.0f)) -> 0.0f).foreach { case (expr, 
expected) =>
+      Seq(evaluateWithoutCodegen(expr), 
evaluateWithMutableProjection(expr)).foreach { result =>
+        val sameSign = (result, expected) match {
+          case (r: Double, e: Double) => java.lang.Double.compare(r, e) == 0
+          case (r: Float, e: Float) => java.lang.Float.compare(r, e) == 0
+          case _ => false
+        }
+        assert(sameSign, s"$expr returned $result, expected $expected")
+      }
+    }
+
+    Seq("true", "false").foreach { ansi =>
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> ansi) {
+        DataTypeTestUtils.numericTypeWithoutDecimal.foreach { tpe =>
+          checkConsistencyBetweenInterpretedAndCodegen(PandasMod(_, _), tpe, 
tpe)
+        }
+      }
+    }
+  }
+
+  test("SPARK-60655: pandas_mod keeps the decimal type of the Python-style 
formula") {
+    def dec(value: String, precision: Int, scale: Int): Literal =
+      Literal.create(new java.math.BigDecimal(value), DecimalType(precision, 
scale))
+    def baseFormulaType(l: Expression, r: Expression): DataType =
+      Remainder(Add(Remainder(l, r), r), r).dataType
+
+    Seq((38, 18) -> (38, 18), (18, 2) -> (18, 2), (10, 2) -> (10, 2)).foreach {
+      case ((p, s), (expectedP, expectedS)) =>
+        val operand = Literal.create(null, DecimalType(p, s))
+        assert(PandasMod(operand, operand).dataType === DecimalType(expectedP, 
expectedS))
+    }
+    Seq("true", "false").foreach { allowPrecisionLoss =>
+      withSQLConf(SQLConf.DECIMAL_OPERATIONS_ALLOW_PREC_LOSS.key -> 
allowPrecisionLoss) {
+        Seq((38, 18) -> (38, 18), (10, 2) -> (20, 5), (38, 0) -> (10, 4), (5, 
5) -> (38, 2))
+          .foreach { case ((p1, s1), (p2, s2)) =>
+            val l = Literal.create(null, DecimalType(p1, s1))
+            val r = Literal.create(null, DecimalType(p2, s2))
+            assert(PandasMod(l, r).dataType === baseFormulaType(l, r))
+          }
+      }
+    }
+
+    // The result is exact, also where `(left % right) + right` would lose a 
fraction digit.
+    checkEvaluation(
+      PandasMod(dec("0.100000000000000001", 38, 18), 
dec("0.300000000000000009", 38, 18)),
+      Decimal("0.100000000000000001"))
+    checkEvaluation(
+      PandasMod(dec("1.000000000000000001", 38, 18), dec("1", 38, 18)),
+      Decimal("0.000000000000000001"))
+    checkEvaluation(PandasMod(dec("7.25", 18, 2), dec("-2", 18, 2)), 
Decimal("-0.75"))
+    checkEvaluation(PandasMod(dec("-1.5", 18, 2), dec("4", 18, 2)), 
Decimal("2.5"))
+    Seq("true", "false").foreach { legacy =>
+      withSQLConf(SQLConf.LEGACY_RETAIN_FRACTION_DIGITS_FIRST.key -> legacy) {
+        Seq("true", "false").foreach { ansi =>
+          withSQLConf(SQLConf.ANSI_ENABLED.key -> ansi) {
+            checkEvaluation(
+              PandasMod(dec("-1.5", 38, 18), dec("1000000000000000000000", 22, 
0)),
+              Decimal("999999999999999999998.5"))
+          }
+        }
+      }
+    }
+  }
+
   test("function least") {
     val row = create_row(1, 2, "a", "b", "c")
     val c1 = $"a".int.at(0)


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

Reply via email to