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


##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkDateTimeUtils.scala:
##########
@@ -384,6 +384,13 @@ trait SparkDateTimeUtils {
    */
   def localTimeToNanos(localTime: LocalTime): Long = 
localTime.getLong(NANO_OF_DAY)
 
+  /**
+   * Converts the local time to a value of `TIME(precision)`: the number of 
nanoseconds within the
+   * day, with the fractional digits beyond `precision` truncated, as CAST 
does.
+   */
+  def localTimeToNanos(localTime: LocalTime, precision: Int): Long =

Review Comment:
   **Non-blocking (P2):** This is the shared precision-aware conversion, but 
several producers that know their target `TIME(p)` still store raw values:
   
   - `JDBCValueGetter.TimeGetter`, which `JdbcUtils` picks for every 
`TimeType`, stores `localTime.toNanoOfDay`, while `TimestampNTZNanosGetter` 
takes the column precision.
   - The Avro `(LONG, TimeType)` branch stores `microsToNanos(micros)` for any 
precision, while its nanosecond timestamp branches pass `t.precision`.
   - `TimeTypeOrcOps.makeDeserializer` and the vectorized ORC reader pass the 
stored long through, and the `TimeTypeOrcOps` class comment still says nothing 
is truncated.
   - `TimeTypeApiOps.makeFromJava` passes PySpark's `TimeType.toInternal` 
value, which includes microseconds, into any `TIME(p)`; that covers 
`createDataFrame` without Arrow and Python UDF results.
   - `mapInArrow` output stored into TIME(0) to TIME(5) keeps six digits, 
because the field reads as TIME(6).
   
   Reading the code, `spark.read.jdbc` with `customSchema` `t TIME(3)` over a 
database value `12:00:00.123456` stores `12:00:00.123456`, which compares 
unequal to `TIME'12:00:00.123'`, while `from_json` of the same string into 
TIME(3) now gives `12:00:00.123`. The PR aims for every TIME(p) producer to 
truncate, and nothing marks these paths as left for later.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60218#issuecomment-6817573423), 
[2](https://github.com/apache/spark/pull/60218#discussion_r4508963855).
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/timeExpressions.scala:
##########
@@ -135,12 +135,19 @@ case class ToTimeParser(fmt: Option[String]) {
     }
   }
 
-  def parse(s: UTF8String): Long = withErrorCondition(s, 
fmt)(formatter.parse(s.toString))
+  // The parser keeps up to 9 fractional digits, but `ToTime` returns 
`TimeType()`, so drop the
+  // digits beyond its precision as CAST does.
+  private def toResultPrecision(nanos: Long): Long =
+    DateTimeUtils.truncateTimeToPrecision(nanos, TimeType.DEFAULT_PRECISION)

Review Comment:
   Thanks for routing the readers and the LocalTime conversions through the 
precision-aware helpers. Leaving the schema-less 
`CatalystTypeConverters.convertToCatalyst` alone makes sense: it does not know 
the target type, and truncating to TIME(6) there would drop digits that TIME(7) 
to TIME(9) values keep. This review raises two problems that remain: Arrow TIME 
data that PySpark sends now loses digits seven to nine in TIME(7) to TIME(9) 
columns, and some other producers, such as the JDBC and Avro readers, still 
store more than p digits.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4508963855","thread_id":"inline:4508963855","verdict_sha256":"d00cbd1e37fa12433c78ac2d0a4afac5c08f868bb229a14ec8135a9deb8c7796"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -1169,27 +1169,71 @@ 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
+    Math.multiplyExact(secondsToFlooredMicros(seconds), NANOS_PER_MICROS)
   }
 
+  // Seconds at or above this magnitude use the BigDecimal conversion. Below 
it, one microsecond is
+  // much wider than the spacing between doubles, which the primitive 
conversion relies on.
+  private val maxSecondsForPrimitiveConversion = 1e9
+
+  /**
+   * Returns the shortest decimal form of `seconds`, as `CAST(seconds AS 
DECIMAL)` gives it, floored
+   * to whole microseconds. The shortest decimal form matters: `2.49E-4 * 1e6` 
is
+   * `248.99999999999997`, and the exact binary value of `1.0E-6` is below one 
microsecond, so
+   * flooring the product or the exact value loses one microsecond. Below
+   * `maxSecondsForPrimitiveConversion` this uses only primitive arithmetic, 
so that it is cheap
+   * per row.
+   */
+  private[util] def secondsToFlooredMicros(seconds: Double): Long = {
+    if (Math.abs(seconds) >= maxSecondsForPrimitiveConversion) {
+      floorToMicros(java.math.BigDecimal.valueOf(seconds))
+    } else {
+      val micros = seconds * MICROS_PER_SECOND
+      val nearestMicros = Math.round(micros)
+      if (nearestMicros / MICROS_PER_SECOND.toDouble == seconds) {
+        // A whole number of microseconds rounds to `seconds`, so it is the 
shortest decimal form.
+        nearestMicros
+      } else {
+        // No whole number of microseconds rounds to `seconds`, so the 
shortest decimal form has
+        // the same floor as the exact value of `seconds`. `micros` can be 
rounded up to the next
+        // whole number, and the exact sign of `seconds * 1e6 - floor` from 
`fma` detects that.
+        val floor = Math.floor(micros)
+        if (Math.fma(seconds, MICROS_PER_SECOND.toDouble, -floor) < 0) {

Review Comment:
   **Nit (P3):** `Math.fma` is an `@IntrinsicCandidate` whose JDK 17 Java body 
computes `new BigDecimal(a).multiply(new BigDecimal(b))`. Where it is not 
intrinsified, such as with `-XX:-UseFMA` or on an x86 CPU or VM without FMA3, 
this line does BigDecimal arithmetic for every row whose `seconds * 1e6` is not 
a whole number, which is most non-aligned inputs, so `time_from_seconds` over a 
DOUBLE or FLOAT column again pays a per-row BigDecimal cost.
   
   The exact sign check matters only when `micros == floor`. `floor` is a whole 
number that a double represents exactly, and rounding is monotonic, so if the 
exact product were below `floor`, the rounded `micros` could not be above it. 
Adding that condition returns the same result for every input and skips the 
call on almost every row; the comment above can say the exact check runs only 
in that case.
   
   ```suggestion
           if (micros == floor && Math.fma(seconds, MICROS_PER_SECOND.toDouble, 
-floor) < 0) {
   ```
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60218#issuecomment-6817573423), 
[2](https://github.com/apache/spark/pull/60218#discussion_r4508963844).
   
   **Verification:**
   - **Regression:** Check that the DOUBLE conversion still equals 
BigDecimal.valueOf floored to microseconds on a large deterministic sample of 
microsecond-aligned values, doubles one to three ulps from them, random values 
in and out of range, and tiny positive and negative values.
   - **Inspection:** Confirm that the conversion reaches Math.fma only when the 
rounded product equals its floor.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -1169,27 +1169,71 @@ 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
+    Math.multiplyExact(secondsToFlooredMicros(seconds), NANOS_PER_MICROS)
   }
 
+  // Seconds at or above this magnitude use the BigDecimal conversion. Below 
it, one microsecond is
+  // much wider than the spacing between doubles, which the primitive 
conversion relies on.
+  private val maxSecondsForPrimitiveConversion = 1e9
+
+  /**
+   * Returns the shortest decimal form of `seconds`, as `CAST(seconds AS 
DECIMAL)` gives it, floored

Review Comment:
   **Nit (P3):** In Spark SQL a bare `DECIMAL` is `DECIMAL(10, 0)`, so 
`CAST(2.49E-4D AS DECIMAL)` is `0`, while the example below needs `0.000249` to 
give 249 microseconds. A reader could take `time_from_seconds(d)` to equal 
`time_from_seconds(CAST(d AS DECIMAL))`, which is false for most fractional 
inputs. The value this mirrors is `BigDecimal.valueOf(seconds)`, the 
`Double.toString` form, as the new `DateTimeUtilsSuite` test says.
   
   ```suggestion
      * Returns the shortest decimal form of `seconds`, as `BigDecimal.valueOf` 
gives it, floored
   ```
   
   **Verification:**
   - **Inspection:** Confirm that the comment no longer says CAST(seconds AS 
DECIMAL) gives the shortest decimal form and that the value it names agrees 
with its 2.49E-4 example.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/aggregate/ApproxCountDistinctForIntervalsSuite.scala:
##########
@@ -232,8 +232,9 @@ class ApproxCountDistinctForIntervalsSuite extends 
SparkFunSuite {
           intEndpoints.map(DateTimeUtils.toJavaTimestamp(_)), TimestampType),
       (intRecords.map(DateTimeUtils.microsToLocalDateTime(_)),
         intEndpoints.map(DateTimeUtils.microsToLocalDateTime(_)), 
TimestampNTZType),
-      (intRecords.map(i => LocalTime.ofNanoOfDay(i.toLong)),
-        intEndpoints.map(i => LocalTime.ofNanoOfDay(i.toLong)), TimeType())
+      // TIME(6) values are whole microseconds.

Review Comment:
   **Nit (P3):** This fixture now uses whole microseconds, but the test `TIME 
type with realistic nanos-of-day magnitudes` in the same suite still uses 
`nearMax = 86399999999999L`. Its endpoints go through `Literal(_)`, which now 
truncates a `LocalTime` to TIME(6), so the last endpoint becomes 
`86399999999000` while the record stays `86399999999999`. 
`ApproxCountDistinctForIntervals.update` skips values above the last endpoint, 
so the record the test calls the edge `nearMax` is never counted and the last 
interval sees 49 values. `checkNDVs` allows about 15% error, so the test still 
passes without covering the inclusive last endpoint. Using `86399999999000L` 
(23:59:59.999999) for `nearMax`, and updating its comments, restores the 
documented case.
   
   **Verification:**
   - **Inspection:** Confirm that every endpoint and record of the TIME 
nanos-of-day test is a whole number of microseconds and that the nearMax record 
equals the last endpoint.
   - **Behavior:** Check that the test still passes with all 50 records of the 
last interval, the nearMax edge included, inside the endpoints.



##########
sql/catalyst/src/main/java/org/apache/spark/sql/vectorized/ArrowColumnVector.java:
##########
@@ -231,7 +231,7 @@ void initAccessor(ValueVector vector) {
     } else if (vector instanceof TimeStampMicroVector timeStampMicroVector) {
       accessor = new TimestampNTZAccessor(timeStampMicroVector);
     } else if (vector instanceof TimeNanoVector timeNanoVector) {
-      accessor = new TimeNanoAccessor(timeNanoVector);
+      accessor = new TimeNanoAccessor(timeNanoVector, timePrecision(type));

Review Comment:
   **Blocking (P1):** This passes the field's precision to the TIME accessor, 
and `ArrowUtils.fromArrowField` reads a `Time(NANOSECOND)` field without the 
`SPARK::time::precision` key as TIME(6). PySpark's `to_arrow_type` maps every 
`TimeType` to `pa.time64("ns")` and tags only the nanosecond timestamp types, 
so no TIME field that PySpark builds carries the key.
   
   Reading the code, with `spark.sql.timeType.enabled=true` a Spark Connect 
Python client running `spark.createDataFrame(pa.table({"t": 
pa.array([123456789], pa.time64("ns"))}), "t time(9)")` now gets 
`00:00:00.123456`: the accessor truncates to six digits, and the `.to(schema)` 
projection then widens TIME(6) to TIME(9) without restoring them. The base 
branch and 4.3.0 return `00:00:00.123456789`. `mapInArrow` with a TIME(7) to 
TIME(9) output column loses the same digits while 
`spark.sql.execution.arrow.pyspark.validateSchema.enabled` is false, its 
default, because the output children are read without a type check.
   
   Older Connect clients will never send the key, so the fallback for an 
untagged field must not drop digits that it has no way to know are extra. The 
new `ArrowColumnVectorSuite` case asserts the six-digit fallback, so it 
currently locks in this loss.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60218#issuecomment-6817573423), 
[2](https://github.com/apache/spark/pull/60218#discussion_r4508963855).
   
   See **Shared repair plan 1** in the review body.



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