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


##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSetOperationsSuite.scala:
##########
@@ -1743,6 +1743,52 @@ class DataFrameSetOperationsSuite extends 
SharedSparkSession with AdaptiveSparkP
     }
   }
 
+  test("SPARK-61356: union outputPartitioning when a child output repeats an 
ExprId") {
+    // `SELECT p, p, w` leaves two output positions with one ExprId. The 
analyzer normally replaces
+    // a repeated output column with a fresh ExprId 
(`DeduplicateUnionChildOutput`); these confs
+    // keep it so the physical union sees it.
+    withSQLConf(
+        SQLConf.UNION_IS_RESOLVED_WHEN_DUPLICATES_PER_CHILD_RESOLVED.key -> 
"false",
+        SQLConf.ENFORCE_TYPE_COERCION_BEFORE_UNION_DEDUPLICATION.key -> 
"false",
+        SQLConf.ANALYZER_DUAL_RUN_LEGACY_AND_SINGLE_PASS_RESOLVER.key -> 
"false",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "5") {
+      def repeated: DataFrame = spark.range(10).selectExpr("id p", "id 
w").select($"p", $"p", $"w")
+
+      // A later child repeats the ExprId. `r` is a union, so for `p2`'s rows 
its second position
+      // holds `r` while its first holds `q`, and its shuffle hashes the first 
one. Reading that
+      // partitioning as one on `c`, the second position, would let the 
aggregate skip its exchange
+      // and split a group over partitions.
+      val p1 = repeated
+      val p2 = spark.range(10, 110).selectExpr("id q", "id % 10 r", "id w2")
+      val r = p1.union(p2).repartition(p1.col("p"))
+      val x = spark.range(10).selectExpr("id x", "id c", "id 
u").repartition($"c")
+      // All three columns are referenced, so `ColumnPruning` adds no 
`Project` below the union.
+      val laterChild = x.union(r).groupBy($"c").agg(sum($"x"), sum($"u"))
+
+      // The first child repeats the ExprId, so this union's own output does. 
Its second child is
+      // hashed by `r`, the second position, while `p` is read from the first 
one.
+      val c0 = repeated
+      val c1 = spark.range(100).selectExpr("id % 10 q", "id r", "id 
w2").repartition($"r")
+      val firstChild = 
c0.repartition(c0.col("p")).union(c1).groupBy(c0.col("p")).agg(sum($"w"))
+
+      Seq(
+        laterChild -> (0 until 10).map(k => Row(k, 12 * k + 550, 12 * k + 
550)),
+        firstChild -> (0 until 10).map(k => Row(k, 11 * k + 450))
+      ).foreach { case (df, expected) =>
+        val unionExec = df.queryExecution.executedPlan.collect { case u: 
UnionExec => u }.head
+        // The analyzer can drop this shape, so assert it survived rather than 
letting the test
+        // go vacuous: hash-partitioned children, one of them repeating an 
ExprId.
+        
assert(unionExec.children.forall(_.outputPartitioning.isInstanceOf[HashPartitioning])
 &&

Review Comment:
   **Non-blocking (P2):** This precondition limits the test to hash-partitioned 
children, so it reaches only Case B. The guard also changes Case A, the 
`KeyedPartitioning` merge, and nothing tests that path with a repeating child. 
With both analyzer confs off, take an `InMemoryCatalog` table `t1 (id bigint, 
data string) PARTITIONED BY (id)` selected as `(id, id, data)`, and `UNION ALL` 
it with `t2 (q bigint, r bigint, w string) PARTITIONED BY (r)` selected as `(q, 
r, w)`. Reading master's code: a project with no aliases keeps each scan's 
`KeyedPartitioning`. The last-wins remap sends `t2`'s `r` to the union's `id`, 
Case A merges the legs, and `EnsureRequirements` satisfies a `GROUP BY id` 
through `GroupPartitionsExec`. The aggregate reads position 0, though, and that 
holds `q` for `t2`'s rows, so its groups split across partitions. The guard 
fixes that. But the existing SPARK-57881 keyed test runs on default confs, so a 
later change to this translation could bring the wrong result ba
 ck with every test green. Keyed union pass-through is not in a release yet, so 
a keyed case here is what keeps that wrong result from shipping.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -1177,6 +1177,16 @@ case class UnionExec(children: Seq[SparkPlan]) extends 
SparkPlan with CodegenSup
    * reports unknown.
    */
   private def rawPartitioning: Partitioning = {
+    // An attribute is read from the first position that carries its `ExprId` 
(see
+    // `AttributeSeq.indexOf`), so the positions of an output that repeats one 
cannot be told
+    // apart by attribute, and they hold different values when a union sits 
below. A child's
+    // partitioning then has no reliable counterpart among this union's output 
attributes, whether
+    // the repeat is in that child's output or, through the first child, in 
this union's own.
+    // The analyzer normally leaves no such child 
(`DeduplicateUnionChildOutput`).
+    if (children.exists(c => c.output.map(_.exprId).distinct.size < 
c.output.size)) {

Review Comment:
   **Blocking (P1):** This returns `UnknownPartitioning` for every union in 
which some child repeats an `ExprId`, before it looks at which columns the 
children's partitionings use, so it also drops claims that are correct on 
master. With both analyzer confs off, take `c0 = spark.range(10).selectExpr("id 
p", "id w").select($"p", $"p", $"w")` and `c1 = spark.range(100).selectExpr("id 
% 10 q", "id r", "id w2")`, and run 
`c0.repartition(c0.col("w")).union(c1.repartition($"w2")).groupBy(c0.col("w")).agg(sum(c0.col("p")))`.
 Reading master's code: `prepareOutputPartitioning` maps `w` and `w2`, each at 
position 2 and repeated in neither output, to the union's `w`, and Case B keeps 
`HashPartitioning(w)`. That claim is right. The aggregate reads `w` at position 
2, the column each child was hashed by, so no exchange is planned. With the 
guard, the union is plain, and `EnsureRequirements` adds a shuffle between the 
partial and final aggregates. A join on `w` would re-shuffle every union row. 
The
  same happens to a key at the first column of an `ExprId` the first child 
repeats, to single-partition legs, and to keyed legs on such columns. Results 
do not change. Only sessions with both analyzer confs off are affected; 
default-config plans stay the same.
   
   The comment above gives as its reason that such a child's partitioning has 
no reliable counterpart among the union's output attributes, but that holds 
only for columns the repeat touches. Expressions bind an attribute at its first 
column (`AttributeSeq.indexOf`), so a child's partitioning on a repeated 
`ExprId` describes that first column. A claim is safe exactly when the union 
output's first column for the mapped `ExprId` is the same position, and both 
shapes in the description fail that test.
   
   See **Shared repair plan 1** in the review body.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to