Skip to content

Commit 9dff80a

Browse files
peter-tothdongjoon-hyun
authored andcommitted
[SPARK-59176][4.2][SQL] Fix a storage-partitioned join that fails when one side reduced onto no key
### What changes were proposed in this pull request? `EnsureRequirements` leaves a side out of the comparison of the two sides' reduced key types when that side has no partition key and its expressions no longer describe the keys it would have had. The types then come from a side that does answer for them. `KeyedPartitioning.keyDataTypes` reports the types the partition key rows were built with. With no key row to read, it falls back to the partition expressions' own types. That is still the right answer while the expressions describe the keys, and a join that reduced both sides' keys leaves expressions that do not (`TransformExpression.reducedWith`, SPARK-59121). Only then is the fallback a type no key of that partitioning would hold, and only then must a caller keep it out of a comparison against a real answer. An empty side that nothing reduced stays in the comparison, which is what keeps the comparison doing its other job. Where one side has a reducer, it holds the connector's `Reducer.resultType()` against the paired transform, and that needs no key row. The `keyDataTypes` scaladoc states the rule the fix follows, in place of the paragraph that described the failure and pointed here. ### Why are the changes needed? A storage-partitioned join whose two legs each reduced both of their sides onto one key space is co-partitioned, and joins without a shuffle. If a leg ends up with no partition key at all, the query fails instead. `v2BucketingPartitionFilterEnabled` produces such a leg whenever its two sides hold disjoint keys, i.e. whenever that leg is empty. SELECT coalesce(l.ts, r.ts) FROM (SELECT d.ts FROM days1 d JOIN years1 y ON y.ts = d.ts) l JOIN (SELECT y.ts FROM days2 d JOIN years2 y ON y.ts = d.ts) r ON l.ts = r.ts With `days2` and `years2` holding disjoint years, and `days` and `years` reducing onto a common `LongType` year key: [STORAGE_PARTITION_JOIN_INCOMPATIBLE_REDUCED_TYPES] Storage-partition join partition transforms produced incompatible reduced types, left reducers: [] returned: ["BIGINT"], right reducers: [] returned: ["INT"]. SQLSTATE: 42K09 Both reducer lists are empty, which is the sign that there was nothing left to reduce and nothing to compare. `INT` is the `years` transform's own result type, not a type any key row holds. ### Does this PR introduce _any_ user-facing change? Yes. The query above returns its result instead of failing. Only unreleased versions are affected: the failure is reachable through SPARK-59121, and before that the same shape failed on a `ClassCastException` from applying the reduce a second time. ### How was this patch tested? Two new `KeyGroupedPartitioningSuite` tests. The first covers the shape above in both join orders, since the side to leave out can be either one, and with both an inner and a full outer join. The inner join intersects the two key sets to nothing and so has nothing to sort, while the full outer join keeps the other side's keys and sorts them by the reported types, which is what makes those types matter. Each part of the fix fails this test on its own when disabled. The second covers an empty side that is not marked, to pin that it stays in the comparison. A one-side `days` -> `years` reduce whose `years` side is emptied by an upstream inner join under the partition filter, against a reducer returning `DateType` where the target transform is `IntegerType`, still raises `STORAGE_PARTITION_JOIN_INCOMPATIBLE_REDUCED_TYPES`. ### Was this patch authored or co-authored using generative AI tooling? Generated-by: Claude Code (Opus 5) #### Backport to branch-4.2 A cherry-pick of #58486's two commits, squashed, with **one line tailored**: the config is named `V2_BUCKETING_ALLOW_JOIN_KEYS_SUBSET_OF_PARTITION_KEYS` on this branch, not `V2_BUCKETING_ALLOW_KEYS_SUBSET_OF_PARTITION_KEYS`. Nothing else differs from the `branch-4.3` backport. Measured on the branch tip: `SPARK-59176: a leg reduced onto no key at all still joins` fails there with `STORAGE_PARTITION_JOIN_INCOMPATIBLE_REDUCED_TYPES`, the same shape as on master, so the branch is affected. The precondition is present: SPARK-59121 reached `branch-4.2` as #58482. 172 tests green across `KeyGroupedPartitioningSuite`, `GroupPartitionsExecSuite` and `EnsureRequirementsSuite`, plus 12 in `ShuffleSpecSuite`. `dev/lint-scala` clean. Closes #58500 from peter-toth/SPARK-59176-reduced-key-types-no-key-4.2. Authored-by: Peter Toth <peter.toth@gmail.com> Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>
1 parent fcd6894 commit 9dff80a

3 files changed

Lines changed: 119 additions & 29 deletions

File tree

‎sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -457,17 +457,18 @@ case class KeyedPartitioning(
457457
*
458458
* The two cases can meet, and then the fallback is not truthful. A marked partitioning can end up
459459
* with no key, for instance when `v2BucketingPartitionFilterEnabled` intersects two sides that
460-
* hold disjoint keys, and it then reports the un-reduced transform's type while the other leg of
461-
* the same pairing reports the reducer's. `EnsureRequirements`' reduced-types check compares the
462-
* two and fails a query whose result is empty. The same query fails on a `ClassCastException`
463-
* without this marker, so nothing regresses. SPARK-59176 tracks the fix, which needs the
464-
* reducer's result type recorded where the key is missing.
460+
* hold disjoint keys, and this then reports the un-reduced transform's type. What it reports is a
461+
* fact about the key rows, so with no key row there is no fact, and a caller must not hold the
462+
* fallback against a real answer. The reduced-types comparison in `EnsureRequirements` leaves out
463+
* a marked side that has no key for that reason (SPARK-59176). An unmarked one still answers,
464+
* since its expressions describe the keys it would have had, and stays in the comparison.
465465
*
466466
* `ShuffleExchangeExec` is the one reader that stays on `expressionDataTypes`. It evaluates the
467467
* expressions to place the other child's rows, and it runs on executors, where this value is not
468468
* available. `expressionsDescribeKeys` is what keeps that site sound.
469469
*
470-
* Only the first key's types are read, and nothing enforces that the rest match.
470+
* Only the first key's types are read, and nothing enforces that the rest match. SPARK-59187 is
471+
* to carry the types on the partitioning instead of sampling a key row.
471472
*/
472473
@transient lazy val keyDataTypes: Seq[DataType] =
473474
partitionKeys.headOption.map(_.dataTypes).getOrElse(expressionDataTypes)

‎sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -561,7 +561,20 @@ case class EnsureRequirements(
561561
val (rightReducedDataTypes, rightReducedKeys) = rightReducers.fold(
562562
(rightPartitioning.keyDataTypes, rightPartitioning.partitionKeys)
563563
)(rightPartitioning.reduceKeys)
564-
val reducedDataTypes = if (leftReducedDataTypes == rightReducedDataTypes) {
564+
// The reduced types are the types of the key rows the merge below sees. A side with no key
565+
// still answers for them while its expressions describe the keys it would have had, and
566+
// `keyDataTypes` falls back to exactly those types. After a reduce the expressions no
567+
// longer describe them, so the fallback is a type no key of that partitioning would hold,
568+
// and comparing it against a real answer fails a co-partitioned query (SPARK-59176). Only
569+
// such a side is left out. An empty one that is not marked stays in, which is what keeps
570+
// the comparison checking a reducer's result type against the paired transform.
571+
val leftTypesDescribeKeys =
572+
leftReducedKeys.nonEmpty || leftPartitioning.expressionsDescribeKeys
573+
val rightTypesDescribeKeys =
574+
rightReducedKeys.nonEmpty || rightPartitioning.expressionsDescribeKeys
575+
val reducedDataTypes = if (!leftTypesDescribeKeys) {
576+
rightReducedDataTypes
577+
} else if (!rightTypesDescribeKeys || leftReducedDataTypes == rightReducedDataTypes) {
565578
leftReducedDataTypes
566579
} else {
567580
throw QueryExecutionErrors.storagePartitionJoinIncompatibleReducedTypesError(

‎sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala‎

Lines changed: 98 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -325,20 +325,35 @@ class KeyGroupedPartitioningSuite extends DistributionAndOrderingSuiteBase with
325325
"JOIN testcat.ns.bucket8 b8 ON b12.id = b8.id " +
326326
s"JOIN testcat.ns.bucket$third b ON b12.id = b.id")
327327

328+
/** The `(id, ts)` rows the `withReducedTsJoinLegs` tables are filled from, one per year. */
329+
private val row2020 = "(0, cast('2020-01-01' as timestamp))"
330+
private val row2021 = "(1, cast('2021-01-03' as timestamp))"
331+
private val bothRows = s"$row2020, $row2021"
332+
333+
/** The timestamps those rows hold, as a query over them reports them. */
334+
private val ts2020 = Row(Timestamp.valueOf("2020-01-01 00:00:00"))
335+
private val ts2021 = Row(Timestamp.valueOf("2021-01-03 00:00:00"))
336+
private val bothTimestamps = Seq(ts2020, ts2021)
337+
328338
/**
329339
* Creates `days1` and `days2` partitioned by `days(ts)` and `years1` and `years2` by `years(ts)`,
330340
* all over `(id, ts)`, with the `toYears`-reducing `days` and `years` functions registered.
331-
* `leg1Values` goes into `days1` and `years1`, `leg2Values` into `days2` and `years2`.
341+
* `leg1Values` goes into `days1` and `years1`, `leg2Values` into `days2` and `years2`, unless
342+
* `leg2YearsValues` puts something else into `years2`.
332343
*/
333-
private def withReducedTsJoinLegs(leg1Values: String, leg2Values: String)(body: => Unit): Unit = {
344+
private def withReducedTsJoinLegs(
345+
leg1Values: String,
346+
leg2Values: String,
347+
leg2YearsValues: Option[String] = None)(body: => Unit): Unit = {
334348
withFunction(
335349
UnboundDaysFunctionWithToYearsReducerWithLongResult,
336350
UnboundYearsFunctionWithToYearsReducerWithLongResult) {
337351
val tsColumns = Array(
338352
Column.create("id", LongType),
339353
Column.create("ts", TimestampType))
340354
Seq(("days1", leg1Values, days("ts")), ("days2", leg2Values, days("ts")),
341-
("years1", leg1Values, years("ts")), ("years2", leg2Values, years("ts"))).foreach {
355+
("years1", leg1Values, years("ts")),
356+
("years2", leg2YearsValues.getOrElse(leg2Values), years("ts"))).foreach {
342357
case (table, values, partition) =>
343358
createTable(table, tsColumns, Array(partition))
344359
sql(s"INSERT INTO testcat.ns.$table VALUES $values")
@@ -350,16 +365,16 @@ class KeyGroupedPartitioningSuite extends DistributionAndOrderingSuiteBase with
350365

351366
/**
352367
* Joins `days1` to `years1` and `days2` to `years2`, each reducing both of its sides onto the
353-
* year key space, then joins the two reduced legs to each other.
368+
* year key space, then joins the two reduced legs to each other with `joinType`. `leg2First` puts
369+
* the second leg on the left of that join. The projection takes the timestamp from whichever side
370+
* has it, so an outer join reports the same rows in either order.
354371
*/
355-
private val reducedTsLegJoin =
356-
"""
357-
|SELECT l.ts FROM
358-
| (SELECT d.ts FROM testcat.ns.days1 d JOIN testcat.ns.years1 y ON y.ts = d.ts) l
359-
| JOIN
360-
| (SELECT y.ts FROM testcat.ns.days2 d JOIN testcat.ns.years2 y ON y.ts = d.ts) r
361-
| ON l.ts = r.ts
362-
|""".stripMargin
372+
private def reducedTsLegJoin(leg2First: Boolean = false, joinType: String = "JOIN"): String = {
373+
val leg1 = "SELECT d.ts FROM testcat.ns.days1 d JOIN testcat.ns.years1 y ON y.ts = d.ts"
374+
val leg2 = "SELECT y.ts FROM testcat.ns.days2 d JOIN testcat.ns.years2 y ON y.ts = d.ts"
375+
val (left, right) = if (leg2First) (leg2, leg1) else (leg1, leg2)
376+
s"SELECT coalesce(l.ts, r.ts) AS ts FROM ($left) l $joinType ($right) r ON l.ts = r.ts"
377+
}
363378

364379
private def testWithCustomersAndOrders(
365380
customers_partitions: Array[Transform],
@@ -767,9 +782,7 @@ class KeyGroupedPartitioningSuite extends DistributionAndOrderingSuiteBase with
767782
}
768783

769784
test("SPARK-59121: two sides reduced together are not reduced a second time") {
770-
val both = "(0, cast('2020-01-01' as timestamp)), (1, cast('2021-01-03' as timestamp))"
771-
val one = "(1, cast('2021-01-03' as timestamp))"
772-
withReducedTsJoinLegs(both, one) {
785+
withReducedTsJoinLegs(bothRows, row2021) {
773786
// Both inner joins reduce onto the year key space, and the two legs hold different key sets,
774787
// so the outer join takes the path that pushes the common keys down and computes reducers.
775788
// The two legs are the same pairing, so they are compatible and there is nothing left to
@@ -779,7 +792,7 @@ class KeyGroupedPartitioningSuite extends DistributionAndOrderingSuiteBase with
779792
SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
780793
SQLConf.V2_BUCKETING_ALLOW_JOIN_KEYS_SUBSET_OF_PARTITION_KEYS.key -> "true",
781794
SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
782-
checkAnswer(sql(reducedTsLegJoin), Seq(Row(Timestamp.valueOf("2021-01-03 00:00:00"))))
795+
checkAnswer(sql(reducedTsLegJoin()), Seq(ts2021))
783796
}
784797
}
785798
}
@@ -882,8 +895,7 @@ class KeyGroupedPartitioningSuite extends DistributionAndOrderingSuiteBase with
882895
}
883896

884897
test("SPARK-59121: two sides reduced onto the same keys still join without a shuffle") {
885-
val values = "(0, cast('2020-01-01' as timestamp)), (1, cast('2021-01-03' as timestamp))"
886-
withReducedTsJoinLegs(values, values) {
898+
withReducedTsJoinLegs(bothRows, bothRows) {
887899
// Each inner join reduces both of its sides onto the year key space, and the projections keep
888900
// one reduced partitioning per side. Refusing to compare reduced keys must not go so far as
889901
// to refuse these two. They came out of the same pairing, so they carry the same keys and
@@ -892,17 +904,81 @@ class KeyGroupedPartitioningSuite extends DistributionAndOrderingSuiteBase with
892904
SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
893905
SQLConf.V2_BUCKETING_ALLOW_JOIN_KEYS_SUBSET_OF_PARTITION_KEYS.key -> "true",
894906
SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
895-
val df = sql(reducedTsLegJoin)
907+
val df = sql(reducedTsLegJoin())
896908

897-
checkAnswer(df, Seq(
898-
Row(Timestamp.valueOf("2020-01-01 00:00:00")),
899-
Row(Timestamp.valueOf("2021-01-03 00:00:00"))))
909+
checkAnswer(df, bothTimestamps)
900910
val plan = stripAQEPlan(df.queryExecution.executedPlan)
901911
assert(collectShuffles(plan).isEmpty, "should not add shuffle for any of the three joins")
902912
}
903913
}
904914
}
905915

916+
test("SPARK-59176: a leg reduced onto no key at all still joins") {
917+
withReducedTsJoinLegs(bothRows, row2020, leg2YearsValues = Some(row2021)) {
918+
// The second leg's two sides hold disjoint years, so the partition filter intersects them to
919+
// nothing and the leg reports a reduced partitioning with no key. The reduced types then have
920+
// to come from the first leg. The marked expressions still name the un-reduced `days` and
921+
// `years` transforms, whose types are not the `LongType` the reduced keys hold.
922+
withSQLConf(
923+
SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
924+
SQLConf.V2_BUCKETING_PARTITION_FILTER_ENABLED.key -> "true",
925+
SQLConf.V2_BUCKETING_ALLOW_JOIN_KEYS_SUBSET_OF_PARTITION_KEYS.key -> "true",
926+
SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
927+
// Both orders, since the side that has no key is the one to leave out of the comparison.
928+
// And both join types, since the inner join intersects the two key sets to nothing and so
929+
// has nothing to sort, while the full outer join keeps the other side's keys and sorts them
930+
// by the reported types.
931+
Seq("JOIN" -> Nil, "FULL OUTER JOIN" -> bothTimestamps).foreach {
932+
case (joinType, expected) =>
933+
Seq(false, true).foreach { leg2First =>
934+
val df = sql(reducedTsLegJoin(leg2First, joinType))
935+
936+
checkAnswer(df, expected)
937+
assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).isEmpty,
938+
"the two legs are the same pairing, so all three joins are co-partitioned")
939+
}
940+
}
941+
}
942+
}
943+
}
944+
945+
test("SPARK-59176: an empty side whose expressions describe its keys keeps the reducer check") {
946+
withFunction(UnboundDaysFunctionWithToYearsReducerWithDateResult) {
947+
createTable(items, itemsColumns, Array(days("arrive_time")))
948+
sql(s"INSERT INTO testcat.ns.$items VALUES " +
949+
s"(0, 'aa', 39.0, cast('2020-01-01' as timestamp))")
950+
951+
Seq(purchases -> "2020-01-01", "purchases2" -> "2022-01-01").foreach {
952+
case (table, day) =>
953+
createTable(table, purchasesColumns, Array(years("time")))
954+
sql(s"INSERT INTO testcat.ns.$table VALUES (1, 42.0, cast('$day' as timestamp))")
955+
}
956+
957+
// The inner join intersects two disjoint year key sets, so its leg reports a `years(time)`
958+
// partitioning with no key. Nothing reduced it, so its expressions still describe the keys it
959+
// would have had, and the reduced-types comparison must still run. This `days` function
960+
// breaks the reducer contract, returning `DateType` where the target `years` transform is
961+
// `IntegerType`, and that is what the comparison is there to catch.
962+
withSQLConf(
963+
SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
964+
SQLConf.V2_BUCKETING_PARTITION_FILTER_ENABLED.key -> "true",
965+
SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
966+
val e = intercept[SparkException] {
967+
sql(
968+
s"""
969+
|${selectWithMergeJoinHint("i", "e")} i.id
970+
|FROM testcat.ns.$items i
971+
|JOIN (SELECT p.time FROM testcat.ns.$purchases p
972+
| JOIN testcat.ns.purchases2 p2 ON p2.time = p.time) e
973+
|ON e.time = i.arrive_time
974+
|""".stripMargin).collect()
975+
}
976+
assert(e.getMessage.contains(
977+
"Storage-partition join partition transforms produced incompatible reduced types"))
978+
}
979+
}
980+
}
981+
906982
test("partitioned join: join with two partition keys and matching & sorted partitions") {
907983
val items_partitions = Array(bucket(8, "id"), days("arrive_time"))
908984
createTable(items, itemsColumns, items_partitions)

0 commit comments

Comments
 (0)