Introducing a new way to review your PRs.

Read the announcement

eventual-inc / daft

High-performance data engine for AI and multimodal workloads. Process images, audio, video, and structured data at any scale

View on GitHub

19 documents · Updated Nov 11, 2026

docs / logical-plans-and-optimizer

Logical plans and optimizer

Daft represents a relational query as a logical plan before it runs. The plan records what each operation means, the expressions that drive it, and the schema that it produces. This page expands Query planning and connects with the SQL interface.

Planning stages

The planning path turns a DataFrame operation or SQL statement into a checked and optimized tree. It then lowers that tree into a local plan that an execution runner can schedule.

flowchart LR
    A[DataFrame operation or SQL] --> B[LogicalPlanBuilder]
    B --> C[Logical plan tree]
    C --> D[Expression resolution and schema checks]
    D --> E[Rule-based optimization]
    E --> F[Local physical plan]
    F --> G[Native or Ray execution]

Logical plan construction

The LogicalPlanBuilder is the main fluent interface for creating a plan. Each operation returns a new builder with a new plan root. This lets callers build a query step by step without running the data, while the builder keeps the current output schema available for later operations. src/…/mod.rs• L54-70

SQL uses the same path. The SQL planner resolves tables, aliases, common table expressions, columns, and clauses into builder operations instead of creating a separate execution model. src/…/planner.rs• L160-178, src/…/planner.rs• L270-315, src/…/planner.rs• L390-460

The logical-plan crate is the shared boundary for this planning model. It exposes the Rust builder and plan types, and it registers the Python-facing builder plus source, sink, and join options when Python support is enabled. src/…/lib.rs• L3-36, src/…/lib.rs• L38-60

References: src/…/mod.rs• L54-70 src/…/planner.rs• L160-178 src/…/planner.rs• L270-315 src/…/planner.rs• L390-460 src/…/lib.rs• L3-36 src/…/lib.rs• L38-60

Logical plan optimization

Optimization changes the shape of the logical tree without changing the query result. The optimizer applies ordered batches of rules. A batch can run once or repeat until it reaches a fixed point. The plan tracker stops a batch when it sees no change or detects a cycle. src/…/optimizer.rs• L58-105, src/…/optimizer.rs• L317-398

The builder selects the normal rule flow from planning and execution settings. The flow simplifies expressions, moves safe work toward sources, chooses join order when enabled, materializes scan tasks, and adds statistics needed by later choices. src/…/mod.rs• L1022-1061, src/…/mod.rs• L1098-1167

References: src/…/optimizer.rs• L58-105 src/…/optimizer.rs• L124-238 src/…/optimizer.rs• L317-398 src/…/mod.rs• L1022-1061

Local plan creation

Lowering is the step that turns a logical operation into an execution-ready local operation. The translator walks the optimized tree from its sources upward. It binds expressions to the input schema and creates local scan, transform, aggregate, join, window, and write nodes. It also returns the external inputs needed by those scan nodes. src/…/translate.rs• L21-33, src/…/translate.rs• L34-188

The local plan is not a second description of query meaning. It is a form that includes execution choices such as hash aggregation, hash join, sort-merge join, concrete scan inputs, and write steps. The native and Ray runners optimize the builder before they create and run this plan. src/…/plan.rs• L71-133, daft/…/ray_runner.py• L616-635

References: src/…/translate.rs• L21-33 src/…/translate.rs• L34-188 src/…/plan.rs• L71-133 daft/…/ray_runner.py• L616-635

Logical plan model

The logical plan is a tree of relational nodes. A node has zero, one, or two child plans and describes one step in the result relation. Nodes use shared references so optimizer rules can walk and rebuild subtrees while preserving the plan as a value. src/…/logical_plan.rs• L29-78, src/…/logical_plan.rs• L558-592

Relational node families

Each node family represents a different kind of change to rows, columns, grouping, ordering, data placement, or output. The important distinction is whether a node changes the relation’s shape or only controls how data moves.

FamilyPurposeTypical logical nodes
Sources and sinksConnect the query to input data or an output targetSource, Sink
Row and column transformsSelect, compute, filter, reshape, sample, or cap rowsProject, UDFProject, Filter, Explode, Unpivot, Sample, Limit, Offset
Grouped operationsReduce rows or add values based on groups and windowsAggregate, Pivot, Window, Distinct
Ordering and placementState order or partition intent without running itSort, TopN, Repartition, Shard, Shuffle, IntoBatches, IntoPartitions
Two-input operationsCombine or compare two relationsJoin, AsofJoin, Concat, Union, Intersect
Query scope and internal markersPreserve names or mark work needed by later stagesSubqueryAlias, StageCheckpointKeys, MonotonicallyIncreasingId

References: src/…/logical_plan.rs• L29-66 src/…/logical_plan.rs• L558-592

Expressions and columns

An expression is a description of a value derived from literals, columns, or functions. Builders first accept expressions that may not yet identify one exact input field. The resolver then checks scope, expands wildcards, assigns columns to the correct input, and rejects invalid uses such as an ambiguous join column or an aggregate in a row-level operation. src/…/resolve_expr.rs• L287-405, src/…/resolve_expr.rs• L408-441

Join expressions use left and right column references so the same name can be understood on both sides. The join builder also makes output names safe when both inputs contain the same column, while USING columns can remain merged. src/…/mod.rs• L715-762, src/…/join.rs• L193-218, src/…/join.rs• L236-339

References: src/…/resolve_expr.rs• L20-126 src/…/resolve_expr.rs• L287-441 src/…/join.rs• L193-218 src/…/join.rs• L236-339

Schema propagation

A schema is the ordered set of output fields and their types for a plan node. Schema propagation makes the plan useful before execution: a later operation can resolve its expressions, and callers can inspect the expected result without reading all rows.

Output schemas

Most unary nodes keep the input schema. Projection-like nodes derive a new schema from their expressions. Aggregates derive fields from group keys and aggregate expressions. Joins derive a combined schema and apply the join type’s rules. Shape-changing operations such as explode, unpivot, pivot, and window operations carry a schema that describes their new fields. src/…/logical_plan.rs• L148-193, src/…/project.rs• L43-70, src/…/agg.rs• L36-55, src/…/join.rs• L193-218

Source schemas may be narrower than the physical source schema when a projection is pushed into the scan. This keeps the logical output contract aligned with the columns that the rest of the query needs. src/…/mod.rs• L202-254

References: src/…/logical_plan.rs• L148-193 src/…/project.rs• L43-70 src/…/agg.rs• L36-55 src/…/join.rs• L193-218 src/…/mod.rs• L202-254

Required columns

The planner derives the input columns needed by each node from its expressions. This information lets projection and filter pushdown remove unused data while preserving fields needed for predicates, grouping, ordering, join keys, and output values. src/…/logical_plan.rs• L196-398

Schema work continues during lowering. The translator binds logical expressions to the concrete input schema and passes the declared output schema into each local node. This keeps expression references and output fields consistent across the planning boundary. src/…/translate.rs• L102-188, src/…/translate.rs• L213-250

References: src/…/logical_plan.rs• L196-398 src/…/translate.rs• L102-188 src/…/translate.rs• L213-250

Optimization behavior

The optimizer seeks the same result with less data movement and less work. It uses plan rewrites for general improvements, source pushdowns for work that a data source can do early, and statistics for choices that depend on estimated row counts or sizes.

Rewrite rules

The default rule flow combines expressions, removes redundant nodes, pushes filters and projections down, moves limits and aggregations when safe, splits work around user functions, and rewrites subqueries and joins. Fixed-point batches matter because one rewrite can expose another rewrite below it. src/…/optimizer.rs• L124-238

Limit movement reduces the rows that later work must process while preserving the result order and join meaning. A limit can commute with row-preserving projection and partition-shaping nodes when projection expressions do not explode rows. It can fold with another limit, become a TopN after a sort, or add a source pushdown that includes any skipped rows from an offset. src/…/push_down_limit.rs• L51-204

Join-aware limit movement is narrower. For a left or right join, the limit can apply to the preserved outer input before the join, using limit + offset as the input bound and keeping the final limit above the join. It does not move through inner, full outer, semi, or anti joins because trimming either input can change matches or null-extended rows. src/…/push_down_limit.rs• L206-315

Pushdown is limited by semantics. For example, a filter stays above a checkpointed source so the source key set remains complete. A materialized scan also stops later filter pushdown because its task list has already been fixed. src/…/push_down_filter.rs• L81-120

References: src/…/optimizer.rs• L124-238 src/…/push_down_limit.rs• L51-204 src/…/push_down_limit.rs• L206-315 src/…/push_down_filter.rs• L81-120 src/…/push_down_projection.rs• L28-64

Join order

Join reordering treats a connected group of joins as a join graph. It uses estimated statistics to choose a lower-cost order when the graph is within the supported size limit. The setting can disable this step or select the dynamic-programming orderer. src/…/mod.rs• L20-64

References: src/…/mod.rs• L20-64 src/…/join_graph.rs• L583-715

Scan materialization and statistics

Scan materialization changes a source from a scan operator into a fixed set of scan tasks. The optimizer performs this before it enriches the plan with statistics. Statistics are approximate row count, size, and accumulated selectivity values. They guide planning choices and remain attached to plan nodes for display and execution metadata. src/…/materialize_scans.rs• L18-49, src/…/enrich_with_stats.rs• L29-41, src/…/stats.rs• L6-26

References: src/…/materialize_scans.rs• L18-49 src/…/enrich_with_stats.rs• L29-41 src/…/stats.rs• L6-26 src/…/source.rs• L70-117

Local-plan lowering

The local plan is the first plan form that names concrete execution operators. It retains schemas and statistics but replaces unresolved expressions with bound expressions and replaces logical intent with an operator supported by the runner.

Operator mapping

The translator preserves the logical tree’s data flow while choosing local forms for each operation. A global aggregate becomes an ungrouped aggregate. A grouped aggregate becomes a hash aggregate. An equality join becomes a hash join, while an inner join with no keys becomes a cross join. Window nodes become one of several local window forms based on their partition and order needs. src/…/translate.rs• L213-328, src/…/translate.rs• L429-542

The local plan also carries the inputs that sit outside the operator tree. These inputs can be in-memory partitions, scan tasks, or glob paths. Source IDs connect those inputs to local scan nodes. src/…/translate.rs• L34-97, src/…/lib.rs• L28-50

References: src/…/translate.rs• L34-97 src/…/translate.rs• L213-328 src/…/translate.rs• L429-542 src/…/lib.rs• L28-50

Lowering boundaries

Some logical nodes are planning-only and must disappear before lowering. Set operations, aliases, and offsets are expected to be rewritten into supported local forms. A remaining node at this boundary indicates that the optimizer did not complete the contract. src/…/translate.rs• L703-710

Runner support also affects the result of lowering. The native path treats repartition and IntoPartitions as no-ops and falls back from unsupported join strategies where possible. The Ray path builds a distributed physical plan after optimization. src/…/translate.rs• L429-449, src/…/translate.rs• L583-594, daft/…/ray_runner.py• L616-666

References: src/…/translate.rs• L429-449 src/…/translate.rs• L583-594 src/…/translate.rs• L703-710 daft/…/ray_runner.py• L616-666

Plan inspection

The builder exposes the current logical plan, its schema, and readable tree forms before execution. ASCII, Mermaid, and JSON views help an engineer compare the original and optimized shape without inspecting execution output. src/…/mod.rs• L1209-1229, daft/…/builder.py• L61-95

Optimization can assign node IDs for plan tracking and execution metrics when logical-plan instrumentation is enabled. These IDs connect plan nodes to later observations, but they do not change the relational meaning of the plan. src/…/mod.rs• L1160-1207

References: src/…/mod.rs• L1160-1229 daft/…/builder.py• L61-95

Change checklist

When these files or sections are changed, remember to consider these:

  • A new or changed logical node must stay consistent across its schema rule, child traversal, expression mapping, display form, optimizer rewrites, and local translation.
  • A changed output field or join naming rule must remain compatible with expression resolution and with the bound expressions created during local lowering.
  • A new source pushdown must update both the source output schema and the required-column calculation so downstream nodes do not lose fields.
  • A new optimizer-only node must have a clear removal or lowering rule before the local translator sees it.
  • A change to scan task creation must preserve the order of scan materialization and statistics enrichment.
  • A changed limit rule must preserve row order and join semantics. Check source support, offsets, row-expanding projections, and the fixed-point behavior of repeated optimizer passes.
  • A changed join strategy must be checked against the capabilities of both native and Ray lowering paths.

Important failure modes

TriggerConsequenceGuard
A column resolves on both sides of a joinPlanning fails with an ambiguous column errorQualify the column or use a join-side expression
A logical node reaches local translation even though it is planning-onlyTranslation returns an internal errorAdd or restore the optimizer rewrite that removes the node
A non-equality join predicate reaches local loweringExecution returns a not-implemented errorUse supported equality keys or a runner path that supports the predicate
Statistics enrichment runs before physical scan tasks existSource statistics cannot be derived from the scan planKeep scan materialization before statistics enrichment
A limit moves through a row-expanding projectionThe result can contain rows that the original limit would excludeKeep the limit above projections that contain explode
A limit moves into the wrong side of an inner or outer joinMatches or null-extended rows changePush only into the preserved side of a left or right join
Native execution receives a repartition requestThe request is ignored and the input plan is used as-isUse the Ray runner when partition placement is part of the query contract
A filter is pushed below a checkpointed sourceThe checkpoint key set can miss rows that must be trackedKeep the filter above the checkpointed source

Key files

FileWhy to read it
src/…/logical_plan.rsDefines the logical node tree, child relationships, schemas, and required-column view
src/…/lib.rsDefines the public planning boundary and the Python-facing registrations for plan construction and source or sink options
src/…/mod.rsShows how DataFrame-style operations create plans and how the optimizer is assembled
src/…/resolve_expr.rsExplains column scope, wildcard expansion, join-side resolution, and expression checks
src/…/optimizer.rsDefines rule batches, fixed-point behavior, and the default optimization order
src/…/push_down_limit.rsShows how row limits move through safe plan shapes, reach supported sources, combine with sorts, and respect join semantics
src/…/push_down_filter.rsShows how semantic limits control filter movement toward sources
src/…/mod.rsShows when join order can change and how the choice is bounded
src/…/stats.rsDefines the statistics carried through planning
src/…/translate.rsMaps optimized logical operations to local execution operators and external inputs
src/…/plan.rsDefines the local operator tree and its schema and task context
src/…/planner.rsShows how SQL scopes and clauses enter the shared logical-plan path
daft/…/builder.pyProvides the Python-facing logical builder and plan inspection surface