≈ The Lake

Part 9 · Query execution · Chapter 30

DataSource V2 and scan planning for tables

How Delta and Iceberg plug into Spark 4.0: the DSv2 read API, where the optimizer pushes filters, Delta's V1 fallback and PrepareDeltaScan, Iceberg's SparkScanBuilder, how files become tasks, and the runtime filters: dynamic partition pruning, Bloom filters and Databricks dynamic file pruning.

complete ~35 min

After this chapter you should be able to:
  • Trace a query on a Delta table and on an Iceberg table from catalog lookup to the files scanned.
  • Say which filters prune files, which are pushed into the reader, and which Spark re-checks on rows.
  • Compute the split size and task count for a scan with Spark's and Iceberg's planners.
  • Predict whether dynamic partition pruning becomes a broadcast reuse, a subquery or nothing, and explain how dynamic file pruning differs.

Chapter 29 ended with a physical plan whose leaf was a FileScan with PushedFilters and a ReadSchema. This chapter is about that leaf: how Spark finds the table, how much of the query it hands to the table format, which files survive, and how they become tasks. Chapters 25 and 26 covered the pruning itself (partition values and min/max statistics). Here the subject is the plumbing that calls it, and the pruning that can only happen at runtime.

The simulator in src/sim/spark/scan.ts ports the split planners of Spark and Iceberg and the decisions of PartitionPruning, PlanDynamicPruningFilters and InjectRuntimeFilter, and runs them on a 90-day partitioned table.

The connector read API

DataSource V2 (DSv2) is the Java interface set in org.apache.spark.sql.connector. A read goes through five objects, each made by the one before:

ObjectMade byJob
TableCatalogspark.sql.catalog.<name> configloadTable(ident) returns a Table[Spark TableCatalog]
Table with SupportsReadthe catalogschema, capabilities, newScanBuilder(options)[Spark SupportsRead]
ScanBuilderthe tablereceives pushdowns, then build()[Spark ScanBuilder]
Scanthe builderreadSchema(), toBatch(), optional statistics and partitioning[Spark Scan]
Batchthe scanplanInputPartitions() on the driver, createReaderFactory() for executors[Spark Batch]

Pushdown is negotiated through mix-in interfaces on the builder. SupportsPushDownV2Filters has pushPredicates(Predicate[]), which returns the predicates Spark must still evaluate after the scan, and pushedPredicates(), which reports the ones the source used.[Spark SupportsPushDownV2Filters] SupportsPushDownRequiredColumns.pruneColumns(StructType) passes the columns the query needs.[Spark SupportsPushDownRequiredColumns] There are others for aggregates, limits, offsets, samples and top-N.

One interface sits on the Scan, not the builder: SupportsRuntimeV2Filtering. Its filterAttributes() names the columns the scan can filter on after planning, and filter(Predicate[]) receives runtime predicates. Spark then calls toBatch() again.[Spark SupportsRuntimeV2Filtering] This is how dynamic partition pruning reaches a V2 source.

Quiz Check: the read APIAnswers are scheduled for spaced review on the Review page.

Q1. In what order does Spark call the DSv2 read API for a batch query?

How sure are you?

Where the optimizer pushes filters

Pushdown is a set of optimizer rules, and their order matters. In Spark 4.0 the default batches run Pre CBO Rules and then Early Filter and Projection Push-Down.[Spark Optimizer batches] SparkOptimizer fills the second with SchemaPruning, V2ScanRelationPushDown, PruneFileSourcePartitions and a few others. After all the default batches it appends PartitionPruning (dynamic partition pruning) and then InjectRuntimeFilter.[Spark SparkOptimizer] Static pruning therefore happens before the runtime filters are even inserted.

V2ScanRelationPushDown is a fold over seven steps:[Spark V2ScanRelationPushDown]

val pushdownRules = Seq[LogicalPlan => LogicalPlan](
  createScanBuilder,       // DataSourceV2Relation -> ScanBuilderHolder(table.newScanBuilder(options))
  pushDownSample,
  pushDownFilters,         // Filter(cond, holder): split conjuncts, PushDownUtils.pushFilters
  pushDownAggregates,
  pushDownLimitAndOffset,
  buildScanWithPushedAggregate,
  pruneColumns)            // pruneColumns(requiredSchema), then build() -> DataSourceV2ScanRelation
pushdownRules.foldLeft(plan) { (newPlan, rule) => rule(newPlan) }

pushDownFilters splits the condition into conjuncts and sets aside any with a subquery. It hands the rest to the builder and rebuilds a Filter from whatever comes back, plus the subquery conjuncts. The source code comment says it directly: “postScanFilters and pushedFilters can overlap, e.g. the parquet row group filter.” A filter used only to skip files or row groups is both pushed and post-scan, because skipping by statistics is approximate.

V1 file sources take a parallel path, FileSourceStrategy. It splits filters into partition-key filters and data filters. Data filters are translated to sources.Filters and given to the Parquet reader as PushedFilters. The filter that stays above the scan is filterSet -- partitionKeyFilters.[Spark FileSourceStrategy] A partition filter is exact (every row in the file has that value), so Spark drops it. A data filter is kept.

Quiz Check: pushdownAnswers are scheduled for spaced review on the Review page.

Q1. What does SupportsPushDownV2Filters.pushPredicates return?

How sure are you?

Q2. Which runs first in the Spark 4.0 optimizer?

How sure are you?
A pushed filter can still run in Spark
  1. Split the predicate Spark offers eligible conjuncts to the connector’s scan builder.
Inside the scan
  1. Pushed filter The connector can use it to plan files, partitions or row groups.
Above the scan
  1. Residual filter Spark evaluates predicates that the connector returns for post-scan evaluation.
A predicate can take both paths. For example, skipping a row group by its bounds still leaves matching and nonmatching rows in other groups.[Spark pushdown rule]

Delta: a V2 table read through V1

Delta registers DeltaCatalog, and loadTable returns a DeltaTableV2 for a Delta table. That class implements Table, SupportsWrite and V2TableWithV1Fallback, but not SupportsRead.[Delta DeltaTableV2] Reads are turned back into V1 during analysis. DeltaAnalysis matches FallbackToV1DeltaRelation: a DataSourceV2Relation over a DeltaTableV2 that is not tagged to stay V2 (MERGE uses that tag).[Delta FallbackToV1DeltaRelation] It is replaced with a LogicalRelation over DeltaTableV2.toBaseRelation.[Delta DeltaRelation.fromV2Relation] That calls DeltaLog.createRelation, which builds a HadoopFsRelation with the Parquet format and a TahoeLogFileIndex as its file index.[Delta DeltaLog.createRelation]

So a Delta read is a normal Spark file scan whose file listing comes from the log. Listing every file at planning time would be slow and could run twice for the same table in one query. Delta’s session extension injects PrepareDeltaScan as a pre-CBO rule, followed by ConstantFolding.[Delta session extension] For each scan of a TahoeLogFileIndex with its filters (and limit), it runs data skipping once and swaps in a PreparedDeltaFileIndex:[Delta PrepareDeltaScan]

// PrepareDeltaScan.prepareDeltaScan (trimmed)
val deltaScans = new mutable.HashMap[LogicalPlan, DeltaScan]()
transformWithSubqueries(plan) {
  case scan @ DeltaTableScan(planWithRemovedProjections, filters, fileIndex, limit, delta) =>
    val scanGenerator = getDeltaScanGenerator(fileIndex)          // pins the snapshot
    val preparedScan = deltaScans.getOrElseUpdate(planWithRemovedProjections.canonicalized,
      filesForScan(scanGenerator, limit, filters, delta))         // partition + stats skipping
    val preparedIndex = getPreparedIndex(preparedScan, fileIndex)
    optimizeGeneratedColumns(scan, preparedIndex, filters, limit, delta)
}

filesForScan is the skipping of chapters 25 and 26. It drops filters with subqueries, non-deterministic filters and filters on file metadata. It separates partition-only filters from data filters. With no data filters it only evaluates partition values. Otherwise it builds min/max predicates over the stats column.[Delta DataSkippingReader.filesForScan] The protocol allows this use: per-file statistics “can be used for eliminating files based on query predicates or as inputs to query optimization.”[Delta PROTOCOL.md: Per-file Statistics]

At physical planning, FileSourceScanExec asks the index for files with the plan’s filters. PreparedDeltaFileIndex.matchingFiles returns the prepared list if the filters are the same ones it was prepared with. If they differ, it logs “Prepared scan does not match actual filters” and runs filesForScan again on the pinned snapshot.[Delta PreparedDeltaFileIndex] The prepared index also fixes the snapshot version, so every scan of the table in one query reads the same version.

Quiz Check: DeltaAnswers are scheduled for spaced review on the Review page.

Q1. How does a batch read of a Delta table get its file list?

How sure are you?

Iceberg: SparkScanBuilder and SparkBatchQueryScan

Iceberg is a native DSv2 source. SparkCatalog.loadTable returns a SparkTable. A time-travel or branch identifier gives a SparkTable pinned to that snapshot.[Iceberg SparkCatalog.loadTable] newScanBuilder returns a SparkScanBuilder, which implements SupportsPushDownV2Filters, SupportsPushDownRequiredColumns, SupportsPushDownAggregates, SupportsPushDownLimit and SupportsReportStatistics.[Iceberg SparkScanBuilder]

Its pushPredicates sorts predicates into three kinds, as its own comment lists:[Iceberg SparkScanBuilder.pushPredicates]

for (Predicate predicate : predicates) {
  Expression expr = SparkV2Filters.convert(predicate);          // null if not convertible
  if (expr != null) {
    Binder.bind(schema.asStruct(), expr, caseSensitive);         // must bind to the schema
    expressions.add(expr);
    pushableFilters.add(predicate);                              // used to prune files
  }
  if (expr == null || unpartitioned()
      || !ExpressionUtil.selectsPartitions(expr, table, caseSensitive)) {
    postScanFilters.add(predicate);                              // Spark re-checks rows
  }
}

A filter that selects whole partitions in every partition spec is evaluated “completely on Iceberg side”. Everything else that converts is used for pruning and also returned to Spark. build() makes a SparkBatchQueryScan over an Iceberg TableScan with those expressions.[Iceberg SparkScanBuilder.build] Planning the scan walks the snapshot’s manifests. ManifestGroup drops manifests whose partition summaries cannot match, then filters entries by partition and metrics.[Iceberg ManifestGroup] The spec states the rule: “Manifests that contain no matching files, determined using file counts, partition summaries, or column stats, may be skipped.”[Iceberg spec: Scan Planning]

SparkBatchQueryScan also implements SupportsRuntimeV2Filtering. Its filterAttributes() are the source columns of all partition fields that are in the read schema. filter() projects each runtime predicate through every spec with an inclusive projection and drops the planned tasks whose partition does not match. If any are dropped, it resets the task list so splits are planned again.[Iceberg SparkBatchQueryScan.filter]

Quiz Check: IcebergAnswers are scheduled for spaced review on the Review page.

Q1. Iceberg table partitioned by identity(pickup_date). Which of these filters does Spark not re-evaluate on rows?

How sure are you?

From files to tasks

The files that survive are cut into splits and grouped into read tasks. Spark and Iceberg do this differently.

Spark (Delta and other file sources). FileSourceScanExec.createReadRDD computes a split size, cuts each splittable file into pieces of that size, sorts the pieces by length descending, and packs them.[Spark createReadRDD][Spark PartitionedFileUtil.splitFiles] The split size and the packing are in FilePartition:[Spark FilePartition]

def maxSplitBytes(sparkSession: SparkSession, calculateTotalBytes: => Long): Long = {
  val defaultMaxSplitBytes = conf.filesMaxPartitionBytes          // 128MB
  val openCostInBytes = conf.filesOpenCostInBytes                 // 4MB
  val minPartitionNum = conf.filesMinPartitionNum.getOrElse(sparkSession.leafNodeDefaultParallelism)
  val bytesPerCore = calculateTotalBytes / minPartitionNum        // total includes 4MB per file
  Math.min(defaultMaxSplitBytes, Math.max(openCostInBytes, bytesPerCore))
}

// Assign files to partitions using "Next Fit Decreasing"
partitionedFiles.foreach { file =>
  if (currentSize + file.length > maxSplitBytes) closePartition()
  currentSize += file.length + openCostInBytes
  currentFiles += file
}

Three consequences follow. On a big scan the split size is 128MB, so each task reads about 128MB. On a small scan on a big cluster, bytesPerCore is small and files are cut into pieces of 4MB or more so that every core gets work. And because each file costs 4MB extra in the packing, a task holds fewer small files than their bytes alone would allow. The defaults are spark.sql.files.maxPartitionBytes 128MB and spark.sql.files.openCostInBytes 4MB. If spark.sql.files.maxPartitionNum is set and exceeded, the packing is redone with a larger split size.[Spark SQLConf files.*]

Iceberg. SparkPartitioningAwareScan.taskGroups adjusts the split size and calls TableScanUtil.planTaskGroups.[Iceberg SparkPartitioningAwareScan.taskGroups] The defaults are table properties: read.split.target-size 128MB, read.split.planning-lookback 10, read.split.open-file-cost 4MB, and read.split.adaptive-size.enabled true.[Iceberg TableProperties] With adaptive sizing and no explicit split size, the split size shrinks only when the scan would give fewer splits than slots:[Iceberg TableScanUtil.adjustSplitSize][Iceberg SparkScan.adjustSplitSize]

long splitCount = LongMath.divide(scanSize, splitSize, RoundingMode.CEILING);
long adjustedSplitSize = Math.max(scanSize / parallelism, Math.min(MIN_SPLIT_SIZE, splitSize)); // 16MB
return splitCount < parallelism ? adjustedSplitSize : splitSize;

The parallelism is max(defaultParallelism, spark.sql.shuffle.partitions), so at least 200 by default.[Iceberg SparkReadConf.parallelism] The splits are then bin-packed with weight max(sizeBytes, filesCount × openFileCost).[Iceberg TableScanUtil.planTaskGroups] BinPacking.PackingIterator keeps up to lookback open bins and puts each item in the first bin it fits. When a new bin makes more than lookback bins, it emits the heaviest one (largestBinFirst).[Iceberg BinPacking] Unlike Spark’s planner, it does not sort first. The look-back is what lets a small file fill a gap left by a large one.

Quiz Check: splitsAnswers are scheduled for spaced review on the Review page.

Q1. A Delta scan selects 40 files totalling 2 GB on a 400-core cluster, default settings. What is maxSplitBytes?

How sure are you?

Q2. An Iceberg scan of 300 MB with default settings and 64 cores. What split size does it use?

How sure are you?

Dynamic partition pruning

Chapter 25 introduced dynamic partition pruning (DPP). Here is the decision in full. PartitionPruning looks at each equi-join conjunct. It inserts a predicate on one side when three things hold. The side’s key must trace down to a filterable scan: a partition column of a HadoopFsRelation or Hive table, or a filterAttribute of a SupportsRuntimeV2Filtering scan. The join type must allow pruning that side. And the other side must have a filter that isLikelySelective (a comparison, IN, LIKE, a string predicate) and must not be a stream.[Spark PartitionPruning][Spark isLikelySelective]

// PartitionPruning.insertPredicate (trimmed)
lazy val hasBenefit = pruningHasBenefit(pruningKey, partScan, filteringKeys.head, filteringPlan)
if (conf.exchangeReuseEnabled || hasBenefit) {
  Filter(DynamicPruningSubquery(pruningKey, filteringPlan, joinKeys, indices,
    onlyInBroadcast = conf.dynamicPartitionPruningReuseBroadcastOnly || !hasBenefit), pruningPlan)
} else pruningPlan

pruningHasBenefit estimates the bytes pruned as filterRatio × sizeInBytes of the partitioned plan. It compares that with the overhead, the summed sizeInBytes of the other side’s scans. The ratio is 1 - otherDistinct / partDistinct from CBO column statistics when both exist and the partitioned side has more distinct values. Otherwise it is fallbackFilterRatio, 0.5.[Spark pruningHasBenefit][Spark SQLConf DPP]

The predicate is resolved at physical planning by PlanDynamicPruningFilters, which has three outcomes:[Spark PlanDynamicPruningFilters]

  1. If exchange reuse is on and the plan has a BroadcastHashJoinExec whose build side is the same plan as the filtering side, the predicate becomes InSubqueryExec over a SubqueryBroadcastExec. It reuses the broadcast, so the dimension is read once.
  2. Else, if onlyInBroadcast is set, the predicate becomes a true literal, which cleanup rules remove. With the default reuseBroadcastOnly = true, this is what happens to every DPP predicate under a sort-merge join.
  3. Else it becomes an InSubquery over an aggregate of the filtering plan: the dimension side runs twice.

For a V1 scan (Delta), the runtime predicate is applied in FileSourceScanExec.dynamicallySelectedPartitions. It evaluates the predicate against the partition values of the statically selected files, and the SQL metrics show both file counts.[Spark FileSourceScanExec] For a V2 scan, BatchScanExec calls filter() on the scan and then toBatch().planInputPartitions() again.[Spark BatchScanExec]

Quiz Check: DPPAnswers are scheduled for spaced review on the Review page.

Q1. Default settings. A fact table partitioned by date joins a filtered dimension with a sort-merge join (no broadcast). What happens to the DPP predicate?

How sure are you?

Q2. What must hold for PartitionPruning to insert a predicate on the fact side? (Select all.) (select all that apply)

How sure are you?

Runtime Bloom filters

DPP needs a partition column. For a join on a data column, Spark 4.0 has a different runtime filter. InjectRuntimeFilter runs right after PartitionPruning. For each equi-join key without a DPP filter, it may add might_contain(bloomFilter, xxhash64(key)) above the large side, built from a BloomFilterAggregate over the other side.[Spark InjectRuntimeFilter] It does so only when all of these hold:[Spark InjectRuntimeFilter conditions]

  • The keys are simple: no UDFs, LIKE or regex.
  • The join is probably a shuffle join (neither side broadcasts by hint or size), or the application side has a shuffle below it.
  • The largest scan under the application side is at least applicationSideScanSizeThreshold, 10GB.
  • The creation side is a selective filter over a scan.
  • The creation side’s sizeInBytes is at most creationSideThreshold, 10MB.

The last condition interacts with chapter 29: without CBO, a Filter does not shrink sizeInBytes. A 600MB dimension with a selective filter is still estimated at 600MB, so no Bloom filter is built. At most spark.sql.optimizer.runtimeFilter.number.threshold (10) such filters are injected per query.[Spark SQLConf runtime filters] A Bloom filter discards rows during the scan’s Filter. It does not skip files, because no file statistic records hashes of the join key.

Quiz Check: Bloom filtersAnswers are scheduled for spaced review on the Review page.

Q1. A 40 GB fact table shuffle-joins a dimension estimated at 600 MB with a selective filter, no CBO. Does InjectRuntimeFilter add a Bloom filter?

How sure are you?

Dynamic file pruning on Databricks

DFP is the runtime version of chapter 26: min/max skipping with values that come from the other side of a join. It pays off only when file ranges on the join key are narrow, which is what Z-order or liquid clustering on that key gives you. On a table written in arrival order, every file spans almost every key, and there is nothing to skip.

Quiz Check: DFPAnswers are scheduled for spaced review on the Review page.

Q1. What does Databricks dynamic file pruning add over open-source DPP?

How sure are you?

Try it

The lab runs a count over trips, a 90-day table partitioned by pickup_date with 8 files per day. Each bar is a pruning stage, and the strip at the bottom shows the read tasks. Things to try:

  • Join calendar: DPP keeps the 5 holiday days. Set autoBroadcastJoinThreshold to -1: the join becomes sort-merge, and with reuseBroadcastOnly on, the predicate becomes true and nothing is pruned. Untick reuseBroadcastOnly: the subquery runs twice and pruning comes back.
  • Tick driver_id BETWEEN 1000 AND 1999 with arrival-order layout: data skipping drops nothing. Switch the layout to sorted by driver_id: one file per day survives.
  • Join drivers: DPP does not apply (not a partition column), and the Bloom filter is rejected on the 600MB estimate. Turn on dynamic file pruning: it skips nothing in arrival order, and keeps one file per day when sorted.
  • Compare task planning. With all 720 files, Spark makes 544 tasks, because small files share a task. With the 40 holiday files on 400 cores, the split size drops to about 7MB and Spark makes nearly 400 tasks. Switch to Iceberg: its split size stays at 16MB, the floor of adjustSplitSize.
SELECT count(*) FROM trips t JOIN calendar c ON t.pickup_date = c.date WHERE c.is_holiday

trips is partitioned by pickup_date: 90 days of 8 files, 47.6 GB. calendar is 12 KB with 5 holidays; drivers is 600 MB, and drivers who signed up in 2026 have the highest ids.

  1. All files in the snapshot720 of 720 files, 47.6 GB
    AddFile actions in the snapshot.
  2. Static partition pruning720 of 720 files, 47.6 GB
    No partition filter.
  3. Data skipping (min/max)720 of 720 files, 47.6 GB
    No data filter.
  4. Dynamic partition pruning40 of 720 files, 2.7 GB
    The join is a broadcast hash join, so the pruning subquery reuses the broadcast (SubqueryBroadcastExec).
Read tasks

FilePartition.maxSplitBytes = min(128 MB, max(4 MB, bytes / 64 cores)) = 45 MB. 84 splits, packed Next Fit Decreasing into 68 tasks.

Summary

  • DSv2 reads go TableCatalog.loadTable → Table.newScanBuilder → pushdowns → build() → Scan.toBatch → planInputPartitions. SupportsRuntimeV2Filtering adds a filter step after planning.
  • Pushdown runs in Early Filter and Projection Push-Down. pushPredicates returns the post-scan filters, which can overlap the pushed ones. File sources drop exact partition filters after the scan and keep data filters.
  • Delta reads fall back to V1: a HadoopFsRelation over TahoeLogFileIndex. The pre-CBO rule PrepareDeltaScan runs skipping once per distinct scan and pins the snapshot in a PreparedDeltaFileIndex.
  • Iceberg’s SparkScanBuilder pushes every convertible filter and keeps as post-scan those that do not select whole partitions. Manifests are pruned by partition summaries, then entries by partition and metrics.
  • Spark splits at min(128MB, max(4MB, bytes/cores)) and packs Next Fit Decreasing with a 4MB open cost. Iceberg splits at 128MB, shrinking to no less than 16MB when there are fewer splits than max(cores, 200), and packs with a look-back of 10.
  • DPP needs a partition key, a pruning join type and a selective filter on the other side. It reuses a broadcast. Under a sort-merge join it becomes true by default.
  • Runtime Bloom filters cover shuffle joins on data columns, but only when the creation side is estimated at 10MB or less. They drop rows, not files. Databricks DFP skips Delta files by join-key values, and needs clustering on that key to help.

Concepts in this chapter

Explained here

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 11 quiz questions.

Review this chapter's cards → Review all due cards