spark-test commented on code in PR #59975:
URL: https://github.com/apache/spark/pull/59975#discussion_r4582590813


##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/TimeFormatter.scala:
##########
@@ -17,16 +17,30 @@
 
 package org.apache.spark.sql.catalyst.util
 
+import java.text.ParsePosition
 import java.time.LocalTime
 import java.time.format.DateTimeFormatter
 import java.util.Locale
 
+import scala.util.control.NonFatal
+
 import org.apache.spark.sql.catalyst.util.SparkDateTimeUtils._
 import org.apache.spark.unsafe.types.UTF8String
 
 sealed trait TimeFormatter extends Serializable {
   def parse(s: String): Long // returns nanoseconds since midnight
 
+  // A non-throwing variant of `parse`, returning None instead of throwing 
when the input cannot be
+  // parsed. Used by schema inference to probe the time type without paying an 
exception per
+  // non-time value. Subclasses override it to return None without throwing 
for input that does
+  // not match the time format; out-of-range fields may still raise an 
exception caught internally.

Review Comment:
   Thanks for checking it. Rewording the comment on master first and bringing 
it back with a later backport is fine with me: only the comment is affected, 
and inference results don't change.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4577099115","thread_id":"inline:4577099115","verdict_sha256":"f057cee3ac2c8c0fe143bbe8494d3457333bf48781bd03af0e31b418d4407eb0"}
 -->



##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/TimeFormatter.scala:
##########
@@ -50,6 +64,20 @@ class Iso8601TimeFormatter(pattern: String, locale: Locale, 
isParsing: Boolean)
     localTimeToNanos(localTime)
   }
 
+  override def parseOptional(s: String): Option[Long] = {
+    try {
+      val parsePosition = new ParsePosition(0)
+      val parsed = formatter.parseUnresolved(s, parsePosition)
+      if (parsed != null && s.length == parsePosition.getIndex) {
+        Some(parse(s))

Review Comment:
   **Blocking (P1):** With `spark.sql.timeType.enabled` on and a custom 
`timeFormat`, every value that fully matches the pattern is now parsed twice. 
`formatter.parseUnresolved` (line 70) is used only for the null and whole-input 
checks, and then `parse(s)` runs `formatter.parse` over the same text again 
(line 63) before strict resolution. On the base branch, as in the v4.3.0 
release, each probe called `parse` once.
   
   Schema inference in CSV, JSON (with `inferTimestamp`) and XML calls this 
probe for each value it tests as TIME, and a column already inferred as TIME 
re-enters the probe on every row, so the extra parse and its allocations (a 
`ParsePosition`, a parse context and an unresolved result) grow with the rows 
inferred. These values never threw on the base branch, so they gain nothing 
from this change and only pay the extra work. Inferred schemas are unaffected, 
and so are inference without a `timeFormat` and values the pattern rejects, 
which now avoid the exception.
   
   **Recommended change:** Make Iso8601TimeFormatter.parseOptional parse and 
resolve each value in one pass: call formatter.toFormat.parseObject(s, 
parsePosition) with a fresh ParsePosition, return None unless the result is 
non-null and parsePosition.getIndex equals s.length, and otherwise convert the 
resolved TemporalAccessor with toLocalTime and localTimeToNanos as parse does, 
keeping the NonFatal catch. Extend the time formatter parity tests to a 
fraction-of-second pattern and a pattern without an hour field. The second 
parse came in with commit ab29cf5016d, which replaced the one-pass conversion 
of unresolved fields from commit 8a6036a9bd8 with a call to parse; its message 
gives no reason, and the description says the call keeps clock-hour and AM/PM 
resolution identical to parse, one of two options an earlier review on this PR 
listed. The repair starts from the current code, keeps that strict resolution 
and drops only the extra parse; it does not return to the conversion of unres
 olved fields, which skips strict resolution.
   
   **Why this works:** DateTimeFormatter.toFormat returns a java.text.Format 
whose parseObject parses the text once and resolves it with the formatter's own 
resolver style and fields, the same STRICT resolution formatter.parse applies, 
and returns null with an error index instead of throwing when the text does not 
match or does not resolve. Checking for null and for whole-input consumption 
reproduces parse's acceptance, and converting the resolved value with the same 
toLocalTime and localTimeToNanos reproduces its result, so each matching value 
is parsed once.
   
   **Scope:** One method in the time formatter, plus parity cases in the time 
formatter tests.
   
   **Compatibility:** parse, the readers and SQL functions that call it, 
DefaultTimeFormatter.parseOptional, and every inferred schema behave exactly as 
before.
   
   **Risks:** Parity with parse now rests on the JDK's toFormat contract 
instead of on calling parse directly, so a pattern the parity tests do not 
cover could in principle resolve differently; the extended parity tests reduce 
that risk, and the change is confined to one method that can be reverted to the 
current two-pass code. Values that match only a prefix of the pattern now pay a 
resolution step before the whole-input check, and a prefix with an out-of-range 
field, such as '25:00:00x' under 'HH:mm:ss', raises and catches an exception 
inside the JDK where the current pre-check returns None without one; results 
are unchanged, and on the base branch parse raised an exception for every value 
that matched only a prefix.
   
   **Constraints:** Keep parse unchanged: the CSV, JSON and XML readers and the 
SQL time functions rely on it. Keep the NonFatal catch, so a fatal JVM error 
still propagates and every other failure maps to None. Leave 
DefaultTimeFormatter.parseOptional and the inference call sites unchanged.
   
   **Exclusions:**
   - Values that match a pattern's syntax but fail strict resolution, such as 
'17:30:01' under 'hh:mm:ss', still raise and catch one exception inside the JDK 
resolver, as on the base branch; removing it would need Spark's own range 
checks before resolution.
   - Master's SPARK-59546 commit converts the unresolved fields directly; 
changing it is outside this backport.
   
   **Success:** Iso8601TimeFormatter.parseOptional parses each value once, with 
no separate pre-check before the value is parsed and resolved. parseOptional 
returns the same result as Try(parse(s)).toOption for every custom pattern and 
input, including clock-hour, AM/PM, fraction-of-second and out-of-range cases. 
Values that do not match the pattern, including ones with trailing text, still 
return None without an exception escaping parseOptional. CSV, JSON and XML 
schema inference results are unchanged.
   
   **Verification:**
   - **Behavior:** For custom patterns covering 24-hour, clock-hour and AM/PM 
hours (HH, hh, KK, kk and 'hh:mm:ss a'), a fraction-of-second field, and a 
pattern without an hour field such as 'mm:ss a', parseOptional equals 
Try(parse).toOption over in-range, out-of-range, prefix-only and non-matching 
inputs.
   - **Inspection:** Iso8601TimeFormatter.parseOptional makes one parsing call 
into the DateTimeFormatter per value: it no longer runs parseUnresolved as a 
pre-check and then calls parse on the same value.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/xml/XmlSuite.scala:
##########
@@ -3678,6 +3678,24 @@ class XmlSuite
     }
   }
 
+  test("SPARK-59546: unusable timeFormat does not break XML inference") {
+    withSQLConf(SQLConf.TIME_TYPE_ENABLED.key -> "true") {
+      val xml = "<ROW><time>plain</time></ROW>"
+      val options = baseOptions + ("timeFormat" -> "EEE HH:mm")
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        Seq(xml).toDF("value").coalesce(1).write.text(path)
+        // The Dataset[String] input, and the multi-line file read, where an 
escaping error fails
+        // the query instead of producing a corrupt record.

Review Comment:
   **Nit (P3):** `XmlSuiteWithLegacyParser` also runs this test with the legacy 
XML parser, and with that parser an exception escaping inference would not fail 
the query on the multi-line file read. There, `MultiLineXmlDataSource.infer` 
tokenizes the file and calls `XmlInferSchema.infer(RDD[String])` 
(XmlDataSource.scala:306-335), whose per-record handler turns a non-fatal 
exception into a corrupt-record schema in PERMISSIVE mode 
(XmlInferSchema.scala:216-217), just as the Dataset[String] read does under 
both parsers. Only the default parser's `inferFromReaders` rethrows it 
(XmlInferSchema.scala:329-332). In an XML suite, 'escaping error' can also read 
as an XML character-escaping problem. The assertions would still fail under 
both parsers if the construction guard were removed, so only the comment needs 
to change, for example:
   
   ```suggestion
           // If an exception escaped schema inference, the Dataset[String] 
read would produce a
           // corrupt record, as would the multi-line file read with the legacy 
parser; with the
           // default parser, the multi-line file read would fail the query.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59975#discussion_r4577099163).
   
   **Verification:**
   - **Inspection:** The comment above the reads in the XML unusable-timeFormat 
test attributes failing the query only to the default parser's multi-line file 
read, attributes a corrupt record to the Dataset[String] read and to the legacy 
parser, and calls the error an exception that escapes schema inference.



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