cloud-fan commented on code in PR #60690:
URL: https://github.com/apache/spark/pull/60690#discussion_r4624217709
##########
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:
**Non-blocking (P2):** For a Project over a Join, the alias for an
input-file-only access goes into a Project over whichever Join child outputs
the struct (replaceWithAliases, NestedColumnAliasing.scala:184-194), and
PreReadCheck accepts a Join whose other side scans no file. Take `SELECT
c.s.by_file[input_file_name()].owner FROM cfg c JOIN facts f ON c.k = f.k`,
where cfg is a VALUES clause, a local Seq or a range and facts is a Parquet
table. Reading the code, the alias is computed either on the driver by
ConvertToLocalRelation or in the tasks that build cfg's broadcast; neither sets
InputFileBlockHolder, so every joined row built from one cfg row gets
`by_file['']`. With nested column aliasing off, the access is evaluated above
the broadcast join, in the task that scans facts, so each joined row gets the
owner for its own file. The array form `c.s.arr[CAST(input_file_block_start()
AS INT)].x` reads index -1 when aliased, which gives null with ANSI off and
INVALID_ARRAY_INDEX wi
th ANSI on.
The base branch already returns these values, but the exemption's reason,
that the alias keeps the value for the row's file (lines 232-236), does not
hold for a side that reads no file, so these inputs keep the failure this PR
fixes for other non-deterministic accesses. Above a shuffled join, both plans
read the empty holder; the difference shows when the file side is streamed in
the stage that evaluates the access.
**Recommended change:** Stop exempting input-file-only accesses when nested
column aliasing aliases below a Join. In NestedColumnAliasing.unapply, when the
operator below the Project, or below the Project's Filter, is a Join, collect
candidates with a collector that aliases an access only when it is
deterministic. For an access such as `s.m[input_file_name()].x`, only its
deterministic part (`s.m`) is then aliased below the Join, and the access
itself is evaluated above it; every other operator keeps the current exemption.
One way to do this is to give rewritePlanIfSubsetFieldsUsed an extractor
argument that it passes to getAttributeToExtractValues, and to give
collectRootReferenceAndExtractValue and canAlias a flag that turns the
input-file exemption off. Update the doc comment of
isNondeterministicOnlyThroughInputFile to say that the exemption does not apply
below a Join, because the side that outputs the struct may scan no file. Add
optimizer plan tests for an input-file-only a
ccess above a Join, and an end-to-end join test, in the nested schema pruning
tests over file sources, that joins a local relation holding the struct to a
file table.
**Why this works:** Below a Join, an input-file-only access is then handled
like any other non-deterministic access. The collector descends into it and
returns its deterministic extractions, the rules alias those below the Join,
and the access is evaluated in the Project above the Join, once per joined row.
There it reads the same input file value as the query evaluated without nested
column aliasing. Below an operator with one input, the alias still runs where
that input's rows are produced, so the exemption keeps the row's file as before.
**Compatibility:** Input-file-only nested accesses below a Repartition,
RepartitionByExpression, RebalancePartitions, Sort, Window, limit, Sample,
Generate, Aggregate or Expand are still aliased below the operator, so there
they keep reading the scanned row's file.
**Risks:** Above a sort-merge or shuffled hash join, or a broadcast join
that broadcasts the file side, a nested access that reads a struct from the
file side and whose only non-determinism is an input file function now sees an
empty string or -1 from that function instead of the row's file, the same value
the function gives outside a nested access or with nested column aliasing off.
The access then returns a different value, such as null for a map lookup keyed
by input_file_name(), and an array index built from input_file_block_start() or
input_file_block_length() becomes -1, which fails with INVALID_ARRAY_INDEX when
ANSI mode is on. Above a broadcast join that streams the file side, the value
does not change, because the access is still evaluated in the task that scans
the file. No conf restores the old value: turning nested column aliasing off
gives the new one.
**Constraints:** Keep the exemption, and the plans it produces, below every
operator other than a Join. Leave the handling of rand()-based and other
non-deterministic accesses unchanged.
**Verification:**
- **Regression:** An optimizer plan test over a Join shows that a nested
access indexed by an input file function, both an array index built from
input_file_block_start() and a map key from input_file_name(), has only its
deterministic part aliased below the Join and is evaluated above it, for a
Project directly over the Join and for a Project over a Filter over the Join.
- **Behavior:** An end-to-end join between a local relation that holds the
struct and a file table, with the local side broadcast, returns the same rows
with nested column aliasing on and off for an access indexed by an input file
function, and those rows carry the file table's value rather than the null or
empty value that the side reading no file would give.
##########
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:
**Nit (P3):** FileScanRDD sets InputFileBlockHolder for each file and unsets
it once the last file is done (FileScanRDD.scala:251-252 and 309). Above
`sortWithinPartitions`, a Sort that nested column aliasing pushes through with
no shuffle, the sort drains the scan before it emits rows, so an input file
function evaluated there returns an empty string or -1. On a Join side that
scans no file, the holder is never set. The comment would be accurate if it
said these functions return the row's file only while a file scan in the
evaluating task is producing the row, and named those cases along with the
shuffle.
See **Shared repair plan 1** in the review body.
##########
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:
**Nit (P3):** canAlias also accepts an access whose only non-determinism is
an input file function, so the collector returns
`s.arr[CAST(input_file_block_start() AS INT)].x` whole, and for
`s.arr[CAST(input_file_block_start() AS INT)].inner[CAST(rand() AS INT)].z` it
returns the non-deterministic `s.arr[CAST(input_file_block_start() AS
INT)].inner`. This comment and the one in the dedup test
(NestedColumnAliasingSuite.scala:369-370) both say the opposite; they should
name the input-file exemption, which is also why the dedup guard keeps its
`p.deterministic` check (line 302).
See **Shared repair plan 1** in the review body.
##########
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:
**Nit (P3):** The exemption matches three classes
(NestedColumnAliasing.scala:240), but this access, like the mixed index at line
990, uses only InputFileBlockStart, and no changed test builds a nested access
over input_file_name() or input_file_block_length(). If either were dropped
from the pattern, `s.m[input_file_name()].x` above a Repartition would be
evaluated above the shuffle and read an empty string instead of the row's file,
with every changed test still passing. Running this test once for each of the
three functions would catch that.
**Verification:**
- **Regression:** For each of input_file_name(), input_file_block_start()
and input_file_block_length(), a nested access whose only non-determinism is
that function is aliased below a Repartition, and the test fails when that
function is removed from the exemption.
--
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]