Sub topic 9
What the Optimiser Rewrites and Why Results Stay the Same
This chapter assumes you can write Polars expressions (pl.col, select, filter, with_columns, group_by). It also assumes you know a LazyFrame records a plan and that collect() runs it. Here you will learn what kinds of rewrites the optimiser makes, and the rules that keep your results unchanged.
What the optimiser does
When you call collect(), Polars does not run your steps as written. It first passes the logical plan through the query optimiser. The optimiser is a set of rewrite rules. Each rule looks for a pattern in the plan tree and replaces it with a cheaper plan that gives the same answer.
The optimiser never changes what the query means. It only changes how the work is done. The cost it targets is mainly I/O and memory. Reading fewer columns, reading fewer rows, and computing each value once are the usual savings.
The main rewrites
Each rewrite below has its own chapter. This table is a map of them.
| Rewrite | What changes | Typical saving |
|---|---|---|
| Predicate pushdown | Filters move toward the data source, ideally into the scan | Fewer rows read and processed |
| Projection pushdown | Only columns used later are kept, ideally read from the file | Fewer columns read |
| Slice pushdown | `head`, `limit` and `slice` move toward the scan | Reading stops early |
| Expression simplification | Constants are folded and expressions are rewritten more simply | Less compute per row |
| Type coercion | Mixed types are resolved to one type in a consistent way | Correct, predictable dtypes |
| Common subexpression elimination | A repeated expression is computed once and reused | Less duplicated compute |
Watching a rewrite happen
The query below has a column it never uses (note). It also filters after with_columns, although the filter only needs temp.
import polars as pl
df = pl.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
"note": ["a", "b", "c", "d"],
})
query = (
df.lazy()
.with_columns(temp_f=pl.col("temp") * 9 / 5 + 32)
.filter(pl.col("temp") > 4)
.select("city", "temp_f")
)
print(query.explain(optimized=False)) # as written
print(query.explain()) # after optimisation
eager = (
df.with_columns(temp_f=pl.col("temp") * 9 / 5 + 32)
.filter(pl.col("temp") > 4)
.select("city", "temp_f")
)
print(query.collect().equals(eager))In the unoptimised plan the steps appear in the order you wrote them. In the optimised plan, expect the filter to sit next to the data source. Expect the source node to show that only the columns the query needs are used. The last line prints True, because both routes give the same DataFrame.
The exact text of explain() output differs between Polars versions. Look for where the filter and the column list appear, not for an exact string.
Why the results stay the same
A rewrite is only safe if it preserves the result. Polars applies a rule only when it can show the rule is safe for the nodes involved. These are the conditions behind that.
Dependencies decide what can move
A filter can move below a step only if the filter does not need anything that step produces. Consider two orders of the same two operations.
import polars as pl
df = pl.DataFrame({"g": ["a", "a", "b"], "v": [1, 5, 10]})
filter_first = (
df.filter(pl.col("v") > 2)
.group_by("g")
.agg(pl.col("v").sum())
.sort("g")
)
aggregate_first = (
df.group_by("g")
.agg(pl.col("v").sum())
.filter(pl.col("v") > 2)
.sort("g")
)
print(filter_first) # a -> 5, b -> 10
print(aggregate_first) # a -> 6, b -> 10The two orders disagree for group a. In the second query, v after agg is the group total, not the original column. The filter refers to a value that only exists after the aggregation, so the optimiser must leave it there. A filter on g is different. It only uses a column that passes through group_by unchanged, so it can move below it.
Only rewrites the optimiser can reason about
The optimiser can only prove a rewrite safe when it understands the step. Native expressions are data it can inspect. A Python function inside map_elements is opaque. Polars cannot know which columns it touches, whether it is deterministic, or whether it has side effects, so it avoids rewrites that depend on that knowledge. This is why UDFs limit optimisation. A later chapter covers it in detail.
Operations whose result depends on row position or randomness
Some steps depend on which rows are present or in which order. Examples are shift, cumulative functions, sample, and anything that depends on row numbers. Moving a filter before such a step would change which rows it sees. A rule that is safe for col("x") * 2 is not automatically safe for col("x").shift(1). Polars treats these steps with more care, which is one reason a filter sometimes does not reach the scan.
Row order is preserved by default
Unless you opt out, the optimiser keeps the row order your query defines. It does not reorder rows to make a step cheaper, because results that differ only in order would still be a change of result. Operations such as group_by do not promise a group order unless you ask for one (for example with maintain_order=True or by sorting). The optimiser does not make that stronger or weaker.
What "same result" does and does not cover
"Same result" means the same values, dtypes and row order for the same inputs. Two things sit outside that promise.
- Floating-point sums can differ in the last digits when work is split across threads in a different way. This can happen between runs even without the optimiser. Compare floats with a tolerance.
- Error behaviour can differ. If a filter removes a row early, a failing expression on that row may never run. In an unoptimised order it would have run and raised. Treat a query that works only because of the optimiser as a bug in the query.
Reading the plan to confirm a rewrite
A practical routine for any slow lazy query:
- Print
explain(optimized=False)to see what you wrote. - Print
explain()to see what will run. - Find where each filter sits. A filter inside the scan node is pushed down. A separate filter node above the scan is not.
- Check the column list at the scan. If it shows more columns than you use, something blocks projection pushdown.
- Look for expressions that appear once, where you wrote them twice. That suggests common subexpression elimination worked.
Exercise
A query runs group_by("region").agg(pl.col("amount").sum().alias("total")) and then .filter(pl.col("total") > 1000). Can the optimiser move this filter below the group_by, and why or why not?
Show answer
No. The filter uses total, a column that only exists after the aggregation. Applying it earlier would filter individual rows by a value that has not been computed yet, which changes the result. A filter on region could be moved below the group_by, because that column passes through unchanged.
Exercise
Why does query.collect().equals(eager) return True in the chapter's first example, even though the optimiser moved the filter and dropped the note column?
Show answer
Predicate and projection pushdown are rewrites that preserve meaning. The filter depends only on temp, which is available at the source. The note column is never used by a later step. So the optimised plan returns the same values, dtypes and row order as the eager version.