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

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


The following commit(s) were added to refs/heads/master by this push:
     new cb6cf5bffade [SPARK-61256][SQL] Fix wrong results by stale 
partitioning and ordering when a checkpointed Dataset is joined with its source
cb6cf5bffade is described below

commit cb6cf5bffade58a2933db9bec4431017b08a1ea6
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Mon Nov 9 19:39:10 2026 -0800

    [SPARK-61256][SQL] Fix wrong results by stale partitioning and ordering 
when a checkpointed Dataset is joined with its source
    
    ### What changes were proposed in this pull request?
    
    This PR fixes a correctness issue: a checkpointed Dataset can report a 
partitioning and an ordering over the columns of its source Dataset, so a query 
that joins it with the source can return wrong results.
    
    `LogicalRDD.fromDataset`, which `Dataset.checkpoint`, 
`Dataset.localCheckpoint`, `ForeachBatchSink` and `UnionLoopExec` of recursive 
CTEs use, takes `output` from the analyzed plan, but copies 
`outputPartitioning` and `outputOrdering` from the executed plan without 
mapping them onto that output. They can refer to other attributes:
    
    1. `RemoveRedundantAliases` removes a same-name root alias, e.g., 
`select($"id".as("id"))` or `toDF("id")` over a column `id`. The executed plan 
then outputs the source column, while `output` is the alias.
    2. Some physical operators report a partitioning or an ordering over the 
columns that they do not output, e.g., `SerializeFromObjectExec` of a typed 
`map`, `GenerateExec` and `MapInBatchExec` report the partitioning of their 
child, and a column-pruned `InMemoryTableScanExec` reports the ordering of the 
cached plan.
    
    This PR maps the partitioning and the ordering of the executed plan onto 
`output` by position with an `AttributeMap`, like `rewriteStatsAndConstraints` 
maps the optimized plan for the stats and the constraints. If the partitioning 
still refers to other attributes, this PR replaces it with 
`UnknownPartitioning`, like `PartitioningPreservingUnaryExecNode` drops such a 
partitioning. For the ordering, this PR keeps only the leading sort orders over 
`output`, like `AliasAwareQueryOutputOrdering`.
    
    ### Why are the changes needed?
    
    The stale attributes are the columns of the source Dataset. When the 
checkpoint is joined with its source, e.g., as the streamed side of a broadcast 
hash join, the join passes the partitioning and the ordering of the checkpoint 
up. Then, an aggregate or a window over the source column skips its shuffle or 
its sort.
    
    ```scala
    // Issue 1: It should return 16 rows with count 8, but returns 128 rows 
with count 1.
    val src = spark.range(0, 16, 1, 4)
    val cp1 = src.select($"id".as("id")).localCheckpoint()
    broadcast(src).join(cp1, src("id") % 2 === cp1("id") % 
2).groupBy(src("id")).count().collect()
    
    // Issue 2: It should return 16 rows with count 8, but returns 64 rows with 
count 2.
    val cp2 = src.as[Long].map(x => x).toDF().localCheckpoint()
    broadcast(src).join(cp2, src("id") % 2 === cp2("value") % 
2).groupBy(src("id")).count().collect()
    
    // Issue 3: It should return count 8 for all 128 rows, but returns count 1 
for all of them.
    import org.apache.spark.sql.expressions.Window
    val src3 = spark.range(0, 16, 1, 1)
    val cp3 = src3.select($"id".as("id")).localCheckpoint()
    broadcast(src3).join(cp3, src3("id") % 2 === cp3("id") % 2)
      .select(src3("id"), 
count(lit(1)).over(Window.partitionBy(src3("id")))).collect()
    
    // Issue 4: It should return the rows sorted by `id`, but returns unsorted 
rows.
    val c4 = src3.select($"id", ($"id" % 2).as("p")).cache()
    val cp4 = c4.select($"p").localCheckpoint()
    broadcast(src3).join(cp4, src3("id") % 2 === 
cp4("p")).orderBy(src3("id")).select(src3("id")).collect()
    ```
    
    These examples use the default configurations, because 
`AdaptiveSparkPlanExec` does not wrap a `range` without an exchange. When the 
source has an exchange, e.g., `repartition`, the same issue happens if AQE is 
disabled when checkpointing, because `AdaptiveSparkPlanExec` reports 
`UnknownPartitioning`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, this fixes wrong results. This issue exists since Apache Spark 2.1.0 
([v2.1.0](https://github.com/apache/spark/releases/tag/v2.1.0), 2016-12-15, 
SPARK-17972), which made a checkpoint keep the partitioning and the ordering of 
the executed plan.
    
    ### How was this patch tested?
    
    Pass the CIs with the newly added test case, which fails without this fix.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #60246 from dongjoon-hyun/SPARK-61256.
    
    Authored-by: Dongjoon Hyun <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    
    skip-checks: true
---
 .../apache/spark/sql/execution/ExistingRDD.scala   | 31 ++++++++++++++++++++--
 .../scala/org/apache/spark/sql/DatasetSuite.scala  | 25 +++++++++++++++++
 2 files changed, 54 insertions(+), 2 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
index 7daec42cbdb8..c0a2aa1b9287 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
@@ -205,11 +205,38 @@ object LogicalRDD extends Logging {
 
     val (stats, constraints) = rewriteStatsAndConstraints(logicalPlan, 
optimizedPlan)
 
+    // The executed plan can output other attributes than 
`logicalPlan.output`, e.g. when
+    // `RemoveRedundantAliases` removes a same-name root alias. So map its 
partitioning and ordering
+    // onto `logicalPlan.output` by position, and drop the parts that still 
refer to other
+    // attributes, e.g. the input attributes of `SerializeFromObjectExec` or 
the pruned columns of
+    // `InMemoryTableScanExec`.
+    val toOutput = AttributeMap(executedPlan.output.zip(logicalPlan.output))
+    val outputSet = AttributeSet(logicalPlan.output)
+    def remap[E <: Expression](e: E): E =
+      e.transform { case a: Attribute => toOutput.getOrElse(a, a) 
}.asInstanceOf[E]
+    val partitioning = firstLeafPartitioning(executedPlan.outputPartitioning) 
match {
+      case p: Expression =>
+        val remapped = remap(p)
+        if (remapped.references.subsetOf(outputSet)) {
+          remapped
+        } else {
+          UnknownPartitioning(p.numPartitions)
+        }
+      case p => p
+    }
+    // Like `AliasAwareQueryOutputOrdering`, take the leading sort orders over 
the output only.
+    val ordering = executedPlan.outputOrdering.map(remap).map { order =>
+      order.children.filter(_.references.subsetOf(outputSet)) match {
+        case child +: rest => Some(order.copy(child = child, 
sameOrderExpressions = rest))
+        case _ => None
+      }
+    }.takeWhile(_.isDefined).flatten
+
     LogicalRDD(
       originDataset.logicalPlan.output,
       rdd,
-      firstLeafPartitioning(executedPlan.outputPartitioning),
-      executedPlan.outputOrdering,
+      partitioning,
+      ordering,
       isStreaming,
       None
     )(originDataset.sparkSession, stats, constraints, fromCheckpoint)
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/DatasetSuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/DatasetSuite.scala
index b155fa5e86dd..c6de7d3f64a6 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/DatasetSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/DatasetSuite.scala
@@ -1977,6 +1977,31 @@ class DatasetSuite extends SharedSparkSession
     assert(cp2.join(cp2).columns === Array("id", "ID", "id", "ID"))
   }
 
+  test("SPARK-61256: checkpoint should not use the partitioning and ordering 
over the columns " +
+      "of its source Dataset") {
+    val src = spark.range(0, 16, 1, 4)
+    // `RemoveRedundantAliases` removes the root alias, so the executed plan 
reports the
+    // partitioning and the ordering over the `id` of `src`.
+    val cp = 
src.select($"id".as("id")).localCheckpoint().logicalPlan.asInstanceOf[LogicalRDD]
+    assert(cp.outputPartitioning.asInstanceOf[Expression].references === 
cp.outputSet)
+    assert(cp.outputOrdering.map(_.references) === Seq(cp.outputSet))
+
+    // A typed `map` reports the partitioning of its input, which is not in 
its output.
+    val cp2 = src.as[Long].map(x => x).toDF().localCheckpoint()
+    val agg = broadcast(src).join(cp2, src("id") % 2 === cp2("value") % 2)
+      .groupBy(src("id")).count()
+    checkAnswer(agg, (0L until 16L).map(Row(_, 8L)))
+
+    // A column-pruned scan of a cache reports the ordering over `id`, which 
is not in its output.
+    val single = spark.range(0, 16, 1, 1)
+    val cached = single.select($"id", ($"id" % 2).as("p")).cache()
+    val cp3 = cached.select($"p").localCheckpoint()
+    val sorted = broadcast(single).join(cp3, single("id") % 2 === cp3("p"))
+      .orderBy(single("id")).select(single("id"))
+    checkAnswer(sorted, (0L until 16L).flatMap(i => Seq.fill(8)(Row(i))))
+    cached.unpersist()
+  }
+
   test("Dataset().localCheckpoint() lazy with StorageLevel") {
     val df = spark.range(10).repartition($"id" % 2)
     val checkpointedDf = df.localCheckpoint(eager = false, 
StorageLevel.DISK_ONLY)


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

Reply via email to