Repository navigation
Conversation
szehon-ho
left a comment
There was a problem hiding this comment.
Thanks this is interesting. Initially I was thinking, the data source can have a config to group themselves. But it is true that previous to the SPJ refactor Spark did this even without SPJ case.
I'm ok with it. cc @peter-toth to take another look as well
|
Thanks for the PR, @rekbun. I'd rather not make the grouping logic more complex without a concrete case that needs it. Could you share which connector and what table layout you hit this with? The only connector I know of that reports If a scan doesn't need its
There are other ways to cut the number of tasks:
|
|
Thanks for the careful review, @peter-toth , and for the context on Iceberg. That is helpful. The source where we hit this is an in-house DataSource V2 connector for Hive-format bucketed tables. The tables are partitioned by hour and bucketed by a key, and the reported partitioning contains the bucket key, not the hour. The connector currently emits one input per bucket file to retain its per-file sort order. For example, with one file per bucket in each hourly partition, reading a day produces 24 inputs with the same reported key, and a week produces 168. Before the refactor, Spark grouped those inputs by key, so these scans ran one task per bucket. After it, in the affected queries that still require a downstream shuffle, each input can execute as a separate scan task. That increased task setup, execution, and scheduling overhead in existing production jobs, with higher driver memory pressure and longer runtimes. COALESCE is a valid workaround when placed before an existing shuffle. For restoring the historical task count, the bucket count provides a natural target. The difficulty is applying that workaround across existing queries and choosing suitable parallelism as data volume and skew change. Generic coalescing is not key-aware, and placing it between a scan and a consumer that relies on keyed partitioning can introduce an exchange. Size-aware packing using HasPartitionStatistics.sizeInBytes() is a promising longer-term direction for addressing both small tasks and oversized tasks for large or skewed keys. I would be glad to work on that with you. The opt-in would provide a compatibility option while that is developed. I take the point about complexity. I’ll narrow the PR to the default-off scan-grouping option, preserve required ordering and existing SPJ behavior, and keep unrelated planning changes separate. The public reproducer shows 48 scan tasks becoming two, with the same results and the required shuffle retained. Would that narrower scope address your concern? |
|
Thanks for the concrete case, that helps. One note on the pre-4.2 behavior: when a key had more than one split, 4.1 grouped them and dropped the scan's reported ordering ( Where a plan uses the scan's partitioning, like a storage-partitioned join or an aggregate on the bucket key, I'm not against a default-off option for this. Is the case below a shuffle the only one you need? If so, nothing there needs the splits grouped by key, since the shuffle redistributes the rows anyway. A coalesce placed where an exchange goes above the keyed scan would be enough, for example down to the scan's number of keys, which is the task count you had before 4.2. Placed only there, it can't break a consumer that relies on the keyed partitioning. Unlike grouping by key, it doesn't turn a key with many splits into one large task. It also wouldn't need the k-way merge handling, the The current head also changes two plans with the option on:
Neither shape has an exchange above the scan, so a coalesce only there would leave both alone. Separately, SPARK-55092 changed this behavior in 4.2 without a migration note. If we agree on the option, could you add one in this PR? It could describe the 4.2 change and point to the option. |
|
Thanks for reworking this into a coalesce below the shuffle, @rekbun. It is the shape I suggested, and it no longer touches the SPJ plans. Looking at it again, I'm not sure the key count is the right target, though:
File sources already handle this. So I'd rather go for a general option, independent of
Would that work for your connector, and would you be open to doing it in that form? Do its splits report their size, or would a count cap be enough? @dongjoon-hyun @cloud-fan @viirya @ulysses-you @LuciferYang @pan3793, I'm surprised Spark has no generic answer for small DSv2 splits. Did I miss one, or do you have other ideas? |
|
Thank you @peter-toth for the ping. V1 already had this problem, and it did not solve it with a task-count target. A bucketed
Concretely I see two directions. Both are gated by a plan-level decision about what the consumers rely on; they differ in who performs the regrouping. 1. Disable the keyed layout when it buys nothing. The timing is the awkward part: 2. Spark-side size-based re-sizing. The gate here is not "SPJ did not happen". Coalescing inside a partition, or inside a key group, keeps the keyed layout intact, so the same sizing can apply when SPJ is in effect; only a regrouping that crosses partition boundaries requires the layout to be unused, which is the case 1 gates on. With that distinction, Spark can size the stage from an interface that already exists, and @peter-toth and @szehon-ho have both pointed at it: |
|
Thanks, @peter-toth and @ulysses-you. Our inputs don’t implement HasPartitionStatistics today. The connector already has file lengths, so we can expose them. For this PR, I’d take the Spark-side sizing approach using that existing interface. It would cover unkeyed V2 scans too. I’d start with the cases Peter listed where the plan doesn’t use the scan’s partitioning or ordering, and pack inside the scan so partial aggregation benefits as well. I’ll keep it default-off and add the 4.2 migration note. |
|
I’ve updated the PR with the Spark-side size-based packing approach we discussed, keeping it default-off. I’ve also added the 4.2 migration note, regression tests and local comparisons with COALESCE. |
There was a problem hiding this comment.
Thanks for the rework, @rekbun!
This packs adjacent V2 batch scan inputs by HasPartitionStatistics.sizeInBytes() plus an opening cost, inside BatchScanExec, when no operator above the scan uses its partitioning or ordering. A packed scan stops claiming its keyed partitioning and ordering, and packs the runtime-filtered inputs at execution. It covers most of what we discussed in the thread, and the requirement walk looks right to me. The main gap is a plan materialized for reuse, which loses its keyed layout.
Blocking
- 1. A cached or checkpointed plan loses its keyed layout: the root of a plan being materialized has no consumer yet, so its scan is packed, and later queries that would use its
KeyedPartitioningshuffle instead.CacheManageralready turns off rules that change a cached plan's output partitioning, so packing belongs on that list. Measured with a one-line fix. inline - 2. The description is a history of the PR: it opens with "Replace the earlier key-count coalesce ... following the review discussion" and says "No new connector replanning API is introduced". Both describe earlier revisions and this thread, not the change against master.
dev/merge_spark_pr.pyturns the description into the commit message, so the measurement program and the trial tables would land there too. Please describe the change as it stands and move the measurements to a comment.
Non-blocking
- 3. Run packing as its own rule after
EnsureRequirements: asDisableUnnecessaryBucketedScandoes, instead of from insideEnsureRequirements.apply. I tried it on this head. inline - 4. The packing re-runs of the SPJ suites lose
@ExtendedSQLTest: the annotation is not inherited, so they run in the regularsqljob. inline - 5. Move the SPARK-55092 migration note to its own docs PR: it documents a 4.2 change, so it should reach
branch-4.2, where this PR's option does not exist. inline
Minor
- 6.
packstill handles pruned slots that no caller passes: theNonecase and its scaladoc sentence are dead since the last commit. inline - 7. The five new configs have no typed accessor:
PackV2ScanPartitionsreads them withconf.getConf(...). Their file-source counterparts have one each (filesMaxPartitionBytesand the others,SQLConf.scala:9443-9449). - 8. JIRA: SPARK-60265's summary still describes per-key grouping below shuffles, with component Optimizer. Please update it to the size-based packing.
|
|
||
| ## Upgrading from Spark SQL 4.1 to 4.2 | ||
|
|
||
| - Since Spark 4.2, V2 scans no longer unconditionally group input splits sharing a reported partition key into one task (SPARK-55092). Spark still groups splits when needed to satisfy a downstream distribution, such as for a storage-partitioned join. Other scans can execute one task per split, increasing overhead for connectors with many small splits per key. Before 4.2, grouping multiple splits also discarded their reported ordering. Spark 4.4 introduces the default-off `spark.sql.sources.v2.scanPartitionPacking.enabled` option to pack eligible batch V2 scan inputs by estimated size, with an explicit count fallback when sizes are unavailable. This policy is independent of partition keys and does not restore unconditional per-key grouping. See [DataSource V2 Scan Task Sizing](sql-performance-tuning.html#datasource-v2-scan-task-sizing) for its scope and tradeoffs. |
There was a problem hiding this comment.
Finding 5. This note documents a 4.2 behavior change, so 4.2.x users should find it in branch-4.2's migration guide. In this PR, which is a 4.4 feature, it only reaches branch-4.x and master, and its "Spark 4.4 introduces ..." sentence keeps it from being backported as written. Could the SPARK-55092 note go into a separate docs PR that can also be merged to branch-4.2? This PR then needs only the tuning section, since a new opt-in option needs no migration note. Also, the blank line after this bullet turns the whole section into a loose list.
There was a problem hiding this comment.
Done: removed here and moved to #59970 (SPARK-60763).
|
Moved from the PR description: local synthetic measurements of size-based packing against Local synthetic measurements against COALESCEThese use
The small uniform case performs similarly with a suitable COALESCE. In the skewed case, count-matched COALESCE places all four large inputs in one task; size packing leaves each oversized input separate. One-task COALESCE removes the exchange, while the default and packed cases retain the required exchange. These local timings illustrate the sizing tradeoff and do not establish production speedups. The measurement source and reproduction command are below. The generated CSV records trial ranges and every task's row count. Local measurement source, trial ranges and reproductionSave the source below as build/sbt -Phive \
'set LocalProject("sql") / Test / unmanagedSources += file("/tmp/ScanPackingMeasurements.scala")' \
'sql/Test/runMain org.apache.spark.sql.connector.ScanPackingMeasurements /tmp/scan-packing-measurements.csv'The SBT source setting applies only to that invocation. The fixture uses existing Spark test helpers and stays outside the PR source tree. It generates rows, with no storage IO. Five measured rounds follow two warmup rounds; case order is shuffled deterministically. A one-task COALESCE legitimately removes the exchange, and the reproducer checks that shape as well as complete answers.
package org.apache.spark.sql.connector
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
import java.util.OptionalLong
import scala.collection.mutable
import scala.util.Random
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.connector.catalog.Table
import org.apache.spark.sql.connector.expressions.FieldReference
import org.apache.spark.sql.connector.read._
import org.apache.spark.sql.connector.read.partitioning.{KeyGroupedPartitioning, Partitioning}
import org.apache.spark.sql.execution.CoalesceExec
import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.util.CaseInsensitiveStringMap
// Local synthetic measurements, outside the PR source tree. No file IO is simulated.
class ScanPackingMeasurementSource extends TestingV2Source {
override def getTable(options: CaseInsensitiveStringMap): Table = new SimpleBatchTable {
override def newScanBuilder(options: CaseInsensitiveStringMap): ScanBuilder =
new SimpleScanBuilder with SupportsReportPartitioning {
private val keys = options.get("keys").toInt
private val inputs = options.get("rows").split(",").zipWithIndex.map { case (rows, i) =>
ScanPackingMeasurementInput(i % keys, rows.toInt)
}
override def planInputPartitions(): Array[InputPartition] =
inputs.map(p => p: InputPartition)
override def outputPartitioning(): Partitioning =
new KeyGroupedPartitioning(Array(FieldReference("i")), inputs.length)
override def createReaderFactory(): PartitionReaderFactory =
ScanPackingMeasurementReaderFactory
}
}
}
case class ScanPackingMeasurementInput(key: Int, rows: Int)
extends HasPartitionStatistics with HasPartitionKey {
override def partitionKey(): InternalRow = InternalRow(key)
override def sizeInBytes(): OptionalLong = OptionalLong.of(rows.toLong * 16)
override def numRows(): OptionalLong = OptionalLong.of(rows)
override def filesCount(): OptionalLong = OptionalLong.empty()
}
object ScanPackingMeasurementReaderFactory extends PartitionReaderFactory {
override def createReader(input: InputPartition): PartitionReader[InternalRow] = {
val p = input.asInstanceOf[ScanPackingMeasurementInput]
new PartitionReader[InternalRow] {
private var row = -1
override def next(): Boolean = { row += 1; row < p.rows }
override def get(): InternalRow = InternalRow(p.key, row)
override def close(): Unit = {}
}
}
}
object ScanPackingMeasurements {
case class Scenario(name: String, keys: Int, rows: Seq[Int])
case class Variant(name: String, packing: Boolean, coalesce: Option[Int])
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder().master("local[4]")
.appName("SPARK-60265 local scan packing measurements")
.config("spark.ui.enabled", "false")
.config(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key, "false")
.config(SQLConf.SHUFFLE_PARTITIONS.key, "4")
.config(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key, "4MB")
.config(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES.key, "0")
.config(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM.key, "4")
.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
val out = mutable.ArrayBuffer.empty[String]
out += "scenario,variant,raw_inputs,scan_stage_tasks,shuffles,rows," +
"median_ms,min_ms,max_ms,task_rows"
try {
val scenarios = Seq(
Scenario("small_inputs", 8, Seq.fill(512)(128)),
Scenario("large_single_key", 1, Seq.fill(64)(65536)),
Scenario("skewed_inputs", 1, Seq.fill(32)(512) ++ Seq.fill(4)(524288)))
scenarios.foreach { scenario =>
def query(v: Variant): DataFrame = {
spark.conf.set(SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key, v.packing)
val loaded = spark.read.format(classOf[ScanPackingMeasurementSource].getName)
.option("keys", scenario.keys).option("rows", scenario.rows.mkString(",")).load()
val input = v.coalesce.map(loaded.coalesce).getOrElse(loaded)
input.groupBy((col("j") % 32).as("g"))
.agg(count(lit(1)).as("n"), sum("i").as("k"), sum("j").as("s"))
}
val packed = Variant("size_packing", true, None)
val initial = query(packed)
val packedScan = initial.queryExecution.executedPlan.collect {
case scan: BatchScanExec => scan
}.head
val packedCount = packedScan.inputRDD.getNumPartitions
val variants = Seq(
Variant("default", false, None), packed,
Variant("coalesce_matching_count", false, Some(packedCount)),
Variant("coalesce_key_count", false, Some(scenario.keys)))
val samples = mutable.Map.empty[String, Vector[Double]].withDefaultValue(Vector.empty)
var expected = Option.empty[Seq[Row]]
// Two warmup rounds, then five interleaved measured rounds with deterministic ordering.
for (round <- -2 until 5; variant <- new Random(42 + round).shuffle(variants)) {
val df = query(variant)
val started = System.nanoTime()
val answer = df.collect().toSeq.sortBy(_.getInt(0))
val elapsed = (System.nanoTime() - started) / 1000000.0
assert(answer.map(_.getLong(1)).sum == scenario.rows.map(_.toLong).sum)
expected.foreach(rows => assert(answer == rows))
expected = Some(answer)
val shuffles = df.queryExecution.executedPlan.collect {
case e: ShuffleExchangeExec => e
}.size
assert(shuffles == (if (variant.coalesce.contains(1)) 0 else 1))
if (round >= 0) samples(variant.name) = samples(variant.name) :+ elapsed
}
variants.foreach { variant =>
val df = query(variant)
df.collect()
val plan = df.queryExecution.executedPlan
val scan = plan.collect { case scan: BatchScanExec => scan }.head
val counts = plan.collect { case c: CoalesceExec => c }.headOption match {
case Some(c) => c.execute().mapPartitions(i => Iterator.single(i.size)).collect().toSeq
case None => scan.inputRDD.mapPartitions(i => Iterator.single(i.size)).collect().toSeq
}
assert(counts.map(_.toLong).sum == scenario.rows.map(_.toLong).sum)
val times = samples(variant.name).sorted
val shuffles = plan.collect { case e: ShuffleExchangeExec => e }.size
val line = Seq(scenario.name, variant.name, scenario.rows.size, counts.size, shuffles,
scenario.rows.map(_.toLong).sum, f"${times(times.size / 2)}%.3f",
f"${times.head}%.3f", f"${times.last}%.3f", counts.mkString(";")).mkString(",")
out += line
println("MEASUREMENT " + line.split(",").take(9).mkString(","))
}
}
Files.write(Paths.get(args(0)), (out.mkString("\n") + "\n")
.getBytes(StandardCharsets.UTF_8))
} finally {
spark.stop()
}
}
} |
|
Thanks @peter-toth. All points are addressed in 3231cce and 6718798, with follow-ups in 06a5b46, 56e153c and a020f22:
|
|
Thank you @rekbun, let me check this tomorrow. |
There was a problem hiding this comment.
Re-checked through a020f22: findings 1 to 8 are resolved, and nothing regressed. The new cached and checkpointed scan tests fail when packing is left on for those plans, so they pin finding 1. A few new points on the opt-in path remain.
Blocking
- 9. Packing plans every eligible scan's inputs while planning (late catch): the guard calls
planInputPartitions()on each candidate, which an unkeyed scan with a fixed columnar mode otherwise defers to execution (SPARK-44505). A scan with a runtime filter then also plans its whole table, twice with AQE. Packing every eligible scan and deciding the groups only ininputRDDavoids it. inline
Non-blocking
- 10. Every checkpoint is planned again once packing is on (new):
forCheckpointbuilds a secondQueryExecutioneven when no scan gets packed, and that execution refreshes versioned tables again. Re-planning only when a scan is packed avoids both. inline - 11. A V2 file scan takes the count fallback (late catch):
FilePartitionreports no size, so withmaxPartitionNum=2an 8-file Parquet scan runs as 2 tasks, ignoringspark.sql.files.maxPartitionBytes. inline
Minor
- 12. The new configs split the
spark.sql.sources.v2.bucketing.*block (late catch). inline - 13. The
minPartitionNumdefault repeatsSparkSession.leafNodeDefaultParallelism(late catch). inline - 14.
V2ScanPartitionCoalescerrepeatsGroupedPartitionCoalescer(late catch). inline - 15.
maxPartitionNumdoesn't mean whatspark.sql.files.maxPartitionNummeans (new): it applies only when a size is missing, so "mirroring the file source settings" in the description, which becomes the commit message, overstates it.
| def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = { | ||
| node match { | ||
| case scan: BatchScanExec if !needsPartitioning && !needsOrdering && | ||
| scan.partitionPacking.isEmpty && |
There was a problem hiding this comment.
Finding 11. FilePartition doesn't implement HasPartitionStatistics, so a V2 file scan always takes the count fallback in pack (V2ScanPartitionPacking.scala:47). A session that sets maxPartitionNum for an unsized connector then also re-chunks its Parquet and ORC scans by count. With spark.sql.sources.useV1SourceList empty, a Parquet scan of 8 files planned as 8 FilePartitions runs as 2 tasks of 40,000 rows with maxPartitionNum=2, ignoring spark.sql.files.maxPartitionBytes. spark.sql.files.* already sizes those scans, as it does V1 file scans, which this option leaves alone. Leaving FileScan out keeps them that way:
| scan.partitionPacking.isEmpty && | |
| scan.partitionPacking.isEmpty && !scan.scan.isInstanceOf[FileScan] && |
with FileScan in the datasources.v2 import. The same scan then runs 8 tasks.
There was a problem hiding this comment.
Done in dc626a7: FileScans are excluded, with your 8-file Parquet case as a test.
a020f22 to
dc626a7
Compare
|
Thanks for the careful review, @peter-toth. All seven points are addressed in 9. Planning: The rule now only marks eligible scans; 10. Checkpoints: A checkpoint no longer builds a second logical, optimized, or physical plan. When packing withdrew 11. V2 file scans: 12. Config placement: The five configs now follow 13. Default: The minimum count uses 14. Coalescer: Packed scans now use 15. Description: "Mirroring" is removed, and the description now states the exact relationship to the file-source |
There was a problem hiding this comment.
Re-checked through dc626a7: findings 9 to 15 are resolved, and nothing regressed. With packing on, the DPP probe from finding 9 now plans its scan once, at execution, with the 2 inputs DPP keeps. That matches packing off, with AQE on and off.
This round I also looked at the design again, against what Spark already does for similar features. Findings 17 and 18 come from that. Following those features is more limited in places, but it keeps the logic simpler. The rest can come back later if someone needs it.
Blocking
- 16. The
GroupedPartitionCoalescerchanges need a ticket and PR of their own (new): keeping the groups out of the task binary and the new location choice also change the coalescer storage-partitioned joins use, which is an improvement of its own. Could you move them to a separate improvement ticket and PR that lands before this one? inline - 17.
maxPartitionNumdoes not cap a scan whose inputs all report sizes (late catch):spark.sql.files.maxPartitionNumcaps every file scan, but this config caps only a scan with an input that reports no size. With 8 sized inputs andmaxPartitionNum=2, the V2 scan runs 8 tasks, while a Parquet scan drops from 36 partitions to 3 under the files cap. Giving it the files meaning on both paths is a few lines inpack. inline - 18. Keeping the root's layout goes further than Spark's similar rule (new):
DisableUnnecessaryBucketedScantreats the root as having no consumer and protects only cached plans, throughCacheManager. The checkpoint put-back and the streamingkeepsRootLayoutchangeQueryExecution,AdaptiveSparkPlanExec,InsertAdaptiveSparkPlan,IncrementalExecution,DatasetandLogicalRDD, only to keep a layout for later queries. Following the bucketed-scan rule keeps the logic simpler, at the cost of the layout of a checkpoint with packed scans at its root. inline
@ulysses-you, @cloud-fan, are you OK with this direction?
| * indices that should be grouped together. Only the driver reads it, | ||
| * so it is not serialized into tasks. | ||
| */ | ||
| class GroupedPartitionCoalescer( |
There was a problem hiding this comment.
Finding 16. This narrows what I asked for in finding 14. Reusing this coalescer for packing is right, but changing it is an improvement of its own, separate from packing:
- The groups stay out of the task binary.
GroupPartitionsExechas always shipped them there, although onlygetPartitionson the driver reads them. - Tied hosts are spread across groups, and a group of one partition names no location.
For GroupPartitionsExec over a scan, none of the location changes fire, because its child's RDD reports no locations. This PR's test "storage-partitioned groups over a scan take their first input's location" shows it. So the location changes only pay off for packing, and they are why the description needs its "With the option off" paragraph. Packing does not need them to work correctly.
Could you move these changes, the new GroupPartitionsExecSuite test and the locality checks in PackV2ScanPartitionsReadSuite (:135 and :175-179) to a separate improvement ticket and PR that lands before this one? This PR can then use the coalescer as that PR leaves it.
There was a problem hiding this comment.
Moved to SPARK-61279 (#60256): the transient groups, the tie spreading and the single-partition groups. The :135 test is now that PR's "groups over a parent without locations take their first input's location" test. It coalesces a mapped RDD, as GroupPartitionsExec does over a scan, since the source the :135 test read is a fixture of this PR. Its other test covers the tie spreading and single-partition groups that :175-179 checked, so I dropped those checks and the source's hosts option here. The description's "With the option off" paragraph is gone too. This PR keeps only the call to the coalescer and a sentence in its scaladoc that mentions packing.
| } | ||
| } | ||
|
|
||
| rewrite(plan, keepRootLayout || requiredDistribution.exists(_ != UnspecifiedDistribution), |
There was a problem hiding this comment.
Finding 18. Spark already has a rule like this one. DisableUnnecessaryBucketedScan withdraws a V1 bucketed scan's layout where nothing uses it. It starts at the root as if nothing consumed it (DisableUnnecessaryBucketedScan.scala:152), and only cached plans opt out, through CacheManager (SPARK-33075). It does nothing for checkpoints or streaming. On master, a join of two bucketed tables runs without a shuffle, but the same join on a localCheckpoint() of one of them shuffles, with AQE on and off.
This PR goes further. It also keeps the root's layout for checkpoints and streaming micro-batches. All of that only keeps a layout for later queries. A withdrawn claim is recorded as withdrawn, so the rows stay correct without it. Part of it follows what I asked for in findings 1 and 10, so this walks back the checkpoint half of finding 1.
Following the bucketed-scan rule means calling rewrite(plan, needsPartitioning = false, needsOrdering = false) here, so the rule needs no parameters. The rest then changes like this:
ExistingRDD.scala,Dataset.scala,InsertAdaptiveSparkPlan.scalaandIncrementalExecution.scalago back to master. The checkpoint runswithRegularShuffleagain, andfromDatasetlosesproducedBy.QueryExecution.scalaandAdaptiveSparkPlanExec.scalakeep only the rule in their preparation lists.forCheckpoint,lazyCheckpointPlan,executedPlanPrepared,keepsRootLayoutand thekeepRootLayoutparameters go.BatchScanExec.withoutPackinggoes, since only the checkpoint uses it.- The
CacheManagerline stays, since the bucketed-scan rule has it too. - The tuning guide and the description say in one sentence that a checkpoint or a
foreachBatchDataset with packed scans at its root does not record their layout, as with auto bucketed scans.
I tried it on this head with the packing suites, the three packing re-runs and the DPP packing suites:
- 588 of 603 tests pass, and no test returns other rows.
- 12 of the 15 failures check the put-back,
keepRootLayoutorrequiredDistributionthemselves. - The other 3 are the SPARK-53322 checkpoint tests in the packing re-run of
KeyGroupedPartitioningSuite("checkpointed scans avoid shuffles for aggregates", "are used for SPJ", "can shuffle other children on SPJ"). With packing on, a later join or aggregate over a checkpointed keyed scan then shuffles. That is the cost, the same one auto bucketed scans have.
Treating the root as a consumer instead would keep those three, but DPP would no longer reuse the join's broadcast. The build side at a DPP subquery's root would stay unpacked while the join packs it below its broadcast, and 61 tests fail that way.
So I'd follow the bucketed-scan rule, and keeping the root's layout can come back as a follow-up if someone needs it.
There was a problem hiding this comment.
Done. ExistingRDD, Dataset, InsertAdaptiveSparkPlan and IncrementalExecution are back to master, so the checkpoint runs withRegularShuffle again and fromDataset has no producedBy. forCheckpoint, lazyCheckpointPlan, executedPlanPrepared, keepsRootLayout, the keepRootLayout parameters, requiredDistribution and BatchScanExec.withoutPacking are gone. PackV2ScanPartitions is now an object that QueryExecution and AdaptiveSparkPlanExec list right after StampUnionDecisions, and it calls rewrite(plan, needsPartitioning = false, needsOrdering = false). The CacheManager line stays.
With packing on, a checkpoint with packed scans at its root no longer records their layout, so a later join over it shuffles. PackV2ScanPartitionsPlanSuite checks that, and the tuning guide and the description state it in one sentence. The packing re-run of KeyGroupedPartitioningSuite excludes the three SPARK-53322 checkpoint tests, with a comment pointing to that test.
c48ffa2 to
1719eba
Compare
|
Thanks, @peter-toth. I agree with all three, and following the existing features made the change smaller. Addressed in
|
|
Thank you @rekbun and @peter-toth . I don't particularly like this approach, and the reason is structural rather than a matter of implementation detail. V1 already shows where this ends: The other direction is to extend |
|
@ulysses-you @rekbun, I agree that marking the scan and packing its inputs in I see the problem differently, though. It is not many small partitions with distinct keys. It is many small splits, often of the same key:
So what's missing is packing splits by size, the way Iceberg packs its file scan tasks to a target size. That applies to unkeyed scans too. Coalescing across keys, with the layout kept, is a different feature. It only matters where a consumer reads the layout, and there GPE already groups by key. For the mechanism, what about a separate operator instead of a mode of the scan?
Longer term, I could imagine a partitioning that carries an optional key and an optional size per partition. A planner-inserted operator could then group by key, by size or both, to satisfy a requirement or reach a target size. It could also merge keys where that is allowed. That would also give the distribution-preserving coalescing you describe, but I'd keep it out of this PR. |
|
Thanks, @peter-toth. A separate operator works for me. The relationship between new operator and gpe just like the AQE side's shuffle read and shuffle exchange. It settles the part of my concern that matters most: the decision leaves Agreed on the framing: the common case is many small splits, often of one key, and unkeyed scans need the same packing. The distribution-preserving coalescing I described, with a plan-time partitioning and shared boundaries across co-partitioned scans, can be a follow-up outside this PR. |
|
Thanks, @peter-toth and @ulysses-you. I'll rework it as a separate operator, as Peter described:
@ulysses-you, agreed on the analogy with AQE's shuffle read: the node only regroups the partitions it reads. The distribution-preserving version would then be a grouping over GPE that reports a coalesced keyed partitioning, modeled on |
1719eba to
b7e945d
Compare
b7e945d to
92ad2d4
Compare
|
I pushed the rework (4d14ea3). It's stacked on #60256's new head and on #60453, a separate fix it needs (the memory bullet below).
Two corrections to my last comment:
|
92ad2d4 to
4d14ea3
Compare
|
Thanks for the rework, @rekbun, and for the follow-up PRs! Let's take them one at a time, so that each review stays focused:
I'll pick up the next one once the one before it lands. |
…ks and improve its location choice ### What changes were proposed in this pull request? This PR changes `GroupedPartitionCoalescer`, which `GroupPartitionsExec` uses to coalesce partitions for storage-partitioned operations: - It marks its groups `transient`. `CoalescedRDD`, and `SortedMergeCoalescedRDD` for a k-way merge, keep the coalescer, so its groups were serialized into every task binary, although only `getPartitions` on the driver reads them. - It checks, with a message, that it is asked for as many partitions as it has groups, since a caller sizes the coalesced RDD by its groups. - A group of several partitions prefers a host only when more of its partitions prefer it than any other host. It finds each partition's locations through the parent's lineage with `SparkContext.getPreferredLocs`, as `DefaultPartitionCoalescer` does. Before, it read only the parent's own `preferredLocations` and took the most common entry, the first in a hash map's order on a tie. Over a scan, `GroupPartitionsExec` coalesces the scan's mapped RDD, which reports no locations of its own, so no group named one. - A partition counts once for each host, however often and in whatever form it names that host, and a null host is ignored. - When the only location that the group's partitions name on the chosen host is an executor or an HDFS cache, the group keeps that location instead of the host. - Other groups name no location: a group of one partition, a group with no host ahead, a group that shares partitions with another group, as the slots of a key do under `REPLICATED_FOR_JOIN`, and any group when the parent, or an RDD that its narrow dependencies reach, is persisted. The scheduler then finds the locations itself when it submits each stage, as it did on master over a scan. It offers every location of a group of one's partition, the locations of a group's first partition that has any, and the executor that holds a cached block. ### Why are the changes needed? Large groupings no longer add to the task binary of every task. Groups of several partitions over a scan, where more of the inputs prefer one host than any other, now prefer that host. Before, they named none, and the scheduler offered the locations of the group's first input that had any. A group gets one location, once, when the coalesced RDD's partitions are computed, while the scheduler looks cached blocks up at each stage submission and can offer several locations. So the coalescer leaves the choice to the scheduler where its one location would be worse: - over persisted data, where only the scheduler sees the cached blocks; - for a group of one, where the scheduler offers every location of its partition; - where no host is ahead, since naming one tied host would mostly narrow the scheduler's offer of the first input's locations; - for groups that share partitions, since a zip would copy their one host into every task of the key in a partially clustered join. Left to the scheduler, each task gets master's locations: its own split's when the split side comes first in the zip, and every location of the first replicated input otherwise. SPARK-60265 (#59522) reuses this coalescer for V2 scan partition packing. ### Does this PR introduce _any_ user-facing change? There is no API change. Storage-partitioned groups of several partitions over a scan, where more of the inputs prefer one host than any other, now prefer one location: that host, or the only location that the group's inputs name on it, such as an executor. Before, no group named a location. Over a parent that reports locations of its own, a group named its partitions' most common location before, and it now follows the same rules. As with `DefaultPartitionCoalescer`, a group gets its location when the coalesced RDD's partitions are computed, and the partitions of a group that votes have their locations looked up once more for that. Otherwise the scheduler finds the locations itself, as on master over a scan: - for a group of one partition; - for a group with no host ahead; - for groups that share partitions, as the slots of a key do in a partially clustered join; - for groups whose parent's narrow lineage is persisted, such as a `GroupPartitionsExec` over an `InMemoryTableScanExec`; - where no input reports a location, as with the in-memory test connectors. The exception is a join that zips the grouped RDDs directly: a row-based `GroupPartitionsExec` right under a shuffled hash join, or under a sort-merge join that needs no sort. `ZippedPartitionsRDD` copies each side's own location when it computes its partitions. So when one side's group names a location, the other side adds none if its group names none, as a group of one, a group with no host ahead or a group over cached data does, and the task prefers that one location. Over cached data, the task then reads the block remotely. On master over a scan, such a task got the locations of the first input that had any on the zip's first side (the streamed side under whole-stage codegen), or the executor that holds that side's cached block. Where a `ColumnarToRowExec` or a `SortExec` sits between the grouping and the join, as over a vectorized scan, the zip has no locations of its own, and the scheduler finds them as on master. A host that holds a replica of every input also narrows the offer. That happens when a single writer on a datanode loaded the table, since HDFS puts the first replica of each block on the writer's node. The host is then ahead in every group of several partitions, so each of those groups names it alone and their tasks all prefer it. The tasks that do not fit there wait for the locality timeout and then read remotely, where on master they could start node-local to their first input on another replica. A weak plurality narrows a single group the same way: with ten inputs where one host holds two and every other host one, the group names that host, where master offered its first input's replicas. Returning several locations for a group, such as the leading host plus the first input's replicas, would remove this; that is left for the follow-up on an alternative design. ### How was this patch tested? Six tests in `GroupPartitionsExecSuite`: - A group names no location when no host is ahead, and the scheduler then offers its first input's locations. A group of one names none either. It also covers the partition-count check in both directions, a host ahead with and without a majority, a host counted once per partition however it is named, null hosts, and that tasks do not carry the groups. - Groups over a mapped parent, as over a scan, prefer the hosts found through its lineage. The scheduler finds a group of one's location through the lineage, and a group names none when nothing in the lineage has a host. - In a zip, a side over a map, as over a scan, whose group names a host decides the task's location, both against a group of one and against a group over cached data, for which the scheduler alone would offer the executor that holds the block. - Groups over a persisted parent, and over one two maps down, as over an `InMemoryTableScanExec`, name no location, so once the data is cached the scheduler offers the executor that holds the block. - A group of several partitions keeps an executor or HDFS-cache location that is the only one its inputs name on the host, also next to an input on another host, and gets the host otherwise. For groups of one, the scheduler offers an executor location, an HDFS-cache location, and all three hosts of a replicated input. - Groups that share partitions, as the slots of a split key in a partially clustered join, name no location and look none up, while an unshared group next to them still votes, looking each input up once. Zipped with the split side's groups of one, the tasks get master's locations in both zip orders: their own split's when the split side comes first, and every location of the first replicated input otherwise. Locally, with JDK 21: - `GroupPartitionsExecSuite`, `KeyGroupedPartitioningSuite` and its three runtime-filter variants, `EnsureRequirementsSuite`, the six `DynamicPartitionPruningV2*` suites and the `DataSourceV2FileSourceDPPSuite` variants: 711 tests in 14 suites passed (9 ignored when AQE is on, as on master). - SQL scalastyle (main and test) and `sql/mimaReportBinaryIssues` passed. ```bash build/sbt \ 'sql/testOnly org.apache.spark.sql.execution.datasources.v2.GroupPartitionsExecSuite org.apache.spark.sql.connector.KeyGroupedPartitioning* org.apache.spark.sql.execution.exchange.EnsureRequirementsSuite org.apache.spark.sql.DynamicPartitionPruningV2* org.apache.spark.sql.connector.DataSourceV2FileSourceDPPSuite*' \ 'sql/scalastyle' 'sql/Test/scalastyle' 'sql/mimaReportBinaryIssues' ``` ### Was this patch authored or co-authored using generative AI tooling? Generated-by: Claude Code (Claude Opus 5.5) Closes #60256 from rekbun/SPARK-61279. Authored-by: Rakesh <rkchoudhary0208@gmail.com> Signed-off-by: Peter Toth <peter.toth@gmail.com> skip-checks: true
4d14ea3 to
b4335fa
Compare
…f tasks and improve its location choice ### Differences from #60256 This is a backport of #60256 to `branch-4.x`. The cherry-pick of `05055e0c41c` conflicted only in `GroupPartitionsExecSuite`: on master the file ends with `InterpretedYears`, a test helper from SPARK-60541 (#59866), which `branch-4.x` doesn't have, so this PR adds only the `LocationCountingRDD` helper. `GroupedPartitionCoalescer` is the same as on master. On `branch-4.x`, with JDK 21: `GroupPartitionsExecSuite`, `KeyGroupedPartitioningSuite` and its three runtime-filter variants, `EnsureRequirementsSuite`, the six `DynamicPartitionPruningV2*` suites and the `DataSourceV2FileSourceDPPSuite` variants passed (713 tests, 9 ignored when AQE is on), and SQL scalastyle passed. ### What changes were proposed in this pull request? This PR changes `GroupedPartitionCoalescer`, which `GroupPartitionsExec` uses to coalesce partitions for storage-partitioned operations: - It marks its groups `transient`. `CoalescedRDD`, and `SortedMergeCoalescedRDD` for a k-way merge, keep the coalescer, so its groups were serialized into every task binary, although only `getPartitions` on the driver reads them. - It checks, with a message, that it is asked for as many partitions as it has groups, since a caller sizes the coalesced RDD by its groups. - A group of several partitions prefers a host only when more of its partitions prefer it than any other host. It finds each partition's locations through the parent's lineage with `SparkContext.getPreferredLocs`, as `DefaultPartitionCoalescer` does. Before, it read only the parent's own `preferredLocations` and took the most common entry, the first in a hash map's order on a tie. Over a scan, `GroupPartitionsExec` coalesces the scan's mapped RDD, which reports no locations of its own, so no group named one. - A partition counts once for each host, however often and in whatever form it names that host, and a null host is ignored. - When the only location that the group's partitions name on the chosen host is an executor or an HDFS cache, the group keeps that location instead of the host. - Other groups name no location: a group of one partition, a group with no host ahead, a group that shares partitions with another group, as the slots of a key do under `REPLICATED_FOR_JOIN`, and any group when the parent, or an RDD that its narrow dependencies reach, is persisted. The scheduler then finds the locations itself when it submits each stage, as it did on master over a scan. It offers every location of a group of one's partition, the locations of a group's first partition that has any, and the executor that holds a cached block. ### Why are the changes needed? Large groupings no longer add to the task binary of every task. Groups of several partitions over a scan, where more of the inputs prefer one host than any other, now prefer that host. Before, they named none, and the scheduler offered the locations of the group's first input that had any. A group gets one location, once, when the coalesced RDD's partitions are computed, while the scheduler looks cached blocks up at each stage submission and can offer several locations. So the coalescer leaves the choice to the scheduler where its one location would be worse: - over persisted data, where only the scheduler sees the cached blocks; - for a group of one, where the scheduler offers every location of its partition; - where no host is ahead, since naming one tied host would mostly narrow the scheduler's offer of the first input's locations; - for groups that share partitions, since a zip would copy their one host into every task of the key in a partially clustered join. Left to the scheduler, each task gets master's locations: its own split's when the split side comes first in the zip, and every location of the first replicated input otherwise. SPARK-60265 (#59522) reuses this coalescer for V2 scan partition packing. ### Does this PR introduce _any_ user-facing change? There is no API change. Storage-partitioned groups of several partitions over a scan, where more of the inputs prefer one host than any other, now prefer one location: that host, or the only location that the group's inputs name on it, such as an executor. Before, no group named a location. Over a parent that reports locations of its own, a group named its partitions' most common location before, and it now follows the same rules. As with `DefaultPartitionCoalescer`, a group gets its location when the coalesced RDD's partitions are computed, and the partitions of a group that votes have their locations looked up once more for that. Otherwise the scheduler finds the locations itself, as on master over a scan: - for a group of one partition; - for a group with no host ahead; - for groups that share partitions, as the slots of a key do in a partially clustered join; - for groups whose parent's narrow lineage is persisted, such as a `GroupPartitionsExec` over an `InMemoryTableScanExec`; - where no input reports a location, as with the in-memory test connectors. The exception is a join that zips the grouped RDDs directly: a row-based `GroupPartitionsExec` right under a shuffled hash join, or under a sort-merge join that needs no sort. `ZippedPartitionsRDD` copies each side's own location when it computes its partitions. So when one side's group names a location, the other side adds none if its group names none, as a group of one, a group with no host ahead or a group over cached data does, and the task prefers that one location. Over cached data, the task then reads the block remotely. On master over a scan, such a task got the locations of the first input that had any on the zip's first side (the streamed side under whole-stage codegen), or the executor that holds that side's cached block. Where a `ColumnarToRowExec` or a `SortExec` sits between the grouping and the join, as over a vectorized scan, the zip has no locations of its own, and the scheduler finds them as on master. A host that holds a replica of every input also narrows the offer. That happens when a single writer on a datanode loaded the table, since HDFS puts the first replica of each block on the writer's node. The host is then ahead in every group of several partitions, so each of those groups names it alone and their tasks all prefer it. The tasks that do not fit there wait for the locality timeout and then read remotely, where on master they could start node-local to their first input on another replica. A weak plurality narrows a single group the same way: with ten inputs where one host holds two and every other host one, the group names that host, where master offered its first input's replicas. Returning several locations for a group, such as the leading host plus the first input's replicas, would remove this; that is left for the follow-up on an alternative design. ### How was this patch tested? Six tests in `GroupPartitionsExecSuite`: - A group names no location when no host is ahead, and the scheduler then offers its first input's locations. A group of one names none either. It also covers the partition-count check in both directions, a host ahead with and without a majority, a host counted once per partition however it is named, null hosts, and that tasks do not carry the groups. - Groups over a mapped parent, as over a scan, prefer the hosts found through its lineage. The scheduler finds a group of one's location through the lineage, and a group names none when nothing in the lineage has a host. - In a zip, a side over a map, as over a scan, whose group names a host decides the task's location, both against a group of one and against a group over cached data, for which the scheduler alone would offer the executor that holds the block. - Groups over a persisted parent, and over one two maps down, as over an `InMemoryTableScanExec`, name no location, so once the data is cached the scheduler offers the executor that holds the block. - A group of several partitions keeps an executor or HDFS-cache location that is the only one its inputs name on the host, also next to an input on another host, and gets the host otherwise. For groups of one, the scheduler offers an executor location, an HDFS-cache location, and all three hosts of a replicated input. - Groups that share partitions, as the slots of a split key in a partially clustered join, name no location and look none up, while an unshared group next to them still votes, looking each input up once. Zipped with the split side's groups of one, the tasks get master's locations in both zip orders: their own split's when the split side comes first, and every location of the first replicated input otherwise. Locally, with JDK 21: - `GroupPartitionsExecSuite`, `KeyGroupedPartitioningSuite` and its three runtime-filter variants, `EnsureRequirementsSuite`, the six `DynamicPartitionPruningV2*` suites and the `DataSourceV2FileSourceDPPSuite` variants: 711 tests in 14 suites passed (9 ignored when AQE is on, as on master). - SQL scalastyle (main and test) and `sql/mimaReportBinaryIssues` passed. ```bash build/sbt \ 'sql/testOnly org.apache.spark.sql.execution.datasources.v2.GroupPartitionsExecSuite org.apache.spark.sql.connector.KeyGroupedPartitioning* org.apache.spark.sql.execution.exchange.EnsureRequirementsSuite org.apache.spark.sql.DynamicPartitionPruningV2* org.apache.spark.sql.connector.DataSourceV2FileSourceDPPSuite*' \ 'sql/scalastyle' 'sql/Test/scalastyle' 'sql/mimaReportBinaryIssues' ``` ### Was this patch authored or co-authored using generative AI tooling? Co-authored with Claude Code. Closes #60721 from rekbun/SPARK-61279-4.x. Authored-by: Rakesh <rkchoudhary0208@gmail.com> Signed-off-by: Peter Toth <peter.toth@gmail.com> skip-checks: true
|
Thank for the rebase @rekbun. Let me review this PR next week. |
|
Thank you @rekbun for the update, I have another thought about the position of the new operator. Design review: pack at the scan, not at the shufflePlan B : pack directly above the BatchScan for simple plansToday If the node is inserted directly above the
Sketch: The eligibility should be stated as a requirement, not only as an operator list: the path from the scan to the shuffle must be 1:1 in partitions, and the operator immediately above the node must not require a distribution or an ordering from its child:
A global With this placement the node still reports Then follow-up: coalescing after GroupPartitionsExecThe plans that do expose a keyed layout (storage-partitioned joins, aggregations on the scan keys) should not be handled by tier 1. A separate follow-up can add a coalescing above Please state the boundary explicitly for the AQE local-read case (a keyed scan that goes straight into a hash shuffle, with no GPE in the plan): either accept the loss in tier 1, or skip tier 1 when the shuffle's parent needs the pre-shuffle layout. A follow-up ticket for the GPE-based coalescing would make the split complete. Other findings
|
|
Thanks @ulysses-you for the placement idea. I think Plan B leaves one case open. Its list covers every operator on the path, and for a sort aggregate it says that the required ordering comes from a local sort above the node. That holds where
Putting the node directly above the scan in such a plan would need a new local sort, which the plan without packing doesn't have. So the rule has to check an ordering that an operator on the path requires all the way down to the node, not only for the operator directly above it. I suggested placing the node directly below the shuffle, so that the operators between the node and the scan run unchanged and nothing has to be proven about them. The cost was that they run once per input split. SPARK-61647 is a consequence of that, since each packed task runs one partial aggregate per split. Above the scan, the operators run once per packed task, as over a V1 file scan, so a partial aggregate combines all inputs of the task and keeps one map. Two things could get most of that benefit without an extra sort:
In short, the best position depends on what runs between the scan and the shuffle:
So I don't think one fixed position fits every plan. The lowest safe point picks the best one for each plan, without adding work. @ulysses-you, @rekbun, what do you think? On the follow-up, I agree that it should not be solved here. Coalescing keyed groups while keeping the layout is a different problem, so it needs its own ticket. As we discussed earlier, it is also not the problem this PR solves. |
|
Thanks @ulysses-you and @peter-toth. I agree with the lowest safe point, and I'll implement it as a check rather than an operator list:
For projects, filters, partial hash aggregates and a broadcast hash join's streamed side, the node then goes directly above the scan. A partial aggregate builds one map per packed task instead of one per input, On the AQE local read, I'll accept the loss in this PR and state it in the description. The local read appears only when AQE turns the join above into a broadcast join at runtime, after this shuffle is planned, so the rule can't account for it. Results don't change, since AQE keeps the full shuffle read where an operator needs the keyed layout. Other findings:
Agreed that the follow-up needs its own ticket. To add to my earlier comment on it:
|
|
thank you @peter-toth and @rekbun , agreed with the lowest safe point, and with deciding it through |
Adds spark.sql.sources.v2.scanPartitionPacking.* (off by default). A new physical rule, PackV2ScanPartitions, runs after RemoveRedundantSorts, with and without AQE. It puts a new node, PackScanPartitionsExec, between a ShuffleExchangeExec and its child when that child reads one non-file BatchScanExec through projects, filters, sorts, partial aggregates or the streamed side of a broadcast hash join. A shuffle reads only its child's rows, so the node reports UnknownPartitioning(0), and the scan and the operators below it keep the partitioning and ordering they have on master. BatchScanExec is unchanged. When the node executes, it packs the scan's adjacent inputs that runtime filtering left, by HasPartitionStatistics.sizeInBytes(), with FilePartition's rule and target, but in the scan's order and without splitting an input. As with spark.sql.files.maxPartitionNum, when packing by size gives more groups than maxPartitionNum, the inputs are packed again with a target of their total size divided by it. A scan with an input that reports no valid size is grouped by count into at most maxPartitionNum groups, and only when it is set. Inputs that runtime filtering emptied join a neighboring group. The node coalesces its child's RDD with GroupedPartitionCoalescer. Scans of file-based V2 sources are left to spark.sql.files.*. The node reports SQL metrics and shows in EXPLAIN.
The suites in org.apache.spark.sql.connector and org.apache.spark.sql.execution.datasources.v2 are tagged DataSourceV2Test since SPARK-61685, and CI runs them in the sql - DSv2 tests job. Tag the packing suites and the packing re-runs of DSv2 suites the same way, instead of ExtendedSQLTest or no tag.
0722f22 to
73d0543
Compare
|
Thanks @ulysses-you and @peter-toth. Updated in 73d0543, and rebased on master without #60453:
With the node above the scan, I filed SPARK-62333 for coalescing whole key groups above The description is updated to match. |
…ng cost per file - Place PackScanPartitionsExec at the lowest point between the scan and the shuffle where ValidateRequirements passes: directly above the scan, or above an operator on the path that relies on the scan's ordering, with directly below the shuffle as the last candidate. Operators above the node run once per packed task. - Charge the opening cost once for each file an input reports through HasPartitionStatistics.filesCount(), and at least once, and let an input join a group only if all of its files would, as FilePartition does. - Set the version of the scan partition packing configs to 4.5.0. - Pin the plan shape of the AQE local-read test, test the rule order against RemoveRedundantSorts, and validate the plans inside AQE query stages in the packing tests.
73d0543 to
17c249b
Compare
There was a problem hiding this comment.
Re-checked through 17c249b. Findings 16, 17 and 18 are resolved, and the node goes at the lowest safe point as agreed in the placement thread. The packing suites pass (819 tests), and without its exclusion the SPARK-58974 test fails only its setup check, as you wrote. Three new points:
Non-blocking
- 19.
maxPartitionNumcan raise the task count (new): The second pass packs with a target ofceilDiv(total, cap), which can fall below the first pass's target. With 30 inputs of 60, 60 and 70 MB, a cap of 17 to 19 then runs all 30 inputs apart, where no cap runs 20 tasks. This is the rule I suggested for finding 17, andFilePartitionshares it. Keeping the first target as a floor fixes it, and the packing suites still pass. inline
Minor
- 20. "Left as they are" for scans without sizes (new): Partitions that runtime filtering emptied in a keyed scan still join a neighbor, so this page and the
maxPartitionNumdoc should say so, as the tuning guide does. inline - 21. The tuning guide names the internal
spark.sql.shuffle.localPipelined.enabled(new). inline
| val numGroups = groups.fold(numInputs)(_.size) | ||
| maxPartitionNum.filter(numGroups > _) match { | ||
| case Some(cap) => | ||
| val capped = bySize(sizes, openCosts, ceilDiv(total, cap)) |
There was a problem hiding this comment.
Finding 19. When packing by size gives more groups than maxPartitionNum, the inputs are packed again with a target of ceilDiv(total, cap). Next fit leaves room at the end of each group, so the first pass can give more groups than total / target. A cap between those two counts then makes the second target smaller than the first, and the second pass merges less:
- 30 inputs of 60, 60 and 70 MB, repeated, at the defaults (
128MB,4MBopening cost) withminPartitionNum=1: without a cap, the 60 MB inputs pair up and each 70 MB input stays alone, so the scan runs 20 tasks. - With
maxPartitionNumset to 17, 18 or 19, the target drops to about 119, 112 or 106 MB. No two inputs fit together, so all 30 run apart, while the warning says Spark "rescales it to 30".
This is the rule I suggested for finding 17, and FilePartition behaves the same: getFilePartitions over the same sizes, sorted as file scans sort them, also gives 30 for those caps. Since the cap is there to widen groups, the second pass can keep the first target as a floor:
val target = math.min(maxPartitionBytes, math.max(openCostInBytes, total / minGroups))
val groups = bySize(sizes, openCosts, target)
...
val capped = bySize(sizes, openCosts, math.max(target, ceilDiv(total, cap)))I ran this on this head. The example then gives 20 tasks for caps 16 to 19, and 15 tasks for a cap of 15. V2ScanPartitionPackingSuite, PackV2ScanPartitionsSuite, PackV2ScanPartitionsReadSuite and PackV2ScanPartitionsPipelinedSuite still pass. That includes the FilePartition parity test, whose generated sizes don't hit this shape. The parity test's comment and the "As spark.sql.files.maxPartitionNum" wording would then need to say where the two differ. The files side can get the same floor in a ticket of its own.
| through `filesCount()`, and at least one. This applies to keyed and unkeyed batch scans and is | ||
| disabled by default. Inputs are packed in the order the scan reads them, which for a keyed scan with | ||
| V2 bucketing enabled is the order of their partition keys. Return `OptionalLong.empty()` when the | ||
| size is unknown. If any input of a scan reports no size, Spark leaves the scan's inputs unchanged, |
There was a problem hiding this comment.
Finding 20. For a keyed scan, this doesn't quite hold. Runtime filtering pads each pruned split with an empty partition (PushDownUtils.scala:449-464), and packSlots folds every empty partition into the group before it, even when the inputs stay apart (V2ScanPartitionPacking.scala:115-146). So a pruned keyed scan whose inputs report no size runs fewer tasks than it has partitions. The tuning guide says so ("even when Spark leaves the other inputs as they are"), but this page and the maxPartitionNum doc (SQLConf.scala:3694, "such a scan's inputs are left as they are") don't. One sentence in both would do, e.g. "Partitions that runtime filtering emptied still join a neighboring task."
| map tasks limit how finely AQE can split a skewed shuffle partition, for skew joins and rebalances | ||
| alike. Under AQE, a local shuffle read with one mapper per task over a packed shuffle no longer | ||
| reports the scan's keyed layout, so where an operator needs that layout, AQE keeps the full shuffle | ||
| read. With the experimental local pipelined shuffle (`spark.sql.shuffle.localPipelined.enabled`), a |
There was a problem hiding this comment.
Finding 21. spark.sql.shuffle.localPipelined.enabled is .internal() (SQLConf.scala:1481-1482), and this sentence would be its only mention in docs/. The interaction is already stated in the code comments and the PR description. In the user guide, I'd drop the sentence or describe the behavior without naming the key.
spark-test
left a comment
There was a problem hiding this comment.
Review summary
The review found two gaps in the documentation the PR adds for the opt-in DataSource V2 scan partition packing. The pages list what enabling packing costs but not locality: a task that packs several inputs is offered only the host most of them prefer, or its first input's locations when no host is ahead, so inputs whose preferredLocations() name other hosts are read remotely, which the tuning guide, the DataSource V2 guide and the doc of spark.sql.sources.v2.scanPartitionPacking.enabled should say. Separately, the DataSource V2 guide and the maxPartitionNum doc say that a scan with an unsized input is left as it is, while partitions that runtime filtering emptied still join a neighboring task; that is the point already raised in the existing thread on docs/sql-v2-data-sources.md line 374. The review also covered, with no finding, the PackV2ScanPartitions placement rule and its rule order, the size and count packing rules and their parity with spark.sql.files.*, and the node's connector calls, metrics and plan reuse.
Findings
2 total: 0 P0, 0 P1, 1 P2, 1 P3.
Non-blocking (P2)
- Packing docs do not disclose that packed tasks can read inputs away from their preferred hosts —
docs/sql-performance-tuning.md:743— see inline.
Nit (P3)
- V2 guide and maxPartitionNum doc omit that emptied partitions still merge —
docs/sql-v2-data-sources.md:374— unresolved in existing discussion.
PR description suggestions
- Under "Does this PR introduce any user-facing change?", also list that a task packing several inputs prefers only the host most of them prefer, or its first input's locations when no host is ahead, so inputs whose connectors report other preferred locations can be read remotely.
- Say that the PR rewrites the public
HasPartitionStatisticsjavadoc: it now covers keyed and unkeyed inputs, definessizeInBytes()as the estimated bytes an input reads from storage without any opening cost, with a negative value meaning unknown, definesfilesCount()as the files that each add an opening cost, and drops the earlier statement that Spark uses these statistics to decide whether partition grouping applies.
Generated by Omnigent on Databricks
| The operators below the node, if any, run as they do without packing, once per input, and | ||
| `spark_partition_id()` there sees the input's index. Code that reads `TaskContext.partitionId()`, | ||
| such as a UDF, sees the packed task's index wherever it runs, and so does the shuffle, so a | ||
| round-robin repartition can place rows differently. Packing can reduce useful parallelism, and fewer |
There was a problem hiding this comment.
Non-blocking (P2): This list of what enabling packing costs leaves out locality. For a task that packs several inputs, GroupedPartitionCoalescer names only the host that more of those inputs prefer than any other host; when no host is ahead it names none, and the scheduler offers the locations of the task's first input that names any. Inputs of the task whose hosts are not the ones it is offered are then read away from the hosts their preferredLocations() name, while on the base branch each input is its own task, offered its own hosts. In the review's model of the head code, 4,000 inputs of 8 MB placed round-robin over 20 hosts pack about eleven to a task at the defaults, no host is ahead in any task, and about 91% of the bytes are read away from their preferred host. For a connector that reads host-local data, this adds network I/O that the documentation does not warn users about when they turn the option on; whether the saved scheduling outweighs it depends on input sizes and placement.
Stating it in this list, in the paragraph of docs/sql-v2-data-sources.md that follows the preferredLocations() sentence, and in the doc of spark.sql.sources.v2.scanPartitionPacking.enabled would make it a disclosed trade-off of the opt-in path, for example: "A task that packs several inputs prefers the host that more of them prefer than any other host or, when no host is ahead, the locations of the first of them that names any, so inputs that prefer other hosts can be read remotely." A shorter "prefers the host most of its inputs prefer" would misstate the tie case, where the first input's hosts need not be among the tied hosts. Grouping inputs by host is a separate design choice that this does not ask for.
Verification:
- Inspection: The DataSource V2 Scan Partition Packing section of the tuning guide, the DataSource V2 guide's paragraph on preferredLocations() and packing, and the doc of spark.sql.sources.v2.scanPartitionPacking.enabled each state that the inputs of a packed task can be read away from the hosts they prefer, and wherever they say which hosts a task of several inputs prefers, they match GroupedPartitionCoalescer.preferredLocation and the scheduler's fallback: the host that more of the task's inputs prefer than any other host or, when no host is ahead, the locations of the first input that names any.
…nNum - Above maxPartitionNum, pack the inputs again with at least the first target, so that the cap never gives more tasks than packing without it. - Say in the maxPartitionNum doc and the DSv2 guide that partitions emptied by runtime filtering still join a neighboring task. - Drop the internal local pipelined shuffle config from the tuning guide.
ulysses-you
left a comment
There was a problem hiding this comment.
Thank you @rekbun!
One note on CI: the latest commits pushed on Nov 24-25 (up to 18799236) did not trigger any Build workflow run on rekbun/spark (the last run on spj-scan-grouping was 0722f22c on Nov 20), so the upstream Build check is reporting ACTION_REQUIRED ("A supported Build check is not available for this PR head commit"). Could you check GitHub Actions on your fork and push a commit once Actions is enabled to trigger CI?
On the code itself, the implementation looks solid overall (0 blocking issues), with 1 non-blocking test-fixture note and 4 minor nits inline.
| SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true", | ||
| SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "1k", | ||
| SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false", | ||
| SQLConf.SHUFFLE_PARTITIONS.key -> "4") { |
There was a problem hiding this comment.
Non-blocking: with V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES = 2400L, lrt's three 100-byte splits pack into numMappers = 1, so OptimizeShuffleWithLocalRead emits four PartialMapperPartitionSpec(0, ...) specs and AQEShuffleReadExec.outputPartitioning falls back to UnknownPartitioning(4) by mapper-index uniqueness alone (1 != 4) without consulting PackScanPartitionsExec.outputPartitioning. Even with numMappers = 2 (e.g., 200 / 3), lrt reports an ungrouped KeyedPartitioning([[1], [1], [2]], isGrouped = false) that ValidateRequirements already rejects on the upper SortMergeJoinExec. To make this test discriminate PackScanPartitionsExec.outputPartitioning, use numMappers > 1 with SHUFFLE_PARTITIONS >= numMappers and a keyed scan whose unpacked layout would satisfy the join (or clarify the comment/PR description).
| for (packing <- Seq(false, true)) { | ||
| withSQLConf(enabled -> packing.toString) { | ||
| val ids = spark.table(s"testcat.ns.$items") | ||
| .select(expr("spark_partition_id()").as("pid"), taskPartition().as("tid")) |
There was a problem hiding this comment.
Nit: docs/sql-performance-tuning.md notes that spark_partition_id() below PackScanPartitionsExec sees the input partition index while TaskContext.partitionId() sees the packed task index, whereas this test only places PackScanPartitionsExec directly above BatchScanExec. Consider also covering a case where PackScanPartitionsExec sits above ProjectExec (for example under a partial SortAggregateExec reading scan ordering).
| PackScanPartitionsExec(plan, packing) | ||
| } else { | ||
| plan match { | ||
| case join: BroadcastHashJoinExec => join.buildSide match { |
There was a problem hiding this comment.
Nit: readsOneScan, pathToScan, and this BroadcastHashJoinExec branch support placing PackScanPartitionsExec above BroadcastHashJoinExec (when an operator above BHJ relies on the streamed scan's ordering), while existing BHJ tests only place PackScanPartitionsExec below BHJ. Consider adding a test for this placement path.
| // The node itself is not listed, so a child that is already packed is not packed again. | ||
| private def readsOneScan(plan: SparkPlan): Boolean = plan match { | ||
| case scan: BatchScanExec => !scan.scan.isInstanceOf[FileScan] | ||
| case _: ProjectExec | _: FilterExec | _: SortExec => readsOneScan(plan.children.head) |
There was a problem hiding this comment.
Nit: SortExec is matched regardless of global (consistent with DisableUnnecessaryBucketedScan.isAllowedUnaryExecNode). When SortExec(global = true) survives above a key-ordered scan beneath a downstream shuffle, ValidateRequirements places PackScanPartitionsExec above it; consider adding a test for that fallback path.
| * `PackScanPartitionsExec` executes, so equal nodes planned at different times stay equal for | ||
| * exchange and stage reuse. | ||
| */ | ||
| case class V2ScanPartitionPacking( |
There was a problem hiding this comment.
Nit: consider adding require guards (maxPartitionBytes > 0, openCostInBytes >= 0, minPartitionNum.forall(_ > 0), maxPartitionNum.forall(_ > 0)) so direct callers in package v2 do not rely solely on SQLConf validators.
What changes were proposed in this pull request?
This PR adds opt-in, size-based packing of DataSource V2 batch scan inputs that a shuffle reads.
New configurations
spark.sql.sources.v2.scanPartitionPacking.enabled(defaultfalse).spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes(default128MB) and the internalspark.sql.sources.v2.scanPartitionPacking.openCostInBytes(default4MB). They are the counterparts ofspark.sql.files.maxPartitionBytesandspark.sql.files.openCostInBytes, applied with the same packing rule as files. The opening cost is charged once for each file an input reports throughHasPartitionStatistics.filesCount(), and at least once, and an input joins a task only if all of its files would, asFilePartitionchecks each file. Files are sorted by size before packing; inputs keep the order the scan reads them in.spark.sql.sources.v2.scanPartitionPacking.minPartitionNum(default:spark.sql.leafNodeDefaultParallelism), likespark.sql.files.minPartitionNum.spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum(default: unset), likespark.sql.files.maxPartitionNum. When packing by size gives more tasks, Spark packs the inputs again with a target of their total size divided by it. For a scan with an input that reports no size, it is a hard cap: that scan's inputs are grouped by count into at most that many tasks.Where the node goes
PackV2ScanPartitions, runs afterReplaceHashWithSortAggandRemoveRedundantSorts, in both regular planning and AQE query stage preparation.ShuffleExchangeExec's child reads oneBatchScanExec. The path to the scan may go through projects, filters, sorts, partial aggregates or the streamed side of a broadcast hash join.DisableUnnecessaryBucketedScanallows. Other such operators, such as expand and generate, are not packed yet.PackScanPartitionsExec, reportsUnknownPartitioning(0)and no ordering. The rule puts it at the lowest point on that path whereValidateRequirementsstill passes:spark.sql.files.*.What the node does at execution
HasPartitionStatistics.sizeInBytes()plus an opening cost per file, asFilePartition.getFilePartitionspacks files. Unlike files, inputs stay in the scan's order and are never split.maxPartitionNumis set. Otherwise they stay as they are.GroupedPartitionCoalescer, the coalescer that storage-partitioned joins use (SPARK-61279). A group of several inputs prefers a host when more of its inputs prefer that host than any other. Otherwise, as for a group of one or over persisted data, the scheduler finds the locations.Side effects
spark.sql.shuffle.localPipelined.enabled, a plan with a packing node keeps regular shuffles, since the node's width is known only at execution. This holds even if the node then packs nothing.Observability and docs
PackScanPartitionsnode. Its SQL metrics report the number of input partitions, the number of partitions, and the largest number of input partitions in one partition.HasPartitionStatisticsjavadoc;DataSourceReader.partitionsdocstring;Why are the changes needed?
A DSv2 scan runs one task per
InputPartition. Connectors that report many small inputs pay task setup and scheduling overhead for each one. AQE cannot resize a leaf stage, because it works from shuffle statistics.File sources, including file-based V2 sources, already pack files by size. Other DSv2 scans have no equivalent. This became more visible in Spark 4.2, when SPARK-55092 stopped grouping splits that share a reported partition key unless an operator needs that grouping.
Does this PR introduce any user-facing change?
Yes, when the new option is enabled: the map stage of an eligible shuffle runs fewer, larger tasks.
spark_partition_id(), see the packed task's partition. Code that readsTaskContext.partitionId(), such as a UDF, sees the packed task's partition wherever it runs. So does the shuffle, so a round-robin repartition can place rows differently.The option is off by default.
How was this patch tested?
New suites:
V2ScanPartitionPackingSuite,PackV2ScanPartitionsSuite,PackV2ScanPartitionsReadSuiteandPackV2ScanPartitionsPipelinedSuite. A newPythonDataSourceSuitetest checks that a Python data source scan is grouped by count only whenmaxPartitionNumis set.The new tests cover:
maxPartitionNumcap. This includes that sized inputs pack asFilePartitionpacks files of the same sizes, the opening cost per reported file (also end to end), and inputs that runtime filtering emptied. A scan whose inputs stay apart builds no group per input, also through the path the node calls.maxof a string, with no sort added, and still packing there.RemoveRedundantSorts: a sort that only the scan's ordering makes redundant is dropped before the node is placed.planInputPartitions(),toBatch()orcreateReaderFactory()calls, for keyed and unkeyed scans, with AQE on and off. Scans that defer input planning still plan only when they execute (SPARK-44505).spark.sql.shuffle.localPipelined.enabled, a plan with a packing node keeps regular shuffles, with AQE on and off.These existing suites also run with packing enabled:
KeyGroupedPartitioningSuite, except two tests whose setup reads a shuffled scan's keyed layout above the node, which reports none:DynamicPartitionPruningsuites.The new suites and these re-runs are tagged
DataSourceV2Test, as the suites they extend are since SPARK-61685, so CI runs them insql - DSv2 tests.Locally, with JDK 21:
KeyGroupedPartitioningSuite, both runtime-filter suites, the three row-level operation suites and the six DSv2DynamicPartitionPruningsuites, plusSQLConfSuite: 854 tests passed (2 excluded, 9 ignored when AQE is on, as without packing).GroupPartitionsExecSuite,KeyGroupedPartitioningSuite, both runtime-filter suites,EnsureRequirementsSuite,ValidateRequirementsSuite,CachedTableSuite,ReplaceHashWithSortAggSuite,StorageFilterPushDownSuite,DataSourceV2Suite,ExplainSuite, bothDynamicPartitionPruningV2Suitevariants,AdaptiveQueryExecSuite,QueryExecutionSuite,SparkPlanSuite,SameResultSuite,PlannerSuite,WriteDistributionAndOrderingSuiteandPythonDataSourceSuite: 1225 tests passed (3 ignored when AQE is on, as on master).Was this patch authored or co-authored using generative AI tooling?
Generated-by: Codex (GPT-6) and Claude Code (Claude Opus 5.5)