You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "rich7420 (via GitHub)" <gi...@apache.org> on 2026/10/10 06:50:09 UTC

[PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

rich7420 opened a new pull request, #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847

   ## Which issue does this PR close?
   
   Closes #5883.
   
   ## Rationale for this change
   
   A filter such as `l IS NOT NULL AND id > 5` currently loses native Iceberg pruning on `id` when the collection null check cannot be pushed down.
   
   ## What changes are included in this PR?
   
   Retain supported predicates in positive conjunctions while preserving the exact post-scan filter. OR still requires a safe predicate from both branches; NOT requires its entire child to convert exactly.
   
   Add serializer and native scan regressions for complex null checks, nested AND/OR/NOT, result parity and reduced reader I/O. Update the Iceberg user guide.
   
   ## How are these changes tested?
   
   On main `bfacc43a5`, Spark 4.1 / JDK 21:
   
   - Root-reactor compilation, Spotless and Scalastyle passed.
   - 28 serializer tests passed.
   - Native Iceberg testing completed with 118 passing test executions and one expected cancellation for SPARK-55626. The new regression confirms Spark result parity, native execution and reduced bytes scanned.
   - Native library built from this checkout and verified against the library used by the JVM tests.
   
   Please apply `run-iceberg-tests` for broader Iceberg-version coverage; keep Draft pending CI.
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4345061265


##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -1009,6 +1082,18 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
     // schema so a filter column projected out of the scan output is still recognized.
     val pageIndexUnsupportedColumns =
       IcebergReflection.pageIndexUnsupportedColumns(metadata.tableSchema)
+    // Columns whose type changed over the table's history; residual predicates comparing them
+    // with a literal are dropped, except equality. The scan schema also covers a column that
+    // VERSION AS OF reads after it was dropped from the table.
+    val promotedColumns = Seq(metadata.tableSchema, metadata.scanSchema)
+      .flatMap(IcebergReflection.promotedColumns(metadata.table, _))
+      .toSet
+    // add_files, migrate and snapshot set a name mapping and import files without checking their
+    // types against the schema. Such files commonly hold narrower physical types, such as Hive
+    // TINYINT and SMALLINT stored as INT32 with INT_8 or INT_16 annotations, which iceberg-rust
+    // compares incorrectly. So partial pushdown is not extended to these tables, and they push a
+    // residual only when it converts whole.
+    val partialPushdown = metadata.nameMapping.isEmpty

Review Comment:
   [P1] [P1] Preserve rows from unrecorded promotions when enabling partial pushdown. A table whose `id` was promoted from `INT` to `BIGINT` before Iceberg 0.12 can have physical `INT` files, no name mapping, and only schema ID `0` in its reconstructed history. `promotedColumns` consequently returns empty, and this gate enables partial pushdown. For rows `(1, array(1)), (2, array(2)), (3, array(3))`, `WHERE l IS NOT NULL AND id < 3000000000` should return all three rows. The base drops the mixed residual, but this head retains `NotNull(id) AND LessThan(id, 3000000000)`, and the pinned reader drops every row. This extends #7138 to queries that previously returned correct results. Please retain a conservative partial-pushdown guard for potentially promoted columns unless physical types are verified, or fix the native comparison before enabling this path.
   
   Evidence: Reproduced in `/tmp/review6847-622d-1c0zesk4`. `LegacyPromotionProbe.scala` creates an unpartitioned table with an INT Parquet file, promotes its logical column to BIGINT, and writes the supported v1 schema-only metadata representation emitted by Iceberg 0.11.1. Upstream old/current TableMetadataParser sources confirm this representation and its reconstruction as a single schema. `legacy-spark.log` records schema IDs `[0]`, `promoted=Set()`, no name mapping, Spark results `[1,2,3]`, base serialization `None`, and exact-head serialization containing the retained range. `legacy-native.log` records the same file returning three rows without pushdown and zero with the emitted `NotNull(id) AND id < 3000000000` predicate. The reader uses iceberg-rust `1f3bc34058e3f3e45336bc5428f37b92649a608b`, Arrow 59.3.0, `rewrite_not().bind(...)`, and row selection enabled.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "rich7420 (via GitHub)" <gi...@apache.org>.
rich7420 commented on PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#issuecomment-6110919163

   @sunchao thanks for the review , I will update as soon as possible 


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "rich7420 (via GitHub)" <gi...@apache.org>.
rich7420 commented on PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#issuecomment-6333809953

   Thanks @mbutrovich. I split the fixes for #7136, #7137 and the promoted-column part of #7138 into #7156, and rebased this PR on top of it. On top of #7156, this PR only adds partial pushdown, so the benchmark below compares it with #7156, not with `main`.
   
   On "native Iceberg pruning": `ArrowReader` can use the pushed conjuncts to prune row groups using statistics, select rows using the page index and filter rows with the `RowFilter` during decode. I updated the description to say so.
   
   I also simplified the change. The serde converts the residual once, and each kept conjunct goes through the same rules as a residual that converts in full. The earlier version also restricted every `BIGINT` and `DOUBLE` column to `=` when only part of the residual converted, which blocked pruning on `BIGINT` keys.
   
   Benchmark: I added partial filter cases to `CometIcebergReadBenchmark` (16M rows, 8 files, each spanning the whole key range, so Iceberg's file pruning skips nothing). Each query is `l IS NOT NULL AND <range>`, and only the range can be pushed. Each timing cell shows the best Comet time from each of two runs (run 1 / run 2):
   
   | Pushed range | #7156 | This PR | Bytes scanned |
   |---|---|---|---|
   | 1% of a clustered `INT` column | 1303 / 1276 ms | 67 / 63 ms | 663 MiB → 14 MiB |
   | 1% of a clustered `BIGINT` column | 1308 / 1284 ms | 64 / 67 ms | 633 MiB → 13 MiB |
   | 1% of a scattered `INT` column | 1265 / 1245 ms | 1232 / 1208 ms | 671 MiB → 671 MiB |
   | 90% of a scattered `INT` column | 1358 / 1367 ms | 1466 / 1508 ms | 671 MiB → 671 MiB |
   
   The 90% scattered case was the least favorable case measured: statistics skip nothing and the `RowFilter` removes few rows, and it was 8–10% slower in these runs. Within a single build, the timings with the range pushed and with it written as `scattered + 0` to prevent pushdown differed by 0–5%, so part of that gap is run-to-run variation.
   
   Separately, while checking promoted columns I found that iceberg-rust's page-index evaluator can wrongly skip pages whose bounds have a narrower type than the table column, such as `INT32` pages on a `BIGINT` column, which drops matching rows. I opened apache/iceberg-rust#3507 to fix it.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4241016471


##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -733,36 +740,42 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
       val left = icebergExprToProto(
         IcebergReflection.getMethod(exprClass, "left").invoke(icebergExpr),
         output,
-        pageIndexUnsupportedColumns)
+        pageIndexUnsupportedColumns,
+        allowPartial)
       val right = icebergExprToProto(
         IcebergReflection.getMethod(exprClass, "right").invoke(icebergExpr),
         output,
-        pageIndexUnsupportedColumns)
+        pageIndexUnsupportedColumns,
+        allowPartial)
       (left, right) match {
-        // Push the residual only if it converts whole. Dropping a conjunct is safe in positive
-        // position but strengthens the predicate under a NOT (De Morgan), which would wrongly
-        // prune, and tracking polarity across arbitrary nesting is error prone. So an
-        // unconvertible conjunct elides the whole residual; the post-scan CometFilter is exact.
         case (Some(l), Some(r)) => Some(logicalPredicate(isAnd = true, l, r))
+        // Dropping a positive conjunct weakens the predicate; the post-scan filter stays exact.
+        // Inside NOT, every descendant must convert exactly, including nested AND/OR nodes.
+        case (l, r) if allowPartial => l.orElse(r)

Review Comment:
   [P1] Keep Spark-incompatible floating-point comparisons out of partial residuals. With native Iceberg scanning enabled, create an unpartitioned table containing `(CAST('-0.0' AS DOUBLE), array(1))` and `(CAST('0.0' AS DOUBLE), array(1))` as `(f, l)`, then query `WHERE l IS NOT NULL AND f = CAST(0 AS DOUBLE)`. Spark returns both rows. Previously the unsupported array null check caused the entire residual to be omitted. This branch now retains `NotNull(f) AND Eq(f, 0.0)`, and the pinned iceberg-rust reader uses Arrow equality, which distinguishes signed zeros and drops the negative-zero row. The exact post-scan filter cannot recover it. Although standalone floating-point pushdown already has this limitation, this PR exposes it on mixed predicates that previously avoided it. Please decline unsafe floating-point leaves or provide Spark-compatible reader comparisons, with a regression covering this mixed predicate.
   
   Evidence: Fresh reproduction in `/tmp/comet6847-03cb-check.i0elyH`: `serde-validation.log` shows the actual residual shape converting to `None` at the base and `AND(NotNull(f), Eq(f, 0.0))` at the head. `spark-zero.log` records Spark 4.1.3/Iceberg 1.11.0 returning both zero bit patterns. `native-zero.log` records the same Parquet file and full projected schema returning two rows without pushdown and one row (`0000000000000000`) with that predicate. The reader was compiled with iceberg-rust `af1da4c5bc86178c38c1c6db0578bdd9fb7021e3`, Arrow 59.3.0, and `with_row_selection_enabled(true)`, matching the checkout. Its `predicate_visitor.rs::eq` calls `arrow_ord::cmp::eq`; Spark’s `SQLOrderingUtil.compareDoubles` equates signed zeros across all supported versions.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "rich7420 (via GitHub)" <gi...@apache.org>.
rich7420 commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4349337145


##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -1009,6 +1082,18 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
     // schema so a filter column projected out of the scan output is still recognized.
     val pageIndexUnsupportedColumns =
       IcebergReflection.pageIndexUnsupportedColumns(metadata.tableSchema)
+    // Columns whose type changed over the table's history; residual predicates comparing them
+    // with a literal are dropped, except equality. The scan schema also covers a column that
+    // VERSION AS OF reads after it was dropped from the table.
+    val promotedColumns = Seq(metadata.tableSchema, metadata.scanSchema)
+      .flatMap(IcebergReflection.promotedColumns(metadata.table, _))
+      .toSet
+    // add_files, migrate and snapshot set a name mapping and import files without checking their
+    // types against the schema. Such files commonly hold narrower physical types, such as Hive
+    // TINYINT and SMALLINT stored as INT32 with INT_8 or INT_16 annotations, which iceberg-rust
+    // compares incorrectly. So partial pushdown is not extended to these tables, and they push a
+    // residual only when it converts whole.
+    val partialPushdown = metadata.nameMapping.isEmpty

Review Comment:
   Thanks, you're right. Before this PR the array null check kept the whole residual out of the scan, so these queries returned the right rows, and partial pushdown exposed them to #7138.
   
   Fixed in b5fc1be16. The residual is first converted with #7156's rules. Only if that fails and the table allows partial pushdown is it converted again keeping the supported conjuncts. That second pass treats every `BIGINT`, `DOUBLE` and `DECIMAL` column as promoted, since the schema history cannot rule out a promotion made before 0.12, so they keep only null checks and `=` outside `NOT`. Residuals that convert whole are unchanged from #7156.
   
   The new test `partial residuals do not compare columns promoted before Iceberg 0.12` appends a file written with `INT` and `FLOAT` columns to a `BIGINT`/`DOUBLE` table with one schema and no name mapping. It checks `l IS NOT NULL AND` each of `id > 0`, `id < 3000000000`, `id != 3000000000`, `id IN (1, 3000000000)` and `d != 0.1`, with `id = 2` and `d = 0.5` as controls. Without the fix it fails on `id > 0`: Spark returns 2 rows and Comet 0, because the page index skips the `INT32` page.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "mbutrovich (via GitHub)" <gi...@apache.org>.
mbutrovich commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4329274950


##########
docs/source/user-guide/latest/iceberg.md:
##########
@@ -113,8 +113,30 @@ The native Iceberg reader supports the following features:
 
 NULL checks on struct, array, and map columns still use native scans and return correct
 results, but are not pushed into iceberg-rust, which binds accessors only for primitive fields.
-These residuals provide no native row-group pruning, nor do conjunctions containing them;
-safe partial pruning is tracked in [#5883](https://github.com/apache/datafusion-comet/issues/5883).
+These null checks provide no native row-group pruning. In a positive conjunction, supported
+primitive predicates still prune row groups and pages, while the post-scan filter evaluates the
+complete condition. `OR` requires a safely pushable predicate from both branches, and expressions
+inside `NOT` must convert completely before they can be pushed. When only part of a condition can
+be pushed, predicates on `BIGINT` and `DOUBLE` columns in it are pushed only for `=` and null
+checks, because a data file can store a narrower type than its column without any record of it.
+
+Tables with a `schema.name-mapping.default` property push a conjunction only when every predicate
+in it can be pushed. The `add_files`, `migrate` and `snapshot` procedures set this property when
+they import data files, and an imported file can store a narrower type than its column.
+
+Spark treats `-0.0` as equal to `0.0` and sorts every NaN above all numbers, but iceberg-rust
+uses IEEE 754 total ordering. On `FLOAT` and `DOUBLE` columns, range comparisons and comparisons
+with `0.0`, `-0.0` or NaN are therefore evaluated after the native scan.
+
+Some other predicates are also evaluated only after the native scan:
+
+- Negated equality on a nullable column. Iceberg passes `<=>` as `=`, so for `NOT (a <=> 1)` the
+  native reader would drop NULL rows that Spark keeps, and `a <> 1` reaches Comet in the same
+  form.
+- Comparisons other than `=` with a literal on a column whose type was promoted, for example
+  from `INT` to `BIGINT`, because older data files keep the original type. If expiring
+  snapshots removed older schemas, this applies to every `BIGINT` and `DOUBLE` column. A
+  promotion made before Iceberg 0.12, which kept no schema history, cannot be detected.

Review Comment:
   Could this section be shorter? It grows from two sentences to 24 lines, and most of the new text explains why each rule exists, which the code comments and the Known Issues entry already cover. It also says the kept predicates "prune row groups and pages", but iceberg-rust also uses them to filter rows during decode. Here's a version that keeps every rule a user can act on:
   
   ```suggestion
   These null checks are not pushed, but the other predicates in a positive conjunction still are.
   iceberg-rust uses a pushed predicate to skip row groups and pages and to filter rows during
   decode, and the filter above the scan evaluates the complete condition. `OR` is pushed only when
   both branches can be, and `NOT` only when its whole child can be.
   
   Some predicates are left to the filter above the scan because iceberg-rust would return
   different rows than Spark:
   
   - Range comparisons on `FLOAT` and `DOUBLE` columns, and comparisons with `0.0`, `-0.0` or NaN.
   - `NOT` over equality on a nullable column.
   - Comparisons other than `=` on a column whose type was promoted. This applies to every `BIGINT`
     and `DOUBLE` column when only part of a condition is pushed, or when expiring snapshots removed
     older schemas.
   
   Tables with a `schema.name-mapping.default` property push a condition only when all of it can be
   pushed.
   ```



##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -679,17 +679,66 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
    *   - An exception means reflection over Iceberg's expression API did something unexpected, so
    *     no such decision was reached. It propagates instead of folding into `None`, which would
    *     make the two indistinguishable; see [[serializeResidual]].
+   *
+   * @param promotedColumns
+   *   columns whose older data files may hold a narrower type; see
+   *   [[IcebergReflection.promotedColumns]]
+   * @param partialPushdown
+   *   whether a residual that does not convert whole may push the conjuncts that do, leaving the
+   *   rest to the post-scan filter
    */
   def icebergExprToProto(
       icebergExpr: Any,
       output: Seq[Attribute],
-      pageIndexUnsupportedColumns: Set[String]): Option[OperatorOuterClass.IcebergPredicate] = {
+      pageIndexUnsupportedColumns: Set[String],
+      promotedColumns: Set[String] = Set.empty,
+      partialPushdown: Boolean = true): Option[OperatorOuterClass.IcebergPredicate] = {

Review Comment:
   Should `promotedColumns` and `partialPushdown` be required here and in `serializeResidual` (lines 838-839)? The one production call, at line 1263, passes both. The defaults are the least safe pair, no promoted columns and partial pushdown allowed, so a new caller that leaves them out skips the promotion guard without a compile error. As I read it, only `CometIcebergNativeScanSuite` relies on them.



##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -679,17 +679,66 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
    *   - An exception means reflection over Iceberg's expression API did something unexpected, so
    *     no such decision was reached. It propagates instead of folding into `None`, which would
    *     make the two indistinguishable; see [[serializeResidual]].
+   *
+   * @param promotedColumns
+   *   columns whose older data files may hold a narrower type; see
+   *   [[IcebergReflection.promotedColumns]]
+   * @param partialPushdown
+   *   whether a residual that does not convert whole may push the conjuncts that do, leaving the
+   *   rest to the post-scan filter
    */
   def icebergExprToProto(
       icebergExpr: Any,
       output: Seq[Attribute],
-      pageIndexUnsupportedColumns: Set[String]): Option[OperatorOuterClass.IcebergPredicate] = {
+      pageIndexUnsupportedColumns: Set[String],
+      promotedColumns: Set[String] = Set.empty,
+      partialPushdown: Boolean = true): Option[OperatorOuterClass.IcebergPredicate] = {
+    val attributes = output.map(attr => attr.name -> attr).toMap
+    def convert(promoted: Set[String], partial: Boolean) =
+      icebergExprToProto(
+        icebergExpr,
+        ResidualScope(attributes, pageIndexUnsupportedColumns, promoted, partial),
+        underNot = false)
+    // Pushing part of a residual must not rely on the schema history, which misses some
+    // promotions, such as those made before Iceberg 0.12. So when the residual does not convert
+    // whole, every BIGINT and DOUBLE column counts as promoted. Whole residuals rely on the
+    // history, since limiting them too would stop range pruning on all such columns until
+    // apache/iceberg-rust#3122 is fixed.
+    convert(promotedColumns, partial = false).orElse {
+      if (partialPushdown) {
+        val widened = output.collect {
+          case attr if attr.dataType == LongType || attr.dataType == DoubleType => attr.name
+        }
+        convert(promotedColumns ++ widened, partial = true)
+      } else {
+        None
+      }
+    }
+  }
+
+  /** What [[icebergExprToProto]] consults at every node of a residual. */
+  private case class ResidualScope(
+      attributes: Map[String, Attribute],
+      pageIndexUnsupportedColumns: Set[String],
+      promotedColumns: Set[String],
+      partialPushdown: Boolean)

Review Comment:
   What does `ResidualScope` represent? The doc comment says it's what the walk "consults at every node", which fits any argument. As I read it, it holds the settings for one of the two passes at lines 707-716, and it mixes values that are the same in both passes (`attributes`, `pageIndexUnsupportedColumns`) with values that differ (`promotedColumns`, `partialPushdown`). Meanwhile `underNot`, the one value that changes during the walk, stays a separate argument.
   
   The field `partialPushdown` also means something different from the parameter of the same name at line 695. The parameter says whether the table allows partial pushdown at all. The field says whether this pass may drop a conjunct, and it is `false` on the first pass even when the table allows it. Could the type and that field get names that say what they hold (for example `dropUnconvertedConjuncts` for the field), with a short doc comment on each field?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "rich7420 (via GitHub)" <gi...@apache.org>.
rich7420 commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4344990621


##########
spark/src/test/scala/org/apache/comet/CometIcebergNativeSuite.scala:
##########
@@ -4201,6 +4203,440 @@ class CometIcebergNativeSuite
     }
   }
 
+  test("partial residual pushdown preserves complex filters and reduces reader work") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.partial_residual_test"
+        // Keep split sizing fixed so repeated footer reads do not dominate the byte comparison.
+        spark.sql(s"""
+          CREATE TABLE $table (
+            id INT,
+            l ARRAY<INT>,
+            m MAP<STRING, INT>,
+            s STRUCT<v: INT>,
+            payload STRING
+          ) USING iceberg
+          TBLPROPERTIES (
+            'read.split.adaptive-size.enabled' = 'false',
+            'write.parquet.row-group-size-bytes' = '16384',
+            'write.parquet.compression-codec' = 'uncompressed'
+          )
+        """)
+        try {
+          spark
+            .range(10000)
+            .repartition(1)
+            .sortWithinPartitions("id")
+            .selectExpr(
+              "CASE WHEN id % 97 = 0 THEN NULL ELSE CAST(id AS INT) END AS id",
+              "CASE WHEN id % 2 = 0 THEN array(CAST(id AS INT)) ELSE NULL END AS l",
+              "CASE WHEN id % 3 = 0 THEN map('v', CAST(id AS INT)) ELSE NULL END AS m",
+              "CASE WHEN id % 5 = 0 THEN named_struct('v', CAST(id AS INT)) ELSE NULL END AS s",
+              "repeat(sha2(CAST(id AS STRING), 256), 2) AS payload")
+            .write
+            .format("iceberg")
+            .mode("append")
+            .saveAsTable(table)
+
+          // One unpartitioned file containing several row groups: the byte savings must come
+          // from the reader, rather than Iceberg's manifest/file pruning or partition selection.
+          val files = spark.sql(s"SELECT file_path FROM $table.files").collect()
+          assert(files.length == 1, s"Expected one data file, got ${files.length}")
+          val reader = org.apache.parquet.hadoop.ParquetFileReader.open(
+            org.apache.parquet.hadoop.util.HadoopInputFile.fromPath(
+              new org.apache.hadoop.fs.Path(files.head.getString(0)),
+              spark.sessionState.newHadoopConf()))
+          try {
+            assert(reader.getRowGroups.size > 3, "Fixture needs multiple row groups for pruning")
+          } finally {
+            reader.close()
+          }
+
+          def checkAndGetScan(predicate: String): CometIcebergNativeScanExec = {
+            val query = s"SELECT * FROM $table WHERE $predicate"
+            val (_, plan) = checkSparkAnswer(query)
+            val scans = collectIcebergNativeScans(plan)
+            assert(scans.length == 1, s"Expected one native scan for $query:\n$plan")
+            scans.head
+          }
+
+          val fullScan = checkAndGetScan("l IS NOT NULL")
+          val fullBytes = fullScan.metrics("bytes_scanned").value
+          assert(fullBytes > 0, "Full read must report bytes")
+          assert(fullScan.metrics("output_rows").value == 10000L)
+
+          val partialScan = checkAndGetScan("l IS NOT NULL AND id BETWEEN 1000 AND 1099")
+          val partialBytes = partialScan.metrics("bytes_scanned").value
+          assert(fullScan.metrics("num_splits").value > 0L)
+          assert(partialScan.metrics("num_splits").value == fullScan.metrics("num_splits").value)
+          assert(
+            partialScan.metrics("output_rows").value < 1000L,
+            "The native reader must apply the primitive residual before the complex filter")
+          assert(
+            partialBytes * 2 < fullBytes,
+            s"Partial residual must prune reads: partial=$partialBytes, full=$fullBytes")
+
+          Seq(
+            "m IS NOT NULL AND id BETWEEN 1000 AND 1099",
+            "s IS NULL AND id BETWEEN 1000 AND 1099",
+            "id >= 1000 AND (l IS NOT NULL OR m IS NULL)",
+            "(id < 100 AND l IS NOT NULL) OR (id >= 9900 AND m IS NOT NULL)",
+            "id < 100 OR l IS NOT NULL",
+            "NOT (id < 2000 AND l IS NOT NULL)",
+            "NOT ((id < 100 AND l IS NOT NULL) OR (id >= 9900 AND m IS NOT NULL))")
+            .foreach { predicate =>
+              val _ = checkAndGetScan(predicate)
+            }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("floating-point residuals preserve signed zeros in native scans") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.floating_residual_test"
+        spark.sql(s"CREATE TABLE $table (id INT, f FLOAT, d DOUBLE, l ARRAY<INT>) USING iceberg")
+        try {
+          withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+            // One file containing both zeros keeps file pruning from deciding the comparison.
+            // Distinct ids make a missing signed-zero row observable without comparing floats.
+            spark
+              .sql("""
+                SELECT id, CAST(v AS FLOAT) AS f, CAST(v AS DOUBLE) AS d, l
+                FROM VALUES
+                  (1, '-0.0', array(1)),
+                  (2, '0.0', array(1)),
+                  (3, '1.0', CAST(NULL AS ARRAY<INT>)),
+                  (4, '-1.0', array(1)),
+                  (5, NULL, array(1)),
+                  (6, 'NaN', array(1))
+                AS input(id, v, l)
+              """)
+              .coalesce(1)
+              .write
+              .format("iceberg")
+              .mode("append")
+              .saveAsTable(table)
+            assert(spark.sql(s"SELECT file_path FROM $table.files").collect().length == 1)
+            val rows = spark.sql(s"SELECT id, f, d FROM $table").collect().sortBy(_.getInt(0))
+            assert(java.lang.Float.floatToRawIntBits(rows(0).getFloat(1)) == Int.MinValue)
+            assert(java.lang.Double.doubleToRawLongBits(rows(0).getDouble(2)) == Long.MinValue)
+            assert(java.lang.Float.floatToRawIntBits(rows(1).getFloat(1)) == 0)
+            assert(java.lang.Double.doubleToRawLongBits(rows(1).getDouble(2)) == 0L)
+          }
+
+          for ((column, dataType) <- Seq("f" -> "FLOAT", "d" -> "DOUBLE")) {
+            val zero = s"CAST(0 AS $dataType)"
+            val negativeZero = s"CAST('-0.0' AS $dataType)"
+            val one = s"CAST(1 AS $dataType)"
+            val minusOne = s"CAST(-1 AS $dataType)"
+            val predicates = Seq(
+              s"$column = $zero",
+              s"$column = $negativeZero",
+              s"$column >= $zero",
+              s"$column <= $negativeZero",
+              s"$column IN ($zero, $one)",
+              s"NOT ($column < $zero)",
+              // Nonzero literals push equality and IN; range comparisons stay out.
+              s"$column = $one",
+              s"$column IN ($one, $minusOne)",
+              s"NOT ($column IN ($one, $minusOne) AND id > 1)",
+              s"$column < $one",
+              s"$column > $minusOne",
+              s"NOT ($column = $one)",
+              s"$column = $zero OR id = 3",
+              s"NOT ($column = $zero AND id > 1)",
+              s"$column IS NULL",
+              s"$column IS NOT NULL")
+            for (predicate <- predicates;
+              prefix <- Seq("", "l IS NOT NULL AND ")) {
+              checkIcebergNativeScan(s"SELECT id FROM $table WHERE $prefix($predicate)")
+            }
+          }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("negated null-safe equality keeps NULL rows in native scans") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.null_safe_residual_test"
+        spark.sql(s"CREATE TABLE $table (id INT, b BOOLEAN, l ARRAY<INT>) USING iceberg")
+        try {
+          withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+            // One file keeps file pruning from deciding the comparison.
+            spark
+              .sql("""
+                SELECT * FROM VALUES
+                  (NULL, NULL, array(1)), (1, true, array(1)), (2, false, array(1))
+                AS t(id, b, l)
+              """)
+              .coalesce(1)
+              .write
+              .format("iceberg")
+              .mode("append")
+              .saveAsTable(table)
+            assert(spark.sql(s"SELECT file_path FROM $table.files").collect().length == 1)
+          }
+          // Iceberg converts `id <=> 1` to an equality, which is false for a NULL id in Spark but
+          // NULL in the native reader, so only its negation can drop the NULL row. Spark also
+          // writes that negation as IS DISTINCT FROM and, for booleans, IS NOT TRUE.
+          val predicates = Seq(
+            "NOT (id <=> 1)",
+            "NOT (id <=> 1 AND id < 5)",
+            "NOT (id <=> 1) OR id = 2",
+            "id IS DISTINCT FROM 1",
+            "b IS NOT TRUE",
+            "NOT b",
+            "NOT (id = 1)",
+            "id != 1")
+          for (predicate <- predicates;
+            prefix <- Seq("", "l IS NOT NULL AND ")) {
+            checkIcebergNativeScan(s"SELECT id FROM $table WHERE $prefix($predicate)")
+          }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("literal residuals on promoted columns keep rows from older files") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.promoted_residual_test"
+        spark.sql(s"CREATE TABLE $table (id INT, f FLOAT, l ARRAY<INT>) USING iceberg")
+        try {
+          withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+            // One file, so that its FLOAT bounds keep it for f = 0.1D below.
+            spark.sql(s"""INSERT INTO $table SELECT /*+ COALESCE(1) */ * FROM VALUES
+              (1, 0.5, array(1)), (2, 2.5, array(1)), (3, 0.1, array(1)), (6, 0.05, array(1))
+              AS v(id, f, l)""")
+            spark.sql(s"ALTER TABLE $table ALTER COLUMN id TYPE BIGINT")
+            spark.sql(s"ALTER TABLE $table ALTER COLUMN f TYPE DOUBLE")
+            spark.sql(s"INSERT INTO $table VALUES (4, 0.5D, array(1)), (5, 4.5D, array(1))")
+          }
+          // The first file still stores INT and FLOAT. iceberg-rust skips its pages for range and
+          // IN predicates on the promoted types, and casts 3000000000 to a NULL INT.
+          val predicates = Seq(
+            "id > 0",
+            "id < 3",
+            "id IN (1, 2)",
+            "id < 3000000000",
+            "id = 2",
+            "id = 2 OR id = 3000000000",
+            "f IN (0.5D, 4.5D)",
+            "f = 0.5D",
+            "f = 0.1D")
+          def checkPredicates(): Unit =
+            for (predicate <- predicates;
+              prefix <- Seq("", "l IS NOT NULL AND ")) {
+              checkIcebergNativeScan(s"SELECT id FROM $table WHERE $prefix($predicate)")
+            }
+          checkPredicates()
+
+          // The native reader narrows 0.1D to the FLOAT 0.1, which Spark does not consider equal
+          // to it. The first file's bounds, 0.05 to 2.5, keep it in the scan for that.
+          val narrowed = s"SELECT id FROM $table WHERE f = 0.1D"
+          val df = spark.sql(narrowed)
+          df.collect()
+          val scanned =
+            collectIcebergNativeScans(df.queryExecution.executedPlan).head
+              .metrics("resultDataFiles")
+              .value
+          assert(scanned == 1, s"Expected the first file to be scanned, scanned $scanned files")
+
+          // Expiring the first snapshot with cleanExpiredMetadata (Iceberg 1.8+) drops the original
+          // schema, while the file that snapshot wrote stays in the table.
+          if (icebergVersionAtLeast(1, 8)) {
+            val icebergTable =
+              loadIcebergTable(spark, "test_cat", "db", "promoted_residual_test")
+                .asInstanceOf[org.apache.iceberg.Table]
+            val expire = icebergTable
+              .expireSnapshots()
+              .expireOlderThan(System.currentTimeMillis())
+              .retainLast(1)
+            classOf[org.apache.iceberg.ExpireSnapshots]
+              .getMethod("cleanExpiredMetadata", classOf[Boolean])
+              .invoke(expire, java.lang.Boolean.TRUE)
+            expire.commit()
+            spark.sql(s"REFRESH TABLE $table")
+            val schemas = loadIcebergTable(spark, "test_cat", "db", "promoted_residual_test")
+              .asInstanceOf[org.apache.iceberg.Table]
+              .schemas()
+            assert(schemas.size == 1 && !schemas.containsKey(0))
+            assert(spark.sql(s"SELECT * FROM $table").count() == 6)
+            checkPredicates()
+          }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("residuals on tables with imported files are pushed only whole") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.imported_residual_test"
+        spark.sql(s"CREATE TABLE $table (id BIGINT, t INT, f FLOAT) USING iceberg")
+        try {
+          withTempDir { dir =>
+            // The file stores id as INT and t as TINYINT. Importing it the way add_files does
+            // adds a name mapping but records no schema change.
+            val source = new File(dir, "source").getAbsolutePath
+            withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+              spark
+                .sql("SELECT CAST(id AS INT) AS id, CAST(id AS TINYINT) AS t, " +
+                  "CAST(id AS FLOAT) AS f FROM range(1, 4)")
+                .coalesce(1)
+                .write
+                .parquet(source)
+            }
+            val icebergTable = loadIcebergTable(spark, "test_cat", "db", "imported_residual_test")
+              .asInstanceOf[org.apache.iceberg.Table]
+            icebergTable
+              .updateProperties()
+              .set(
+                TableProperties.DEFAULT_NAME_MAPPING,
+                NameMappingParser.toJson(MappingUtil.create(icebergTable.schema())))
+              .commit()
+            val file = new File(source).listFiles().find(_.getName.endsWith(".parquet")).get
+            icebergTable
+              .newAppend()
+              .appendFile(
+                DataFiles
+                  .builder(icebergTable.spec())
+                  .withPath(file.getAbsolutePath)
+                  .withFileSizeInBytes(file.length())
+                  .withRecordCount(3)
+                  .withFormat(FileFormat.PARQUET)
+                  .build())
+              .commit()
+            withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+              spark.sql(s"INSERT INTO $table VALUES (4, 4, 4.0)")
+            }
+            spark.sql(s"REFRESH TABLE $table")
+
+            // The float range is never pushed, so each residual converts only in part. Pushing
+            // that part would skip the imported file's pages, or narrow 200 to a NULL TINYINT.
+            for (predicate <- Seq(
+                "id > 0",
+                "id < 3000000000",
+                "id IN (1, 2)",
+                "t < 200",
+                "t IN (1, 200)")) {
+              checkIcebergNativeScan(
+                s"SELECT id FROM $table WHERE f > CAST(0.5 AS FLOAT) AND $predicate")
+            }
+            checkIcebergNativeScan(s"SELECT id FROM $table WHERE id = 2 AND t = 2")
+          }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("partial residuals push only equality on BIGINT and DOUBLE columns") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.unrecorded_promotion_test"
+        spark.sql(s"CREATE TABLE $table (id BIGINT, f FLOAT, d DOUBLE) USING iceberg")
+        try {
+          withTempDir { dir =>
+            // The file stores id as INT and d as FLOAT under the table's field ids, and neither
+            // a schema nor a name mapping records it, as after a promotion before Iceberg 0.12.
+            val source = new File(dir, "source").getAbsolutePath
+            def fieldId(id: Long) = new MetadataBuilder().putLong("parquet.field.id", id).build()
+            val schema = new StructType()
+              .add("id", IntegerType, nullable = true, fieldId(1))
+              .add("f", FloatType, nullable = true, fieldId(2))
+              .add("d", FloatType, nullable = true, fieldId(3))
+            val rows = Seq(Row(1, 1.0f, 0.5f), Row(2, 2.0f, 2.5f), Row(3, 3.0f, 4.5f))
+            withSQLConf(
+              CometConf.COMET_ENABLED.key -> "false",
+              "spark.sql.parquet.fieldId.write.enabled" -> "true") {
+              spark
+                .createDataFrame(spark.sparkContext.parallelize(rows, 1), schema)
+                .write
+                .parquet(source)
+            }
+            val icebergTable =
+              loadIcebergTable(spark, "test_cat", "db", "unrecorded_promotion_test")
+                .asInstanceOf[org.apache.iceberg.Table]
+            val file = new File(source).listFiles().find(_.getName.endsWith(".parquet")).get
+            icebergTable
+              .newAppend()
+              .appendFile(
+                DataFiles
+                  .builder(icebergTable.spec())
+                  .withPath(file.getAbsolutePath)
+                  .withFileSizeInBytes(file.length())
+                  .withRecordCount(rows.size)

Review Comment:
   Fixed with `withRecordCount(rows.size.toLong)`. The Spark 3.5 / Scala 2.12 `-Pstrict-warnings` test-compile now passes locally.



##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -733,36 +740,42 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
       val left = icebergExprToProto(
         IcebergReflection.getMethod(exprClass, "left").invoke(icebergExpr),
         output,
-        pageIndexUnsupportedColumns)
+        pageIndexUnsupportedColumns,
+        allowPartial)
       val right = icebergExprToProto(
         IcebergReflection.getMethod(exprClass, "right").invoke(icebergExpr),
         output,
-        pageIndexUnsupportedColumns)
+        pageIndexUnsupportedColumns,
+        allowPartial)
       (left, right) match {
-        // Push the residual only if it converts whole. Dropping a conjunct is safe in positive
-        // position but strengthens the predicate under a NOT (De Morgan), which would wrongly
-        // prune, and tracking polarity across arbitrary nesting is error prone. So an
-        // unconvertible conjunct elides the whole residual; the post-scan CometFilter is exact.
         case (Some(l), Some(r)) => Some(logicalPredicate(isAnd = true, l, r))
+        // Dropping a positive conjunct weakens the predicate; the post-scan filter stays exact.
+        // Inside NOT, every descendant must convert exactly, including nested AND/OR nodes.
+        case (l, r) if allowPartial => l.orElse(r)

Review Comment:
   Fixed. Equality on a nullable column is no longer pushed when it appears anywhere under `NOT`, so `l IS NOT NULL AND NOT (id <=> 1)` keeps the row where `id` is NULL. The runtime regression test covers your expression and its nested variants. This fix now lives in #7156.



##########
docs/source/user-guide/latest/iceberg.md:
##########
@@ -113,8 +113,30 @@ The native Iceberg reader supports the following features:
 
 NULL checks on struct, array, and map columns still use native scans and return correct
 results, but are not pushed into iceberg-rust, which binds accessors only for primitive fields.
-These residuals provide no native row-group pruning, nor do conjunctions containing them;
-safe partial pruning is tracked in [#5883](https://github.com/apache/datafusion-comet/issues/5883).
+These null checks provide no native row-group pruning. In a positive conjunction, supported
+primitive predicates still prune row groups and pages, while the post-scan filter evaluates the
+complete condition. `OR` requires a safely pushable predicate from both branches, and expressions
+inside `NOT` must convert completely before they can be pushed. When only part of a condition can
+be pushed, predicates on `BIGINT` and `DOUBLE` columns in it are pushed only for `=` and null
+checks, because a data file can store a narrower type than its column without any record of it.
+
+Tables with a `schema.name-mapping.default` property push a conjunction only when every predicate
+in it can be pushed. The `add_files`, `migrate` and `snapshot` procedures set this property when
+they import data files, and an imported file can store a narrower type than its column.
+
+Spark treats `-0.0` as equal to `0.0` and sorts every NaN above all numbers, but iceberg-rust
+uses IEEE 754 total ordering. On `FLOAT` and `DOUBLE` columns, range comparisons and comparisons
+with `0.0`, `-0.0` or NaN are therefore evaluated after the native scan.
+
+Some other predicates are also evaluated only after the native scan:
+
+- Negated equality on a nullable column. Iceberg passes `<=>` as `=`, so for `NOT (a <=> 1)` the
+  native reader would drop NULL rows that Spark keeps, and `a <> 1` reaches Comet in the same
+  form.
+- Comparisons other than `=` with a literal on a column whose type was promoted, for example
+  from `INT` to `BIGINT`, because older data files keep the original type. If expiring
+  snapshots removed older schemas, this applies to every `BIGINT` and `DOUBLE` column. A
+  promotion made before Iceberg 0.12, which kept no schema history, cannot be detected.

Review Comment:
   Applied your version, thanks.



##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -679,17 +679,66 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
    *   - An exception means reflection over Iceberg's expression API did something unexpected, so
    *     no such decision was reached. It propagates instead of folding into `None`, which would
    *     make the two indistinguishable; see [[serializeResidual]].
+   *
+   * @param promotedColumns
+   *   columns whose older data files may hold a narrower type; see
+   *   [[IcebergReflection.promotedColumns]]
+   * @param partialPushdown
+   *   whether a residual that does not convert whole may push the conjuncts that do, leaving the
+   *   rest to the post-scan filter
    */
   def icebergExprToProto(
       icebergExpr: Any,
       output: Seq[Attribute],
-      pageIndexUnsupportedColumns: Set[String]): Option[OperatorOuterClass.IcebergPredicate] = {
+      pageIndexUnsupportedColumns: Set[String],
+      promotedColumns: Set[String] = Set.empty,
+      partialPushdown: Boolean = true): Option[OperatorOuterClass.IcebergPredicate] = {

Review Comment:
   Both are now required in `icebergExprToProto` and `serializeResidual`, and the tests pass them explicitly.



##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -679,17 +679,66 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
    *   - An exception means reflection over Iceberg's expression API did something unexpected, so
    *     no such decision was reached. It propagates instead of folding into `None`, which would
    *     make the two indistinguishable; see [[serializeResidual]].
+   *
+   * @param promotedColumns
+   *   columns whose older data files may hold a narrower type; see
+   *   [[IcebergReflection.promotedColumns]]
+   * @param partialPushdown
+   *   whether a residual that does not convert whole may push the conjuncts that do, leaving the
+   *   rest to the post-scan filter
    */
   def icebergExprToProto(
       icebergExpr: Any,
       output: Seq[Attribute],
-      pageIndexUnsupportedColumns: Set[String]): Option[OperatorOuterClass.IcebergPredicate] = {
+      pageIndexUnsupportedColumns: Set[String],
+      promotedColumns: Set[String] = Set.empty,
+      partialPushdown: Boolean = true): Option[OperatorOuterClass.IcebergPredicate] = {
+    val attributes = output.map(attr => attr.name -> attr).toMap
+    def convert(promoted: Set[String], partial: Boolean) =
+      icebergExprToProto(
+        icebergExpr,
+        ResidualScope(attributes, pageIndexUnsupportedColumns, promoted, partial),
+        underNot = false)
+    // Pushing part of a residual must not rely on the schema history, which misses some
+    // promotions, such as those made before Iceberg 0.12. So when the residual does not convert
+    // whole, every BIGINT and DOUBLE column counts as promoted. Whole residuals rely on the
+    // history, since limiting them too would stop range pruning on all such columns until
+    // apache/iceberg-rust#3122 is fixed.
+    convert(promotedColumns, partial = false).orElse {
+      if (partialPushdown) {
+        val widened = output.collect {
+          case attr if attr.dataType == LongType || attr.dataType == DoubleType => attr.name
+        }
+        convert(promotedColumns ++ widened, partial = true)
+      } else {
+        None
+      }
+    }
+  }
+
+  /** What [[icebergExprToProto]] consults at every node of a residual. */
+  private case class ResidualScope(
+      attributes: Map[String, Attribute],
+      pageIndexUnsupportedColumns: Set[String],
+      promotedColumns: Set[String],
+      partialPushdown: Boolean)

Review Comment:
   Removed it. The recursive walk now takes plain parameters instead, and its Scaladoc documents `attributes`, `promotedColumns`, `dropUnconvertedConjuncts` and `underNot`. `partialPushdown` is the table-level switch, and it sets `dropUnconvertedConjuncts` for a single pass over the residual.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4329119726


##########
spark/src/test/scala/org/apache/comet/CometIcebergNativeSuite.scala:
##########
@@ -4201,6 +4203,440 @@ class CometIcebergNativeSuite
     }
   }
 
+  test("partial residual pushdown preserves complex filters and reduces reader work") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.partial_residual_test"
+        // Keep split sizing fixed so repeated footer reads do not dominate the byte comparison.
+        spark.sql(s"""
+          CREATE TABLE $table (
+            id INT,
+            l ARRAY<INT>,
+            m MAP<STRING, INT>,
+            s STRUCT<v: INT>,
+            payload STRING
+          ) USING iceberg
+          TBLPROPERTIES (
+            'read.split.adaptive-size.enabled' = 'false',
+            'write.parquet.row-group-size-bytes' = '16384',
+            'write.parquet.compression-codec' = 'uncompressed'
+          )
+        """)
+        try {
+          spark
+            .range(10000)
+            .repartition(1)
+            .sortWithinPartitions("id")
+            .selectExpr(
+              "CASE WHEN id % 97 = 0 THEN NULL ELSE CAST(id AS INT) END AS id",
+              "CASE WHEN id % 2 = 0 THEN array(CAST(id AS INT)) ELSE NULL END AS l",
+              "CASE WHEN id % 3 = 0 THEN map('v', CAST(id AS INT)) ELSE NULL END AS m",
+              "CASE WHEN id % 5 = 0 THEN named_struct('v', CAST(id AS INT)) ELSE NULL END AS s",
+              "repeat(sha2(CAST(id AS STRING), 256), 2) AS payload")
+            .write
+            .format("iceberg")
+            .mode("append")
+            .saveAsTable(table)
+
+          // One unpartitioned file containing several row groups: the byte savings must come
+          // from the reader, rather than Iceberg's manifest/file pruning or partition selection.
+          val files = spark.sql(s"SELECT file_path FROM $table.files").collect()
+          assert(files.length == 1, s"Expected one data file, got ${files.length}")
+          val reader = org.apache.parquet.hadoop.ParquetFileReader.open(
+            org.apache.parquet.hadoop.util.HadoopInputFile.fromPath(
+              new org.apache.hadoop.fs.Path(files.head.getString(0)),
+              spark.sessionState.newHadoopConf()))
+          try {
+            assert(reader.getRowGroups.size > 3, "Fixture needs multiple row groups for pruning")
+          } finally {
+            reader.close()
+          }
+
+          def checkAndGetScan(predicate: String): CometIcebergNativeScanExec = {
+            val query = s"SELECT * FROM $table WHERE $predicate"
+            val (_, plan) = checkSparkAnswer(query)
+            val scans = collectIcebergNativeScans(plan)
+            assert(scans.length == 1, s"Expected one native scan for $query:\n$plan")
+            scans.head
+          }
+
+          val fullScan = checkAndGetScan("l IS NOT NULL")
+          val fullBytes = fullScan.metrics("bytes_scanned").value
+          assert(fullBytes > 0, "Full read must report bytes")
+          assert(fullScan.metrics("output_rows").value == 10000L)
+
+          val partialScan = checkAndGetScan("l IS NOT NULL AND id BETWEEN 1000 AND 1099")
+          val partialBytes = partialScan.metrics("bytes_scanned").value
+          assert(fullScan.metrics("num_splits").value > 0L)
+          assert(partialScan.metrics("num_splits").value == fullScan.metrics("num_splits").value)
+          assert(
+            partialScan.metrics("output_rows").value < 1000L,
+            "The native reader must apply the primitive residual before the complex filter")
+          assert(
+            partialBytes * 2 < fullBytes,
+            s"Partial residual must prune reads: partial=$partialBytes, full=$fullBytes")
+
+          Seq(
+            "m IS NOT NULL AND id BETWEEN 1000 AND 1099",
+            "s IS NULL AND id BETWEEN 1000 AND 1099",
+            "id >= 1000 AND (l IS NOT NULL OR m IS NULL)",
+            "(id < 100 AND l IS NOT NULL) OR (id >= 9900 AND m IS NOT NULL)",
+            "id < 100 OR l IS NOT NULL",
+            "NOT (id < 2000 AND l IS NOT NULL)",
+            "NOT ((id < 100 AND l IS NOT NULL) OR (id >= 9900 AND m IS NOT NULL))")
+            .foreach { predicate =>
+              val _ = checkAndGetScan(predicate)
+            }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("floating-point residuals preserve signed zeros in native scans") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.floating_residual_test"
+        spark.sql(s"CREATE TABLE $table (id INT, f FLOAT, d DOUBLE, l ARRAY<INT>) USING iceberg")
+        try {
+          withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+            // One file containing both zeros keeps file pruning from deciding the comparison.
+            // Distinct ids make a missing signed-zero row observable without comparing floats.
+            spark
+              .sql("""
+                SELECT id, CAST(v AS FLOAT) AS f, CAST(v AS DOUBLE) AS d, l
+                FROM VALUES
+                  (1, '-0.0', array(1)),
+                  (2, '0.0', array(1)),
+                  (3, '1.0', CAST(NULL AS ARRAY<INT>)),
+                  (4, '-1.0', array(1)),
+                  (5, NULL, array(1)),
+                  (6, 'NaN', array(1))
+                AS input(id, v, l)
+              """)
+              .coalesce(1)
+              .write
+              .format("iceberg")
+              .mode("append")
+              .saveAsTable(table)
+            assert(spark.sql(s"SELECT file_path FROM $table.files").collect().length == 1)
+            val rows = spark.sql(s"SELECT id, f, d FROM $table").collect().sortBy(_.getInt(0))
+            assert(java.lang.Float.floatToRawIntBits(rows(0).getFloat(1)) == Int.MinValue)
+            assert(java.lang.Double.doubleToRawLongBits(rows(0).getDouble(2)) == Long.MinValue)
+            assert(java.lang.Float.floatToRawIntBits(rows(1).getFloat(1)) == 0)
+            assert(java.lang.Double.doubleToRawLongBits(rows(1).getDouble(2)) == 0L)
+          }
+
+          for ((column, dataType) <- Seq("f" -> "FLOAT", "d" -> "DOUBLE")) {
+            val zero = s"CAST(0 AS $dataType)"
+            val negativeZero = s"CAST('-0.0' AS $dataType)"
+            val one = s"CAST(1 AS $dataType)"
+            val minusOne = s"CAST(-1 AS $dataType)"
+            val predicates = Seq(
+              s"$column = $zero",
+              s"$column = $negativeZero",
+              s"$column >= $zero",
+              s"$column <= $negativeZero",
+              s"$column IN ($zero, $one)",
+              s"NOT ($column < $zero)",
+              // Nonzero literals push equality and IN; range comparisons stay out.
+              s"$column = $one",
+              s"$column IN ($one, $minusOne)",
+              s"NOT ($column IN ($one, $minusOne) AND id > 1)",
+              s"$column < $one",
+              s"$column > $minusOne",
+              s"NOT ($column = $one)",
+              s"$column = $zero OR id = 3",
+              s"NOT ($column = $zero AND id > 1)",
+              s"$column IS NULL",
+              s"$column IS NOT NULL")
+            for (predicate <- predicates;
+              prefix <- Seq("", "l IS NOT NULL AND ")) {
+              checkIcebergNativeScan(s"SELECT id FROM $table WHERE $prefix($predicate)")
+            }
+          }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("negated null-safe equality keeps NULL rows in native scans") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.null_safe_residual_test"
+        spark.sql(s"CREATE TABLE $table (id INT, b BOOLEAN, l ARRAY<INT>) USING iceberg")
+        try {
+          withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+            // One file keeps file pruning from deciding the comparison.
+            spark
+              .sql("""
+                SELECT * FROM VALUES
+                  (NULL, NULL, array(1)), (1, true, array(1)), (2, false, array(1))
+                AS t(id, b, l)
+              """)
+              .coalesce(1)
+              .write
+              .format("iceberg")
+              .mode("append")
+              .saveAsTable(table)
+            assert(spark.sql(s"SELECT file_path FROM $table.files").collect().length == 1)
+          }
+          // Iceberg converts `id <=> 1` to an equality, which is false for a NULL id in Spark but
+          // NULL in the native reader, so only its negation can drop the NULL row. Spark also
+          // writes that negation as IS DISTINCT FROM and, for booleans, IS NOT TRUE.
+          val predicates = Seq(
+            "NOT (id <=> 1)",
+            "NOT (id <=> 1 AND id < 5)",
+            "NOT (id <=> 1) OR id = 2",
+            "id IS DISTINCT FROM 1",
+            "b IS NOT TRUE",
+            "NOT b",
+            "NOT (id = 1)",
+            "id != 1")
+          for (predicate <- predicates;
+            prefix <- Seq("", "l IS NOT NULL AND ")) {
+            checkIcebergNativeScan(s"SELECT id FROM $table WHERE $prefix($predicate)")
+          }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("literal residuals on promoted columns keep rows from older files") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.promoted_residual_test"
+        spark.sql(s"CREATE TABLE $table (id INT, f FLOAT, l ARRAY<INT>) USING iceberg")
+        try {
+          withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+            // One file, so that its FLOAT bounds keep it for f = 0.1D below.
+            spark.sql(s"""INSERT INTO $table SELECT /*+ COALESCE(1) */ * FROM VALUES
+              (1, 0.5, array(1)), (2, 2.5, array(1)), (3, 0.1, array(1)), (6, 0.05, array(1))
+              AS v(id, f, l)""")
+            spark.sql(s"ALTER TABLE $table ALTER COLUMN id TYPE BIGINT")
+            spark.sql(s"ALTER TABLE $table ALTER COLUMN f TYPE DOUBLE")
+            spark.sql(s"INSERT INTO $table VALUES (4, 0.5D, array(1)), (5, 4.5D, array(1))")
+          }
+          // The first file still stores INT and FLOAT. iceberg-rust skips its pages for range and
+          // IN predicates on the promoted types, and casts 3000000000 to a NULL INT.
+          val predicates = Seq(
+            "id > 0",
+            "id < 3",
+            "id IN (1, 2)",
+            "id < 3000000000",
+            "id = 2",
+            "id = 2 OR id = 3000000000",
+            "f IN (0.5D, 4.5D)",
+            "f = 0.5D",
+            "f = 0.1D")
+          def checkPredicates(): Unit =
+            for (predicate <- predicates;
+              prefix <- Seq("", "l IS NOT NULL AND ")) {
+              checkIcebergNativeScan(s"SELECT id FROM $table WHERE $prefix($predicate)")
+            }
+          checkPredicates()
+
+          // The native reader narrows 0.1D to the FLOAT 0.1, which Spark does not consider equal
+          // to it. The first file's bounds, 0.05 to 2.5, keep it in the scan for that.
+          val narrowed = s"SELECT id FROM $table WHERE f = 0.1D"
+          val df = spark.sql(narrowed)
+          df.collect()
+          val scanned =
+            collectIcebergNativeScans(df.queryExecution.executedPlan).head
+              .metrics("resultDataFiles")
+              .value
+          assert(scanned == 1, s"Expected the first file to be scanned, scanned $scanned files")
+
+          // Expiring the first snapshot with cleanExpiredMetadata (Iceberg 1.8+) drops the original
+          // schema, while the file that snapshot wrote stays in the table.
+          if (icebergVersionAtLeast(1, 8)) {
+            val icebergTable =
+              loadIcebergTable(spark, "test_cat", "db", "promoted_residual_test")
+                .asInstanceOf[org.apache.iceberg.Table]
+            val expire = icebergTable
+              .expireSnapshots()
+              .expireOlderThan(System.currentTimeMillis())
+              .retainLast(1)
+            classOf[org.apache.iceberg.ExpireSnapshots]
+              .getMethod("cleanExpiredMetadata", classOf[Boolean])
+              .invoke(expire, java.lang.Boolean.TRUE)
+            expire.commit()
+            spark.sql(s"REFRESH TABLE $table")
+            val schemas = loadIcebergTable(spark, "test_cat", "db", "promoted_residual_test")
+              .asInstanceOf[org.apache.iceberg.Table]
+              .schemas()
+            assert(schemas.size == 1 && !schemas.containsKey(0))
+            assert(spark.sql(s"SELECT * FROM $table").count() == 6)
+            checkPredicates()
+          }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("residuals on tables with imported files are pushed only whole") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.imported_residual_test"
+        spark.sql(s"CREATE TABLE $table (id BIGINT, t INT, f FLOAT) USING iceberg")
+        try {
+          withTempDir { dir =>
+            // The file stores id as INT and t as TINYINT. Importing it the way add_files does
+            // adds a name mapping but records no schema change.
+            val source = new File(dir, "source").getAbsolutePath
+            withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+              spark
+                .sql("SELECT CAST(id AS INT) AS id, CAST(id AS TINYINT) AS t, " +
+                  "CAST(id AS FLOAT) AS f FROM range(1, 4)")
+                .coalesce(1)
+                .write
+                .parquet(source)
+            }
+            val icebergTable = loadIcebergTable(spark, "test_cat", "db", "imported_residual_test")
+              .asInstanceOf[org.apache.iceberg.Table]
+            icebergTable
+              .updateProperties()
+              .set(
+                TableProperties.DEFAULT_NAME_MAPPING,
+                NameMappingParser.toJson(MappingUtil.create(icebergTable.schema())))
+              .commit()
+            val file = new File(source).listFiles().find(_.getName.endsWith(".parquet")).get
+            icebergTable
+              .newAppend()
+              .appendFile(
+                DataFiles
+                  .builder(icebergTable.spec())
+                  .withPath(file.getAbsolutePath)
+                  .withFileSizeInBytes(file.length())
+                  .withRecordCount(3)
+                  .withFormat(FileFormat.PARQUET)
+                  .build())
+              .commit()
+            withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+              spark.sql(s"INSERT INTO $table VALUES (4, 4, 4.0)")
+            }
+            spark.sql(s"REFRESH TABLE $table")
+
+            // The float range is never pushed, so each residual converts only in part. Pushing
+            // that part would skip the imported file's pages, or narrow 200 to a NULL TINYINT.
+            for (predicate <- Seq(
+                "id > 0",
+                "id < 3000000000",
+                "id IN (1, 2)",
+                "t < 200",
+                "t IN (1, 200)")) {
+              checkIcebergNativeScan(
+                s"SELECT id FROM $table WHERE f > CAST(0.5 AS FLOAT) AND $predicate")
+            }
+            checkIcebergNativeScan(s"SELECT id FROM $table WHERE id = 2 AND t = 2")
+          }
+        } finally {
+          spark.sql(s"DROP TABLE $table")
+        }
+      }
+    }
+  }
+
+  test("partial residuals push only equality on BIGINT and DOUBLE columns") {
+    assume(icebergAvailable, "Iceberg not available in classpath")
+
+    withHadoopCatalog("test_cat") {
+      withSQLConf(
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+        val table = "test_cat.db.unrecorded_promotion_test"
+        spark.sql(s"CREATE TABLE $table (id BIGINT, f FLOAT, d DOUBLE) USING iceberg")
+        try {
+          withTempDir { dir =>
+            // The file stores id as INT and d as FLOAT under the table's field ids, and neither
+            // a schema nor a name mapping records it, as after a promotion before Iceberg 0.12.
+            val source = new File(dir, "source").getAbsolutePath
+            def fieldId(id: Long) = new MetadataBuilder().putLong("parquet.field.id", id).build()
+            val schema = new StructType()
+              .add("id", IntegerType, nullable = true, fieldId(1))
+              .add("f", FloatType, nullable = true, fieldId(2))
+              .add("d", FloatType, nullable = true, fieldId(3))
+            val rows = Seq(Row(1, 1.0f, 0.5f), Row(2, 2.0f, 2.5f), Row(3, 3.0f, 4.5f))
+            withSQLConf(
+              CometConf.COMET_ENABLED.key -> "false",
+              "spark.sql.parquet.fieldId.write.enabled" -> "true") {
+              spark
+                .createDataFrame(spark.sparkContext.parallelize(rows, 1), schema)
+                .write
+                .parquet(source)
+            }
+            val icebergTable =
+              loadIcebergTable(spark, "test_cat", "db", "unrecorded_promotion_test")
+                .asInstanceOf[org.apache.iceberg.Table]
+            val file = new File(source).listFiles().find(_.getName.endsWith(".parquet")).get
+            icebergTable
+              .newAppend()
+              .appendFile(
+                DataFiles
+                  .builder(icebergTable.spec())
+                  .withPath(file.getAbsolutePath)
+                  .withFileSizeInBytes(file.length())
+                  .withRecordCount(rows.size)

Review Comment:
   [P2] Convert `rows.size` to `Long` explicitly before passing it to `withRecordCount`. The required Spark 3.5/Scala 2.12 strict build enables numeric-widening warnings as errors, so this new fixture fails test compilation with `implicit numeric widening` instead of completing successfully. This blocks the required CI check. Using `withRecordCount(rows.size.toLong)` preserves the fixture's behavior and removes the compilation failure.
   
   Evidence: Exact-head CI job https://github.com/apache/datafusion-comet/actions/runs/39475272780/job/118816221478 ran `./mvnw -B test-compile -Pspark-3.5,delta -Pstrict-warnings -DskipTests` and reported `CometIcebergNativeSuite.scala:4612: implicit numeric widening`, followed by failure of `scala-test-compile-first`. The changed line passes the Int-valued `rows.size` to the Long-valued record-count API.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "rich7420 (via GitHub)" <gi...@apache.org>.
rich7420 commented on PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#issuecomment-6420409016

   @andygrove Reruns confirm slowdown; added opt-out. Details in description.
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4315888505


##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -733,36 +740,42 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
       val left = icebergExprToProto(
         IcebergReflection.getMethod(exprClass, "left").invoke(icebergExpr),
         output,
-        pageIndexUnsupportedColumns)
+        pageIndexUnsupportedColumns,
+        allowPartial)
       val right = icebergExprToProto(
         IcebergReflection.getMethod(exprClass, "right").invoke(icebergExpr),
         output,
-        pageIndexUnsupportedColumns)
+        pageIndexUnsupportedColumns,
+        allowPartial)
       (left, right) match {
-        // Push the residual only if it converts whole. Dropping a conjunct is safe in positive
-        // position but strengthens the predicate under a NOT (De Morgan), which would wrongly
-        // prune, and tracking polarity across arbitrary nesting is error prone. So an
-        // unconvertible conjunct elides the whole residual; the post-scan CometFilter is exact.
         case (Some(l), Some(r)) => Some(logicalPredicate(isAnd = true, l, r))
+        // Dropping a positive conjunct weakens the predicate; the post-scan filter stays exact.
+        // Inside NOT, every descendant must convert exactly, including nested AND/OR nodes.
+        case (l, r) if allowPartial => l.orElse(r)

Review Comment:
   [P1] [P1] Preserve NULL matches in retained negated null-safe comparisons. With native Iceberg scanning enabled, create an unpartitioned `(id INT, l ARRAY<INT>)` table containing `(NULL, array(1))`, `(1, array(1))`, and `(2, array(1))`, then query `WHERE l IS NOT NULL AND NOT (id <=> 1)`. Spark returns the NULL and 2 rows. The base omits this mixed residual, but this branch now retains `NOT(Eq(id, 1))`. Native `rewrite_not()` turns it into `NotEq`, whose Arrow comparison produces NULL for a null input and filters that row out. Only ID 2 survives, and the post-scan filter cannot recover the missing row. Please decline these null-sensitive negative residuals, including those produced by `NOT`, or preserve their null-inclusive semantics in native filtering, with a regression for this mixed predicate.
   
   Evidence: Fresh reproduction in `/tmp/comet6847-review-20261019-phKbuI`: `nullsafe-spark.log` records Spark 4.1.3/Iceberg 1.11.0 returning `[NULL, 2]`, the actual residual `(not_null(l) and not(id == 1))`, base serialization `None`, and exact-head serialization `NOT(Eq(id, 1))`. `nullsafe-native.log` records the same Parquet file returning `[NULL, 1, 2]` without pushdown and `[2]` with the retained predicate, leaving two versus one rows after the original condition. The reader uses iceberg-rust `af1da4c5bc86178c38c1c6db0578bdd9fb7021e3`, Arrow 59.3.0, `rewrite_not().bind(...)`, and `with_row_selection_enabled(true)`, matching the checkout. Its `predicate_visitor.rs::not_eq` calls Arrow `neq`, which returns null for null input.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "rich7420 (via GitHub)" <gi...@apache.org>.
rich7420 commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4349337145


##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -1009,6 +1082,18 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
     // schema so a filter column projected out of the scan output is still recognized.
     val pageIndexUnsupportedColumns =
       IcebergReflection.pageIndexUnsupportedColumns(metadata.tableSchema)
+    // Columns whose type changed over the table's history; residual predicates comparing them
+    // with a literal are dropped, except equality. The scan schema also covers a column that
+    // VERSION AS OF reads after it was dropped from the table.
+    val promotedColumns = Seq(metadata.tableSchema, metadata.scanSchema)
+      .flatMap(IcebergReflection.promotedColumns(metadata.table, _))
+      .toSet
+    // add_files, migrate and snapshot set a name mapping and import files without checking their
+    // types against the schema. Such files commonly hold narrower physical types, such as Hive
+    // TINYINT and SMALLINT stored as INT32 with INT_8 or INT_16 annotations, which iceberg-rust
+    // compares incorrectly. So partial pushdown is not extended to these tables, and they push a
+    // residual only when it converts whole.
+    val partialPushdown = metadata.nameMapping.isEmpty

Review Comment:
   Thanks, confirmed. Before this PR the array null check kept the whole residual out of the scan, so this was a regression.
   
   Fixed in b5fc1be16. Residuals that convert in full are unchanged from #7156. Otherwise, on tables without a name mapping, a partial pass treats every `BIGINT` and `DOUBLE` column as promoted and keeps only their null checks and `=` outside `NOT`. `DECIMAL` predicates are still not pushed.
   
   The regression test `partial residuals do not compare columns promoted before Iceberg 0.12` reads an `INT`/`FLOAT` file in a `BIGINT`/`DOUBLE` table with one schema and no name mapping. Without the fix, `l IS NOT NULL AND id > 0` returns 0 rows instead of 2.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: preserve supported Iceberg residual conjuncts [datafusion-comet]

Posted by "rich7420 (via GitHub)" <gi...@apache.org>.
rich7420 commented on code in PR #6847:
URL: https://github.com/apache/datafusion-comet/pull/6847#discussion_r4301795451


##########
spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala:
##########
@@ -733,36 +740,42 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
       val left = icebergExprToProto(
         IcebergReflection.getMethod(exprClass, "left").invoke(icebergExpr),
         output,
-        pageIndexUnsupportedColumns)
+        pageIndexUnsupportedColumns,
+        allowPartial)
       val right = icebergExprToProto(
         IcebergReflection.getMethod(exprClass, "right").invoke(icebergExpr),
         output,
-        pageIndexUnsupportedColumns)
+        pageIndexUnsupportedColumns,
+        allowPartial)
       (left, right) match {
-        // Push the residual only if it converts whole. Dropping a conjunct is safe in positive
-        // position but strengthens the predicate under a NOT (De Morgan), which would wrongly
-        // prune, and tracking polarity across arbitrary nesting is error prone. So an
-        // unconvertible conjunct elides the whole residual; the post-scan CometFilter is exact.
         case (Some(l), Some(r)) => Some(logicalPredicate(isAnd = true, l, r))
+        // Dropping a positive conjunct weakens the predicate; the post-scan filter stays exact.
+        // Inside NOT, every descendant must convert exactly, including nested AND/OR nodes.
+        case (l, r) if allowPartial => l.orElse(r)

Review Comment:
   Addressed at `aaf808d29`: FLOAT/DOUBLE comparisons and IN predicates are no longer pushed, including standalone predicates and leaves under AND/OR/NOT. Floating-point null checks and independent safe conjuncts remain eligible.
   
   Added the mixed signed-zero regression; both the serializer and runtime controls fail before the fix. At this head, 29 serializer tests, six targeted native tests (including 44 floating-point queries) and [upstream CI](https://github.com/apache/datafusion-comet/actions/runs/38160026569) passed.
   
   Could you apply `run-iceberg-tests` for broader coverage? I tried the fork CI path, but GitHub rejects dispatch with “Actions has been disabled for this repository.”



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org