viirya commented on code in PR #7731:
URL: https://github.com/apache/datafusion-comet/pull/7731#discussion_r4703091770


##########
spark/src/main/scala/org/apache/spark/sql/comet/CometNativeScanExec.scala:
##########
@@ -384,3 +411,55 @@ object CometNativeScanExec {
     batchScanExec
   }
 }
+
+/**
+ * Spark can expose the same plan to collect and to an RDD consumer that stops 
after one row. A
+ * larger native batch may decode timestamps past that row. Scope the extra 
overflow check to the
+ * collecting action's tasks, even when the actions share a cached execution 
RDD.
+ */
+case class CometParquetResultExec(child: SparkPlan) extends UnaryExecNode with 
CometPlan {

Review Comment:
   Unfiltered scans have the same batch-boundary exposure today. They always 
use checked conversion, so `select(ts).limit(1)` with an overflow at row 5000 
fails in Comet (8192-row batches) but not in Spark (4096). Should this scoping 
cover them too? If we accept the difference there, could we drop this node and 
the local property here, and keep only the native deferral and the gate? Either 
way, an issue to align the two paths would help.



##########
native/core/src/parquet/schema_adapter.rs:
##########
@@ -49,6 +49,93 @@ use std::fmt::{self, Display};
 use std::hash::{Hash, Hasher};
 use std::sync::Arc;
 
+/// Tag scan predicates that Spark evaluates only after decoding. The file's
+/// timestamp units are available only when the reader adapts the predicates.
+pub(crate) fn protect_timestamp_overflow(
+    predicates: Vec<Arc<dyn PhysicalExpr>>,
+    required_schema: &SchemaRef,
+) -> Vec<Arc<dyn PhysicalExpr>> {
+    let timestamp_roots: Arc<[FieldRef]> = required_schema
+        .fields()
+        .iter()
+        .filter(|field| has_timestamp_unit(field.data_type(), 
TimeUnit::Microsecond))
+        .cloned()
+        .collect();
+    if timestamp_roots.is_empty() {
+        return predicates;
+    }
+    predicates
+        .into_iter()
+        .map(|predicate| {
+            Arc::new(CometOnlyPredicate {
+                predicate,
+                timestamp_roots: Arc::clone(&timestamp_roots),
+            }) as Arc<dyn PhysicalExpr>
+        })
+        .collect()
+}
+
+#[derive(Debug, Eq)]
+pub(super) struct CometOnlyPredicate {

Review Comment:
   `evaluate` returning `true` is safe only because the filter above the scan 
re-evaluates every data filter. Could the doc comment state that? A name like 
`DeferrablePredicate` would also say more about what it does.



##########
spark/src/main/scala/org/apache/spark/sql/comet/CometNativeScanExec.scala:
##########
@@ -75,6 +77,27 @@ case class CometNativeScanExec(
     with ShimStreamSourceAwareSparkPlan
     with CometScanWithPlanData {
 
+  private[comet] def canCheckFilteredTimestampOverflow: Boolean = {

Review Comment:
   For `a = b`, `upper(x) = 'A'` or `a + b > 5`, `InferFiltersFromConstraints` 
adds `isnotnull(...)`, which always translates. So with default pushdown this 
mostly applies to `<=>` or an `OR` with an untranslatable branch. Is there a 
workload you have in mind that reaches it?



##########
docs/source/user-guide/latest/parquet.md:
##########
@@ -298,11 +298,16 @@ for production, so do not turn it off to avoid an entry 
on this page.
   differ only in such bytes distinct: they match Spark in a release build, and 
a debug build
   panics on top-level values 
([#7032](https://github.com/apache/datafusion-comet/issues/7032), part of
   [#4764](https://github.com/apache/datafusion-comet/issues/4764)).
-- **`TIMESTAMP_MILLIS` values that overflow when converted to microseconds.** 
In nested fields, and
-  in every column of a scan that has data filters, Comet returns NULL where 
Spark fails with
-  `ArithmeticException: long overflow`
-  ([#5553](https://github.com/apache/datafusion-comet/issues/5553),
-  [#5739](https://github.com/apache/datafusion-comet/issues/5739)).
+- **`TIMESTAMP_MILLIS` values that overflow when converted to microseconds.** 
Spark raises
+  `ArithmeticException: long overflow` when its reader decodes such a value. 
Comet checks the
+  conversion in a V1 Parquet query such as `SELECT s.ts FROM t WHERE id <=> 
match_id` when
+  you call `collect()` and both readers match fields by name. Spark evaluates 
that comparison
+  after decoding the timestamps. Other filtered scans can still return NULL on 
overflow.

Review Comment:
   Could this say that `show()`, `write`, `toLocalIterator` and cached reads 
still return NULL? Do Arrow `toPandas` and Spark Connect go through 
`executeCollect`? It would also help to note that these reads skip row-group 
pruning for files with millisecond timestamps.



##########
native/core/src/parquet/parquet_exec.rs:
##########
@@ -123,12 +123,16 @@ pub(crate) fn init_datasource_exec(
         &session_config.options().execution.parquet,
     );
     spark_parquet_options.use_field_id = use_field_id;
-    // Spark can discard filtered-out values before timestamp conversion using 
statistics,
-    // dictionary, and row-level filters. Comet cannot mirror every pruning 
path, so applying
-    // checked conversion in a filtered scan can fail on values Spark never 
reads. Preserve the
-    // existing safe cast for filtered scans and use checked conversion only 
when every value is
-    // necessarily read.
-    spark_parquet_options.checked_timestamp_overflow = data_filters.is_none();
+    // Spark may skip overflowing values via page, dictionary or row filters, 
even
+    // when none serialize for Comet (Some([])). Comet-only predicates are 
removed
+    // by the per-file adapter when they could hide an overflow Spark would 
read.
+    spark_parquet_options.checked_timestamp_overflow = match 
data_filters.as_deref() {

Review Comment:
   Working this out from whether every filter is wrapped hides a flag in the 
expression types. Could the planner pass 
`common.check_filtered_timestamp_overflow` in directly?



##########
native/core/src/parquet/schema_adapter.rs:
##########
@@ -1104,6 +1204,29 @@ struct SparkPhysicalExprAdapter {
 
 impl PhysicalExprAdapter for SparkPhysicalExprAdapter {
     fn rewrite(&self, expr: Arc<dyn PhysicalExpr>) -> DataFusionResult<Arc<dyn 
PhysicalExpr>> {
+        // All tagged predicates in the opener's conjunction share one 
projection.
+        let expr = if self.parquet_options.checked_timestamp_overflow && 
!expr.is::<Column>() {

Review Comment:
   What is `!expr.is::<Column>()` meant to exclude? A short comment would help 
the next reader.



##########
spark/src/test/scala/org/apache/comet/parquet/ParquetReadSuite.scala:
##########
@@ -640,6 +640,124 @@ abstract class ParquetReadSuite extends CometTestBase {
     }
   }
 
+  test("TIMESTAMP_MILLIS overflow when Spark applies filters above the Parquet 
reader") {

Review Comment:
   Could we add a top-level `TIMESTAMP_MILLIS` column? Every case here uses 
`s.ts`. Splitting this into a few smaller tests would also make failures easier 
to read.



##########
spark/src/test/scala/org/apache/comet/parquet/ParquetReadSuite.scala:
##########
@@ -640,6 +640,124 @@ abstract class ParquetReadSuite extends CometTestBase {
     }
   }
 
+  test("TIMESTAMP_MILLIS overflow when Spark applies filters above the Parquet 
reader") {
+    val errorClass =
+      if (isSpark40Plus) "FAILED_READ_FILE.NO_HINT" else 
"_LEGACY_ERROR_TEMP_2064"
+    withTempDir { dir =>
+      val path = new Path(dir.toURI.toString, "part-r-0.parquet")
+      val schema = MessageTypeParser.parseMessageType("""
+        |message root {
+        |  optional int64 id;
+        |  optional int64 match_id;
+        |  optional group s {
+        |    optional int32 k;
+        |    optional int64 ts(TIMESTAMP_MILLIS);
+        |  }
+        |}
+        |""".stripMargin)
+      val writer = createParquetWriter(schema, path)
+      Seq(0L, Long.MaxValue / 1000 + 1).zipWithIndex.foreach { case (millis, 
k) =>
+        val record = new SimpleGroup(schema)
+        record.add(0, k.toLong)
+        record.add(1, 0L)
+        val nested = record.addGroup(2)
+        nested.add(0, k)
+        nested.add(1, millis)
+        writer.write(record)
+      }
+      writer.close()
+
+      Seq(false, true).foreach { rowFilterPushdown =>
+        withSQLConf(
+          CometConf.COMET_PARQUET_ROW_FILTER_PUSHDOWN_ENABLED.key -> 
rowFilterPushdown.toString) {
+          readParquetFile(path.toString) { df =>
+            def checkOverflow(predicate: String): Unit = {
+              val filtered = df.where(predicate).select("s.ts")
+              assert(collect(filtered.queryExecution.executedPlan) {
+                case _: CometNativeScanExec => true
+              }.nonEmpty)
+              val error = checkSparkError(filtered, errorClass)
+              assert(new java.net.URI(error.getMessageParameters.get("path")) 
== path.toUri)
+              assert(error.getCause.getClass == classOf[ArithmeticException])
+              assert(error.getCause.getMessage == "long overflow")
+            }
+
+            def checkWithAndWithoutLimit(predicate: String): Unit = {
+              checkOverflow(predicate)
+              // Spark stops after the valid first batch. Comet can decode 
both rows together.
+              withSQLConf(
+                SQLConf.PARQUET_VECTORIZED_READER_BATCH_SIZE.key -> "1",
+                CometConf.COMET_BATCH_SIZE.key -> "2") {
+                val filtered = df.where(predicate).select("s.ts")
+                checkSparkAnswerAndOperator(filtered.limit(1), 
Seq(classOf[CometNativeScanExec]))
+
+                // The same plan can serve a partial RDD read and a full SQL 
collection.
+                val first = filtered.queryExecution.toRdd.take(1)
+                assert(
+                  first.length == 1 && !first.head.isNullAt(0) && 
first.head.getLong(0) == 0L)
+                val error = intercept[SparkException](filtered.collect())
+                
assert(causeChain(error).last.isInstanceOf[ArithmeticException])
+              }
+            }
+
+            // A column-to-column comparison has no V1 filter. Comet's row 
filter could
+            // otherwise discard the second row before converting its 
timestamp.
+            checkWithAndWithoutLimit("id <=> match_id")
+            checkSparkAnswerAndOperator(
+              df.where("s.k < 0").select("s.ts"),
+              Seq(classOf[CometNativeScanExec]))
+
+            if (isSpark40Plus) {
+              
withSQLConf(SQLConf.NESTED_PREDICATE_PUSHDOWN_FILE_SOURCE_LIST.key -> "") {
+                checkOverflow("s.k >= 0")
+                checkOverflow("s.k < 0")
+              }
+              withSQLConf(SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key -> 
"false") {
+                checkWithAndWithoutLimit("id <=> (SELECT min(id) FROM 
range(2))")
+              }
+            }
+          }
+        }
+      }
+
+      // Spark 4.x translates filters when it builds the reader. Spark 3.5 can 
translate

Review Comment:
   Do we need this block and the global temp view case below? Both cover 
unusual setting changes, and the `cometEnabled = false` branch mostly pins 
Spark's own behaviour.



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