xiliang678 opened a new pull request, #60690:
URL: https://github.com/apache/spark/pull/60690
### What changes were proposed in this pull request?
`NestedColumnAliasing` and `GeneratorNestedColumnAliasing`, both applied by
`ColumnPruning` (together called nested column aliasing in this description),
replace a nested field access with a reference to an alias that they evaluate
in a new `Project` below an operator. With this PR they no longer do that for a
non-deterministic access, unless every source of non-determinism in it is an
input file function (`input_file_name()`, `input_file_block_start()` or
`input_file_block_length()`). For such an access they alias at most the
deterministic extractions below its non-deterministic parts, such as `s.arr` in
`s.arr[CAST(rand(0) * 1000 AS INT)].x`; a bare column below them is carried as
it is.
Both rules get their candidates from
`NestedColumnAliasing.getAttributeToExtractValues`, which takes a candidate
collector as its `extractor` argument, `collectRootReferenceAndExtractValue` by
default. That collector returns a column reference as it is. It returns a
`GetStructField` or `GetArrayStructFields` whole when the expression's child is
a column or another `ExtractValue` (such as a `GetArrayItem`) and `canAlias`
accepts the expression; for any other expression it descends into the children.
`canAlias` is private and called only from this collector. It already rejects
an access that uses a lambda variable or more than one column. With this PR it
also rejects a non-deterministic access, unless the access becomes
deterministic when each input file function in it is replaced by a literal. So
an index that adds `rand(0)` to `input_file_block_start()` is still rejected.
For `s.arr[CAST(rand(0) * 1000 AS INT)].x`, `canAlias` now rejects the
`GetStructField`. Its child, the `GetArrayItem`, is not a candidate type, so
the collector descends again and returns `s.arr`; the index has no column. The
rules alias `s.arr` below the operator, so the other fields of `s` are still
pruned there, and the element access is evaluated above the operator, once per
output row. With this PR, the optimized plan of the subquery of the first query
in the next section is:
```
Project [_extract_arr#463[cast((rand(0) * 1000.0) as int)].x AS v#460]
+- Join Inner, (id#255 = id#258)
:- Project [id#255, s#256.arr AS _extract_arr#463]
: +- Filter isnotnull(id#255)
: +- Relation spark_catalog.default.t1[id#255,s#256,seq#257] parquet
+- Filter isnotnull(id#258)
+- Relation spark_catalog.default.t2[id#258] parquet
```
For a random index into a top-level array column, such as `a[CAST(rand(0) *
1000 AS INT)].b` over the table `t4` in the next section, the collector returns
`a`, and the join carries `a` whole.
Input file functions are exempt because they have one value per input row,
the value for the row's file, so evaluating them below an operator that repeats
rows is correct. They have that value only before a shuffle; above one, they
return an empty string or -1. Today, nested column aliasing evaluates an access
whose only non-determinism comes from them below the operator, so above a
`Repartition` the access still sees the row's file. This PR keeps that. For
example, on master with and without this PR:
```scala
// CREATE TABLE t3 USING parquet AS SELECT 1 AS id,
// named_struct('m', map('0', named_struct('x', 10, 'y', 11)), 'e', 0) AS c
spark.table("t3").repartition(3).selectExpr(
"c.m[CAST(input_file_block_start() AS STRING)].x AS nested", // 10
"input_file_block_start() AS plain") // -1
```
Below the shuffle, `input_file_block_start()` is 0, the start of the block
that holds the row, so `nested` reads the map at key `'0'`. This PR does not
change the difference from `plain`, which is evaluated above the shuffle.
The existing test "Nested fields are not redundant with non-deterministic
parents" in `NestedColumnAliasingSuite` passes non-deterministic accesses to
`getAttributeToExtractValues` to test how it deduplicates them. The default
collector no longer returns such accesses, so the test now passes `extractor =
e => Seq(e)`. The deduplication keeps its determinism check, which still
applies to accesses whose only non-determinism comes from input file functions.
`GeneratorNestedColumnAliasing` uses the default collector for the
`Generate`'s input and for the `Project` above it. It then moves an access to
the generator's output into the generator with a collector of its own, but only
accesses that the default collector returned, so non-deterministic ones are no
longer moved there either (by reading the code).
### Why are the changes needed?
A query's select list is evaluated once per row of its input, so a
non-deterministic expression in it gives each row its own value. Nested column
aliasing evaluates the alias once per row of the operator's input instead. When
the operator repeats input rows, every output row built from one input row then
gets the same value. On master, with AQE on and off:
```sql
CREATE TABLE t1 USING parquet AS
SELECT 1 AS id,
named_struct('arr', transform(sequence(0, 999), i -> named_struct('x', i,
'y', i)), 'e', 0) AS s,
sequence(1, 1000) AS seq;
CREATE TABLE t2 USING parquet AS SELECT 1 AS id FROM range(1000);
-- 1000 joined rows, each picking a random element of s.arr
SELECT count(*), count(DISTINCT v) FROM (SELECT s.arr[CAST(rand(0) * 1000 AS
INT)].x AS v FROM t1 JOIN t2 ON t1.id = t2.id);
-- without this PR: 1000, 1
-- with this PR: 1000, 630
-- 1000 exploded rows, each picking a random element of s.arr (the query
also reads n; see below)
SELECT count(*), count(DISTINCT v), sum(n) FROM (SELECT s.arr[CAST(rand(0) *
1000 AS INT)].x AS v, n FROM t1 LATERAL VIEW explode(seq) g AS n);
-- without this PR: 1000, 1, 500500
-- with this PR: 1000, 630, 500500
-- control: the same random pick from seq, an array of integers; seq[...]
has no struct
-- field access, so nested column aliasing leaves it alone
SELECT count(*), count(DISTINCT v) FROM (SELECT seq[CAST(rand(0) * 1000 AS
INT)] AS v FROM t1 JOIN t2 ON t1.id = t2.id);
-- without and with this PR: 1000, 630
```
1000 random picks from 1000 values give about 632 distinct values on
average. The exact counts in this description come from local runs and can
differ with the partitioning; the signal is one value versus about 632.
Nested column aliasing aliases accesses at these operators (by reading the
code):
- `Project(op)` or `Project(Filter(op))`, where `op` is a `Join`, `Window`,
`Sort`, `GlobalLimit`, `LocalLimit`, `Sample`, `Repartition`,
`RepartitionByExpression` or `RebalancePartitions`: below `op`;
- an `Aggregate` or `Expand`, for the accesses in its own expressions: below
it;
- `Generate` or `Project(Generate)`, for `explode`, `posexplode`, `inline`
and `stack`: below the `Generate`.
Of these, a `Join`, a `Generate`, a `Sample` with replacement and an
`Expand` repeat input rows. The join, `explode` and sample cases were run; the
other generators and `Expand` were not. Other accesses and operators, run on
master over `t1`, `t2` and a new table `t4`, also give one distinct value
without this PR (with this PR in parentheses):
- `s.arr[CAST(monotonically_increasing_id() % 1000 AS INT)].x` over the
join: 1 in 1000 rows (1000).
- `shuffle(s.arr, 0)[0].x` over the join: 1 in 1000 rows (638).
- `spark.table("t1").sample(withReplacement = true, fraction = 1000.0, seed
= 0).selectExpr("s.arr[CAST(rand(0) * 1000 AS INT)].x AS v")`: 1 in 1016 rows
(632).
- `a[CAST(rand(0) * 1000 AS INT)].b` over `t4 JOIN t2 ON t4.id = t2.id`,
where `t4` is `CREATE TABLE t4 USING parquet AS SELECT 1 AS id,
transform(sequence(0, 999), i -> named_struct('b', i, 'c', i)) AS a`: 1 in 1000
rows (630).
Without this PR, the join case needs
`spark.sql.optimizer.nestedSchemaPruning.enabled` (default true): with it off,
the join query gives 630 distinct values. The explode case needs
`spark.sql.optimizer.nestedSchemaPruning.enabled` or
`spark.sql.optimizer.expression.nestedPruning.enabled` (also default true):
with only `spark.sql.optimizer.nestedSchemaPruning.enabled` off, the explode
query still gives 1, and with both off, 630. The explode case also needs the
query to read the generator output `n`: without `n` in the subquery's select
list, the explode query gives 630. By reading the code, `ColumnPruning` has an
earlier case for a `Project` above a `Generate` that does not read all of the
`Generate`'s output; it matches such a `Project` on every iteration, so
`GeneratorNestedColumnAliasing` never sees it.
The released 4.0.0 and 4.3.0 return the same rows as master without this PR
for the three queries in the SQL block above, the first two of them wrong: they
were run with pyspark 4.0.0 and 4.3.0 from PyPI, with AQE on and off. 4.1.0 and
4.2.0 have the same `canAlias` and the same operator lists, by reading the
code; they were not run. The join case dates from SPARK-31736 (3.1.0), which
made nested column aliasing work through a `Join`. The changes that introduced
the explode and sample cases were not looked up, and 3.x was not run.
### Does this PR introduce _any_ user-facing change?
Yes, a correctness fix. A non-deterministic nested field access above a
join, an explode or a sample with replacement now gets its own value for each
output row, unless its only non-determinism comes from input file functions. By
reading the code, the same holds above the other generators listed above and
above an `Expand`; those were not run.
`canAlias` is the only changed code and is called only by the default
collector, so plans change only for queries with a non-deterministic nested
field access, other than one whose only non-determinism comes from input file
functions, at an operator listed above. At such an operator:
- If the operator repeats rows, results were wrong and are now right.
- If it does not (a `Window`, `Sort`, limit, `Sample` without replacement,
`Repartition`, `RepartitionByExpression`, `RebalancePartitions` or
`Aggregate`), each row already got one value. The access is now evaluated in or
above the operator, where the query has it, instead of below it (by reading the
code; not run). The values can change: `rand(0)` is evaluated in a different
order, and above a `Repartition`, `spark_partition_id()` and
`monotonically_increasing_id()` see the partitions above the shuffle, as they
do outside a nested field access.
- In both cases, the operator carries the deterministic part of the access
instead of its result. In the join query above, each joined row carries the
1000-element array `s.arr` instead of one integer, and in the explode query
each of the 1000 rows that the `Generate` outputs carries it. A `Sort` or
`Repartition` would sort or shuffle it too. In the queries run here, the scans
read the same schema with and without this PR:
`struct<id:int,s:struct<arr:array<struct<x:int,y:int>>>>` for `t1` and
`struct<id:int>` for `t2` in the join query, and
`struct<id:int,a:array<struct<b:int,c:int>>>` for `t4`.
This PR adds no conf to restore the old plans. Above an operator that
repeats rows, the old plans give wrong results. Above the other operators, the
old plans were correct; this PR applies the same check there because the
collector does not know the operator, and evaluating a non-deterministic
expression where the query has it is the conservative choice. Limiting the
check to operators that repeat rows would avoid the extra cost there, but the
rules would then have to tell the collector which operator they alias below.
### How was this patch tested?
New tests that fail without the fix:
- `NestedColumnAliasingSuite`, "Do not alias non-deterministic nested field
accesses below a Join" and "... below a Generate": `s.arr[CAST(rand(0) * 1000
AS INT)].x` above a `Join` and above a `Generate` is not evaluated below the
operator, and only `s.arr` is aliased below it. The Join test also checks an
index that adds `rand(0)` to `input_file_block_start()`. Without the fix, the
whole access is aliased below both operators.
- `SchemaPruningSuite`, "non-deterministic nested field accesses get a value
per output row", for Parquet and ORC with the V1 and V2 sources: the access
gives more than one distinct value over a join (1000 rows), an explode (1000
rows) and a seeded sample with replacement of fraction 1000.0 (about 1000
rows), and the join's scan still prunes `s.e`. Without the fix, all three give
one distinct value: `List((join,1), (explode,1), (sample,1))`.
A new test in `NestedColumnAliasingSuite` that passes with and without the
fix, "Alias nested field accesses whose only sources of non-determinism are
input file functions": such an access is still aliased below a `Repartition`.
A changed test: "Nested fields are not redundant with non-deterministic
parents" (see above).
The queries and examples in this description were also run on master through
a temporary test, with AQE on and off, with and without the fix; the results
quoted are from those runs.
Also ran `NestedColumnAliasingSuite`, `ColumnPruningSuite`,
`GeneratorFunctionSuite` and the four `SchemaPruningSuite` subclasses
(`ParquetV1SchemaPruningSuite`, `ParquetV2SchemaPruningSuite`,
`OrcV1SchemaPruningSuite` and `OrcV2SchemaPruningSuite`), which pass, and
scalastyle for the catalyst and sql modules.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)
This pull request and its description were written by Isaac.
--
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]