≈ The Lake

Part 9 · Query execution · Chapter 29

The Spark SQL query lifecycle

From SQL text to a running plan in Spark 4.0: parsing, analysis with fixed-point rule batches, Catalyst's logical optimizations, size statistics and join selection, EnsureRequirements and whole-stage codegen, and how adaptive query execution re-plans with runtime statistics.

complete ~35 min

After this chapter you should be able to:
  • Read an EXPLAIN EXTENDED output phase by phase and say which component produced each.
  • Explain how RuleExecutor runs batches to a fixed point, and name the rules that push filters and prune columns.
  • Predict the join strategy from size estimates, and explain why a Filter does not shrink the estimate.
  • Explain where exchanges, sorts and codegen stages come from, and what AQE changes at runtime.

Part 9 is about the engine that reads the tables of parts 4 to 8. This chapter follows one query through Spark SQL in Spark 4.0.1, from text to the plan that runs. Chapter 30 covers how that plan talks to a table format, chapters 31 and 32 how the scan and operators run, and chapter 33 how shuffles and joins work.

The simulator in src/sim/spark/catalyst.ts is a small Catalyst for a subset of SQL. It has the same phases, the same rule executor and the same size statistics, and a few of the real rules ported to it. Its output has the shape of EXPLAIN EXTENDED, so you can compare it with a real Spark session.

From SQL text to a plan

QueryExecution holds the plans of one query as lazy values, each built from the one before:[Spark QueryExecution]

PlanBuilt byWhat it is
logicalthe parser (SparkSqlParser, ANTLR)unresolved: names are strings
analyzedAnalyzerevery relation, column and function bound, types checked
optimizedPlanOptimizer (SparkOptimizer)rewritten by rule batches
sparkPlanSparkPlannerthe first physical plan its strategies produce
executedPlanthe preparation ruleswith exchanges, sorts, codegen stages and AQE
From SQL text to an executable Spark plan
  1. Parse Build the unresolved logical tree.
  2. Analyze Bind names and check types.
  3. Optimize Rewrite the logical tree with rules.
  4. Plan Pick physical operators and prepare exchanges, sorts and codegen.
When execution starts, adaptive query execution can revise the remaining physical plan using metrics from completed query stages.[Spark QueryExecution]

Nothing runs until an action needs executedPlan. EXPLAIN EXTENDED prints the parsed, analyzed, optimized and physical plans. Setting spark.sql.planChangeLog.level to WARN logs every rule that changed a plan.

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

Q1. In what order does QueryExecution produce its plans?

How sure are you?

Trees and rules

Catalyst plans and expressions are immutable trees of case classes. A rule is a function from tree to tree, usually a transform with a partial function that matches a pattern and rebuilds the matched nodes. A batch is a named list of rules with a strategy: Once, or FixedPoint(n).[Spark RuleExecutor strategies] RuleExecutor.execute is the loop that both the analyzer and the optimizer use:[Spark RuleExecutor.execute]

// RuleExecutor.execute (trimmed)
batches.foreach { batch =>
  var iteration = 1; var lastPlan = curPlan; var continue = true
  while (continue) {
    curPlan = batch.rules.foldLeft(curPlan) { (plan, rule) => rule(plan) }  // one pass
    iteration += 1
    if (iteration > batch.strategy.maxIterations) {
      logWarning(s"Max iterations (${iteration - 1}) reached for batch ${batch.name}")
      continue = false
    }
    if (curPlan.fastEquals(lastPlan)) continue = false                   // fixed point
    lastPlan = curPlan
  }
}

Each pass applies every rule of the batch in order. The batch ends when a whole pass changes nothing, or after maxIterations. For the optimizer that is spark.sql.optimizer.maxIterations, 100 by default.[Spark SQLConf] Rules are written to be small and local, and the fixed point composes them. Pushing a filter through a project lets column pruning fire, which lets the next pass push the filter further. The lab lists every rule that changed the plan, with its batch and pass.

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

Q1. How does a FixedPoint batch in RuleExecutor decide to stop?

How sure are you?

Analysis

The parser accepts any identifier. 'trips and 't.fare in the parsed plan are unresolved, which EXPLAIN marks with a leading quote. The Analyzer’s main batch is Resolution, a fixed point over rules such as ResolveRelations (catalog lookup), ResolveReferences (bind each name to an attribute of a child’s output), ResolveFunctions and ResolveAliases, plus the type-coercion rules.[Spark Analyzer batches] Each resolved attribute gets an exprId, the #7 in city_id#7. From then on, columns are identified by that id, not by name, which is how a plan can join two tables that both have city_id.

When the batches finish, CheckAnalysis walks the plan and turns whatever is left into an error with a class: TABLE_OR_VIEW_NOT_FOUND, UNRESOLVED_COLUMN.WITH_SUGGESTION, AMBIGUOUS_REFERENCE, MISSING_AGGREGATION. The simulator reports the same classes.

Spark 4.0 also contains a single-pass resolver, which resolves the plan “in a single post-order traversal”. It sits behind the internal flag spark.sql.analyzer.singlePassResolver.enabled, whose doc says “This feature is currently under development”.[Spark SQLConf: single-pass resolver] The fixed-point analyzer is what runs by default.

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

Q1. Where does [UNRESOLVED_COLUMN.WITH_SUGGESTION] come from?

How sure are you?

Logical optimization

Optimizer.defaultBatches lists about thirty batches. SparkOptimizer adds more after them, such as partition pruning, runtime filters and Python UDF extraction.[Spark Optimizer batches][Spark SparkOptimizer] The core is one rule set run three times:

// Optimizer.defaultBatches (trimmed)
val operatorOptimizationRuleSet = Seq(
  PushProjectionThroughUnion, ReorderJoin, EliminateOuterJoin, PushDownPredicates,
  ColumnPruning, CollapseProject, ..., NullPropagation, ConstantPropagation,
  ConstantFolding, BooleanSimplification, SimplifyConditionals, PruneFilters, SimplifyCasts, ...)
Batch("Operator Optimization before Inferring Filters", fixedPoint, operatorOptimizationRuleSet: _*),
Batch("Infer Filters", Once, InferFiltersFromGenerate, InferFiltersFromConstraints),
Batch("Operator Optimization after Inferring Filters", fixedPoint, operatorOptimizationRuleSet: _*),

The rules that matter most for a lakehouse:[Spark Optimizer rule set]

  • PushDownPredicates combines adjacent filters and moves deterministic conjuncts below projects, and below joins to the side whose output they reference. A filter on d.rating lands directly above drivers.
  • ColumnPruning inserts projects so that each subtree produces only the attributes used above it. Together with the pushed filters, this becomes the scan’s ReadSchema and PushedFilters (chapter 30). Chapter 8’s Parquet pushdown starts here.
  • ConstantFolding and BooleanSimplification evaluate 4 + 0.5 to 4.5 and drop true AND x.
  • InferFiltersFromConstraints derives new predicates from constraints. For an inner equi-join it adds isnotnull(key) on both sides, and it copies a.k = 5 to b.k = 5. Those inferred filters are then pushed by the second run of the rule set.

The order is deliberate. Inferring filters needs filters to have been pushed already, and the inferred ones need pushing again.

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

Q1. For ... trips t JOIN drivers d ON t.driver_id = d.driver_id WHERE d.rating > 4 + 0.5, what does the optimizer do? (Select all.) (select all that apply)

How sure are you?

Statistics and physical planning

SparkPlanner tries its strategies in order and takes the first plan: createSparkPlan calls planner.plan(...).next().[Spark createSparkPlan] The strategies include FileSourceStrategy (scans), Aggregation (a partial and a final HashAggregate), JoinSelection and BasicOperators.

Join selection depends on the estimated size of each side. Without cost-based optimization, sizes come from SizeInBytesOnlyStatsPlanVisitor:[Spark SizeInBytesOnlyStatsPlanVisitor]

  • A file-based relation reports its files’ total size.
  • A unary node, Filter included, keeps the child’s row count and scales by row width: child.sizeInBytes × outputRowSize / childRowSize. Row size is 8 bytes plus each column type’s defaultSize: 4 for int and date, 8 for long and double, 20 for string.[Spark EstimationUtils.getSizePerRow]
  • A join multiplies its children’s sizes, and a global aggregate is one row.

So Filter(home_city = 'Berlin', drivers) is estimated at the full 600 MB scaled by width, however selective the filter is. Then JoinSelection follows its documented order for equi-joins without hints:[Spark JoinSelection]

  1. Broadcast hash join if a side’s size is at most spark.sql.autoBroadcastJoinThreshold (10MB). If both qualify, the smaller side is broadcast.[Spark canBroadcastBySize]
  2. Shuffled hash join if spark.sql.join.preferSortMergeJoin is false (it is true by default), the build side is under threshold × shuffle partitions, and it is at least 3× smaller than the other side.[Spark canBuildLocalHashMapBySize]
  3. Sort-merge join if the keys are sortable.
  4. A cartesian product for inner joins, and broadcast nested loop join as the last resort.

Hints (/*+ BROADCAST(d) */, MERGE, SHUFFLE_HASH) are checked first, in that order.

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

Q1. Without CBO statistics, what sizeInBytes does Spark estimate for Filter(rating > 4.5, drivers) when drivers is 600 MB?

How sure are you?

Q2. With default settings and no hints, which join does JoinSelection pick for an equi-join of a 40 GB table and a 600 MB table?

How sure are you?

Preparing the plan: exchanges and codegen

The planner’s output does not yet say where data moves. QueryExecution.preparations runs a list of physical rules. With AQE on, the first, InsertAdaptiveSparkPlan, wraps the plan and applies the rest per stage at runtime.[Spark QueryExecution.preparations]

// QueryExecution.preparations (trimmed)
adaptiveExecutionRule.toSeq ++ Seq(
  CoalesceBucketsInJoin, PlanDynamicPruningFilters(sparkSession), PlanSubqueries(sparkSession),
  RemoveRedundantProjects, EnsureRequirements(), InsertSortForLimitAndOffset,
  ReplaceHashWithSortAgg, RemoveRedundantSorts, RemoveRedundantWindowGroupLimits,
  DisableUnnecessaryBucketedScan, ApplyColumnarRulesAndInsertTransitions(...),
  CollapseCodegenStages()) ++ Seq(ReuseExchangeAndSubquery)

EnsureRequirements. Every physical operator declares a required distribution and ordering for each child. A sort-merge join needs both sides hash-partitioned on the join keys and sorted by them. A final aggregate needs its input clustered by the grouping keys, or in a single partition for a global aggregate. A broadcast join needs a broadcast of its build side. Where a child’s outputPartitioning does not satisfy the requirement, the rule inserts ShuffleExchangeExec with spark.sql.shuffle.partitions (200) partitions, or a BroadcastExchangeExec. Where the ordering is missing, it inserts a SortExec.[Spark EnsureRequirements] If the children are already partitioned on the keys, for example by bucketing or an earlier exchange, no shuffle is added. Chapter 33 is about what an exchange costs.

CollapseCodegenStages. Operators that implement CodegenSupport are fused into one generated Java function per stage: a WholeStageCodegenExec over a run of them, shown as *(n) in EXPLAIN. An operator that does not support codegen gets an InputAdapter above it and starts a new stage. So does an expression that falls back (CodegenFallback), or a schema wider than spark.sql.codegen.maxFields (100). Exchanges are never codegen. The children of a sort-merge join or shuffled hash join get their own stages.[Spark CollapseCodegenStages] Stage ids are assigned children first, which is why the scan at the bottom is *(1). Chapter 32 shows what the fused code looks like and compares it with vectorized execution.

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

Q1. Who inserts Exchange hashpartitioning(key, 200) and Sort under a SortMergeJoin?

How sure are you?

Q2. What ends a whole-stage codegen stage (the *(n) prefix)? (Select all.) (select all that apply)

How sure are you?

Adaptive query execution

Static plans rest on estimates, and the estimates above ignore filters. Adaptive query execution (AQE) replans at stage boundaries using sizes measured at runtime. It arrived in Spark 3.0, released in June 2020, under SPARK-31412.[Spark 3.0.0 release notes] Spark 3.2 enabled it by default.[Spark 3.2.0 release notes] It is spark.sql.adaptive.enabled, default true at the pin.[Spark SQLConf: AQE]

AdaptiveSparkPlanExec runs the query as a loop:[Spark AdaptiveSparkPlanExec]

  1. Cut the plan into query stages at exchanges, and materialize every stage whose children are done. Broadcast stages are submitted first.
  2. Wait for a stage to finish. Its MapOutputStatistics gives the bytes in every shuffle partition.
  3. Replace the finished parts of the logical plan with LogicalQueryStages that carry the real sizes. Re-optimize with AQEOptimizer, whose batches include DynamicJoinSelection,[Spark AQEOptimizer] then plan again. Adopt the new physical plan if its cost is lower, or equal but different.
  4. Create the next stages and repeat until the result stage.

Within this loop, three optimizations matter most:

  • Join strategy switch. Re-planning calls JoinSelection again, now with runtime sizes. Those use spark.sql.adaptive.autoBroadcastJoinThreshold, which falls back to the static threshold. The Berlin drivers turn out to be a few MB, so the sort-merge join becomes a broadcast hash join. The large side’s shuffle has already run, so it is read locally from the mappers instead of fetched (OptimizeShuffleWithLocalRead). DynamicJoinSelection can also go the other way. It demotes a broadcast whose side is mostly empty partitions, and prefers a shuffled hash join when every partition fits a local hash map.[Spark DynamicJoinSelection]
  • Coalescing partitions. CoalesceShufflePartitions merges contiguous small partitions, greedily, up to a target size.[Spark CoalesceShufflePartitions][Spark ShufflePartitionsUtil] The target is advisoryPartitionSizeInBytes (64MB). But coalescePartitions.parallelismFirst is true by default, which lowers it to total size / default parallelism so the cluster stays busy. minPartitionSize (1MB) is the floor. A partition below the floor that cannot fit either neighbour is merged into the smaller one anyway.
  • Skew join. OptimizeSkewedJoin calls a partition skewed when it is larger than both skewedPartitionFactor × the median (5×) and skewedPartitionThresholdInBytes (256MB). It splits that partition into pieces of about the average non-skewed size, but at least the advisory size, by ranges of map outputs. Each piece joins the whole matching partition of the other side.[Spark OptimizeSkewedJoin]

The rules that change shuffle reads run per stage, from queryStageOptimizerRules: CoalesceShufflePartitions, then OptimizeShuffleWithLocalRead. OptimizeSkewedJoin is among the preparation rules.[Spark AQE rule lists] In the final plan, they show up as AQEShuffleRead nodes.

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

Q1. What can AQE change after a shuffle stage finishes? (Select all.) (select all that apply)

How sure are you?

Q2. Median shuffle partition 40 MB. Which partition size is the smallest that counts as skewed by default?

How sure are you?

Try it

The lab runs the whole lifecycle on three tables: trips (40 GB), drivers (600 MB) and cities (2 MB). You can edit the SQL. Things to try:

  • Broadcast a small dimension, Optimized tab: click through the rules. PushDownPredicates splits the WHERE clause between the sides, and InferFiltersFromConstraints adds isnotnull(city_id) to both.
  • Physical tab: the scan’s PushedFilters and ReadSchema came from the optimizer. Set autoBroadcastJoinThreshold to -1 to get a sort-merge join with two exchanges and two sorts.
  • Sort-merge join, folding: untick preferSortMergeJoin and the join becomes a shuffled hash join, since drivers is under 10MB × 200 and much smaller than trips.
  • AQE switches to broadcast: the static plan is a sort-merge join because the filter does not shrink the estimate. The AQE plan is a broadcast with a local shuffle read.
  • Hot key at 30% on the sort-merge query: AQE marks the join isSkewJoin=true.
  • Analysis error, or a misspelled column: the error class comes from CheckAnalysis.

Tables: trips(trip_id, city_id, driver_id, pickup, fare, notes) 40 GB; cities(city_id, name, country) 2 MB; drivers(driver_id, name, home_city, rating) 600 MB.

Aggregate [name#8], [name#8, sum(fare#5) AS revenue#10]
+- Join Inner, (city_id#2 = city_id#7)
   +- Project [city_id#2, fare#5]
   :  +- Filter ((pickup#4 >= 2026-03-01) AND isnotnull(city_id#2))
   :     +- Relation trips[trip_id#1,city_id#2,driver_id#3,pickup#4,fare#5,notes#6] parquet
   +- Project [city_id#7, name#8]
      +- Filter ((country#9 = DE) AND isnotnull(city_id#7))
         +- Relation cities[city_id#7,name#8,country#9] parquet
Effective rules, in order
  1. Operator Optimization before Inferring Filters, iteration 1
  2. Operator Optimization before Inferring Filters, iteration 1
  3. Infer Filters, iteration 1
  4. Operator Optimization after Inferring Filters, iteration 1
  5. Operator Optimization after Inferring Filters, iteration 2

Click a rule to see the plan right after it ran.

  • sizeInBytes estimate of the optimized plan: 14,416,672,581.5 MB (Filters do not shrink it).

History

Spark began with the RDD paper: Matei Zaharia, Mosharaf Chowdhury, Tathagata Das, Ankur Dave, Justin Ma, Murphy McCauley, Michael J. Franklin, Scott Shenker and Ion Stoica, “Resilient Distributed Datasets: A Fault-Tolerant Abstraction for In-Memory Cluster Computing”, NSDI 2012, at UC Berkeley’s AMPLab.[USENIX NSDI 2012] Spark SQL and the Catalyst optimizer were described by Michael Armbrust and colleagues in “Spark SQL: Relational Data Processing in Spark”, SIGMOD 2015.[DOI 10.1145/2723372.2742797] The paper introduced the DataFrame API alongside SQL, and an optimizer built from Scala pattern-matching rules over trees. Adaptive execution became part of the main engine in Spark 3.0 (2020) and the default in 3.2.

Summary

  • QueryExecution builds the parsed, analyzed, optimized, physical and executed plans lazily, in that order.
  • Analyzer and optimizer are both RuleExecutors. A batch applies its rules pass after pass until a pass changes nothing, or until maxIterations (100).
  • Analysis binds names to attributes with exprIds. CheckAnalysis turns leftovers into errors with classes.
  • The operator optimization rules (PushDownPredicates, ColumnPruning, ConstantFolding, …) run before and after InferFiltersFromConstraints. Their result becomes the scan’s pushed filters and read schema.
  • Size-only statistics scale by row width and ignore filter selectivity. JoinSelection broadcasts at 10MB or less, uses shuffled hash join only when preferSortMergeJoin is false, and otherwise uses sort-merge.
  • EnsureRequirements adds exchanges (200 partitions) and sorts. CollapseCodegenStages fuses operators into *(n) stages, split at exchanges and non-codegen nodes.
  • AQE replans per stage with real sizes. It switches joins to broadcast, coalesces partitions toward 64MB (or total/parallelism), and splits partitions above max(256MB, 5 × median).

Concepts in this chapter

Explained here

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 10 quiz questions.

Review this chapter's cards → Review all due cards