Catalyst and Tungsten
Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 2:20 on Wednesday. Two versions of one query run side by side on SwiftKart's 3 TB orders table. Yours filters status == "shipped" after a join. Its plan shows the filter inside the Parquet scan, an isnotnull you never wrote, and 4 of 8 columns read. The other version does the same filter in a Python UDF. It returns the same rows and reads every byte. Nora puts the two plans next to each other: "Somebody rewrote your query. Who, and why not the other one?"
You'll learn to
- Follow a query through the four phases of Catalyst
- Explain why rules run in rounds, and what a UDF blocks
- Say what statistics and the cost-based optimiser change
- Find codegen stages and vectorised reads in a plan
Learn
Someone rewrote your query
The somebody is Catalyst, Spark's optimiser.
Catalyst sees your query as a tree: a scan at the bottom, your steps stacked on top. All of its work is done by rules. A rule is a small function that looks for one pattern in the tree and puts something better in its place. A filter above a join? Move it below. A sum of two constants? Work it out now.
A query passes through four phases.
- Analysis checks every name and type.
- Optimisation rewrites the tree to give the same result for less work.
- Physical planning picks how to run each step: which scan, which join.
- Code generation compiles the steps into Java.
DataFrames, SQL and Spark Connect all build the same tree, so they all get the same optimiser.
From DataFrame code to generated code
Five phases in a row: unresolved plan, analysed plan, optimised plan, physical plan and generated code, joined by the Analyzer, the Optimizer, the planner and codegen.
Read it in the direction of the arrows. The label on each arrow is the part of Catalyst that does that step. The next sections take them one at a time.
First, every name is checked
The first phase is the Analyzer. Your code says amount. The Analyzer looks the table up in the catalog, finds the column, and replaces the name with a typed reference that has its own id: amount#5. It also works out the type of every expression and adds the casts you left out, such as cast(qty as bigint) before a sum.
A name it cannot find stops the query before any data is read. The error names the column and suggests the ones that exist: "[UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name amout cannot be resolved. Did you mean one of the following? [...]"
On a classic cluster that happens the moment you define the DataFrame. With Spark Connect it happens when the plan is first sent to the server.
Analyse a plan with a typo
import minicatalyst as mc
plan = mc.Project(['order_id', 'amout'], mc.Scan('orders'))
try:
mc.analyze(plan)
except mc.AnalysisException as e:
print(e)
fixed = mc.analyze(mc.Project(['order_id', 'amount'], mc.Scan('orders')))
print(mc.show(fixed))
The first plan asks for amout and is stopped with Spark's real error text. The second resolves and prints its tree. minicatalyst is this module's model of Catalyst (open minicatalyst.py). Plans are Scan, Filter, Project, Join and Aggregate nodes. Expressions are tuples such as ('>', 'amount', ('+', 20, 30)), where a plain string is a column and a quoted string like "'shipped'" is a literal.
Then the rules run, round after round
The second phase is the Optimizer. It keeps its rules in groups called batches, and it runs a batch in rounds: every rule, then every rule again, until a whole round changes nothing. That end state is called a fixed point. A safety cap stops a batch after 100 rounds.
Why rounds? Because one rewrite makes room for the next. Step through a tiny filter: amount > (20 + 30).
One rewrite makes room for the next
A filter over a scan of orders, rewritten in four steps: as written with a sum on the right side, after constant folding, after an inferred not-null check, and after both checks are handed to the scan.
As written. The right side of the comparison is a sum, not a fixed value. No file reader can use
amount > (20 + 30).ConstantFolding. This rule looks for an expression made only of constants and computes it once, now:
20 + 30becomes50.InferFiltersFromConstraints. A null amount can never be greater than 50, so this rule adds
isnotnull(amount). It costs almost nothing and file readers understand it.Into the scan. Both checks are now a plain column against a fixed value, so they can be handed to the reader. This last step was impossible before the first one.
Each step is one rule firing. The filter stays above the scan as well: the reader skips what it can, and the filter checks the rows that are left.
Your query, rule by rule
Catalyst on a SwiftKart join of orders and customers: the parsed and analysed plans, then constant folding, predicate pushdown, inferred not-null filters and column pruning each highlighting the node they change, then the physical plan with the join chosen by size against the broadcast threshold, and the codegen stages.
Now the query from the scene, with its join. Press Next step: each rule highlights the node it changes. When you reach the physical plan, move the threshold to 48 MB, or switch CBO on, and watch the sort-merge join become a broadcast hash join. The sections below explain why.
What each rule did to the query
| Rule | Before | After |
|---|---|---|
| ConstantFolding | amount (20 + 30) | amount 50 |
| PushDownPredicates | One Filter above the Join | A Filter on each side, with only the conditions about that side |
| InferFiltersFromConstraints | status = 'shipped'; join on customerid | isnotnull(status), and isnotnull(customerid) on both sides |
| ColumnPruning | Scans of 8 and 7 columns | Scans of 4 and 2 columns: only what is used |
| Pushed into the scan (planner) | Filter above the scan | Same Filter, plus PushedFilters for the Parquet reader |
This is everything the scene showed you: the filter in the scan, the isnotnull you never wrote, 4 of 8 columns. The isnotnull checks are safe because a null never equals 'shipped' and never matches a join key.
Remember: the order of your built-in steps does not matter, because Catalyst reorders them. What matters is that Catalyst can see them.
Watch the rules fire
import minicatalyst as mc
query = mc.Project(['order_id', 'country', 'amount'],
mc.Filter(('and', ('and', ('=', 'status', "'shipped'"), ('=', 'country', "'Japan'")),
('>', 'amount', ('+', 20, 30))),
mc.Join(mc.Scan('orders'), mc.Scan('customers'), 'customer_id')))
best = mc.optimize(query, trace=True)
print(mc.fired())
optimize runs mc.RULES in this order: constant_folding, combine_filters, push_down_predicates, infer_not_null, prune_columns, push_filters_into_scan, round after round. It prints the plan after every rule that changed it, and the last line lists the rules that fired. Each rule is ten to twenty lines of Python. Open the file and read one.
The trap: a Python UDF is a black box. This is the other version of your query. Catalyst only knows that the UDF returns a value. It cannot fold it, cannot infer an isnotnull from it, and cannot push it into the scan. The plan gets a BatchEvalPython (or ArrowEvalPython) node that ships every row to Python workers and back. The same holds, more mildly, for any function wrapped around a column. Write the logic with built-in functions and Catalyst does the rest.
From a tree to something that runs
The optimised tree still says only what to compute. The third phase, the planner, decides how. It runs a few strategies, each for one kind of step.
- The file strategy builds the
FileScan. It sorts your filters intoPartitionFilters(skip folders),PushedFilters(handed to the reader) andDataFilters, and setsReadSchema. - The aggregation strategy turns a
groupByinto a partialHashAggregate, an Exchange and a final one (Lesson 12.3). JoinSelectionpicks the join (Lesson 12.4).
Then one more rule, EnsureRequirements, asks each operator what it needs from the rows below it. A sort-merge join needs both sides shuffled by the key and sorted. Where a side is not already like that, the rule adds an Exchange and a Sort.
What the planner added for a sort-merge join
The physical plan of a sort-merge join as a tree: on each side a file scan, a filter in one codegen stage, then an Exchange and a Sort added by EnsureRequirements, and the join on top as codegen stage 5.
Read each branch from the bottom up. The amber nodes are in nobody's code: the planner added an Exchange and a Sort on each side. An aggregate on the same key right after this join would need no second Exchange. The *(n) badges come up below.
The planner works from guesses
To choose a join, the planner needs sizes, and nothing has run yet. So every node of the plan carries an estimate.
By default the estimate is a size in bytes and nothing more. A scan is the size of its files. A filter keeps the size of its input. Selecting fewer columns scales the size down by row width.
Spark can do better if you give it facts. ANALYZE TABLE t COMPUTE STATISTICS FOR COLUMNS a, b stores the row count and, for each column, the number of distinct values, the min, the max and the null count. Switch on the cost-based optimiser (spark.sql.cbo.enabled, false by default) and a filter is estimated from them: an equality keeps 1 / distinct values of the rows.
Stale statistics mislead it and AQE measures real sizes anyway, so many teams leave CBO off.
explain(mode="cost"), without and with CBO
Runs on Databricks:
spark.sql("ANALYZE TABLE swiftkart.customers COMPUTE STATISTICS FOR COLUMNS customer_id, country")
japan = (spark.table("swiftkart.customers")
.filter("country = 'Japan'").select("customer_id", "country"))
spark.conf.set("spark.sql.cbo.enabled", "false")
japan.explain(mode="cost")
spark.conf.set("spark.sql.cbo.enabled", "true")
japan.explain(mode="cost")
== Optimized Logical Plan ==
Project [customer_id#20L, country#24], Statistics(sizeInBytes=48.0 MiB)
+- Filter (isnotnull(country#24) AND (country#24 = Japan)), Statistics(sizeInBytes=160.0 MiB)
+- Relation swiftkart.customers[customer_id#20L,name#21,email#22,city#23,country#24,signup_date#25,segment#26] parquet, Statistics(sizeInBytes=160.0 MiB)
...
== Optimized Logical Plan ==
Project [customer_id#20L, country#24], Statistics(sizeInBytes=1367.2 KiB, rowCount=4.00E+4)
+- Filter (isnotnull(country#24) AND (country#24 = Japan)), Statistics(sizeInBytes=4.5 MiB, rowCount=4.00E+4)
+- Relation swiftkart.customers[customer_id#20L,name#21,email#22,city#23,country#24,signup_date#25,segment#26] parquet, Statistics(sizeInBytes=160.0 MiB, rowCount=2.00E+6)
Physical plans left out. Read the Statistics on each line, from the bottom. Without CBO the filter keeps 160 MB, and the Project scales it to 160 x 36 / 120 = 48 MB: too big to broadcast. With CBO, 2 million rows / 50 countries = 40,000 rows of 35 bytes (country measured at 7 bytes, plus 12 of string overhead): 1.4 MB. #20L marks a bigint.
One filter, estimated twice
Three bars in megabytes: the estimate without the cost-based optimiser is 48, the broadcast threshold is 10, and the estimate with the cost-based optimiser is about 1.3.
The two estimates from the output above, next to the 10 MB broadcast threshold. The same Japanese customers are planned as a sort-merge join with one guess and as a broadcast with the other.
Three tables, a groupBy, and join reorder
Catalyst on order lines joined to orders and Japanese customers and grouped by status: pushdown, inferred filters, pruning, cost-based join reorder when CBO is on, then the partial and final aggregates around an Exchange and the join strategies by size.
With CBO off the joins run in the order they were written. Switch CBO on: orders join the 40,000 Japanese customers first, by broadcast, and only then the 2.4 billion lines. Reordering joins by cost needs spark.sql.cbo.joinReorder.enabled, which is also false by default.
One function per stage
The last phase turns the plan into code. The classic way to run a plan makes every operator a separate object that hands rows to the next one: for each row, one function call per operator. A billion rows through five operators is five billion calls.
Whole-stage code generation removes the calls. It fuses a chain of operators into one Java function with one tight loop, and compiles it when the job starts. Values stay in local variables and never travel between objects.
In a plan, *(2) in front of an operator means "inside generated function number 2". A function ends at an Exchange, at an operator that cannot generate code (a Python UDF is one), and between a sort-merge join and its two inputs.
explain(mode="codegen")
Runs on Databricks:
delivered.explain(mode="codegen")
Found 1 WholeStageCodegen subtrees.
== Subtree 1 / 1 (maxMethodCodeSize:282; maxConstantPoolSize:193(0.29% used); numInnerClasses:0) ==
*(1) Project [order_id#0, amount#5]
+- *(1) Filter (isnotnull(status#3) AND (status#3 = delivered))
+- *(1) ColumnarToRow
+- FileScan parquet [order_id#0,status#3,amount#5] ...
Generated code:
/* 001 */ public Object generate(Object[] references) {
/* 002 */ return new GeneratedIteratorForCodegenStage1(references);
/* 003 */ }
/* 004 */
/* 005 */ // codegenStageId=1
/* 006 */ final class GeneratedIteratorForCodegenStage1 extends org.apache.spark.sql.execution.BufferedRowIterator {
...
This is the delivered-orders query of Lesson 12.2. The real output runs to a few hundred lines: one processNext() loop that reads a batch, checks the filter and writes two columns, with no call between operators. On very wide queries, watch maxMethodCodeSize against the 64 KB limit in the table below.
Rows as bytes
Generated code needs data it can reach fast, and one Java object per row is slow to create and slow to clean up. So Spark's execution layer, Tungsten, keeps each row as a short run of raw bytes: an UnsafeRow. It has three parts.
- A null bit set: one bit per field, rounded up to 8 bytes. Up to 64 fields fit in 8 bytes.
- One 8-byte word per field. A number sits in its word. A string puts its offset and length there.
- A variable-length region with the bytes of the strings, each padded to a multiple of 8.
Rows like this are compared, hashed and copied as bytes, in memory Spark manages itself. A hash aggregate over a billion rows creates no billion objects for the garbage collector.
One order as an UnsafeRow: 40 bytes
A bar of 40 bytes: an 8-byte null bit set, three 8-byte words for order_id, the offset and length of status, and amount, then 8 bytes holding the 7 bytes of shipped plus padding.
Read it left to right: 8 + 3 x 8 + 8 = 40 bytes. A null field keeps its word, with its bit set, and adds no variable bytes. A 65th field needs a second word of null bits.
Reading columns in batches
One more piece feeds the generated code. Parquet stores data by column, and Spark reads it that way. Its vectorised reader decodes 4,096 rows at a time into one array per column. That is what Batched: true on a FileScan means. Looping over an array is far cheaper than building rows one value at a time.
The operators above the scan still work on rows. So a ColumnarToRow node sits in between and hands the values over row by row. Pushed filters act one level earlier: the reader skips whole row groups by their min, max and null statistics.
On Databricks, Photon goes one step further and keeps everything in column batches, never rows. The table has the details.
Numbers to remember
| Setting or name | Default | What it is |
|---|---|---|
| spark.sql.optimizer.maxIterations | 100 (internal) | Rounds before a rule batch gives up. Some batches run Once |
| The "Operator Optimization" batch | dozens of rules | Among them PushDownPredicates, ColumnPruning, CollapseProject, ConstantFolding, BooleanSimplification, ReorderJoin |
| The "Infer Filters" batch | InferFiltersFromConstraints | Adds the isnotnull checks. With CBO on, a "Join Reorder" batch runs CostBasedJoinReorder |
| spark.sql.optimizer.excludedRules | a list of rule names | Switches named rules off. spark.sql.planChangeLog.level logs every change a rule makes |
| Rules that finish the physical plan | EnsureRequirements, CollapseCodegenStages, ReuseExchangeAndSubquery | Add an Exchange or a Sort where needed, group operators into codegen stages, let a repeated subtree run once |
| spark.sql.cbo.enabled | false | The cost-based optimiser. spark.sql.cbo.joinReorder.enabled is false too |
| The size-only estimate | no row counts | A Project scales the size by row width: 8 bytes plus each column's default width (20 for a string). A join multiplies its two sides |
| Column statistics | distinct count, min, max, null count, lengths | Stored by ANALYZE TABLE ... FOR COLUMNS. Histograms only with spark.sql.statistics.histogram.enabled |
| spark.sql.codegen.wholeStage | true | Fused functions, compiled at runtime by Janino, in place of the classic one-call-per-row design (the Volcano model) |
| spark.sql.codegen.hugeMethodLimit | 65535 | Past 64 KB of bytecode, or past 100 fields (spark.sql.codegen.maxFields), Spark falls back to the slower path for that subtree and logs a warning |
| spark.sql.parquet.enableVectorizedReader | true | Batches of 4,096 rows (spark.sql.parquet.columnarReaderBatchSize). Structs, arrays and maps are vectorised too, by default since Spark 3.4 |
| Photon (Databricks) | on for SQL warehouses and serverless compute, optional on classic clusters | A C++ engine, vectorised end to end. It runs under the same Catalyst plan, swaps in its own operators, falls back to Spark for what it does not support, and is marked in its own colour in the query profile |
What changed at SwiftKart
You rewrite the other version. The Python UDF becomes one built-in comparison: F.col("status") == "shipped". Its plan now matches yours, with the filter in PushedFilters, the isnotnull, and 4 of 8 columns. Both versions read the same bytes.
Nora's rule for code reviews: "If Catalyst cannot see it, Catalyst cannot move it."
The plan is now as good as Spark can make it. Whether the job survives the night is another question. A join builds its hash tables in memory, and last night one executor ran out. Lesson 12.8 opens the executor up: the memory manager.
In one line
Catalyst checks the names, rewrites the plan with rules until nothing changes, picks scans and joins from size estimates, and compiles each stage into one function over rows kept as bytes, but only for logic it can see.
Interview corner
Walk me through what Catalyst does with a DataFrame query.
The query is an unresolved logical plan. The Analyzer resolves tables and columns against the catalog, assigning typed attributes with ids and adding casts; unknown names fail here. The Optimizer runs rule batches, many to a fixed point: constant folding, predicate pushdown, column pruning, collapsing projections, inferring isnotnull from joins and comparisons. The planner's strategies build physical operators (the FileScan with pushed filters, partial and final aggregates, the join strategy by size), EnsureRequirements inserts Exchanges and Sorts, and CollapseCodegenStages groups operators for code generation.
What is whole-stage code generation, and when does Spark not use it?
Instead of calling next() on one iterator per operator for every row, Spark generates one Java function per stage that loops over the input and does all the fused operators' work inline, compiled by Janino; *(n) marks stage n in explain. A stage ends at an Exchange, at operators without codegen support such as Python UDF evaluation, and between a sort-merge join and its inputs. Spark falls back to the interpreted path when the generated method exceeds 64 KB of bytecode or the schema has more than 100 fields.
Why do statistics matter, and why is CBO off by default?
The planner chooses broadcast against sort-merge joins, and CBO chooses join order, from estimated sizes and row counts. Without CBO only sizeInBytes exists, and a filter does not shrink it, so a filtered dimension can miss a broadcast. ANALYZE TABLE ... FOR COLUMNS stores row counts, distinct counts, min, max and lengths; with spark.sql.cbo.enabled they give selectivities and join cardinalities. It is off by default because statistics cost a scan to gather, go stale, and AQE now corrects many bad choices with real sizes at runtime.
What is Tungsten, and why is UnsafeRow faster than Java objects?
Tungsten is Spark's execution layer: rows in a compact binary format managed in Spark's own memory pages, code generation, and cache-friendly algorithms. An UnsafeRow is a null bit set, one 8-byte word per field and a padded variable-length region, so a three-column order is 40 bytes that can be hashed, compared and copied as bytes. That avoids an object per value, cuts garbage collection and makes serialisation for shuffles and caches cheap. The vectorised Parquet reader complements it with 4,096-row column batches; Photon goes further, in C++.