cloud-fan commented on code in PR #60218:
URL: https://github.com/apache/spark/pull/60218#discussion_r4508963844


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -1169,25 +1169,35 @@ object DateTimeUtils extends SparkDateTimeUtils {
   }
 
   /**
-   * Creates a TIME value from seconds since midnight (decimal type).
+   * Creates a TIME(6) value from seconds since midnight (decimal type). The 
digits beyond
+   * microseconds are truncated.
    * @param seconds Seconds (0 to 86399.999999)
    * @return Nanoseconds since midnight
    */
   def timeFromSeconds(seconds: Decimal): Long = 
withTimeConversionErrorHandling {
-    val operand = new java.math.BigDecimal(NANOS_PER_SECOND)
-    seconds.toJavaBigDecimal.multiply(operand).longValueExact()
+    secondsToMicrosPrecisionNanos(seconds.toJavaBigDecimal)
   }
 
   /**
-   * Creates a TIME value from seconds since midnight (floating point type).
+   * Creates a TIME(6) value from seconds since midnight (floating point 
type). The digits beyond
+   * microseconds are truncated.
    * @param seconds Seconds (0 to 86399.999999)
    * @return Nanoseconds since midnight
    */
   def timeFromSeconds(seconds: Double): Long = withTimeConversionErrorHandling 
{
     if (seconds.isNaN || seconds.isInfinite) {
       throw new DateTimeException("Cannot convert NaN or Infinite value to 
TIME")
     }
-    (seconds * NANOS_PER_SECOND).toLong
+    // Use the shortest decimal form of the double, as CAST(double AS DECIMAL) 
does. Otherwise
+    // 3.0E-6 becomes 2.9999...E-6 after the multiplication, and 2 
microseconds after truncation.
+    secondsToMicrosPrecisionNanos(java.math.BigDecimal.valueOf(seconds))

Review Comment:
   **Blocking (P1):** Every DOUBLE or FLOAT row now goes through 
`BigDecimal.valueOf`, which formats the double with `Double.toString` and 
parses it back, followed by `movePointRight`, `setScale(FLOOR)` and 
`longValueExact`. The base branch, and the 4.2.0 and 4.3.0 releases, did a 
single `(seconds * NANOS_PER_SECOND).toLong`. The new cost also lands on rows 
whose result was already a correct TIME(6) value and does not change, such as 
`52200.5`, `0.5` or any integral double. For example, `SELECT 
time_from_seconds(CAST(id % 86400 AS DOUBLE) + 0.5) FROM range(N)` pays it on 
every row and gets the same results as before. In a standalone JDK 17 loop over 
the conversion bodies, the base code took about 1 ns per row and this code 
about 134 ns on such values, or about 261 ns on random values in [0, 86400). A 
primitive floor that returned the same results on every sampled input took 
about 5 ns. A constant argument is folded once and is unaffected. The cost 
grows with the number of rows in a D
 OUBLE or FLOAT column.
   
   **Recommended change:** Compute the microsecond floor of a finite DOUBLE 
with primitive arithmetic, keep the BigDecimal.valueOf conversion only as the 
fallback for very large magnitudes, and add parity tests to the time expression 
tests.
   
   **Why this works:** Let p = seconds * 1e6 and m = Math.round(p). If m / 1e6 
== seconds, the double's shortest decimal form is the microsecond value m, so m 
is the result. Otherwise no microsecond multiple rounds to the double, and the 
shortest-decimal floor equals the floor of the double's exact value: take k = 
Math.floor(p), and use k - 1 when Math.fma(seconds, 1e6, -k) is negative, else 
k. This holds while one microsecond is much wider than the double's spacing, 
which is true far beyond the TIME range; for magnitudes of 1e9 seconds or more 
the method calls the existing BigDecimal path. The result then goes through the 
unchanged multiplyExact and range check.
   
   **Scope:** Rewrite the body of the DOUBLE overload of time_from_seconds as a 
primitive computation with a BigDecimal fallback, and add parity tests.
   
   **Compatibility:** Every value and error time_from_seconds returns for 
DOUBLE and FLOAT input stays exactly as this PR defines it; only the per-row 
cost changes.
   
   **Risks:** The primitive computation is numerically subtle. A mistake would 
return a value one microsecond off with no error, which is why the verification 
compares it with BigDecimal.valueOf on the inputs that separate the 
alternatives. Rows the PR corrects also get faster. Only their performance 
changes, not their values, and restoring the current method body reverts the 
change. JDK 17's Double.toString does not always return the shortest decimal, 
so on JDK 17 the current conversion could differ from JDK 21 and later for some 
double. Sampling found no such double in the TIME range; if one exists, the 
parity check fails on JDK 17 for it, and the primitive computation gives the 
result newer JDKs give.
   
   **Constraints:** Results must equal the current shortest-decimal floor for 
every finite input, including negative values, so negative inputs below one 
microsecond still fail the range check. NaN and Infinity keep failing before 
any conversion, with the current message. Magnitudes handled by the fallback 
keep the current BigDecimal path, so 'Overflow in TIME conversion' and the 
range message stay as they are. The comment that explains the conversion keeps 
stating the shortest-decimal results, with an example the alternatives actually 
get wrong.
   
   **Exclusions:**
   - The DECIMAL overload keeps its BigDecimal conversion, because its per-row 
cost is about what the base branch already paid.
   
   **Success:** time_from_seconds over a DOUBLE or FLOAT column does only 
primitive arithmetic per row for inputs below 1e9 seconds, with no BigDecimal 
or String allocation. Every finite DOUBLE gives the same TIME value or error as 
the current shortest-decimal floor, for example 2.49E-4 -> 249 microseconds, 
1.0E-6 -> 1, 0.7 -> 700000, and -1.0E-7 -> range error. Large and non-finite 
DOUBLE inputs fail with the same error condition and message as now.
   
   **Verification:**
   - **Behavior:** Check that time_from_seconds returns the shortest-decimal 
microsecond floor, in both interpreted and generated evaluation, for DOUBLE 
inputs whose binary value lies below their decimal form (2.49E-4, 1.0E-6, 0.7), 
for microsecond multiples across the TIME range, for values a few ulps either 
side of a microsecond boundary, and for 52200.1234567.
   - **Regression:** Compare the new conversion with BigDecimal.valueOf floored 
to microseconds over a large deterministic sample of random, 
microsecond-aligned, near-boundary, out-of-range and tiny positive and negative 
doubles, and require identical results or identical errors for every sample.
   - **Compatibility:** Check that negative sub-microsecond DOUBLE inputs, NaN, 
Infinity and a large finite DOUBLE such as 1.0E10 still fail with 
DATETIME_FIELD_OUT_OF_BOUNDS and their current messages, and that FLOAT inputs 
such as 0.7F still return 00:00:00.699999.
   - **Inspection:** Confirm that the DOUBLE conversion uses only primitive 
arithmetic for inputs below 1e9 seconds and reaches BigDecimal only in the 
large-magnitude fallback.



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