utkarshbajaj opened a new pull request, #60355:
URL: https://github.com/apache/spark/pull/60355
### What changes were proposed in this pull request?
When `CollectLimitExec` runs on the executors (`doExecute`), it shuffles all
child partitions into a single task and then applies LIMIT and OFFSET with
`take`, `slice` or `drop`. The shuffle reader returns the map outputs in the
order they arrive, not in partition order. So when the child is sorted, the
rows can come back out of order, and OFFSET can skip the wrong rows.
`executeCollect`, the driver path, does not have this problem, because it
collects the partitions in partition order.
This PR adds an ordered gather for that single task, behind a new internal
config, `spark.sql.execution.collectLimit.orderedGather.enabled`. It is off by
default and on in tests.
- `OrderedGatherIterator` (new) returns the map outputs in map index order.
It reads them in batches of map index ranges that grow like
`SparkPlan.executeTake` (`spark.sql.limit.initialNumPartitions`,
`spark.sql.limit.scaleUpFactor`), capped by the new
`spark.sql.execution.collectLimit.orderedGather.maxBatchPartitions` (default
100). It stops once LIMIT rows have been returned. Within a batch, a map output
that arrives on its turn is returned as it is read. A map output that arrives
before its turn is spooled to a local temporary file, then read back once and
deleted when its turn comes. Only the rows that can still be returned before
the limit are spooled.
- `BlockStoreShuffleReader.readMapOutputs()` (new) reads the map outputs one
at a time, each labelled with its map index.
- `ShuffleBlockFetcherIterator` reports the map index of the block it last
returned (`currentMapIndex`). It also has a new `orderRequestsByMapIndex`
option, which sends the remote fetch requests in map index order instead of a
random order, so that the map outputs mostly arrive on their turn.
- `ShuffledRowRDD.enableOrderedGather` switches the single-partition gather
to the ordered read, and disables push-based shuffle merging, because merged
blocks lose their map indexes.
- `SpecialLimits` sets a new `CollectLimitExec.childMayBeOrdered` field. It
is false only when no node below the limit can create an order across
partitions, for example a file scan with only filters, projections, aggregates
or joins of unordered inputs above it. Such children keep the existing
unordered gather. The field is hidden from the explain output.
- `MapOutputTracker.convertMapStatuses` indexes the requested map index
range directly, instead of iterating over all earlier map statuses, so reading
a batch costs time proportional to the batch.
- Two new SQL metrics are shown on `CollectLimit` when the ordered gather
runs: the number of ordered gather batches and the ordered gather spool size.
Not in this PR:
- `CollectTailExec` gathers the same way. A TODO notes it for a follow-up.
- `GlobalLimitExec`, a LIMIT that is not the root of the plan, gathers the
same way, and relies on the best-effort `InsertSortForLimitAndOffset`
(SPARK-50124). That rule has a TODO to "add a order preserving mode in the
shuffle reader". This PR adds that mode for `CollectLimitExec`, and a follow-up
can use it for `GlobalLimitExec`.
### Why are the changes needed?
It is a correctness bug. `CollectLimitExec.doExecute` runs whenever a root
LIMIT or OFFSET result is consumed as an RDD rather than through
`executeCollect`: `Dataset.toLocalIterator`, Arrow-based `toPandas` and SparkR
collection, and `df.rdd`, for example. Since
`spark.sql.execution.topKSortFallbackThreshold` defaults to about
`Int.MaxValue`, most `ORDER BY ... LIMIT n` queries are planned as
`TakeOrderedAndProjectExec` and are not affected. These are:
- `ORDER BY ... OFFSET n` without a LIMIT.
- A sort with an operator between it and the LIMIT, such as an `explode`, a
non-deterministic filter or a Python UDF.
- Any LIMIT over a sort when `topKSortFallbackThreshold` is lowered.
The bug only shows up when map outputs come from more than one executor,
since local blocks are read in order. For example, the new
`CollectLimitOrderedGatherClusterSuite` runs this on `local-cluster[2,1,1024]`,
with AQE off and `topKSortFallbackThreshold` set to 1000:
```scala
spark.range(0, 20000, 1, 20).orderBy(col("id").desc).offset(15000).limit(100)
```
The expected rows are 4999 down to 4900. With the new config off,
`CollectLimitExec.execute()` returned rows starting at 8988 in one run and at
11013 in another.
### Does this PR introduce _any_ user-facing change?
No, by default. The new configs are internal, and the ordered gather is off
by default. When it is enabled, `toLocalIterator`, Arrow-based collection and
`df.rdd` of a root LIMIT or OFFSET over a child that may be ordered return the
same rows as `collect()`.
### How was this patch tested?
New tests:
- `CollectLimitOrderedGatherClusterSuite` runs on two executors, so that map
outputs come from both and some arrive before their turn. It checks OFFSET +
LIMIT and OFFSET alone over a sorted child, with host-local disk reads on and
off. With the config off, both tests fail with wrong rows. With it on, they
pass.
- `CollectLimitOrderedGatherSuite` covers:
- the ordered gather with AQE on and off, and with both shuffle writers
(bypass, and sort-based with forced spills);
- sorted children that are not planned as a top-K sort;
- the `childMayBeOrdered` planning for unordered and ordered children,
including AQE replanning and the ordering that a DSv2 scan reports;
- `toLocalIterator` and Arrow collection, batching by
`maxBatchPartitions`, and the metrics;
- unit tests of `OrderedGatherIterator`: batch growth, the spool caps,
spool cleanup, and missing or unexpected map outputs.
- `BlockStoreShuffleReaderSuite`, `ShuffleBlockFetcherIteratorSuite` and
`MapOutputTrackerSuite` cover `readMapOutputs`, `currentMapIndex`, the request
order, and the map index range conversion.
Ran locally:
```
build/sbt 'core/testOnly org.apache.spark.MapOutputTrackerSuite
org.apache.spark.shuffle.BlockStoreShuffleReaderSuite
org.apache.spark.storage.ShuffleBlockFetcherIteratorSuite'
build/sbt 'sql/testOnly
org.apache.spark.sql.execution.CollectLimitOrderedGatherSuite
org.apache.spark.sql.execution.InsertSortForLimitAndOffsetSuite'
build/sbt 'sql/testOnly
org.apache.spark.sql.execution.CollectLimitOrderedGatherClusterSuite'
```
All tests passed. Two Python UDF tests in `InsertSortForLimitAndOffsetSuite`
were canceled locally, because no Python environment was set up. Since the
config is on in tests, existing suites that collect through
`CollectLimitExec.doExecute` also run the ordered gather in CI.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Isaac (Claude Code 2.1.322, 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]