Skip to content

[SPARK-60265][SQL] Add optional size-based packing for V2 batch scans - #59522

Open
rekbun wants to merge 4 commits into
apache:masterfrom
rekbun:spj-scan-grouping
Open

rekbun wants to merge 4 commits into
apache:masterfrom
rekbun:spj-scan-grouping

Conversation

@rekbun

@rekbun rekbun commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

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 (default false).
  • spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes (default 128MB) and the internal spark.sql.sources.v2.scanPartitionPacking.openCostInBytes (default 4MB). They are the counterparts of spark.sql.files.maxPartitionBytes and spark.sql.files.openCostInBytes, applied with the same packing rule as files. The opening cost is charged once for each file an input reports through HasPartitionStatistics.filesCount(), and at least once, and an input joins a task only if all of its files would, as FilePartition checks 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), like spark.sql.files.minPartitionNum.
  • spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum (default: unset), like spark.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

  • A new physical rule, PackV2ScanPartitions, runs after ReplaceHashWithSortAgg and RemoveRedundantSorts, in both regular planning and AQE query stage preparation.
  • It packs a scan when a ShuffleExchangeExec's child reads one BatchScanExec. The path to the scan may go through projects, filters, sorts, partial aggregates or the streamed side of a broadcast hash join.
  • Each of these operators computes each of its partitions from one scan partition. The list starts from the operators that DisableUnnecessaryBucketedScan allows. Other such operators, such as expand and generate, are not packed yet.
  • The new node, PackScanPartitionsExec, reports UnknownPartitioning(0) and no ordering. The rule puts it at the lowest point on that path where ValidateRequirements still passes:
    • directly above the scan, in most plans;
    • above an operator that relies on the scan's ordering, such as a partial sort aggregate with no sort between it and the scan;
    • directly below the shuffle as the last candidate, kept even if the check fails there, since a shuffle requires nothing of its child.
  • The operators above the node run once per packed task, and those below it once per input, as without packing.
  • Above the shuffle, only an AQE local read with one mapper per task reports the layout from before the shuffle (see the side effects).
  • These scans are not packed:
    • a scan that no shuffle reads, such as one at the root of a plan;
    • a scan that a storage-partitioned join or an aggregation on its keys uses;
    • a scan that reaches the shuffle through another operator, such as a union, a coalesce, the build side of a broadcast hash join, or an expand;
    • scans of file-based V2 sources, which are left to spark.sql.files.*.

What the node does at execution

  • It reads the scan's inputs, after runtime filtering, from its child's RDD partitions.
  • It packs adjacent inputs by HasPartitionStatistics.sizeInBytes() plus an opening cost per file, as FilePartition.getFilePartitions packs files. Unlike files, inputs stay in the scan's order and are never split.
  • If any input lacks a valid size, the inputs are grouped by count only when maxPartitionNum is set. Otherwise they stay as they are.
  • Inputs that runtime filtering emptied join the group before them, or the first group when none precedes them, so every scan partition is still computed once.
  • It coalesces its child's RDD with 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.
  • If the child's partitions are not the scan's, as when a plugin replaces the scan, the node leaves them as they are.

Side effects

  • A partial aggregate above the node runs once per packed task, so it emits fewer rows. One below the node, such as a sort aggregate that reads the scan's ordering, still emits its rows per input.
  • Under AQE, a local shuffle read with one mapper per task over a packed shuffle no longer reports the scan's keyed layout. Where an operator needs that layout, AQE keeps the full shuffle read, so results don't change, but a local read that master keeps can be lost. The local read appears only when AQE turns the join above into a broadcast join at runtime, after the shuffle was planned, so the rule can't account for it.
  • Scans whose keyed layout an operator needs are left alone. Coalescing their key groups while keeping the layout is SPARK-62333.
  • With 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

  • EXPLAIN shows a PackScanPartitions node. Its SQL metrics report the number of input partitions, the number of partitions, and the largest number of input partitions in one partition.
  • These describe the new behavior:
    • the HasPartitionStatistics javadoc;
    • the PySpark DataSourceReader.partitions docstring;
    • the DataSource V2 guide;
    • the SQL performance tuning guide;
    • the SQL UI metrics table.

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.

  • Packing can reduce useful parallelism.
  • Fewer map tasks limit how finely AQE can split a skewed shuffle partition.
  • Built-in expressions above the node that take the partition index, such as spark_partition_id(), see the packed task's partition. Code that reads TaskContext.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, PackV2ScanPartitionsReadSuite and PackV2ScanPartitionsPipelinedSuite. A new PythonDataSourceSuite test checks that a Python data source scan is grouped by count only when maxPartitionNum is set.

The new tests cover:

  • Packing: size-based and count-based packing, with and without the maxPartitionNum cap. This includes that sized inputs pack as FilePartition packs 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.
  • Where the node goes:
    • Directly above keyed and unkeyed scans that a shuffle reads through the listed operators, a global sort's range shuffle, and a broadcast hash join's streamed side with either build side, into the expected number of tasks. A sort that a partial sort aggregate needs goes above the node.
    • Above a partial sort aggregate that reads the scan's ordering, including a max of a string, with no sort added, and still packing there.
    • After RemoveRedundantSorts: a sort that only the scan's ordering makes redundant is dropped before the node is placed.
    • Not over a broadcast hash join's build side, a storage-partitioned join, an aggregation on the scan's keys, a union, a coalesce, or V2 file scans.
    • Not again when the plan is planned again.
    • The node leaves an RDD whose partitions are not a scan's as it is.
  • Reading:
    • storage filters;
    • columnar readers with reused batches, and readers closing on early stop and task failure;
    • range ordering and key order;
    • partition-dependent expressions and a UDF above the node, which see the packed task's partition;
    • the preferred hosts of packed tasks.
  • Connector calls: packing adds no planInputPartitions(), toBatch() or createReaderFactory() calls, for keyed and unkeyed scans, with AQE on and off. Scans that defer input planning still plan only when they execute (SPARK-44505).
  • Reuse and AQE: exchange and DPP broadcast reuse, AQE skew splitting, and the SPARK-59671 query (an AQE local read over a split scan) with packing: its answer, that no shuffle read sits over the packed keyed side's shuffle, so the sort merge join above reads it in full, and that the only local reads are the broadcast builds over the narrow sides. Cached plans, checkpoints and a barrier stage over a packed shuffle work as before.
  • Pipelined shuffle: with spark.sql.shuffle.localPipelined.enabled, a plan with a packing node keeps regular shuffles, with AQE on and off.
  • Metrics and EXPLAIN.

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:
    • the SPARK-59671 test, which expects the layout to reach an AQE local read; its query and answer are covered above;
    • the SPARK-58974 collapse skew guard test, which reads it from a project above the scan. Only that setup check fails; what the test checks there (no grouping, the shuffle counts) is decided before packing, and its plans without a shuffle are not packed;
  • both runtime-filter suites;
  • the three row-level operation suites;
  • the six DSv2 DynamicPartitionPruning suites.

The new suites and these re-runs are tagged DataSourceV2Test, as the suites they extend are since SPARK-61685, so CI runs them in sql - DSv2 tests.

Locally, with JDK 21:

  • The packing suites, and with packing enabled KeyGroupedPartitioningSuite, both runtime-filter suites, the three row-level operation suites and the six DSv2 DynamicPartitionPruning suites, plus SQLConfSuite: 854 tests passed (2 excluded, 9 ignored when AQE is on, as without packing).
  • With packing disabled, GroupPartitionsExecSuite, KeyGroupedPartitioningSuite, both runtime-filter suites, EnsureRequirementsSuite, ValidateRequirementsSuite, CachedTableSuite, ReplaceHashWithSortAggSuite, StorageFilterPushDownSuite, DataSourceV2Suite, ExplainSuite, both DynamicPartitionPruningV2Suite variants, AdaptiveQueryExecSuite, QueryExecutionSuite, SparkPlanSuite, SameResultSuite, PlannerSuite, WriteDistributionAndOrderingSuite and PythonDataSourceSuite: 1225 tests passed (3 ignored when AQE is on, as on master).
  • Catalyst and SQL scalastyle, SQL test scalastyle and Java checkstyle passed.
build/sbt \
  'sql/testOnly org.apache.spark.sql.connector.PackV2ScanPartitionsSuite org.apache.spark.sql.connector.PackV2ScanPartitionsReadSuite org.apache.spark.sql.connector.PackV2ScanPartitionsPipelinedSuite org.apache.spark.sql.execution.datasources.v2.V2ScanPartitionPackingSuite org.apache.spark.sql.connector.KeyGroupedPartitioningPackScanPartitionsSuite org.apache.spark.sql.connector.KeyGroupedPartitioningPackRuntimeFilterSuite org.apache.spark.sql.connector.KeyGroupedPartitioningPackCatalystRuntimeFilterSuite org.apache.spark.sql.connector.GroupBasedDeleteFromTablePackScanPartitionsSuite org.apache.spark.sql.connector.GroupBasedNoMetadataDeleteFromTablePackScanPartitionsSuite org.apache.spark.sql.connector.DeltaBasedMergeIntoTablePackScanPartitionsSuite org.apache.spark.sql.connector.DynamicPartitionPruningV2PackScanPartitionsSuiteAEOff org.apache.spark.sql.connector.DynamicPartitionPruningV2PackScanPartitionsSuiteAEOn org.apache.spark.sql.connector.DynamicPartitionPruningV2FilterPackScanPartitionsSuiteAEOff org.apache.spark.sql.connector.DynamicPartitionPruningV2FilterPackScanPartitionsSuiteAEOn org.apache.spark.sql.connector.DynamicPartitionPruningV2CatalystFilterPackScanPartitionsSuiteAEOff org.apache.spark.sql.connector.DynamicPartitionPruningV2CatalystFilterPackScanPartitionsSuiteAEOn org.apache.spark.sql.internal.SQLConfSuite' \
  'sql/testOnly org.apache.spark.sql.execution.datasources.v2.GroupPartitionsExecSuite org.apache.spark.sql.connector.KeyGroupedPartitioningSuite org.apache.spark.sql.connector.KeyGroupedPartitioningRuntimeFilterSuite org.apache.spark.sql.connector.KeyGroupedPartitioningCatalystRuntimeFilterSuite org.apache.spark.sql.execution.exchange.EnsureRequirementsSuite org.apache.spark.sql.execution.exchange.ValidateRequirementsSuite org.apache.spark.sql.CachedTableSuite org.apache.spark.sql.execution.ReplaceHashWithSortAggSuite org.apache.spark.sql.connector.StorageFilterPushDownSuite org.apache.spark.sql.connector.DataSourceV2Suite org.apache.spark.sql.ExplainSuite org.apache.spark.sql.DynamicPartitionPruningV2SuiteAEOff org.apache.spark.sql.DynamicPartitionPruningV2SuiteAEOn org.apache.spark.sql.execution.adaptive.AdaptiveQueryExecSuite org.apache.spark.sql.execution.QueryExecutionSuite org.apache.spark.sql.execution.SparkPlanSuite org.apache.spark.sql.execution.SameResultSuite org.apache.spark.sql.execution.PlannerSuite org.apache.spark.sql.connector.WriteDistributionAndOrderingSuite org.apache.spark.sql.execution.python.PythonDataSourceSuite' \
  'catalyst/scalastyle' 'sql/scalastyle' 'sql/Test/scalastyle' 'catalyst/checkstyle' 'sql/checkstyle'

Was this patch authored or co-authored using generative AI tooling?

Generated-by: Codex (GPT-6) and Claude Code (Claude Opus 5.5)

@szehon-ho szehon-ho left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread docs/sql-performance-tuning.md Resolved
@peter-toth

Copy link
Copy Markdown
Contributor

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 KeyGroupedPartitioning through SupportsReportPartitioning is Iceberg, and it doesn't seem to have this problem. With spark.sql.iceberg.planning.preserve-data-grouping on, it packs the files of each partition into task groups of read.split.target-size (128 MB by default). So it reports several splits for a key only when the key holds more data than that, or when adaptive split sizing splits a small scan to use the cluster's parallelism. In both cases one task per split is what we want below a shuffle.

If a scan doesn't need its KeyGroupedPartitioning but has too many small splits, grouping them by key may not be the best answer either. It brings back the pre-4.2 behavior, and I think the current one is better:

  • A large key becomes one large task.
  • It undoes Iceberg's adaptive split sizing.

There are other ways to cut the number of tasks:

  • coalesce() or the COALESCE hint over the scan works as a workaround today.
  • A size-based packing could use HasPartitionStatistics.sizeInBytes(), like the file sources do with spark.sql.files.maxPartitionBytes.
  • Or another connector could pack its splits the way Iceberg does.

@rekbun

rekbun commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor Author

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.
I am not proposing a change to the default. Multiple splits can be an intentional sizing decision, and grouping a large or skewed key into one task can remove useful parallelism. I would like to keep the previous grouping policy reachable as an explicit, default-off compatibility option for users upgrading Spark whose connectors and workloads relied on it. If a legacy name would make that purpose clearer, I am happy to use one.

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.
Connector-side packing is also a reasonable direction, and we are investigating bounded packing. Our connector reports per-file ordering, so combining files requires either merging their sorted streams or withdrawing that ordering claim and letting Spark add a sort where needed. Packing can be implemented in the connector. The compatibility argument for Spark is that physical planning knows which partitioning and ordering properties the surrounding plan requires, while the connector does not generally see the final physical plan when choosing its inputs.

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?

@peter-toth

Copy link
Copy Markdown
Contributor

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 (DataSourceV2ScanExecBase.outputOrdering). So with 24 files per bucket, those scans had fewer tasks but no ordering before 4.2 either.

Where a plan uses the scan's partitioning, like a storage-partitioned join or an aggregate on the bucket key, EnsureRequirements already groups the splits with a GroupPartitionsExec. So the scans that still run one task per split are the ones whose partitioning nothing uses: below a shuffle, or with no such consumer at all, like a collect, a write or the streamed side of a broadcast join.

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 peel and withJoinKeyPositions exceptions, or the preserveScanGrouping flag. If your connector reports HasPartitionStatistics.sizeInBytes(), the target could also be a size, like spark.sql.files.maxPartitionBytes for file sources.

The current head also changes two plans with the option on:

  • With spark.sql.sources.v2.bucketing.partiallyClusteredDistribution.enabled, the SPJ is planned from the already grouped scan. On the SPARK-42038 test data the join runs 3 tasks instead of 7.
  • A SORT BY id, name over a source that reports [id, name] keeps its SortExec, also with spark.sql.sources.v2.bucketing.preserveOrderingOnCoalesce.enabled.

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.

@rekbun rekbun changed the title [SPARK-60265][SQL] Allow optional grouping of V2 scan splits below shuffles [SPARK-60265][SQL] Allow optional coalescing of V2 scans before required shuffles Oct 23, 2026
@peter-toth

Copy link
Copy Markdown
Contributor

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:

  • It restores the task count your connector got before 4.2. That grouping came from the SPJ code, which grouped keyed scans even where nothing used their partitioning.
  • It has no relation to the data. A key with 100 GB becomes one task, while 10,000 tiny keys stay 10,000 tasks.
  • Too many small splits isn't specific to keyed scans. Any DSv2 scan runs one task per InputPartition, and AQE can't help a leaf stage, since it only works from shuffle statistics.

File sources already handle this. spark.sql.files.maxPartitionBytes and spark.sql.files.openCostInBytes pack files by size, and spark.sql.files.minPartitionNum and spark.sql.files.maxPartitionNum bound the count. DSv2 has HasPartitionStatistics.sizeInBytes() (SPARK-42040) for this kind of decision, but nothing uses it yet. szehon-ho asked about the same thing there.

So I'd rather go for a general option, independent of KeyedPartitioning:

  • Pack a DSv2 scan's splits by size when they report sizeInBytes(), and cap their count otherwise, like the file source configs do.
  • Apply it only where nothing uses the scan's partitioning or ordering. That is below a shuffle, or where there is no consumer at all, like a collect, a write or the streamed side of a broadcast join.
  • Pack at the scan itself. Then a partial aggregate above it combines the splits again, as it did before 4.2.

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?

@ulysses-you

Copy link
Copy Markdown
Contributor

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 FileSourceScanExec reads exactly numBuckets partitions and skips the size-based file packing (maxPartitionBytes / openCostInBytes) of the non-bucketed path. That only pays off when the bucket layout saves something, so DisableUnnecessaryBucketedScan runs right after EnsureRequirements and falls back to the default file-source parallelism when no operator with a ClusteredDistribution / AllTuples requirement is reachable, or when an Exchange separates the scan from it.

KeyGroupedPartitioning is the V2 form of that claim. When SPJ cannot be used it buys nothing, yet it still shapes the plan. Today the only way to switch it off is the session-wide spark.sql.sources.v2.bucketing.enabled, which is all-or-nothing. I would add the V2 counterpart of DisableUnnecessaryBucketedScan: after EnsureRequirements, decide per query that no keyed distribution is consumed, and disable the keyed claim for that scan, so the scan's parallelism is whatever the connector's default planning produces, as it is for V1.

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: Batch.planInputPartitions() usually runs before EnsureRequirements has decided anything, so a Spark-side rule alone can withdraw the claim but cannot change the task count. The connector can re-plan, though, and the plan-level decision is the same for every connector. Today that decision has to be reimplemented in each connector; I did exactly that for Paimon in apache/paimon#3928, where DisableUnnecessaryPaimonBucketedScan is registered through a SparkSessionExtensions query-stage preparation rule, walks the finished physical plan with the same criteria as the V1 rule (an interesting ClusteredDistribution / AllTuples consumer reachable, or a ShuffleExchangeLike in between), and replaces the BatchScanExec with a copy whose scan has bucketed scan disabled. Because the scan is a copy rather than a mutation, partition planning runs again, and getInputPartitions falls back to the connector's default layout. That works, but every downstream connector would repeat the same traversal, the same criteria and the same gating, and the copies will drift apart. The general form is a small connector API instead: Spark owns the detection and triggers the non-bucketed path, and the connector only returns a scan variant that plans without bucketing, as a fresh object so the re-planning is well defined. A connector then reuses the non-bucketed planning path it already has for tables that are not bucketed, instead of reimplementing the rule.

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: HasPartitionStatistics (@since 4.0.0, SPARK-42040) is a public mix-in on InputPartition that reports sizeInBytes(), numRows() and filesCount(), and its javadoc says Spark will use it to decide whether partition grouping applies, though nothing in Spark consumes it yet. Spark can sum the reported bytes, pick a target task size, and coalesce to ceil(total / target) tasks inside a partition, or across the stage when nothing relies on the layout, leaving the plan alone when sizes are absent. That is data-aware, unlike a key-count target, and it is not specific to keyed scans, so it could be the general option that was asked for here. Two limits: it only helps connectors that implement the mix-in (Iceberg does not today, and a connector like the one in this PR would need to report sizes), and coalescing only merges adjacent splits, so the resulting task sizes are approximate where a connector-side packer could do better.

@rekbun

rekbun commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

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.

@rekbun rekbun changed the title [SPARK-60265][SQL] Allow optional coalescing of V2 scans before required shuffles [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans Oct 29, 2026
@rekbun

rekbun commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

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.

@rekbun
rekbun requested a review from szehon-ho October 30, 2026 17:10

@peter-toth peter-toth left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 KeyedPartitioning shuffle instead. CacheManager already 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.py turns 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: as DisableUnnecessaryBucketedScan does, instead of from inside EnsureRequirements.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 regular sql job. 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. pack still handles pruned slots that no caller passes: the None case and its scaladoc sentence are dead since the last commit. inline
  • 7. The five new configs have no typed accessor: PackV2ScanPartitions reads them with conf.getConf(...). Their file-source counterparts have one each (filesMaxPartitionBytes and 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.

Comment thread docs/sql-migration-guide.md Outdated

## 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: removed here and moved to #59970 (SPARK-60763).

@rekbun

rekbun commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Moved from the PR description: local synthetic measurements of size-based packing against COALESCE, measured on 4372e37.

Local synthetic measurements against COALESCE

These use local[4], AQE off, a 4 MiB size target, zero opening cost, suggested minimum four tasks, two warmup rounds and five measured rounds. The row source reports estimated sizes of 16 bytes per row; no storage IO is simulated. COALESCE is placed before partial aggregation. Complete aggregate results match in every case.

Layout Original tasks / median ms Size-packed tasks / median ms Count-matched COALESCE tasks / median ms Bucket-count COALESCE tasks / median ms
512 small inputs, eight keys 512 / 1,085 4 / 57 4 / 60 8 / 67
64 larger inputs, one key 64 / 228 16 / 165 16 / 188 1 / 610
32 small + four oversized inputs, one key 36 / 170 5 / 105 5 / 287 1 / 321

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 reproduction

Save the source below as /tmp/ScanPackingMeasurements.scala, then run from this Spark checkout using JDK 25:

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.

Layout Variant Min–max ms Largest task, rows
small_inputs default 1063.5–1143.3 128
small_inputs size_packing 52.2–63.7 16,384
small_inputs coalesce_matching_count 53.4–64.3 16,384
small_inputs coalesce_key_count 60.3–74.9 8,192
large_single_key default 220.2–230.8 65,536
large_single_key size_packing 163.1–167.9 262,144
large_single_key coalesce_matching_count 181.6–192.1 262,144
large_single_key coalesce_key_count 608.7–623.3 4,194,304
skewed_inputs default 157.2–179.9 524,288
skewed_inputs size_packing 95.3–123.8 524,288
skewed_inputs coalesce_matching_count 283.0–290.9 2,099,200
skewed_inputs coalesce_key_count 318.5–354.4 2,113,536
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()
    }
  }
}

@rekbun

rekbun commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @peter-toth. All points are addressed in 3231cce and 6718798, with follow-ups in 06a5b46, 56e153c and a020f22:

  1. Cached and checkpointed plans. Packing is now in CacheManager's list of configs turned off for cached plans, unless canChangeCachedPlanOutputPartitioning is set. For checkpoints, withRegularShuffle only re-plans when local pipelined shuffle applies, so turning packing off there would not always take effect. Instead, QueryExecution.forCheckpoint plans with packing off, and Dataset.checkpoint passes that execution to LogicalRDD.fromDataset, so a checkpoint's statistics, partitioning and ordering all come from the execution that produced its RDD. The three SPARK-53322 checkpoint tests are back to master's expectations and pass in the packing re-run suite. New tests cover your cached-scan join, also with canChangeCachedPlanOutputPartitioning enabled, and checkpoint() and localCheckpoint() directly. The tuning-doc paragraph about turning packing off before materializing is replaced, and the canChangeCachedPlanOutputPartitioning doc now lists scan packing.
  2. Description. Rewritten to describe the change against master; the measurements are in the comment above.
  3. Separate rule. PackV2ScanPartitions is now its own rule, right after StampUnionDecisions in both QueryExecution.preparations and AQE's queryStagePreparationRules; AQE passes requiredDistribution. EnsureRequirements is unchanged from master, so the shadowed finalPlan is gone. The repeated-planning test runs the new rule after EnsureRequirements.
  4. Test tags. Added @ExtendedSQLTest to the three re-run suites.
  5. Migration note. Removed here and moved to a separate docs PR for master and branch-4.2: [SPARK-60763][DOCS] Add migration note for the V2 scan grouping change in Spark 4.2 #59970 (SPARK-60763).
  6. Typed accessors. Added for the five new configs.
  7. JIRA. SPARK-60265 now describes the size-based packing.

@rekbun
rekbun requested a review from peter-toth November 2, 2026 19:50
@peter-toth

Copy link
Copy Markdown
Contributor

Thank you @rekbun, let me check this tomorrow.

@peter-toth peter-toth left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 in inputRDD avoids it. inline

Non-blocking

  • 10. Every checkpoint is planned again once packing is on (new): forCheckpoint builds a second QueryExecution even 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): FilePartition reports no size, so with maxPartitionNum=2 an 8-file Parquet scan runs as 2 tasks, ignoring spark.sql.files.maxPartitionBytes. inline

Minor

  • 12. The new configs split the spark.sql.sources.v2.bucketing.* block (late catch). inline
  • 13. The minPartitionNum default repeats SparkSession.leafNodeDefaultParallelism (late catch). inline
  • 14. V2ScanPartitionCoalescer repeats GroupedPartitionCoalescer (late catch). inline
  • 15. maxPartitionNum doesn't mean what spark.sql.files.maxPartitionNum means (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 &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
scan.partitionPacking.isEmpty &&
scan.partitionPacking.isEmpty && !scan.scan.isInstanceOf[FileScan] &&

with FileScan in the datasources.v2 import. The same scan then runs 8 tasks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in dc626a7: FileScans are excluded, with your 8-file Parquet case as a test.

@rekbun
rekbun force-pushed the spj-scan-grouping branch from a020f22 to dc626a7 Compare November 6, 2026 22:16
@rekbun

rekbun commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review, @peter-toth. All seven points are addressed in dc626a7c49a, rebased onto master and SPARK-60752.

9. Planning: The rule now only marks eligible scans; inputRDD packs the inputs remaining after runtime filtering. Marked and checkpoint put-back copies share the original PlannedScan, so creating them adds no toBatch, planInputPartitions, or createReaderFactory calls. A put-back scan with runtime filters performs one separate runtime-filter replan. Counting and SPARK-44505/DPP tests cover AQE on and off.

10. Checkpoints: A checkpoint no longer builds a second logical, optimized, or physical plan. When packing withdrew
a layout the checkpoint would record, it copies only the root path needed to put those scans back; exchanges, query
stages, adaptive roots, and subquery plans remain untouched. It uses the Dataset's session and decides from the
prepared plan rather than the current packing setting.

11. V2 file scans: FileScans are excluded and remain governed by spark.sql.files.*. The 8-file V2 Parquet case
remains at 8 partitions with maxPartitionNum=2.

12. Config placement: The five configs now follow FILES_MAX_PARTITION_NUM.

13. Default: The minimum count uses leafNodeDefaultParallelism, resolved at execution. Only configured values
participate in scan equality and reuse.

14. Coalescer: Packed scans now use GroupedPartitionCoalescer. Its groups are transient, tied preferred locations
are spread across groups, and singleton groups leave location selection to the scheduler. Existing SPJ locality is
unchanged and covered by a per-input-host test.

15. Description: "Mirroring" is removed, and the description now states the exact relationship to the file-source
settings, including that maxPartitionNum applies only when an input has no valid size.

@rekbun
rekbun requested a review from peter-toth November 6, 2026 22:59

@peter-toth peter-toth left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 GroupedPartitionCoalescer changes 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. maxPartitionNum does not cap a scan whose inputs all report sizes (late catch): spark.sql.files.maxPartitionNum caps every file scan, but this config caps only a scan with an input that reports no size. With 8 sized inputs and maxPartitionNum=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 in pack. inline
  • 18. Keeping the root's layout goes further than Spark's similar rule (new): DisableUnnecessaryBucketedScan treats the root as having no consumer and protects only cached plans, through CacheManager. The checkpoint put-back and the streaming keepsRootLayout change QueryExecution, AdaptiveSparkPlanExec, InsertAdaptiveSparkPlan, IncrementalExecution, Dataset and LogicalRDD, 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. GroupPartitionsExec has always shipped them there, although only getPartitions on 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.scala and IncrementalExecution.scala go back to master. The checkpoint runs withRegularShuffle again, and fromDataset loses producedBy.
  • QueryExecution.scala and AdaptiveSparkPlanExec.scala keep only the rule in their preparation lists. forCheckpoint, lazyCheckpointPlan, executedPlanPrepared, keepsRootLayout and the keepRootLayout parameters go.
  • BatchScanExec.withoutPacking goes, since only the checkpoint uses it.
  • The CacheManager line stays, since the bucketed-scan rule has it too.
  • The tuning guide and the description say in one sentence that a checkpoint or a foreachBatch Dataset 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, keepRootLayout or requiredDistribution themselves.
  • 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@rekbun

rekbun commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @peter-toth. I agree with all three, and following the existing features made the change smaller. Addressed in 1719eba15ea:

  • 16. The coalescer changes are now SPARK-61279 ([SPARK-61279][SQL] Keep GroupedPartitionCoalescer's groups out of tasks and improve its location choice #60256). This PR is rebased on it.
  • 17. maxPartitionNum now has the files meaning on both paths. With 8 sized inputs and maxPartitionNum=2, the scan runs 2 tasks. While comparing it with FilePartition, I also found that packing by size differed from files when there is an opening cost: an input's own opening cost counted toward the target, and the minimum-count target rounded up. Packing now uses getFilePartitions' rule and maxSplitBytes' rounding. A new test runs 307 sets of sizes through both and gets the same groups, with and without the cap.
  • 18. The checkpoint put-back and the streaming keepsRootLayout are gone. Dataset, LogicalRDD, InsertAdaptiveSparkPlan and IncrementalExecution match master again. QueryExecution and AdaptiveSparkPlanExec only register the rule, which takes no parameters. As with DisableUnnecessaryBucketedScan, the root has no consumer. Cached plans keep their layout, because CacheManager turns packing off for them unless canChangeCachedPlanOutputPartitioning is set.

@ulysses-you

Copy link
Copy Markdown
Contributor

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: FileSourceScanExec packs files inside the scan and reports UnknownPartitioning(0), and spark.sql.files.* has remained a leaf-local size heuristic that is only usable where nothing reads the layout; it never grew distribution-preserving coalescing, the behavior Spark implements for shuffle reads by re-planning at stage boundaries and restating the layout as CoalescedHashPartitioning or a fewer-partition RangePartitioning. This PR repeats the same placement: it packs inside the leaf and decides the groups in BatchScanExec.inputRDD at execution, so the scan must give up its keyed partitioning and ordering and report Unknown(0), and the group count exists only as the runtime RDD's partition count, never as a Partitioning value during planning; because the grouping is next-fit over adjacent inputs, it also ignores key boundaries and can split one key's splits across partitions. The result is that no operator consuming partitioning or ordering can sit above a packed scan, so the rule has to prove a whole-plan property, its applicable set shrinks as layout-aware operators spread, and distribution-preserving coalescing, which needs a re-planning point, an expressible coarsened partitioning, and shared boundaries across co-partitioned scans, has nothing to hook into. Adding a coalesced partitioning type or making the grouping key-aware would not fix this on its own, because the missing piece is a plan-time producer of the group count, and that requires moving the decision out of inputRDD into a node or a stage boundary.

The other direction is to extend GroupPartitionsExec with size-based packing, but that would blur what GPE is for. GPE exists to replace a shuffle: EnsureRequirements inserts it on a keyed side so that the keyed layout, rather than an exchange, establishes co-partitioning, and everything about the node, from plannedPartitioning and the keyed layout checks to replication and padding, is there to keep the partition-to-key mapping valid. Size packing starts from the opposite premise: it is only legal where nobody reads the keyed layout, so the same node would sometimes report a keyed partitioning and sometimes Unknown(n), with the same name, metrics and neighbors but different guarantees, and the existing consumers are written against the keyed meaning; merging distinct keys breaks that invariant as well. Keeping the keyed contract does require the merged groups to be key-group-aware and shared across the two sides, but that is a well-scoped extension the node can grow into step by step, which is exactly what the current design cannot offer. So this route trades a clearer contract for a mode switch and forces every consumer to reason about which mode it is looking at, but it keeps the door open for the coalescing semantics, while the current design closes it.

@peter-toth

Copy link
Copy Markdown
Contributor

@ulysses-you @rekbun, I agree that marking the scan and packing its inputs in inputRDD is not the nicest place for this, even if V1 does the same with spark.sql.files.*.

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:

  • Before 4.2, BatchScanExec grouped the splits of a key, and now GroupPartitionsExec does it where a consumer needs the keyed layout.
  • That grouping also happened to give sensible task sizes when nothing used the KeyedPartitioning.
  • Without a consumer, every InputPartition is a task now, keyed or not.

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?

  • A rule right after EnsureRequirements puts it below each shuffle, wrapping the exchange's child, the way GPE wraps the child of the operator it serves.
  • The operators between the node and the scan keep the scan's own partitioning and ordering, and the exchange never reads its child's layout. So nothing has to be proven about the rest of the plan.
  • It decides the groups at execution, with a coalescer like GPE's. It uses the sizes of the scan's input partitions after runtime filtering, and reports UnknownPartitioning(0).
  • BatchScanExec can then go back to what it is on master: no packing field, no partitioning or ordering override and no packing metrics. The metrics move to the node.
  • This works where the exchange's child reads one scan through narrow operators.
  • The cost is that the operators between the node and the scan run once per original split. A partial aggregate, for example, then emits its partial rows per split rather than per merged task, so with many small splits of the same key it shuffles more than packing inside the scan does.
  • A plan root without an exchange, such as a write, would be a separate case, with the CacheManager exception from the last round.

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.

@ulysses-you

ulysses-you commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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 BatchScanExec.inputRDD, the scan keeps the partitioning and ordering master reports for the operators between it and the node, and the exchange case needs no whole-plan proof. UnknownPartitioning(0) is fine for now, because the node only goes where nothing above reads its layout.

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.

@rekbun

rekbun commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @peter-toth and @ulysses-you. I'll rework it as a separate operator, as Peter described:

  • BatchScanExec, CacheManager and ReplaceHashWithSortAgg go back to master.
  • A rule wraps a ShuffleExchangeExec's child when it reads one non-file DSv2 scan through Project, Filter, Sort, a partial aggregate or a broadcast hash join's streamed side. The first four are the operator DisableUnnecessaryBucketedScan allows, and a broadcast hash join maps each streamed partition to one output partition. The rule runs after RemoveRedundantSorts rather than right after EnsureRequirements, so it doesn't hide the local sort that rule removes under a shuffle, and with AQE it also sees the shuffle that skew join optimization can add.
  • At execution, the node packs the scan's inputs left after runtime filtering with the same packer, and runs them through GroupedPartitionCoalescer. It reports UnknownPartitioning(0). Inputs that runtime filtering emptied stay in the groups, since a global aggregate still emits a row for an empty partition.
  • Plan roots, broadcast build sides and unions stay out of this PR.
  • For locations, I'll take finding 1 in [SPARK-61279][SQL] Keep GroupedPartitionCoalescer's groups out of tasks and improve its location choice #60256, so the groups vote through the scan's lineage.

@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 CoalescedHashPartitioning: whole keys per group, boundaries decided at planning from the keyed splits' sizes, and the same boundaries on both sides of a join.

@rekbun

rekbun commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

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).

  • PackScanPartitionsExec goes between a ShuffleExchangeExec and its child, as described above, and decides its groups from the scan's partitions when it executes. BatchScanExec, CacheManager and ReplaceHashWithSortAgg are back to master.
  • The node reports UnknownPartitioning(0). Above the shuffle, one reader does look at the layout from before it: an AQE local read with one mapper per task. Over a packed shuffle that read reports none, and where an operator needs the scan's layout, AQE keeps the full shuffle read. That's why KeyGroupedPartitioningPackScanPartitionsSuite excludes "SPARK-59671: an AQE local read over a split scan does not lose matches": its setup expects the scan's keyed layout to reach the local read. PackV2ScanPartitionsSuite runs the same query with packing and keeps its answer checks.
  • With the opt-in local pipelined shuffle, a plan with a packing node keeps regular shuffles, since the node's width is known only at execution. PackV2ScanPartitionsPipelinedSuite pins that.
  • The operator list is a conservative start from DisableUnnecessaryBucketedScan's. Expand and generate also map partitions one to one; I left them out for now.
  • Memory: a packed task runs the operators below the node once per input, and keeps whatever they leave to task completion until it ends. A partial hash aggregate's codegen fast hash map left its bucket array, 512 KiB per input, and with a string grouping key also its batch's array of key offsets, as large again. So 2,048 inputs in one task held 1 GiB, or 2 GiB with a string key. Master has the same problem in fewer plans: GroupPartitionsExec above a distinct aggregation's first partial aggregate held 84 MiB with 168 splits of one key. The fix is [SPARK-61647][SQL] Drop a closed fast hash map's buckets and key offsets #60453 (SPARK-61647): the map's close() drops the buckets, and the batch's close() drops the key offsets. With it, a packed task over a hash aggregate keeps about 2 KiB per input (3 KiB with a string key).
  • The read suite again checks that packed tasks prefer their inputs' majority host. I had dropped that check here earlier, but finding 1 on [SPARK-61279][SQL] Keep GroupedPartitionCoalescer's groups out of tasks and improve its location choice #60256 was about exactly this node over a scan's mapped RDD, so this is the end-to-end check for it.

Two corrections to my last comment:

  • Emptied inputs stay in the groups so that every scan partition is still computed once, as on master, not because of global aggregates: the final aggregate emits its row either way.
  • The rule runs after RemoveRedundantSorts for the local sort under a shuffle, and before columnar transitions and codegen. The skew-join reason was wrong: a shuffle that skew join optimization adds sits above a split join, which the rule doesn't follow.

@rekbun
rekbun requested a review from peter-toth November 13, 2026 18:32
@github-actions github-actions Bot removed the AVRO label Nov 15, 2026
@peter-toth

Copy link
Copy Markdown
Contributor

peter-toth pushed a commit that referenced this pull request Nov 19, 2026
…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
peter-toth pushed a commit that referenced this pull request Nov 20, 2026
…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
@peter-toth

Copy link
Copy Markdown
Contributor

Thank for the rebase @rekbun. Let me review this PR next week.

@ulysses-you

Copy link
Copy Markdown
Contributor

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 shuffle

Plan B : pack directly above the BatchScan for simple plans

Today PackV2ScanPartitions inserts the node between a ShuffleExchangeExec and its child, so every operator in the chain runs once per input partition. That is where the per-input lifetime state comes from: a partial aggregate creates one fast hash map per input, a sort one sorter per input, and SPARK-61647 is needed to release the fast map arrays at task end.

If the node is inserted directly above the BatchScanExec, the chain above runs once per packed task. This matches what a v1 file scan does: FilePartition packs files into one scan partition at the scan, and every operator above runs per packed task. Concretely:

  • a partial aggregate keeps one map per task and emits fewer partial rows;
  • a local sort keeps one sorter per task;
  • spark_partition_id() and TaskContext.partitionId() both see the packed task index, instead of the current split where the built-in sees the input index and a UDF sees the task index;
  • per-input lifetime state disappears, so this feature no longer depends on SPARK-61647 (that commit can land as an independent change).

Sketch:

Shuffle
  +- Project/Filter/local Sort/partial Aggregate/BHJ streamed side
       +- PackScanPartitionsExec
            +- BatchScanExec

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:

  • ProjectExec/FilterExec: no requirement;
  • local SortExec: UnspecifiedDistribution, and its outputOrdering is valid for the packed task;
  • partial BaseAggregateExec: requiredChildDistributionExpressions = None means UnspecifiedDistribution (BaseAggregateExec.scala:96-116); a sort aggregate gets its required ordering from the local sort above the node;
  • BroadcastHashJoinExec streamed side: UnspecifiedDistribution (BroadcastHashJoinExec.scala:67-75).

A global SortExec must be excluded: it requires OrderedDistribution(sortOrder) (SortExec.scala:55-56), which UnknownPartitioning(0) does not satisfy. Today the rule matches any SortExec; please narrow it to local sorts, or place the node above a global sort.

With this placement the node still reports UnknownPartitioning(0) and no ordering, which is correct because no operator above it consumes the scan layout. The AQE local-read consequence stays as documented: a one-mapper-per-task local read over a packed shuffle reports an unknown layout, so validation keeps the full shuffle read where an operator would need the scan's keyed layout.

Then follow-up: coalescing after GroupPartitionsExec

The 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 GroupPartitionsExec with a CoalescedKeyedPartitioning: each task holds a set of complete key groups, the layout answers ClusteredDistribution for the grouped case, and pairing compares the per-task key sets, with shared group boundaries for the two sides of a join (the same shape as CoalesceShufflePartitions applying one set of boundaries to all stages in a group, CoalesceShufflePartitions.scala:80-124).

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

  1. openCostInBytes is charged once per InputPartition (V2ScanPartitionPacking.scala:68,165), but HasPartitionStatistics.filesCount() reports how many files one input reads (HasPartitionStatistics.java:44-50), and the same javadoc defines sizeInBytes() as "without any opening cost". An input that reads N files pays N opens but is charged one. With one input per directory of 100 small files, the input is charged 1 MB + 4 MB instead of 1 MB + 100 * 4 MB, so the packer puts many more inputs per task than the per-open model would. Either charge openCostInBytes * max(filesCount.getOrElse(1), 1), or change the sizeInBytes() javadoc and document the per-input model. The file-side peer charges per file (FilePartition.scala:75-81).

  2. The five new configs and their doc rows say 4.4.0 (SQLConf.scala:3619-3690, docs/sql-performance-tuning.md:755-793). branch-4.x has been 4.5.0-SNAPSHOT since 2026-11-21, and dev/next_version_candidates.py prints branch-4.x 4.5.0. These are new configs, so they should say 4.5.0.

  3. The new AQE local-read test describes the plan incorrectly (PackV2ScanPartitionsSuite.scala:345-351): the executed plan reads the wide side (lrt) in full and local-reads the narrow sides (lrs1/lrs2), which are unkeyed, so localReads.forall(... !KeyedPartitioning) is vacuous for the case the excluded SPARK-59671 test covered. The answer assertion is useful; please also pin the plan shape (the wide side stays a full shuffle read and no local read reports a keyed layout), or the exclusion reads as an unexplained coverage loss.

@peter-toth

Copy link
Copy Markdown
Contributor

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 EnsureRequirements added the sort. It adds none, though, where the scan's ordering already satisfies the requirement. For example:

  • A partial SortAggregateExec, as for max of a string, groups by the column that each split is sorted by, such as the sort column of a bucketed table, with its final aggregate above the shuffle.
  • It relies on the scan's ordering through a Project, with no sort between them.
  • With the node directly above the scan, the operator directly above it is the Project, which requires nothing, so the conditions hold.
  • The packed input is then not sorted, so the sort aggregate's required ordering is no longer met.

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:

  • Place the node at the lowest safe point, the lowest point where nothing above it, up to the shuffle, relies on the scan's partitioning or ordering. For projects, filters, partial hash aggregates and the streamed side of a broadcast hash join, that is directly above the scan. Where an operator relies on the scan's ordering, the node goes above it, at worst directly below the shuffle as now.
  • Let the node k-way merge the inputs it packs by the scan's ordering, as GroupPartitionsExec does with preserveOrderingOnCoalesce, instead of only concatenating them. It could then report that ordering and stay directly above the scan even where an operator uses it. A merge opens all inputs of a packed task at once, though. That costs the most in the case of many small splits that this PR targets, so I'd merge only where an operator needs the ordering. This could also come later.

In short, the best position depends on what runs between the scan and the shuffle:

  • A partial hash aggregate is best above the node, where it combines the inputs of a packed task.
  • An operator that relies on the scan's ordering is best below the node, unless the node merges, which has its own cost.

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.

@rekbun

rekbun commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

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:

  • The rule keeps today's eligibility: a one-to-one path from a non-file DSv2 scan to a shuffle.
  • On that path, it tries the node at each position from the scan up and takes the first one where the rewritten subtree passes ValidateRequirements.validate. The node reports no partitioning and no ordering, so a position below an operator that relies on the scan's ordering fails, as in Peter's sort aggregate example. So does a position below a global sort, since UnknownPartitioning doesn't satisfy OrderedDistribution.
  • Directly below the shuffle always passes, so no plan is worse off than with the current placement.

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, spark_partition_id() and TaskContext.partitionId() agree, and this PR no longer needs SPARK-61647. #60453 still fixes the GroupPartitionsExec case on master, so it can go in on its own. The rule still runs before the columnar transitions and CollapseCodegenStages, so the node goes under ColumnarToRowExec and doesn't split a codegen stage. I'd leave the k-way merge for later.

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:

  1. Agreed. The open cost will be charged per file, openCostInBytes * max(filesCount.orElse(1), 1), as FilePartition does.
  2. The five configs and their doc rows will say 4.5.0.
  3. Agreed. The local reads in that test are over lrs1 and lrs2, which are unkeyed, so the assertion holds trivially. I'll fix the comment and pin the plan shape: the lrt shuffle is read in full, and no local read reports a keyed layout.

Agreed that the follow-up needs its own ticket. To add to my earlier comment on it:

  • For transforms with a ReducibleFunction, the existing reducers can coarsen the keys on both sides, e.g. bucket(1024, x) to bucket(64, x), or hours to days. The layout stays a KeyedPartitioning over the reduced keys, so only choosing the reduction from the sizes is new.
  • For identity keys, both sides need the same boundaries over the sorted keys, decided from their combined sizes. That needs a layout with a range of keys per partition.
  • A key above the target stays alone, with partial clustering as today.

@ulysses-you

Copy link
Copy Markdown
Contributor

thank you @peter-toth and @rekbun , agreed with the lowest safe point, and with deciding it through ValidateRequirements rather than an operator list. One thing need to notice, the rule which insert the new operator should be put after the RemoveRedundantSorts to make sure it won't break other optimization rules.

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.
@rekbun

rekbun commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @ulysses-you and @peter-toth. Updated in 73d0543, and rebased on master without #60453:

  • PackV2ScanPartitions tries the node at each position from the scan up and keeps the first where ValidateRequirements.validate passes; directly below the shuffle is the fallback. For projects, filters, local sorts, partial hash aggregates and a broadcast hash join's streamed side, the node goes directly above the scan. In Peter's case it goes above the partial SortAggregateExec, and no sort is added.
  • @ulysses-you, the rule runs after ReplaceHashWithSortAgg and RemoveRedundantSorts, in both QueryExecution.preparations and AQE's queryStagePreparationRules, so the check sees which operators rely on the scan's ordering once those rules have decided. A new test fails if it runs before RemoveRedundantSorts.
  • The opening cost is charged per file: openCostInBytes * max(filesCount.orElse(1), 1). An input joins a task only if all of its files would, as FilePartition checks each file.
  • The five configs and their doc rows say 4.5.0.
  • The AQE local-read test pins the plan: no shuffle read sits over the lrt shuffle, so the sort merge join reads it in full, and the only local reads are the broadcast builds over lrs1 and lrs2. Those report no keyed layout, which holds trivially since both tables are unkeyed.

With the node above the scan, KeyGroupedPartitioningPackScanPartitionsSuite also excludes the SPARK-58974 collapse skew guard test. Only its setup check fails: where the items side is shuffled, the Project it inspects for the collapsed layout now reads the node. What it checks there (no GroupPartitionsExec, the shuffle counts) is decided before packing, and its plans without a shuffle aren't packed.

I filed SPARK-62333 for coalescing whole key groups above GroupPartitionsExec.

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.

@peter-toth peter-toth left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. maxPartitionNum can raise the task count (new): The second pass packs with a target of ceilDiv(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, and FilePartition shares 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 maxPartitionNum doc 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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, 4MB opening cost) with minPartitionNum=1: without a cap, the 60 MB inputs pair up and each 70 MB input stays alone, so the scan runs 20 tasks.
  • With maxPartitionNum set 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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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."

Comment thread docs/sql-performance-tuning.md Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 spark-test left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

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 HasPartitionStatistics javadoc: it now covers keyed and unkeyed inputs, defines sizeInBytes() as the estimated bytes an input reads from storage without any opening cost, with a negative value meaning unknown, defines filesCount() 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ulysses-you left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants