This is an automated email from the ASF dual-hosted git repository.

dongjoon-hyun pushed a commit to branch branch-4.0
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.0 by this push:
     new 01da42fa4cfe [SPARK-61326][SQL] Fix wrong results by stale 
partitioning and ordering when a cached Dataset is joined with its source
01da42fa4cfe is described below

commit 01da42fa4cfe7f89a442001771b79bf32fbab9ab
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Tue Nov 10 07:34:13 2026 -0800

    [SPARK-61326][SQL] Fix wrong results by stale partitioning and ordering 
when a cached Dataset is joined with its source
    
    This PR aims to fix a correctness issue where `InMemoryTableScanExec` 
reports the partitioning and the ordering over attributes that its 
`InMemoryRelation` does not output.
    
    `InMemoryTableScanExec` maps the partitioning and the ordering of the 
cached plan onto `relation.output` by position, but it keeps every attribute 
outside `cachedPlan.output` as it is. Some cached plans report a partitioning 
or an ordering over such attributes.
    - `SerializeFromObjectExec` of a typed `map` reports the 
`RangePartitioning(id)` of its input `Range`.
    - A scan of another cache pruned to some columns reports the partitioning 
and the ordering over the pruned columns, and so does a cache of that scan.
    
    After the remap, this PR
    - drops the partitionings that still refer to other attributes, leaf by 
leaf for a `PartitioningCollection`, and reports `UnknownPartitioning` when 
nothing is left.
    - keeps only the leading sort orders over `relation.output` like 
`AliasAwareQueryOutputOrdering`.
    
    Both check `relation.output` rather than the pruned `attributes` of the 
scan, so the claims over the pruned columns of its own relation are unchanged.
    
    This is the same class of bug as SPARK-61256 (#60246), which fixes 
`LogicalRDD.fromDataset` for checkpoints.
    
    When such a cache is joined with its source, `DeduplicateRelations` keeps 
the attributes of the left side, so the stale attributes in the partitioning or 
the ordering of the scan match them. Spark then skips a shuffle or a sort that 
the query needs and returns wrong results, with AQE on and off.
    
    ```scala
    val src = spark.range(0, 16, 1, 4)
    val c = src.as[Long].map(x => x).toDF().cache()
    val rows = broadcast(src).join(c, src("id") % 2 === c("value") % 2)
      .groupBy(src("id")).count().collect()
    // Issue 1: It should return 16 rows with count 8, but returns 64 rows with 
count 2.
    ```
    
    ```scala
    import org.apache.spark.sql.expressions.Window
    val src = spark.range(0, 16, 1, 4)
    val c1 = src.select($"id", ($"id" % 2).as("p"))
      .repartition(4, $"p").sortWithinPartitions("p", "id").cache()
    val c2 = c1.select($"p").cache()
    val w = Window.partitionBy(c2("p")).orderBy(src("id"))
    val df = broadcast(src).join(c2, src("id") % 2 === 
c2("p")).select(src("id"), rank().over(w))
    df.collect().filter(_.getLong(0) == 14).map(_.getInt(1)).distinct.sorted
    // Issue 2: It should return only 57 (= 7 * 8 + 1), but returns 1, 9, 17, 
25, 33, 41, 49, 57.
    ```
    
    Yes, this fixes wrong results. Such a query now has the shuffle or the sort 
that it needs. A cache partitioned or sorted by its own columns keeps avoiding 
them as before.
    
    Pass the CIs with the newly added test case.
    
    I also checked that both examples above return wrong results on Apache 
Spark 3.5.9, 4.0.5, 4.1.4, 4.2.1 and 4.3.0 with AQE on and off.
    
    Generated-by: Claude Opus 5.5
    
    Closes #60270 from dongjoon-hyun/SPARK-61326.
    
    Authored-by: Dongjoon Hyun <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    (cherry picked from commit f35395086c968d25257b43e4410f378369b6c892)
    Signed-off-by: Dongjoon Hyun <[email protected]>
    (cherry picked from commit e001752714b57299234f59894e3b246d58d5f9c1)
    Signed-off-by: Dongjoon Hyun <[email protected]>
    (cherry picked from commit 862e02abfbf82aa83a11314f6aa27bfab269e1fe)
    Signed-off-by: Dongjoon Hyun <[email protected]>
---
 .../execution/columnar/InMemoryTableScanExec.scala | 39 ++++++++++++++++++----
 .../org/apache/spark/sql/DatasetCacheSuite.scala   | 37 ++++++++++++++++++++
 2 files changed, 70 insertions(+), 6 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/InMemoryTableScanExec.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/InMemoryTableScanExec.scala
index cbd60804b27e..4211d0f7a2a7 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/InMemoryTableScanExec.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/InMemoryTableScanExec.scala
@@ -22,7 +22,7 @@ import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions._
 import org.apache.spark.sql.catalyst.plans.QueryPlan
 import org.apache.spark.sql.catalyst.plans.logical.Statistics
-import org.apache.spark.sql.catalyst.plans.physical.Partitioning
+import org.apache.spark.sql.catalyst.plans.physical.{Partitioning, 
PartitioningCollection, UnknownPartitioning}
 import org.apache.spark.sql.columnar.CachedBatch
 import org.apache.spark.sql.execution.{LeafExecNode, SparkPlan, 
WholeStageCodegenExec}
 import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanExec
@@ -116,18 +116,45 @@ case class InMemoryTableScanExec(
   }
 
   // The cached version does not change the outputPartitioning of the original 
SparkPlan.
-  // But the cached version could alias output, so we need to replace output.
+  // But the cached version could alias output, so we need to replace output. 
The original
+  // SparkPlan can also report a partitioning over attributes it does not 
output, e.g.
+  // `SerializeFromObjectExec` reports the partitioning of its input, so drop 
such partitionings,
+  // leaf by leaf for a `PartitioningCollection`.
   override def outputPartitioning: Partitioning = {
+    // `PartitioningCollection.flatten` is not on this branch, so the 
recursion stays local.
+    def flatten(p: Partitioning): Seq[Partitioning] = p match {
+      case PartitioningCollection(partitionings) => 
partitionings.flatMap(flatten)
+      case other => other +: Nil
+    }
     cachedPlan.outputPartitioning match {
-      case e: Expression => updateAttribute(e).asInstanceOf[Partitioning]
+      case e: Expression =>
+        val partitioning = updateAttribute(e).asInstanceOf[Partitioning]
+        flatten(partitioning).filter {
+          case p: Expression => p.references.subsetOf(relation.outputSet)
+          case _ => true
+        } match {
+          case Seq() => UnknownPartitioning(partitioning.numPartitions)
+          case Seq(p) => p
+          case ps => PartitioningCollection(ps)
+        }
       case other => other
     }
   }
 
   // The cached version does not change the outputOrdering of the original 
SparkPlan.
-  // But the cached version could alias output, so we need to replace output.
-  override def outputOrdering: Seq[SortOrder] =
-    cachedPlan.outputOrdering.map(updateAttribute(_).asInstanceOf[SortOrder])
+  // But the cached version could alias output, so we need to replace output. 
Like the
+  // partitioning, keep only the leading sort orders over the output of the 
relation.
+  override def outputOrdering: Seq[SortOrder] = {
+    cachedPlan.outputOrdering.iterator.map { order =>
+      val validChildren = updateAttribute(order).children
+        .filter(_.references.subsetOf(relation.outputSet))
+      if (validChildren.nonEmpty) {
+        Some(order.copy(child = validChildren.head, sameOrderExpressions = 
validChildren.tail))
+      } else {
+        None
+      }
+    }.takeWhile(_.isDefined).flatten.toSeq
+  }
 
   lazy val enableAccumulatorsForTest: Boolean = 
conf.inMemoryTableScanStatisticsEnabled
 
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/DatasetCacheSuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/DatasetCacheSuite.scala
index 9d8aaf8d90e3..21604ff0a7f5 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/DatasetCacheSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/DatasetCacheSuite.scala
@@ -20,6 +20,8 @@ package org.apache.spark.sql
 import org.scalatest.concurrent.TimeLimits
 import org.scalatest.time.SpanSugar._
 
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.plans.physical.ClusteredDistribution
 import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
 import org.apache.spark.sql.execution.columnar.{InMemoryRelation, 
InMemoryTableScanExec}
 import org.apache.spark.sql.functions._
@@ -328,4 +330,39 @@ class DatasetCacheSuite extends QueryTest
     val df3 = spark.range(5).select(struct($"id".as("name", metadata2)))
     
assert(!df3.queryExecution.executedPlan.exists(_.isInstanceOf[InMemoryTableScanExec]))
   }
+
+  test("SPARK-61326: cache should not report the partitioning and the ordering 
over the columns " +
+      "it does not output") {
+    val src = spark.range(0, 16, 1, 4)
+    // A typed `map` reports the partitioning of its input, which is not in 
its output.
+    val c1 = src.as[Long].map(x => x).toDF().cache()
+    val agg = broadcast(src).join(c1, src("id") % 2 === c1("value") % 2)
+      .groupBy(src("id")).count()
+    checkAnswer(agg, (0L until 16L).map(Row(_, 8L)))
+
+    withSQLConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
+      // A scan of a cached join pruned to `b` reports the partitioning and 
the ordering over `a`
+      // as well, so the cache of that scan does.
+      val a = src.select($"id".as("a"))
+      val b = src.select($"id".as("b"))
+      val c2 = a.join(b, $"a" === $"b").cache().select($"b").cache()
+      c2.collect()
+      val scan = collectFirst(c2.queryExecution.executedPlan) {
+        case s: InMemoryTableScanExec => s
+      }.get
+      
assert(scan.outputPartitioning.satisfies(ClusteredDistribution(scan.output)))
+      assert(scan.outputPartitioning.asInstanceOf[Expression].references === 
scan.outputSet)
+      assert(scan.outputOrdering.map(_.references) === Seq(scan.outputSet))
+    }
+
+    // A scan of a cache sorted by `a` and `b` pruned to `b` reports the 
ordering by `a` and `b`,
+    // which the cache of that scan cannot report even partially.
+    val c3 = src.select($"id".as("a"), ($"id" % 2).as("b"))
+      .sortWithinPartitions("a", "b").cache().select($"b").cache()
+    c3.collect()
+    val ordering = collectFirst(c3.queryExecution.executedPlan) {
+      case s: InMemoryTableScanExec => s.outputOrdering
+    }.get
+    assert(ordering.isEmpty)
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to