spark-test commented on code in PR #60404:
URL: https://github.com/apache/spark/pull/60404#discussion_r4581979484
##########
core/src/main/scala/org/apache/spark/Partitioner.scala:
##########
@@ -329,12 +333,14 @@ private[spark] object RangePartitioner {
*
* @param rdd the input RDD to sketch
* @param sampleSizePerPartition max sample size per partition
+ * @param legacyRddIdSeed whether to mix the RDD id into the per-partition
seeds
* @return (total number of items, an array of (partitionId, number of
items, sample))
*/
def sketch[K : ClassTag](
rdd: RDD[K],
- sampleSizePerPartition: Int): (Long, Array[(Int, Long, Array[K])]) = {
- val shift = rdd.id
+ sampleSizePerPartition: Int,
+ legacyRddIdSeed: Boolean = false): (Long, Array[(Int, Long, Array[K])])
= {
+ val shift = if (legacyRddIdSeed) rdd.id else 0
Review Comment:
**Blocking (P1):** With `shift` now 0 by default, two `RangePartitioner`s
built over the same input draw the same sample, so their bounds differ only
through the ordering that `determineBounds` sorts by. `equals` still compares
only `rangeBounds` and `ascending`, while `getPartition` routes keys with the
partitioner's own ordering, and `OrderedRDDFunctions` documents overriding the
default ordering (`JavaPairRDD.sortByKey` also takes a `Comparator`).
By the review's reading of the code: sort 1,100,000 distinct Int keys in 11
equal partitions with `sortByKey(numPartitions = 2)`, once under
`Ordering[Int]` and once under `Ordering[Int].reverse`. Both constructors see
the same 121 equally weighted candidates and pick the same middle key m as
their only bound, so the two partitioners compare equal although one puts keys
up to m in partition 0 and the other puts keys from m upward there. Joining the
two results, `CoGroupedRDD` takes a one-to-one dependency on the second RDD
instead of shuffling it, and the join returns only the row for m instead of
1,100,000 rows, with no error. On the base branch the two constructors seeded
with different RDD ids, picked different bounds, and the join shuffled.
The same skipped shuffle affects cogroup, subtractByKey, combineByKey
operations given such a partitioner, partitionBy,
repartitionAndSortWithinPartitions and union. The trigger needs the same data
range-partitioned under two orderings and then combined, but the result is
silently wrong.
**Recommended change:** In RangePartitioner.equals, also require the two
partitioners' orderings to be equal, for example
`r.rangeBounds.sameElements(rangeBounds) && r.ascending == ascending &&
r.ordering == ordering`, and keep hashCode as it is. Add a PartitioningSuite
test that builds RangePartitioners over the same odd number of distinct keys
under the default Ordering[Int] and under its reverse with two output
partitions, so both pick the same middle key as their only bound, asserts that
they compare unequal, and asserts that joining the two sortByKey results
returns every key.
**Why this works:** Partitioner equality is what partitionBy, CoGroupedRDD
and the other co-partitioning checks use to decide that two RDDs already place
every key in the same partition. getPartition depends only on the bounds, the
ascending flag and the ordering, so comparing all three makes equality imply
the same routing. Partitioners that share an ordering instance, such as the
default Ordering object of a key type, keep comparing equal, so the shuffles
that the stable bounds let these operations skip stay skipped.
**Scope:** Make RangePartitioner equality also compare the orderings, with a
regression test.
**Compatibility:** Partitioners that share an ordering instance, including
every partitioner built with a key type's default ordering, compare as they do
with the PR, so co-partitioned operations over identical inputs keep skipping
the shuffles they do not need.
**Risks:** Range partitioners whose orderings are separate but equivalent
instances without their own equals, such as two Ordering.by results or the
Comparator-backed orderings that JavaPairRDD.sortByKey builds on each call,
stop comparing equal, so partitionBy and the co-partitioned operations between
them shuffle again. On the base branch such partitioners compared equal only
when their bounds happened to coincide, as for inputs small enough to be
sampled whole, so this costs a shuffle that the base branch also ran for most
inputs. The stricter equality is not behind a flag.
**Constraints:** Keep the stable seeds and the legacy flag as they are; the
fix belongs in equality, not in the sampling. Keep hashCode consistent with
equals; leaving it unchanged is enough, since partitioners that stay equal
still have equal bounds and ascending flags.
**Success:** Two RangePartitioners compare equal only when their bounds,
ascending flags and orderings are equal. Partitioners built over the same data
under an ordering and under its reverse compare unequal even when their bounds
coincide, and joining the two sortByKey results returns every matching row.
Partitioners built over the same data with the same default ordering still
compare equal, as the PR's stable-bounds test asserts.
**Verification:**
- **Regression:** Add a PartitioningSuite test that builds RangePartitioners
with equal bounds and ascending flags but different orderings, such as the
default Ordering[Int] and its reverse with two output partitions over the same
odd number of distinct keys, asserts that they compare unequal, and asserts
that joining the two sortByKey results returns every key.
- **Compatibility:** Run the RangePartitioner equality test and the PR's
stable-bounds test in PartitioningSuite and confirm that partitioners built
with the same default ordering still compare equal.
##########
docs/sql-migration-guide.md:
##########
@@ -29,6 +29,7 @@ license: |
## Upgrading from Spark SQL 4.3 to 4.4
+- Since Spark 4.4, the range bounds of a global sort no longer depend on an
internal RDD id, so a `TABLESAMPLE ... REPEATABLE` (or a seeded
`Dataset.sample`) over an `ORDER BY` returns the same rows on every execution
when the input data, its partitioning and the sort order of its rows are
unchanged. Rows that tie on the sort key can still change which rows are
sampled: they map to the same range partition, but their relative order within
it can change which rows a seeded sample selects. Range partition boundaries,
and so which partition or output file a row lands in, can differ from earlier
versions. To restore the previous behavior, set
`spark.rdd.rangePartitioner.legacyRddIdSeed` to `true`.
Review Comment:
**Non-blocking (P2):** Reading the code, this promise needs one more
condition: the sort's post-shuffle partitions must also be the same. A global
sort's range shuffle is coalesced by adaptive execution, and with
`spark.sql.adaptive.coalescePartitions.parallelismFirst` at its default `true`
the coalescing rule sizes partitions from the SparkContext's default
parallelism, which on a cluster is the number of registered cores unless
`spark.default.parallelism` is set. `SampleExec` seeds each partition with the
seed plus the partition index, so for a shuffle of roughly 1 MB to 64 MB per
core, two runs with different core counts, for example under dynamic
allocation, group the same range partitions differently and sample different
rows although the input is unchanged. The new SQL tests turn coalescing off, so
they do not show this. The note could name this condition and the settings that
remove it: `spark.default.parallelism` set when the application starts (setting
it with `SET` does
not reach the SparkContext), or
`spark.sql.adaptive.coalescePartitions.parallelismFirst` set to `false`.
See **Shared repair plan 1** in the review body.
##########
docs/sql-migration-guide.md:
##########
@@ -29,6 +29,7 @@ license: |
## Upgrading from Spark SQL 4.3 to 4.4
+- Since Spark 4.4, the range bounds of a global sort no longer depend on an
internal RDD id, so a `TABLESAMPLE ... REPEATABLE` (or a seeded
`Dataset.sample`) over an `ORDER BY` returns the same rows on every execution
when the input data, its partitioning and the sort order of its rows are
unchanged. Rows that tie on the sort key can still change which rows are
sampled: they map to the same range partition, but their relative order within
it can change which rows a seeded sample selects. Range partition boundaries,
and so which partition or output file a row lands in, can differ from earlier
versions. To restore the previous behavior, set
`spark.rdd.rangePartitioner.legacyRddIdSeed` to `true`.
Review Comment:
**Nit (P3):** This key is a core SparkConf entry that `RangePartitioner`
reads from `rdd.sparkContext.conf`, so it only takes effect when set as the
application starts. A SQL reader who runs `SET
spark.rdd.rangePartitioner.legacyRddIdSeed=true`, or `spark.conf.set` from a
classic or Spark Connect session, gets `CANNOT_MODIFY_CONFIG`, and a builder on
an existing session ignores it with only a generic warning, so on a Spark
Connect or Thrift server the rollback means restarting the server with the key.
Other entries in this guide say how to set such a setting when their subject
does not make it obvious, for example 'set the static configuration
`spark.sql.dataSource.native.enabled`'. A sentence such as 'This is a Spark
configuration that must be set when the application starts, for example with
`--conf`; it cannot be changed with `SET`.' would make the instruction usable.
**Verification:**
- **Inspection:** Read the note's restore instruction and confirm it tells a
SQL reader to set the configuration at application launch rather than with SET
or spark.conf.set.
##########
core/src/main/scala/org/apache/spark/internal/config/package.scala:
##########
@@ -2934,6 +2934,17 @@ package object config {
.checkValue(_ >= 0, "needs to be a non-negative value")
.createWithDefault(0)
+ private[spark] val LEGACY_RANGE_PARTITIONER_RDD_ID_SEED =
+ ConfigBuilder("spark.rdd.rangePartitioner.legacyRddIdSeed")
+ .internal()
+ .doc("When true, RangePartitioner seeds the samples that pick its range
bounds with the " +
+ "RDD id, so the bounds of the same data can change on every execution.
When false, the " +
+ "seeds depend only on the partition index.")
Review Comment:
**Nit (P3):** Only the reservoir sketch is seeded by the partition index.
The re-sample of oversized partitions passes the constant `byteswap32(-1)` to
`sample`, and `PartitionwiseSampledRDD` hands each re-sampled partition the
next draw from that seed's `Random`, so its seed depends on its rank among the
re-sampled partitions: with partitions 2 and 5 re-sampled, partition 5 gets the
second draw, and with only 5, the first. The bounds still repeat for the same
input, so a sentence that holds for both samplers could be:
```suggestion
"seeds do not depend on the RDD id, so the same input gets the same
bounds every time.")
```
**Verification:**
- **Inspection:** Read the new config's doc and confirm that its description
of the false value holds for the sketch's per-partition seeds and for the
re-sample's seeds, which follow a constant and the partition's rank among the
re-sampled partitions.
##########
core/src/main/scala/org/apache/spark/internal/config/package.scala:
##########
@@ -2934,6 +2934,17 @@ package object config {
.checkValue(_ >= 0, "needs to be a non-negative value")
.createWithDefault(0)
+ private[spark] val LEGACY_RANGE_PARTITIONER_RDD_ID_SEED =
+ ConfigBuilder("spark.rdd.rangePartitioner.legacyRddIdSeed")
Review Comment:
**Nit (P3):** The config naming guideline in `ConfigEntry.scala` asks a
boolean config to be a verb that says what `true` does
(`spark.shuffle.sort.useRadixSort`), as the core legacy flags
`spark.locality.wait.legacyResetOnTaskLaunch` and
`spark.scheduler.stage.legacyAbortAfterKillTasks` are, while `legacyRddIdSeed`
names a thing. Once 4.4 ships this key is the documented restore path, so a
later rename needs an alternative key; renaming it now only touches this line,
the migration note and the PR description, because `RangePartitioner` and both
tests read it through `LEGACY_RANGE_PARTITIONER_RDD_ID_SEED`. For example:
```suggestion
ConfigBuilder("spark.rdd.rangePartitioner.legacySeedWithRddId")
```
**Verification:**
- **Inspection:** Search the repository for the old key string and confirm
no reference remains, and that RangePartitioner and both tests still read the
flag through the unchanged config constant.
##########
sql/core/src/test/scala/org/apache/spark/sql/SQLQuerySuite.scala:
##########
@@ -5401,6 +5402,49 @@ class SQLQuerySuite extends SharedSparkSession with
AdaptiveSparkPlanHelper
Seq(Row(0), Row(1), Row(2)))
}
}
+
+ // Runs a REPEATABLE sample over ORDER BY twice, and once as a CTE read
twice in one query.
+ private def repeatableSampleOverOrderBy(): (Set[Long], Set[Long], Long) = {
+ var result: (Set[Long], Set[Long], Long) = null
+ withTable("t") {
+ spark.range(0, 20000, 1, 4).selectExpr("id AS k", "concat('v', id) AS v")
+ .write.format("parquet").saveAsTable("t")
+ withSQLConf(
+ SQLConf.SHUFFLE_PARTITIONS.key -> "4",
+ SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+ SQLConf.RANGE_EXCHANGE_SAMPLE_SIZE_PER_PARTITION.key -> "100") {
+ val sampled = "(SELECT * FROM (SELECT * FROM t ORDER BY k) " +
+ "TABLESAMPLE (10 PERCENT) REPEATABLE (42))"
+ def run(): Set[Long] = sql(s"SELECT k FROM
$sampled").collect().map(_.getLong(0)).toSet
+ val leftover = sql(s"WITH s AS $sampled SELECT count(*) FROM " +
+ "(SELECT k FROM s EXCEPT SELECT k FROM s WHERE v IS NOT
NULL)").head().getLong(0)
+ result = (run(), run(), leftover)
+ }
+ }
+ result
+ }
+
+ test("SPARK-61561: TABLESAMPLE REPEATABLE over ORDER BY returns the same
rows " +
+ "on every execution") {
+ val (first, second, leftover) = repeatableSampleOverOrderBy()
+ assert(first.size > 1000 && first.size < 3000)
+ assert(first === second && leftover === 0L)
+ }
+
+ test("SPARK-61561: TABLESAMPLE REPEATABLE over ORDER BY returns the same
rows on every " +
+ "execution (gate off reproduces the bug)") {
Review Comment:
**Nit (P3):** The main clause says the rows are the same on every execution,
but the test turns the legacy flag on and asserts `first !== second` and
`leftover > 0L`; 'gate off' also reads as the flag being `false`. A legacy-path
failure would be reported as if the fix had failed, and since the positive
test's whole name is a prefix of this one, `-z` with the positive test's name
runs both. For example:
```suggestion
test("SPARK-61561: with the legacy RDD-id seed on, TABLESAMPLE REPEATABLE
over ORDER BY " +
"can return different rows across executions") {
```
**Verification:**
- **Inspection:** Read the two new test names and confirm each describes the
outcome its assertions check, and that the positive test's phrase no longer
matches the legacy test's name.
##########
sql/core/src/test/scala/org/apache/spark/sql/SQLQuerySuite.scala:
##########
@@ -5401,6 +5402,49 @@ class SQLQuerySuite extends SharedSparkSession with
AdaptiveSparkPlanHelper
Seq(Row(0), Row(1), Row(2)))
}
}
+
+ // Runs a REPEATABLE sample over ORDER BY twice, and once as a CTE read
twice in one query.
+ private def repeatableSampleOverOrderBy(): (Set[Long], Set[Long], Long) = {
+ var result: (Set[Long], Set[Long], Long) = null
+ withTable("t") {
+ spark.range(0, 20000, 1, 4).selectExpr("id AS k", "concat('v', id) AS v")
+ .write.format("parquet").saveAsTable("t")
+ withSQLConf(
+ SQLConf.SHUFFLE_PARTITIONS.key -> "4",
+ SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+ SQLConf.RANGE_EXCHANGE_SAMPLE_SIZE_PER_PARTITION.key -> "100") {
+ val sampled = "(SELECT * FROM (SELECT * FROM t ORDER BY k) " +
+ "TABLESAMPLE (10 PERCENT) REPEATABLE (42))"
+ def run(): Set[Long] = sql(s"SELECT k FROM
$sampled").collect().map(_.getLong(0)).toSet
+ val leftover = sql(s"WITH s AS $sampled SELECT count(*) FROM " +
+ "(SELECT k FROM s EXCEPT SELECT k FROM s WHERE v IS NOT
NULL)").head().getLong(0)
+ result = (run(), run(), leftover)
+ }
+ }
+ result
+ }
+
+ test("SPARK-61561: TABLESAMPLE REPEATABLE over ORDER BY returns the same
rows " +
+ "on every execution") {
+ val (first, second, leftover) = repeatableSampleOverOrderBy()
+ assert(first.size > 1000 && first.size < 3000)
+ assert(first === second && leftover === 0L)
+ }
+
+ test("SPARK-61561: TABLESAMPLE REPEATABLE over ORDER BY returns the same
rows on every " +
+ "execution (gate off reproduces the bug)") {
+ val conf = spark.sparkContext.conf
+ val key = LEGACY_RANGE_PARTITIONER_RDD_ID_SEED.key
+ val prior = conf.getOption(key)
+ conf.set(key, "true")
+ try {
+ val (first, second, leftover) = repeatableSampleOverOrderBy()
+ assert(first !== second)
+ assert(leftover > 0L)
+ } finally {
+ prior.fold(conf.remove(key))(conf.set(key, _))
+ }
Review Comment:
**Nit (P3):** `withSparkContextConf` in `QueryTest.scala`, which this suite
inherits through `SharedSparkSession`, does exactly this capture, set and
restore-or-remove for configs that must be set on the SparkContext, and other
`sql/core` suites use it, so this block duplicates setup that would have to be
kept in sync. For example:
```suggestion
withSparkContextConf(LEGACY_RANGE_PARTITIONER_RDD_ID_SEED.key -> "true")
{
val (first, second, leftover) = repeatableSampleOverOrderBy()
assert(first !== second)
assert(leftover > 0L)
}
```
**Verification:**
- **Behavior:** Run the edited legacy-mode test and confirm it still
observes different rows across executions and across the two CTE reads with the
flag on, and that the SparkContext conf has its prior value for the key
afterwards.
- **Inspection:** Confirm the test no longer reads, sets or restores the
SparkContext conf by hand.
--
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]