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


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

Review Comment:
   **Non-blocking (P2):** This example does not hold. `3.0E-6 * 1e6` is exactly 
`3.0` (and `3.0E-6 * 1e9` is exactly `3000.0`), and the exact binary value of 
`3.0E-6` is `0.0000030000000000000000760...`, slightly above 3e-6. So flooring 
the product and flooring `new BigDecimal(seconds)` both give 3 microseconds 
too, the same as `BigDecimal.valueOf`. The DOUBLE inputs in the new 
`TimeExpressionsSuite` case and in `time.sql` (`1.0E-7`, `3.0E-6`, `52200.5`, 
`-1.0E-7`) also give the same result under all three conversions. So none of 
these tests fails if this line is switched to one of the alternatives, and a 
later optimization of this path could silently return one microsecond too few 
for about 1.8% of values of the form k / 1e6. `2.49E-4` shows the problem: its 
product with 1e6 is `248.99999999999997`, so both alternatives give 248 
microseconds and `valueOf` gives 249. `1.0E-6` and `0.7` show it for the 
exact-value floor, which gives 0 and 699999.
   
   **Verification:**
   - **Regression:** Check that time_from_seconds(2.49E-4D) returns 
00:00:00.000249 and time_from_seconds(1.0E-6D) returns 00:00:00.000001, and 
that these checks fail if the conversion floors the double product or the exact 
binary value instead of the shortest decimal form.
   - **Inspection:** Confirm that each example in the comment justifying the 
conversion is a value the described alternative actually gets wrong.



##########
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:
   **Non-blocking (P2):** This fixes `to_time` and `try_to_time`, but other 
producers still put untruncated values into TIME(p) columns. The JSON, CSV and 
XML `TimeType` converters (`JacksonParser.scala:482-486`, 
`UnivocityParser.scala:276-279`, `StaxXmlParser.scala:761`), behind 
`spark.read.json/csv/xml` and `from_json`, `from_csv` and `from_xml`, call the 
same `timeFormatter.parse` and ignore the field's precision. The 
timestamp-nanos branches next to them do pass `t.precision`. Reading the code, 
`from_json('{"t":"00:00:00.1234567"}', 't TIME').t = TIME'00:00:00.123456'` is 
still false after this PR, while the same comparison with `to_time` is now 
true, and a TIME(3) field read from `12:00:00.123456` keeps 6 digits. The 
LocalTime producers keep every digit too: `Literal.apply(LocalTime)` 
(`literals.scala:92`), `CatalystTypeConverters.TimeConverter`, and 
`TimeTypeOps.toCatalystImpl` and `createSerializer` store all nine digits. So 
`lit(LocalTime.of(0, 0, 0, 123456789))` is a TIME(6)
  literal holding 123456789 ns, and so is the same literal on Spark Connect, 
whose server converts it through `TimeTypeOps`. Spark Connect local relations 
built from Arrow data keep the extra digits as well. These values have the 
problem this PR describes: equality with TIME literals fails, DISTINCT and 
UNION keep duplicates, and a Parquet write changes the value.
   
   **Recommended change:** Add TimeFormatter.parse(s, precision), which 
truncates the parsed nanoseconds to the precision. Use it in ToTimeParser with 
TimeType.DEFAULT_PRECISION and in the JSON, CSV and XML TimeType converters 
with the field's precision. Truncate LocalTime values to the target precision 
in Literal.apply(LocalTime) and the schema-less CatalystTypeConverters 
conversion (TIME(6)), and in TimeTypeOps' external-value conversion and encoder 
serializer (the type's precision). Add JSON, CSV and XML reader tests, 
from_json, from_csv and from_xml tests, and LocalTime literal, DataFrame and 
Dataset tests. In the Spark Connect local-relation conversion, which reads 
Arrow time values without these conversions, add a TODO naming the follow-up 
that truncates Arrow-ingested TIME values to their precision.
   
   **Why this works:** Every producer that turns a string or a LocalTime into a 
TIME(p) value goes through a conversion that takes p and applies 
truncateTimeToPrecision, as CAST does, so none of these producers can store 
more than p digits; Arrow-based ingest is the excluded exception. TIME(7) to 
TIME(9) keep their extra digits up to p.
   
   **Scope:** Move TIME precision truncation into the shared string and 
LocalTime conversions, route the string and LocalTime producers through them, 
and leave Arrow-based ingest to a follow-up.
   
   **Compatibility:** Parse errors, NULL results and the readers' parse-mode 
handling stay as they are, and a TIME column whose precision covers all of the 
input's digits keeps every digit.
   
   **Risks:** JSON, CSV and XML reads, from_json, from_csv and from_xml, and 
LocalTime literals, DataFrames and Datasets with a TIME(p) column now drop 
digits beyond p, and a Dataset of LocalTime read back through TIME(6) no longer 
returns nanoseconds. This is the intended correction, but it changes stored 
values on those paths; the TIME type is a preview behind 
spark.sql.timeType.enabled, and restoring the old calls reverts it. A custom 
timeFormat with more fraction digits than the field precision now truncates 
instead of keeping them, which matches CAST. Until the Arrow follow-up lands, 
Spark Connect DataFrames and Datasets built from LocalTime values keep every 
digit, so on Spark Connect they can disagree with lit of the same LocalTime and 
with to_time on the same string.
   
   **Constraints:** TIME(7), TIME(8) and TIME(9) values keep their digits up to 
their precision. Parse errors, NULL handling and the readers' PERMISSIVE, 
DROPMALFORMED and FAILFAST modes behave as before.
   
   **Exclusions:**
   - Arrow-based ingest of TIME values, such as Spark Connect createDataFrame 
and Dataset data sent as a local relation, is not changed here. 
ArrowColumnVector serves every Arrow reader, so truncating there needs its own 
change; the TODO in the Spark Connect local-relation conversion names that 
follow-up.
   
   **Success:** from_json('{"t":"00:00:00.1234567"}', 't TIME').t = 
TIME'00:00:00.123456' returns true, and JSON, CSV and XML reads with a TIME(p) 
schema store at most p fractional digits with both the default and a custom 
timeFormat. lit(LocalTime.of(0, 0, 0, 123456789)) equals TIME'00:00:00.123456' 
in classic Spark and on Spark Connect, and classic createDataFrame and Dataset 
encoding of LocalTime into TIME(p) keep at most p digits. to_time and 
try_to_time return the same values as after this PR.
   
   **Verification:**
   - **Behavior:** Check that JSON, CSV and XML reads and from_json, from_csv 
and from_xml store 00:00:00.123456 for '00:00:00.1234567' read into TIME(6) and 
12:00:00.123 for '12:00:00.123456' read into TIME(3), with both the default and 
a 9-digit custom timeFormat.
   - **Behavior:** Check that a LocalTime with nanoseconds becomes a TIME value 
with at most the target precision through lit in classic Spark and on Spark 
Connect, through classic createDataFrame with a TIME(p) schema and through a 
classic Dataset encoder, and that it compares equal to the matching TIME 
literal.
   - **Compatibility:** Check that TIME(9) columns read from text sources or 
built from LocalTime keep all nine digits, that to_time and try_to_time results 
are unchanged, and that malformed TIME strings are still handled by the 
readers' parse modes as before.
   - **Regression:** Check that a string read through from_json and the same 
string passed to to_time produce equal TIME values.



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