xiliang678 commented on code in PR #60690:
URL: https://github.com/apache/spark/pull/60690#discussion_r4632851348


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/NestedColumnAliasing.scala:
##########
@@ -220,9 +220,27 @@ object NestedColumnAliasing {
 
   private def canAlias(ev: Expression): Boolean = {
     // we can not alias the attr from lambda variable whose expr id is not 
available
-    !ev.exists(_.isInstanceOf[NamedLambdaVariable]) && ev.references.size == 1
+    !ev.exists(_.isInstanceOf[NamedLambdaVariable]) && ev.references.size == 1 
&&
+      // An alias is evaluated once per row of the operator's input. Below an 
operator that
+      // repeats input rows, such as a Join, a Generate or a Sample with 
replacement, a
+      // non-deterministic access would then give every row built from one 
input row the same
+      // value. For such an access, collectRootReferenceAndExtractValue 
returns only the
+      // deterministic extractions and columns below it, which the callers may 
alias instead.
+      (ev.deterministic || isNondeterministicOnlyThroughInputFile(ev))

Review Comment:
   Thanks, reproduced. This is an existing issue, not one this PR introduces: 
master without this PR aliases these accesses below the `Join` in the same way, 
and the input-file exemption in this PR kept that. With a `VALUES` side that 
holds the struct, broadcast and joined to a one-file Parquet table, 
`c.s.arr[CAST(input_file_block_start() AS INT)].x` gives 10 (element 0) in 
every row with nested column aliasing off, but fails with `INVALID_ARRAY_INDEX` 
(index -1) with it on, both on master and at 1fa5dbe9178, the previous head of 
this PR. The PR description has the full example.
   
   The issue predates this PR, but the exemption is new here and its stated 
reason does not hold below a `Join`, so I fixed it here, in 93b35e25580, as you 
suggested. When `NestedColumnAliasing` aliases below a `Join`, it passes 
`rewritePlanIfSubsetFieldsUsed` a collector with the exemption turned off, so 
only the deterministic part (`s.arr`) is aliased below the `Join`, and the 
access is evaluated above it. Every other operator keeps the exemption, and the 
doc comment of `isNondeterministicOnlyThroughInputFile` now says that it does 
not apply below a `Join`, and why. With the change, the example gives 10 in 
every row. As you noted, above a shuffled join, an access to a struct from the 
side that reads the file now sees an empty string or -1, the same as with 
nested column aliasing off. I ran that case; by reading the code, the same 
holds above a broadcast join that broadcasts that side.
   
   Tests: acaac7d208e adds an optimizer test with an index built from each 
input file function, for a `Project` over the `Join` and a `Project` over a 
`Filter` over the `Join`, and 194089712e1 adds the map access 
`s.m[input_file_name()].x` to it. acaac7d208e also adds a query to the 
`SchemaPruningSuite` test that joins a broadcast local relation holding the 
struct to a file table, and compares the results with nested column aliasing 
off and on. With it off, the query checks that each row reads the start of the 
scanned file block, not the -1 of the side that reads no file. The new 
optimizer test and the new `SchemaPruningSuite` query fail without 93b35e25580. 
The PR description now has the example and the changed behavior.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/NestedColumnAliasing.scala:
##########
@@ -220,9 +220,27 @@ object NestedColumnAliasing {
 
   private def canAlias(ev: Expression): Boolean = {
     // we can not alias the attr from lambda variable whose expr id is not 
available
-    !ev.exists(_.isInstanceOf[NamedLambdaVariable]) && ev.references.size == 1
+    !ev.exists(_.isInstanceOf[NamedLambdaVariable]) && ev.references.size == 1 
&&
+      // An alias is evaluated once per row of the operator's input. Below an 
operator that
+      // repeats input rows, such as a Join, a Generate or a Sample with 
replacement, a
+      // non-deterministic access would then give every row built from one 
input row the same
+      // value. For such an access, collectRootReferenceAndExtractValue 
returns only the
+      // deterministic extractions and columns below it, which the callers may 
alias instead.

Review Comment:
   Fixed in 93b35e25580 and acaac7d208e. The `canAlias` comment now says that a 
non-deterministic access is not aliased unless `exemptInputFile` is true and 
its only sources of non-determinism are input file functions; `collectorBelow` 
sets the flag to false below a `Join`. The comment in the dedup test now says 
that the default extractor returns a non-deterministic read only when its only 
sources of non-determinism are input file functions. That is also why the 
deduplication keeps its `p.deterministic` check, as the PR description says.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/NestedColumnAliasing.scala:
##########
@@ -220,9 +220,27 @@ object NestedColumnAliasing {
 
   private def canAlias(ev: Expression): Boolean = {
     // we can not alias the attr from lambda variable whose expr id is not 
available
-    !ev.exists(_.isInstanceOf[NamedLambdaVariable]) && ev.references.size == 1
+    !ev.exists(_.isInstanceOf[NamedLambdaVariable]) && ev.references.size == 1 
&&
+      // An alias is evaluated once per row of the operator's input. Below an 
operator that
+      // repeats input rows, such as a Join, a Generate or a Sample with 
replacement, a
+      // non-deterministic access would then give every row built from one 
input row the same
+      // value. For such an access, collectRootReferenceAndExtractValue 
returns only the
+      // deterministic extractions and columns below it, which the callers may 
alias instead.
+      (ev.deterministic || isNondeterministicOnlyThroughInputFile(ev))
   }
 
+  /**
+   * Whether the only sources of non-determinism in `e` are input file 
functions. These functions
+   * have one value per input row, but only before any shuffle: above a 
shuffle they return an

Review Comment:
   Fixed in 93b35e25580 and 194089712e1: the doc comment now says that these 
functions describe the file block of the row that a file scan in the task 
evaluating them is producing, and gives examples of where no scan is producing 
a row: above a shuffle, above a `Sort`, which reads all of its input before it 
returns a row, and on a side of a `Join` that reads no file. I checked the 
`Sort` case with the `t3` example from the PR description: above 
`sortWithinPartitions("id")`, `c.m[CAST(input_file_block_start() AS STRING)].x` 
gives null with nested column aliasing off and 10 with it on, on master and 
with this PR. The PR description has the same correction.
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/NestedColumnAliasingSuite.scala:
##########
@@ -969,6 +971,78 @@ class NestedColumnAliasingSuite extends SchemaPruningTest {
 
     comparePlans(optimized, expected)
   }
+
+  private val withArray = LocalRelation(
+    $"id".int,
+    $"s".struct(StructType.fromDDL("arr array<struct<x: int, y: int>>, e 
int")),
+    $"seq".array(IntegerType))
+
+  // `arr[index].x`.
+  private def elementX(arr: Expression, index: Expression): Expression =
+    GetStructField(GetArrayItem(arr, index), 0, Some("x"))
+
+  private val randomIndex = Cast(Multiply(Rand(Literal(0L)), Literal(1000.0)), 
IntegerType)
+
+  test("SPARK-62042: Do not alias non-deterministic nested field accesses 
below a Join") {
+    val other = LocalRelation($"rid".int)
+    // The second index mixes an input file function with rand(), so it is not 
exempt.
+    val mixedIndex = Cast(
+      Add(Cast(InputFileBlockStart(), DoubleType), Multiply(Rand(Literal(0L)), 
Literal(1000.0))),
+      IntegerType)
+    Seq(randomIndex, mixedIndex).foreach { index =>
+      val query = withArray.join(other, condition = Some($"id" === $"rid"))
+        .select(elementX($"s".getField("arr"), index).as("v"))
+        .analyze
+      val optimized = Optimize.execute(query)
+
+      val join = optimized.collectFirst { case j: Join => j }.get
+      assert(join.children.forall(_.deterministic),
+        s"a non-deterministic access is evaluated below the Join:\n$optimized")
+      // Only the deterministic `s.arr` is aliased below the Join, so `s.e` is 
still pruned, and
+      // the element is picked above the Join, once per joined row.
+      val aliases = collectGeneratedAliases(optimized)
+      val expected = withArray.select($"id", 
$"s".getField("arr").as(aliases(0)))
+        .join(other, condition = Some($"id" === $"rid"))
+        .select(elementX($"${aliases(0)}", index).as("v"))
+        .analyze
+      comparePlans(optimized, expected)
+    }
+  }
+
+  test("SPARK-62042: Do not alias non-deterministic nested field accesses 
below a Generate") {
+    val query = withArray
+      .generate(Explode($"seq"), outputNames = Seq("n"))
+      .select(elementX($"s".getField("arr"), randomIndex).as("v"), $"n")
+      .analyze
+    val optimized = Optimize.execute(query)
+
+    val generate = optimized.collectFirst { case g: Generate => g }.get
+    assert(generate.child.deterministic,
+      s"a non-deterministic access is evaluated below the 
Generate:\n$optimized")
+    val aliases = collectGeneratedAliases(optimized)
+    val expected = withArray
+      .select($"s".getField("arr").as(aliases(0)), $"seq")
+      .generate(Explode($"seq"), unrequiredChildIndex = Seq(1), outputNames = 
Seq("n"))
+      .select(elementX($"${aliases(0)}", randomIndex).as("v"), $"n")
+      .analyze
+    comparePlans(optimized, expected)
+  }
+
+  test("SPARK-62042: Alias nested field accesses whose only sources of 
non-determinism are " +
+      "input file functions") {
+    // The access is evaluated below the Repartition, where 
input_file_block_start() still has the
+    // value for the file the row comes from.
+    val access = elementX($"s".getField("arr"), Cast(InputFileBlockStart(), 
IntegerType))

Review Comment:
   Done in acaac7d208e: this test and the new `Join` test now run for an index 
built from each of `input_file_name()` (through `length()`), 
`input_file_block_start()` and `input_file_block_length()`. 194089712e1 also 
adds the map access `s.m[input_file_name()].x` to the `Join` test. By reading 
the code, if a function were dropped from the exemption, its case of this test 
would alias only `s.arr` below the `Repartition` and fail the plan comparison; 
I did not run that.
   



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