spark-test commented on code in PR #60414:
URL: https://github.com/apache/spark/pull/60414#discussion_r4557873448
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/InsertSortForLimitAndOffset.scala:
##########
@@ -114,6 +114,23 @@ object InsertSortForLimitAndOffset extends Rule[SparkPlan]
{
}
case _ => None
}
+ case g: GenerateExec =>
Review Comment:
**Non-blocking (P2):** This case covers generators that run in
`GenerateExec`, but a Python UDTF called in LATERAL position is also a
`Generate`. An example is `INSERT INTO out SELECT * FROM (SELECT u.* FROM
(SELECT * FROM t ORDER BY k) s, LATERAL my_udtf(s.k, s.v) u) LIMIT 10`.
`ExtractPythonUDTFs` plans it as `BatchEvalPythonUDTFExec` or
`ArrowEvalPythonUDTFExec`. Both extend `EvalPythonUDTFExec`, not `GenerateExec`
or `EvalPythonExec`, so the walk returns `None` at them (line 134). The limit
can then still keep rows from whichever map outputs arrive first: the same
wrong result this PR fixes for `explode`. The new conf doc and migration note
describe generators in general, so as written they also claim this case.
`EvalPythonUDTFExec` outputs `requiredChildOutput ++ resultAttrs` and joins
each output row with its queued input row in input order. So a case for the two
operators that passes the missing ordering columns through
`requiredChildOutput`, gated by the same `ignoreGenerate` conf, would close it.
Unlike `GenerateExec`, it always joins through its `JoinedRow`, so widening it
adds no new `terminate()` failure.
**Verification:**
- **Behavior:** A LATERAL Python UDTF between a global sort and a LIMIT, and
one under an OFFSET, neither the query root, get the post-shuffle local sort
for both the pickled and the Arrow UDTF operators, including when the UDTF's
output omits the sort key, and the executed plan keeps the query's schema.
- **Behavior:** With
spark.sql.legacy.orderingAwareLimitOffset.ignoreGenerate=true the same queries
get no post-shuffle local sort.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2654,6 +2654,15 @@ object SQLConf {
.booleanConf
.createWithDefault(Utils.isTesting)
+ val LEGACY_ORDERING_AWARE_LIMIT_OFFSET_IGNORE_GENERATE =
Review Comment:
**Nit (P3):** This entry sits among the data-source confs
(`DATA_SOURCE_DONT_ASSERT_ON_PREDICATE` through `DEFAULT_DATA_SOURCE_NAME`),
about 6,200 lines from `ORDERING_AWARE_LIMIT_OFFSET` (line 8879). That is the
switch it refines, and it makes this one irrelevant when false. Someone
changing or removing `spark.sql.orderingAwareLimitOffset` would not see that a
dependent legacy key exists. Could you declare it right after
`ORDERING_AWARE_LIMIT_OFFSET`, with the same key, doc, version and default?
**Verification:**
- **Inspection:** The entry is declared directly after
ORDERING_AWARE_LIMIT_OFFSET with the same key, doc, version, visibility and
default, and no declaration of it remains between DATA_SOURCE_V2_JOIN_PUSHDOWN
and DEFAULT_DATA_SOURCE_NAME.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/InsertSortForLimitAndOffset.scala:
##########
@@ -114,6 +114,23 @@ object InsertSortForLimitAndOffset extends Rule[SparkPlan]
{
}
case _ => None
}
+ case g: GenerateExec =>
+ extractOrderingAndPropagateOrderingColumns(g.child) match {
+ case Some((ordering, newChild)) =>
+ if
(conf.getConf(SQLConf.LEGACY_ORDERING_AWARE_LIMIT_OFFSET_IGNORE_GENERATE)) {
+ None
+ } else {
+ // GenerateExec streams its input rows in order. Like ProjectExec,
it must keep the
+ // ordering columns in its output so that the sort after the
shuffle can use them.
+ val missingCols = ordering.flatMap(_.references).distinct
+ .filterNot(g.outputSet.contains)
+ val newGen = g.copy(
+ requiredChildOutput = g.requiredChildOutput ++ missingCols,
child = newChild)
Review Comment:
**Blocking (P1):** This widens `requiredChildOutput` even when it was empty,
which is what ColumnPruning leaves when the generator's parent reads only the
generator output, as in `SELECT my_udtf(v) FROM (SELECT k, v FROM t ORDER BY k)
s LIMIT 10` under an INSERT, CTAS or UNION ALL. With a non-empty list,
`GenerateExec.doExecute` leaves the branch that emits generator rows alone and
takes the joined branch, which joins the rows from `terminate()` with the last
input row (GenerateExec.scala lines 110-114). On a partition with no input rows
that left side was never set, so the output projection calls `numFields` on a
null row and the task throws a NullPointerException.
`HiveGenericUDTF.terminate()` returns whatever a Hive UDTF forwards from
`close()`. For example, `GenericUDTFCount2`, which HiveUDFSuite registers,
forwards its count twice. Because the class is `CodegenFallback`, it always
runs this interpreted path. Reading the code, such a query returns the
forwarded rows on the base branch but now fails whenever the generator sees an
empty partition. With `spark.sql.adaptive.enabled=false`, which stateful
streaming also forces, that happens when the input is empty at runtime, or when
the sort key's values repeat with fewer distinct values than shuffle
partitions, which leaves the trailing range partition empty. With adaptive
execution on, a nondeterministic filter such as `rand() < 0.01` between the
sort and the generator can still empty a partition. Built-in generators are not
affected because their `terminate()` returns nothing, and the new tests use
only those, so no test covers this path.
**Recommended change:** In the GenerateExec case of
InsertSortForLimitAndOffset, return no ordering, so the rule keeps the base
branch's plan, when the GenerateExec passes no input column through and its
generator is user-defined (a Hive UDTF, the only kind of generator that can
return rows from terminate()), and add a TODO there naming this exemption. Add
Hive UDTF tests to the Hive execution tests, since a Hive GenericUDTF cannot be
registered from sql/core: one with a UDTF that forwards rows from close() over
an input partition with no rows, and one that checks the exempted plan. Add a
plan test to the sql/core generator tests showing that a built-in generator
without code generation support still gets the post-shuffle sort. Every other
GenerateExec keeps the current widening.
**Why this works:** A GenerateExec that passes no input column through runs
the branch that emits generator rows without pairing them with an input row,
the only branch that can return terminate() rows from a partition with no input
rows. Leaving it unwidened when its generator is user-defined keeps it on that
branch, so the rule can no longer route it onto the joined branch that reads a
missing input row, while built-in generators, whose terminate() returns
nothing, and GenerateExecs that already pass input columns through, which take
the joined branch on the base branch too, keep the PR's fix.
**Scope:** Narrow the new GenerateExec case so it skips user-defined
generators that pass no input column through, cover that case with Hive UDTF
tests, and check in the sql/core generator tests that built-in generators keep
the fix.
**Compatibility:** Every query the PR's own generator tests cover keeps its
post-shuffle sort and results, and with the legacy conf set the rule still
keeps the base branch's plan for every generator.
**Risks:** Queries whose Hive UDTF passes no input column through keep the
base branch's plan, so a LIMIT/OFFSET that is not the query root over them can
still keep arbitrary rows, including for Hive UDTFs that never forward rows
from close(); this holds whatever
spark.sql.legacy.orderingAwareLimitOffset.ignoreGenerate is set to, and the
TODO records it. The migration note's sentence about generators does not
mention this exemption.
**Constraints:** GenerateExecs whose generator is built-in, and
GenerateExecs that already pass input columns through, must keep the PR's
widening and post-shuffle sort. With
spark.sql.legacy.orderingAwareLimitOffset.ignoreGenerate=true the case must
still return no ordering for every GenerateExec, as on the base branch.
**Exclusions:**
- Changing GenerateExec so that terminate() rows of a partition without
input rows get a left side, which would also end the base branch's
NullPointerException for lateral views that pass input columns through a Hive
UDTF; that failure is unchanged by this PR, and fixing it needs nullable
pass-through columns.
**Success:** A query whose Hive UDTF forwards rows from close() and passes
no input column through, between a global sort over an input that is empty at
runtime and a LIMIT/OFFSET that is not the query root, returns the forwarded
rows as on the base branch instead of failing with a NullPointerException. For
a GenerateExec that passes no input column through and runs a user-defined
generator, the rule inserts no post-shuffle sort and leaves its
requiredChildOutput empty. GenerateExecs with built-in generators, including
ones without code generation support, and GenerateExecs that already pass input
columns through are still widened and get the post-shuffle sort. A TODO comment
at the exemption names the queries it leaves on the base branch's plan.
**Verification:**
- **Regression:** With adaptive execution off, a Hive UDTF that forwards
rows from close() and passes no input column through, between a global sort
over an input that is empty at runtime and a LIMIT that is not the query root,
returns the forwarded rows instead of throwing NullPointerException; the same
holds with adaptive execution on, partition coalescing off, and a sort key
whose values repeat with fewer distinct values than shuffle partitions, which
leaves the last range partition empty.
- **Behavior:** A query of that shape over non-empty input keeps the base
branch's plan, with no local sort after the single-partition shuffle and no
pass-through column on the GenerateExec, while the same Hive UDTF with an input
column passed through still gets the post-shuffle sort.
- **Behavior:** A built-in generator without code generation support, such
as stack with more than 50 rows, that passes no input column through still gets
the post-shuffle local sort, and a LIMIT that is not the query root over it
returns the rows generated from the first rows of the sorted input.
##########
docs/sql-migration-guide.md:
##########
@@ -25,6 +25,7 @@ license: |
## Upgrading from Spark SQL 4.4 to 5.0
- Since Spark 5.0, the Spark Thrift Server refuses to start when
`hive.server2.enable.doAs` is `true` and `hive.server2.authentication` verifies
user identities (any recognized type other than `NONE`/`NOSASL`). It
impersonates the connecting user for Hive metastore calls and driver-side file
system access, but executor-side data access still runs as the server's own
service identity, so storage-level permissions are checked against the service
principal rather than the connecting user (SPARK-5159). Spark 4.4 logs a
warning for the same configuration. To restore the previous behavior, set
`spark.sql.hive.thriftServer.allowIneffectiveDoAs` to `true`. Setting
`hive.server2.enable.doAs` to `false` also starts the server, but note that it
stops impersonating metastore calls as well, so it is not a no-op.
+- Since Spark 5.0, a `LIMIT` or `OFFSET` that is not the root of the query
(for example inside `CREATE TABLE AS SELECT`, `INSERT`, a `UNION ALL` branch or
a join) keeps the first rows of a sorted input also when a generator such as
`explode` sits between the sort and the `LIMIT`/`OFFSET`. Previously it could
keep arbitrary rows on a multi-executor cluster. To restore the previous
behavior, set `spark.sql.legacy.orderingAwareLimitOffset.ignoreGenerate` to
`true`.
Review Comment:
**Nit (P3):** An `OFFSET` skips the first rows instead of keeping them. The
new test expects `df.select(explode($"c2")).offset(18)` to return `Row(1),
Row(-1)`, the last two of the 20 sorted rows. Describing the change as
selecting rows by their position in the sorted input fits both LIMIT and OFFSET:
```suggestion
- Since Spark 5.0, a `LIMIT` or `OFFSET` that is not the root of the query
(for example inside `CREATE TABLE AS SELECT`, `INSERT`, a `UNION ALL` branch or
a join) selects rows by their position in the sorted input also when a
generator such as `explode` sits between the sort and the `LIMIT`/`OFFSET`.
Previously it could keep arbitrary rows on a multi-executor cluster. To restore
the previous behavior, set
`spark.sql.legacy.orderingAwareLimitOffset.ignoreGenerate` to `true`.
```
**Verification:**
- **Inspection:** The Spark 5.0 note for this change no longer says the
LIMIT or OFFSET keeps the first rows, describes selection by position in the
sorted input, and still names the generator case and
spark.sql.legacy.orderingAwareLimitOffset.ignoreGenerate.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/InsertSortForLimitAndOffsetSuite.scala:
##########
@@ -129,6 +129,50 @@ class InsertSortForLimitAndOffsetSuite extends
SharedSparkSession
verifySortAdded(df.select(pythonTestUDF($"c2")).offset(2))
}
+ private val ignoreGenerate =
SQLConf.LEGACY_ORDERING_AWARE_LIMIT_OFFSET_IGNORE_GENERATE
+
+ // Generators between a global sort and a non-root LIMIT/OFFSET, with the
expected rows.
+ private def generateLimitQueries(): Seq[(DataFrame, Seq[Row])] = {
+ val df = 1.to(10).map(v => (v, Seq(v, -v))).toDF("c1",
"c2").orderBy($"c1".desc)
+ val nullKeys = Seq[(Option[Int], Seq[Int])]((Some(3), Seq()), (Some(2),
null),
+ (None, Seq(9)), (Some(1), Seq(1, -1))).toDF("k",
"a").orderBy($"k".desc_nulls_last)
+ Seq(
+ df.select(explode($"c2")).limit(2) -> Seq(Row(10), Row(-10)),
+ df.select($"c1", posexplode($"c2")).limit(2) -> Seq(Row(10, 0, 10),
Row(10, 1, -10)),
+ df.select(explode($"c2").as("e")).select($"e" + 1).limit(2) ->
Seq(Row(11), Row(-9)),
+ df.select(explode($"c2")).offset(18) -> Seq(Row(1), Row(-1)),
+ df.selectExpr("explode(filter(c2, x -> x > 100))").limit(2) -> Seq(),
+ df.select(explode($"c2").as("e")).select(explode(array($"e", $"e" +
100))).limit(2) ->
+ Seq(Row(10), Row(110)),
+ nullKeys.select(explode_outer($"a")).limit(3) -> Seq(Row(null),
Row(null), Row(1)))
+ }
+
+ private def withGenerateLimitConfs(extra: (String, String)*)(f: => Unit):
Unit = withSQLConf(
+ Seq(SQLConf.TOP_K_SORT_FALLBACK_THRESHOLD.key -> "1",
+ SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+ SQLConf.ORDERING_AWARE_LIMIT_OFFSET.key -> "true") ++ extra: _*)(f)
+
+ test("SPARK-61573: middle LIMIT/OFFSET preserves data ordering through
Generate") {
+ withGenerateLimitConfs() {
+ generateLimitQueries().foreach { case (df, expected) =>
+ verifySortAdded(df)
+ // UNION ALL keeps duplicates and forces a shuffle, as in the customer
query.
Review Comment:
**Nit (P3):** Nothing in the repository defines "the customer query", so
readers can't tell which shape this stands for, and the reference brings
outside context into Apache source. Describing the shape keeps the comment
self-contained, for example:
```suggestion
// UNION ALL keeps duplicates and makes the LIMIT/OFFSET non-root,
which forces a shuffle.
```
**Verification:**
- **Inspection:** The comment above the UNION ALL check in the generator
test no longer mentions a customer query and describes the query shape the
union exercises.
--
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]