Query planning and optimization
Daft turns a lazy DataFrame workflow or SQL statement into an executable query plan. The planning path preserves the meaning of the requested table while it resolves columns, applies algebraic rewrites, accounts for data placement, and selects work that the active runner can perform. Read Logical plans and optimizer for the detailed logical-plan view and SQL interface for SQL construction.
Planning model
Query planning separates the description of a result from the work that produces it. DataFrame methods add operations to a logical tree, while execution begins only when a runner receives the plan through collection, streaming, writing, or another materialization call.
The planning path has four broad stages:
- A DataFrame operation or SQL clause creates a logical operation.
- The planner resolves expressions and propagates schemas through the operation tree.
- The optimizer rewrites the tree to reduce work while preserving its result.
- The selected runner lowers the optimized tree into executable local or distributed work.
This flow keeps one description of query meaning across the Python DataFrame API and the SQL interface. The runner then adds choices about concrete operators, inputs, tasks, and data movement.
This diagram shows how a lazy request becomes runner work and then result partitions.
flowchart LR
A[DataFrame operations or SQL] --> B[Logical plan]
B --> C[Resolved expressions and schemas]
C --> D[Algebraic and rule rewrites]
D --> E[Partition-aware executable plan]
E --> F{Runner}
F --> G[Native local work]
F --> H[Ray distributed work]
G --> I[Result partitions]
H --> I
Lazy plan construction
The logical plan builder is the shared entry point for DataFrame operations. Each operation returns a new builder with a new plan root, so the caller can reuse an earlier workflow and extend it in different ways. The builder also exposes the current schema before rows are read. src/…/mod.rs• L54-70
A source node represents where data will come from. Later nodes describe projection, filtering, grouping, joins, ordering, partition changes, or output. These nodes state the requested result rather than performing the work at the time the chain is built. src/…/logical_plan.rs• L29-78
The logical-plan crate is the public boundary for this model. It exposes the plan builder, logical plan, clustering specification, and source and sink information. When Python support is enabled, it also registers the builder and source, sink, and join options used by the Python layer. src/…/lib.rs• L3-60
References: src/…/mod.rs• L54-70 src/…/logical_plan.rs• L29-78 src/…/lib.rs• L3-60
SQL plan construction
SQL uses the same logical planning path as the DataFrame API. The SQL planner resolves tables and aliases in the current scope, turns clauses into builder operations, and returns a logical plan for the query. Common table expressions and nested scopes provide names for plans and expressions without creating a separate execution model. src/…/planner.rs• L137-178, src/…/planner.rs• L229-280, src/…/planner.rs• L390-461
This shared path matters because SQL and DataFrame queries receive the same schema checks, optimizer rules, partition decisions, and runner limits after construction. SQL-specific syntax ends at logical-plan construction. See SQL interface for the supported SQL surface.
References: src/…/planner.rs• L137-178 src/…/planner.rs• L229-280 src/…/planner.rs• L390-461
Logical algebra
Logical algebra describes a query as operations over relations and expressions. A relation is the table-shaped result at each point in the tree. An expression describes a value from columns, literals, or functions. The planner combines these two forms so it can reason about which rows and columns each operation needs.
Expression algebra
Expression algebra rewrites a value description without changing its meaning. It can simplify constant and boolean expressions, remove unnecessary casts, expand small membership checks, and use equivalent forms such as comparisons for a range condition. src/…/mod.rs• L16-48, src/…/mod.rs• L50-82
Boolean algebra also gives the planner a way to split a predicate into independent conditions and combine them again. This supports safe movement of individual filter conditions toward the source or toward the input that can evaluate them. src/…/boolean.rs• L11-53
The planner does not apply an algebraic identity only because it is shorter. It must also preserve null behavior, column scope, row order where required, and the meaning of user functions. These conditions define the boundary between a valid rewrite and a change in query results.
References: src/…/mod.rs• L16-48 src/…/mod.rs• L50-82 src/…/boolean.rs• L11-53
Relational algebra
Relational algebra rewrites the tree of table operations. The default optimizer removes redundant nodes, pushes filters and projections toward sources, moves limits and aggregates when safe, rewrites subqueries, and can change join order. These changes reduce rows, columns, or repeated work before execution. src/…/optimizer.rs• L124-238
Limit planning can combine adjacent limits, move a bound across row-preserving stages, turn a limit over a sort into a top-N operation, and push a bound toward a source or the preserved side of an outer join. It stops at operations where trimming an input can change row expansion, matching, or null-extension semantics. src/…/push_down_limit.rs• L44-315
The optimizer applies rules in ordered batches. Some batches run once. Others repeat until no rule changes the plan or until a pass limit is reached. A plan tracker also stops a repeated batch when it detects a previously seen plan, which prevents a rewrite cycle from running forever. src/…/optimizer.rs• L58-105, src/…/optimizer.rs• L317-398
The result is still the same logical query. The optimizer changes the route to that result, not the public meaning of the DataFrame or SQL request.
References: src/…/optimizer.rs• L58-105 src/…/optimizer.rs• L124-238 src/…/optimizer.rs• L317-398 src/…/push_down_limit.rs• L44-315
Required columns and schemas
Schemas and required-column sets give algebraic rewrites a safe view of each operation. A schema states the fields and types produced by a node. Required columns state which input fields are needed for output expressions, predicates, grouping, ordering, or join keys. src/…/logical_plan.rs• L148-193, src/…/logical_plan.rs• L196-239
This information lets the optimizer remove unused fields and push a narrower projection into a source. It must retain every field needed by a condition even when that field is not part of the final output. The same schema is used later to bind expressions to concrete input columns during lowering. src/…/logical_plan.rs• L196-398, src/…/translate.rs• L102-188
References: src/…/logical_plan.rs• L148-193 src/…/logical_plan.rs• L196-398 src/…/translate.rs• L102-188
Partition-aware planning
Partition-aware planning treats data placement as part of execution cost and operator needs. A partition is a unit of data work and result delivery. A clustering specification describes how rows are laid out across partitions, including the number of partitions and, for keyed layouts, the expressions that define the layout.
Partition layouts
Daft represents logical data placement with hash, range, random, or unknown clustering. Hash and range layouts carry keys. Random and unknown layouts carry partition counts but do not promise a key relationship between rows and partitions. The logical form names keys so it can survive plan rewrites; execution binds those keys after the final schema is known. src/…/partitioning.rs• L213-228, src/…/partitioning.rs• L243-299
Repartition requests express a desired layout. Hash repartitioning groups equal keys. Range repartitioning orders rows into key ranges. Random repartitioning spreads rows without a key promise. A requested partition count can be explicit or can inherit the upstream count. src/…/partitioning.rs• L8-14, src/…/partitioning.rs• L40-65
The planner uses these promises to decide when a later operation needs data movement. If the existing layout already satisfies the downstream need, the distributed path can avoid an extra repartition. If it does not, the executable plan adds the required movement or gather stage. src/…/translate.rs• L96-117
References: src/…/partitioning.rs• L8-14 src/…/partitioning.rs• L40-65 src/…/partitioning.rs• L213-299 src/…/translate.rs• L96-117
Partition-sensitive operations
Joins, grouped aggregates, windows, global ordering, and explicit repartition requests can depend on how rows are placed. A local operator can process an input partition by partition only when its semantics allow it. Operations that need matching keys together or a complete order require a suitable layout or a data movement step.
Some row-reducing operations can move before layout work without changing the requested result. A limit can move before repartition-like stages, so fewer rows enter data movement, while the final plan still preserves the required partition layout. src/…/push_down_limit.rs• L62-71, src/…/push_down_limit.rs• L241-276
The optimizer can remove a redundant repartition marker when it does not add useful work. It can also preserve a partition request until the distributed planner can compare it with the layout already produced by upstream stages. src/…/optimizer.rs• L158-175, src/…/partitioning.rs• L233-259
Partition count is therefore an execution property, not only a display property. The optimized distributed plan can report the count that its scheduler will use, and that count can differ from the count suggested by the original lazy chain. daft/…/dataframe.py• L425-462
References: src/…/optimizer.rs• L158-175 src/…/partitioning.rs• L233-259 src/…/push_down_limit.rs• L62-71 src/…/push_down_limit.rs• L241-276 daft/…/dataframe.py• L425-462
Optimization boundaries
Optimization is bounded by correctness and by the point where a logical choice must become runner work. A rule can move or remove an operation only when its result, schema, null behavior, ordering, source contract, and side effects remain valid.
Source boundaries
Source pushdown moves work into a reader when the reader can perform it safely. Filters and projections can reduce data read from a physical source. The optimizer keeps a filter outside a checkpointed source because the checkpoint must see the complete source key set. It also stops pushdown after scan tasks are materialized because the source work has already been fixed. src/…/push_down_filter.rs• L81-120
Limit pushdown follows the same source contract. A source can receive a local row bound when it supports that operation; in-memory sources keep the logical limit above the source. For physical scans, the outer limit can disappear only when the scan can absorb it without an offset. src/…/push_down_limit.rs• L87-150
Scan materialization is a clear boundary in the normal rule flow. It turns a source operator into concrete scan tasks. Statistics enrichment follows that step so row and size estimates can describe the materialized work and guide later planning choices. src/…/materialize_scans.rs• L18-49, src/…/enrich_with_stats.rs• L29-41
References: src/…/push_down_filter.rs• L81-120 src/…/push_down_limit.rs• L87-150 src/…/materialize_scans.rs• L18-49 src/…/enrich_with_stats.rs• L29-41
Runner boundaries
The optimized logical plan is lowered into a physical plan that names executable operators and concrete inputs. Lowering binds expressions to the input schema and maps logical intent to supported forms such as hash aggregates, hash joins, local window operators, scans, and writes. src/…/translate.rs• L21-33, src/…/translate.rs• L213-328, src/…/translate.rs• L429-542
Some logical nodes must be removed before this boundary. Set operations, aliases, and offsets are planning forms that the local translator expects the optimizer to rewrite or eliminate. A node that reaches translation without a supported mapping is a planning error rather than a late data error. src/…/translate.rs• L703-710
Runner choice can narrow the available physical behavior. The native path treats repartition requests as no-ops and falls back from some join strategies. The Ray path creates a distributed physical plan after optimization and can add distributed data movement. src/…/translate.rs• L429-449, src/…/translate.rs• L583-594, daft/…/ray_runner.py• L616-635
References: src/…/translate.rs• L21-33 src/…/translate.rs• L213-328 src/…/translate.rs• L429-542 src/…/translate.rs• L583-594 src/…/translate.rs• L703-710 daft/…/ray_runner.py• L616-635
Inspection boundary
Plan inspection shows the difference between the requested logical tree, the optimized logical tree, and the physical plan. DataFrame.explain() shows the unoptimized plan by default. With show_all=True, it runs optimization and displays the optimized and physical forms for the active runner. daft/…/dataframe.py• L314-423
This boundary is useful when a query is slower than expected. Compare the plans to see whether a filter or projection moved toward a source, whether join order changed, whether a repartition remains, and which physical operators the runner selected. Plan output describes intended work; it does not replace execution metrics or result validation.
References: daft/…/dataframe.py• L314-423 daft/…/builder.py• L74-95
Query execution hand-off
The runner optimizes the builder before it creates executable work. The native runner lowers the optimized builder to a local physical plan and supplies source inputs such as in-memory partitions or scan tasks. The Ray runner creates a distributed physical plan that the scheduler can turn into tasks and partition stages. daft/…/native_runner.py• L131-158, daft/…/ray_runner.py• L616-664
The output of either path is delivered as result partitions. A caller can collect all partitions or consume them as a stream. This keeps the plan boundary independent from the result boundary: planning decides how to produce the data, while the caller decides whether to hold it or consume it incrementally. daft/…/runner.py• L45-69, daft/…/dataframe.py• L587-613, daft/…/dataframe.py• L672-742
References: daft/…/native_runner.py• L131-158 daft/…/ray_runner.py• L616-664 daft/…/runner.py• L45-69 daft/…/dataframe.py• L587-613 daft/…/dataframe.py• L672-742
Change checklist
When these files or sections are changed, remember to consider these:
- Keep every logical node aligned across schema propagation, required-column analysis, child traversal, optimization rewrites, display output, and physical lowering.
- Keep algebraic rewrites consistent with null behavior, ordering, user-function boundaries, and join semantics. A shorter expression is not enough evidence that a rewrite is safe.
- Keep limit pushdown aligned with row-preserving operators. Do not extend it through row-expanding projections or joins without an outer-side guarantee.
- Preserve
limit + offsetwhen pushing bounds into sources or join inputs. Use overflow-safe arithmetic for large values. - Keep source pushdown aligned with source capabilities and with checkpoint behavior. Do not move a filter below a source boundary that must observe all source keys.
- Keep partition layout promises aligned between logical clustering keys, post-optimization schemas, and bound execution keys.
- Keep optimizer-only nodes out of local translation. Every such node needs a rewrite or a deliberate lowering path.
- Keep native and Ray support differences visible when a logical operation exposes runner-specific partition or join behavior.
- Keep scan materialization before statistics enrichment when planning choices depend on concrete scan tasks.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A filter is pushed below a checkpointed source | The checkpoint can miss source keys that must be tracked | Keep the filter above the checkpointed source boundary |
| A filter or projection drops a column still needed by a predicate, group, sort, or join | Expression binding or query results become invalid | Recompute required columns when changing pushdown rules |
| A limit is pushed through an inner, full outer, semi, or anti join | Input rows that affect matches can disappear and change the result | Push a limit only onto the preserved side of a left or right outer join |
| A limit with an offset is pushed as only the final row count | Rows needed to reach the post-offset result are lost | Push limit + offset and retain the outer offset |
| A limit is pushed through a projection that expands rows | The result can contain too few rows | Stop at projections that contain row-expanding expressions such as explode |
limit + offset overflows while a source or join bound is built | The scan or child input receives an invalid bound or planning can fail | Compute in a wide integer and saturate at the target size |
| A logical node reaches physical lowering without a supported mapping | Translation returns an internal or not-implemented error | Add the optimizer rewrite or runner mapping before exposing the node |
| A repartition request is sent to the native runner | The request is ignored and the requested data layout is not created | Use the Ray runner when partition placement is part of the query need |
| Statistics are enriched before scan tasks are materialized | Cost and size estimates cannot describe the planned source work | Preserve scan materialization before statistics enrichment |
| An optimizer batch cycles between equivalent plan shapes | Planning can repeat until its pass limit instead of reaching the intended form | Keep rule batches ordered and rely on plan tracking and pass limits |
| A distributed layout key is bound against a stale schema | The physical stage can use the wrong column or fail to bind | Bind clustering keys only after logical rewrites finish |
Key files
| File | Why to read it |
|---|---|
| src/…/lib.rs | Shows the public logical-plan boundary and the objects exposed to the Python layer. |
| src/…/mod.rs | Shows how lazy operations build immutable logical plans and how the optimizer flow is assembled. |
| src/…/logical_plan.rs | Defines logical operations, output schemas, and required-column analysis. |
| src/…/boolean.rs | Shows the boolean forms that support predicate splitting and recombination. |
| src/…/mod.rs | Shows the expression simplification boundary used by logical optimization. |
| src/…/optimizer.rs | Defines ordered rule batches, fixed-point passes, and cycle protection. |
| src/…/push_down_filter.rs | Shows the semantic limits on source filter movement. |
| src/…/push_down_limit.rs | Shows how row bounds move through safe plan shapes and into supported sources. |
| src/…/materialize_scans.rs | Shows where abstract source work becomes concrete scan tasks. |
| src/…/partitioning.rs | Defines logical partition layouts and their key and count promises. |
| src/…/translate.rs | Shows the hand-off from optimized logical operations to executable local operators. |
| src/…/plan.rs | Defines the local physical operator families and their task context. |
| src/…/translate.rs | Shows how distributed stages use partition layout requirements. |
| daft/…/native_runner.py | Shows native optimization, local lowering, and execution hand-off. |
| daft/…/ray_runner.py | Shows distributed plan creation after optimization. |
| src/…/planner.rs | Shows how SQL scopes and clauses enter the shared logical planning path. |
| daft/…/dataframe.py | Shows lazy plan inspection, partition-count inspection, and execution entry points. |