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

MaxGekk 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 1209583917c0 [SPARK-61175][SQL] Make rint return a canonical NaN 
regardless of the JIT tier
1209583917c0 is described below

commit 1209583917c0dddd509f36ab1a734c0b90f4d9be
Author: Max Gekk <[email protected]>
AuthorDate: Mon Nov 9 21:49:04 2026 +0100

    [SPARK-61175][SQL] Make rint return a canonical NaN regardless of the JIT 
tier
    
    ### What changes were proposed in this pull request?
    
    `Rint` now returns the canonical `Double.NaN` (`0x7ff8000000000000`) 
whenever its result is NaN. The rule lives in one place, a new 
`MathUtils.rint(a: Double)`, which `Rint` passes to `UnaryMathExpression` as 
its function and which its generated code calls, as the generated code of the 
exact arithmetic calls `MathUtils.negateExact` and the like. So `eval`, `f` and 
codegen cannot drift apart. Every non-NaN result is `Math.rint`'s, bit for bit, 
including `-0.0` and the infinities, and C [...]
    
    ### Why are the changes needed?
    
    `rint` calls `java.lang.Math.rint`, and on HotSpot the bits of a NaN result 
depend on which JIT tier runs that call. The interpreter and C1 execute the 
Java implementation, `StrictMath.rint`, which takes the absolute value and 
multiplies the sign back, so a NaN comes out with its sign cleared. C2 replaces 
the call with an intrinsic (`roundsd` on x86), which returns the input NaN with 
its sign. Measured on JDK 25.0.4.1, x86_64 (AMD Zen 5), the raw bits of 
`Math.rint(x)`:
    
    | input | `-Xint` and `-XX:TieredStopAtLevel=1` | `-XX:-TieredCompilation` 
(C2) |
    | :--- | :--- | :--- |
    | `fff8000000000000` | `7ff8000000000000` | `fff8000000000000` |
    | `fff0000000000001` | `7ff8000000000001` | `fff8000000000001` |
    | `fff4000000000000` | `7ffc000000000000` | `fffc000000000000` |
    | `7ff0000000000001` | `7ff8000000000001` | `7ff8000000000001` |
    
    `-XX:+PrintIntrinsics` shows `Math::rint` compiled as an intrinsic under 
C2. Every tier keeps the payload and quiets a signalling NaN; only the sign 
differs.
    
    The NaN that x86 produces at run time is the negative one: `0.0 / 0.0`, 
`Math.sqrt(-1.0)` and `Infinity - Infinity` all give `0xfff8000000000000` in 
every tier, so ordinary inputs reach this. Spark's own `Rint(Sqrt(col))` over a 
row holding `-1.0`, measured end to end on master (`fceb1571d99`), the bits 
read back from the result:
    
    | JVM flags | first call | after the code is compiled |
    | :--- | :--- | :--- |
    | `-Xint` | `7ff8000000000000` | `7ff8000000000000` |
    | `-XX:TieredStopAtLevel=1` (C1) | `7ff8000000000000` | `7ff8000000000000` |
    | `-XX:-TieredCompilation` (C2) | `7ff8000000000000` | `fff8000000000000` |
    
    The three evaluation paths, `eval`, `InterpretedUnsafeProjection` and 
`GenerateUnsafeProjection`, gave the same bits in every row. So the same query 
can return a NaN with a different sign from one run to another, or for the same 
input within one JVM once C2 compiles the code. Spark stores the double as is 
(`UnsafeRowWriter.write(double)` and `UnsafeRow.setDouble` are 
`Platform.putDouble`), so the difference reaches user code through `collect()`, 
typed Datasets, Scala/Java/Python UDF a [...]
    
    Returning the canonical NaN makes the result independent of the tier and 
keeps C2's intrinsic for every other value. A rough loop over 4096 doubles 
under C2 (not JMH) measured about 0.60 to 0.64 ns per call for `Math.rint` and 
0.66 to 0.76 ns with the NaN check, so the check costs about 0.05 ns. Calling 
`StrictMath.rint` instead would also be deterministic (it clears the sign in 
every tier), but it is not an intrinsic and measured 0.74 to 0.94 ns.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for NaN results only. `rint` of a NaN now always returns `Double.NaN` 
(`0x7ff8000000000000`). Before, the result kept the input's payload on every 
tier and its sign on C2 only, so `rint` of `0xfff8000000000000` returned 
`0x7ff8000000000000` or `0xfff8000000000000` depending on the tier, and `rint` 
of `0x7ff8000000000001` returned `0x7ff8000000000001` on every tier. The 
payload is dropped too, so the canonical NaN is the one answer whatever the 
input. NaN still compares, groups, s [...]
    
    `round` and `bround` are left as they are: they return a NaN input 
unchanged and are not JIT-tier dependent.
    
    ### How was this patch tested?
    
    A new test in `MathExpressionsSuite`, "SPARK-61175: rint returns the 
canonical NaN", evaluates `rint` over a bound column holding four NaNs: one 
with a payload (`0x7ff8000000000001`), a signalling one (`0x7ff0000000000001`), 
and the two with the sign bit set. `checkEvaluation` compares the result 
`UnsafeRow` byte for byte with the canonical NaN's row in both the 
`CODEGEN_ONLY` and `NO_CODEGEN` factory modes, and the test also checks the raw 
bits of the interpreted `eval`. Every tier k [...]
    
    The same end-to-end run on this branch gives `7ff8000000000000` for every 
NaN input, in every tier and path, and `rint(-1.0)` stays `0xbff0000000000000`. 
`build/sbt 'catalyst/testOnly *MathExpressionsSuite'` passes (57 tests), and 
with the change to `Rint` and `MathUtils` reverted the new test fails. 
`sql-api`, `catalyst` and catalyst's test scalastyle report no errors or 
warnings.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Opus 5.5)
    
    Closes #60220 from MaxGekk/SPARK-61175-rint-nan.
    
    Lead-authored-by: Max Gekk <[email protected]>
    Co-authored-by: t <[email protected]>
    Signed-off-by: Max Gekk <[email protected]>
    
    (cherry picked from commit 8aac2b7d3e3e452ae4db12fec2a3a273f20da339)
    Signed-off-by: Max Gekk <[email protected]>
---
 .../apache/spark/sql/catalyst/util/MathUtils.scala | 11 +++++++++++
 .../sql/catalyst/expressions/mathExpressions.scala |  8 +++++++-
 .../expressions/MathExpressionsSuite.scala         | 23 ++++++++++++++++++++++
 3 files changed, 41 insertions(+), 1 deletion(-)

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 b829bcd57b40..d22aad62597e 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
@@ -89,6 +89,17 @@ object MathUtils {
 
   def floorMod(a: Long, b: Long): Long = withOverflow(Math.floorMod(a, b))
 
+  /**
+   * `Math.rint` with a canonical NaN result. The bits of a NaN that 
`Math.rint` returns depend on
+   * the JIT tier: the interpreter and C1 run `StrictMath.rint`, which clears 
the sign, while C2's
+   * intrinsic keeps it. Every NaN result becomes `Double.NaN`, which also 
drops a NaN payload;
+   * every other result is `Math.rint`'s, bit for bit.
+   */
+  def rint(a: Double): Double = {
+    val r = Math.rint(a)
+    if (java.lang.Double.isNaN(r)) Double.NaN else r
+  }
+
   // Positive modulo (`pmod`): for `n > 0` the result lies in `[0, n)` (for 
the float/double
   // overloads, when both inputs are finite); for integral `n < 0` it takes 
the sign of the
   // dividend `a` (unlike `floorMod`, which takes the sign of `n`). Matches 
the `pmod` SQL
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/mathExpressions.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/mathExpressions.scala
index 08da25e1d9c3..fa1989dc95ca 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/mathExpressions.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/mathExpressions.scala
@@ -868,9 +868,15 @@ case class Log1p(child: Expression) extends 
UnaryLogExpression(StrictMath.log1p,
   since = "1.4.0",
   group = "math_funcs")
 // scalastyle:on line.size.limit
-case class Rint(child: Expression) extends UnaryMathExpression(math.rint, 
"ROUND") {
+case class Rint(child: Expression) extends UnaryMathExpression(MathUtils.rint, 
"ROUND") {
   override def funcName: String = "rint"
   override def prettyName: String = 
getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("rint")
+
+  override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+    val mathUtils = MathUtils.getClass.getCanonicalName.stripSuffix("$")
+    defineCodeGen(ctx, ev, c => s"$mathUtils.rint($c)")
+  }
+
   override protected def withNewChildInternal(newChild: Expression): Rint = 
copy(child = newChild)
 }
 
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/MathExpressionsSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/MathExpressionsSuite.scala
index 761f5268d456..19b19f0e1b2c 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/MathExpressionsSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/MathExpressionsSuite.scala
@@ -493,6 +493,29 @@ class MathExpressionsSuite extends SparkFunSuite with 
ExpressionEvalHelper {
     checkConsistencyBetweenInterpretedAndCodegen(Rint, DoubleType)
   }
 
+  test("SPARK-61175: rint returns the canonical NaN") {
+    val expr = Rint(BoundReference(0, DoubleType, nullable = true))
+    val canonical = java.lang.Double.doubleToRawLongBits(Double.NaN)
+    // A NaN with a payload, a signalling one, and the two with the sign bit 
set. Every JIT tier
+    // keeps the payload of the first two, so they fail without the fix 
wherever the test runs.
+    // The sign is cleared by the interpreter and C1 but kept by C2, so the 
last two check the
+    // sign only when the code under test has been compiled by C2.
+    val nans = Seq(0x7ff8000000000001L, 0x7ff0000000000001L, 
0xfff8000000000000L,
+      0xfff0000000000001L).map(java.lang.Double.longBitsToDouble)
+    for (nan <- nans) {
+      val row = InternalRow(nan)
+      // checkEvaluation compares the UnsafeRow bytes in both factory modes, 
which sees the bits.
+      checkEvaluation(expr, Double.NaN, row)
+      val interpreted = evaluateWithoutCodegen(expr, row).asInstanceOf[Double]
+      assert(java.lang.Double.doubleToRawLongBits(interpreted) === canonical)
+    }
+    // Every other result keeps its bits, the signed zeros and the infinities 
included.
+    for (d <- Seq(-0.0, 0.0, -0.4, 0.5, 1.5, -2.5, 1e300, 
Double.MinPositiveValue,
+        Double.PositiveInfinity, Double.NegativeInfinity)) {
+      checkEvaluation(expr, math.rint(d), InternalRow(d))
+    }
+  }
+
   test("exp") {
     testUnary(Exp, StrictMath.exp)
     checkConsistencyBetweenInterpretedAndCodegen(Exp, DoubleType)


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

Reply via email to