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.
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]
| Plan | Built by | What it is |
|---|---|---|
logical | the parser (SparkSqlParser, ANTLR) | unresolved: names are strings |
analyzed | Analyzer | every relation, column and function bound, types checked |
optimizedPlan | Optimizer (SparkOptimizer) | rewritten by rule batches |
sparkPlan | SparkPlanner | the first physical plan its strategies produce |
executedPlan | the preparation rules | with exchanges, sorts, codegen stages and AQE |
- Parse Build the unresolved logical tree.
- Analyze Bind names and check types.
- Optimize Rewrite the logical tree with rules.
- Plan Pick physical operators and prepare exchanges, sorts and codegen.
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.
Q1. In what order does QueryExecution produce its plans?
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.
Q1. How does a FixedPoint batch in RuleExecutor decide to stop?
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.
Q1. Where does [UNRESOLVED_COLUMN.WITH_SUGGESTION] come from?
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]
PushDownPredicatescombines adjacent filters and moves deterministic conjuncts below projects, and below joins to the side whose output they reference. A filter ond.ratinglands directly abovedrivers.ColumnPruninginserts projects so that each subtree produces only the attributes used above it. Together with the pushed filters, this becomes the scan’sReadSchemaandPushedFilters(chapter 30). Chapter 8’s Parquet pushdown starts here.ConstantFoldingandBooleanSimplificationevaluate4 + 0.5to4.5and droptrue AND x.InferFiltersFromConstraintsderives new predicates from constraints. For an inner equi-join it addsisnotnull(key)on both sides, and it copiesa.k = 5tob.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.
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)
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’sdefaultSize: 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]
- 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] - Shuffled hash join if
spark.sql.join.preferSortMergeJoinis 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] - Sort-merge join if the keys are sortable.
- 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.
Q1. Without CBO statistics, what sizeInBytes does Spark estimate for Filter(rating > 4.5, drivers) when drivers is 600 MB?
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?
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.
Q1. Who inserts Exchange hashpartitioning(key, 200) and Sort under a SortMergeJoin?
Q2. What ends a whole-stage codegen stage (the *(n) prefix)? (Select all.) (select all that apply)
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]
- Cut the plan into query stages at exchanges, and materialize every stage whose children are done. Broadcast stages are submitted first.
- Wait for a stage to finish. Its
MapOutputStatisticsgives the bytes in every shuffle partition. - Replace the finished parts of the logical plan with
LogicalQueryStages that carry the real sizes. Re-optimize withAQEOptimizer, whose batches includeDynamicJoinSelection,[Spark AQEOptimizer] then plan again. Adopt the new physical plan if its cost is lower, or equal but different. - Create the next stages and repeat until the result stage.
Within this loop, three optimizations matter most:
- Join strategy switch. Re-planning calls
JoinSelectionagain, now with runtime sizes. Those usespark.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).DynamicJoinSelectioncan 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.
CoalesceShufflePartitionsmerges contiguous small partitions, greedily, up to a target size.[Spark CoalesceShufflePartitions][Spark ShufflePartitionsUtil] The target isadvisoryPartitionSizeInBytes(64MB). ButcoalescePartitions.parallelismFirstis 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.
OptimizeSkewedJoincalls a partition skewed when it is larger than bothskewedPartitionFactor× the median (5×) andskewedPartitionThresholdInBytes(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.
Q1. What can AQE change after a shuffle stage finishes? (Select all.) (select all that apply)
Q2. Median shuffle partition 40 MB. Which partition size is the smallest that counts as skewed by default?
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.
PushDownPredicatessplits the WHERE clause between the sides, andInferFiltersFromConstraintsaddsisnotnull(city_id)to both. - Physical tab: the scan’s
PushedFiltersandReadSchemacame 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- Operator Optimization before Inferring Filters, iteration 1
- Operator Optimization before Inferring Filters, iteration 1
- Infer Filters, iteration 1
- Operator Optimization after Inferring Filters, iteration 1
- 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
QueryExecutionbuilds 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 untilmaxIterations(100). - Analysis binds names to attributes with
exprIds.CheckAnalysisturns leftovers into errors with classes. - The operator optimization rules (
PushDownPredicates,ColumnPruning,ConstantFolding, …) run before and afterInferFiltersFromConstraints. Their result becomes the scan’s pushed filters and read schema. - Size-only statistics scale by row width and ignore filter selectivity.
JoinSelectionbroadcasts at 10MB or less, uses shuffled hash join only whenpreferSortMergeJoinis false, and otherwise uses sort-merge. EnsureRequirementsadds exchanges (200 partitions) and sorts.CollapseCodegenStagesfuses 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
Primary sources
Review this chapter
This chapter has 10 quiz questions.