Optimizer

The optimizer rewrites a logical plan into an equivalent one before execution. On the live query path it is a fixed sequence of seven rewrite rules, followed by a greedy join reorder that runs only when ANALYZE statistics exist for every table in the join. It does not compare alternative plans by cost, and it does not choose indexes; index choice is a fixed cascade in the executor (see executor and index overview) (source: src/plan/optimizer.rs, Optimizer::new, Optimizer::optimize).

When it runs

The engine calls Optimizer::optimize from execute_with_timeout_inner after the parse, resolve_natural_joins and promote_where_equijoins steps, when optimizer_enabled() is true. optimizer_enabled reads SYNERGYDB_OPTIMIZER once; 0, false or off disable it, anything else (or unset) leaves it on. If optimize returns an error, the engine uses the unoptimized plan (source: src/query/engine.rs, optimizer_enabled, QueryEngine::execute_with_timeout_inner). The lifecycle page shows the whole sequence.

The optimized plan is cached in opt_plan_cache when plan_opt_cacheable allows it. Plans containing joins are not cached, because the join reorder reads statistics that ANALYZE can change (source: src/query/engine.rs, plan_opt_cacheable).

The engine holds one Optimizer built with Optimizer::new() per QueryEngine; its stats_manager field is None (source: src/query/engine.rs, QueryEngine::new; src/plan/optimizer.rs, Optimizer::new).

Algorithm

flowchart TD S["plan"] --> I["iteration (max 10)"] I --> R1["PredicatePushdown"] --> R2["ProjectionPushdown"] --> R3["ConstantFolding"] --> R4["FilterMerge"] --> R5["LimitPushdown"] --> R6["JoinElimination"] --> R7["RedundantProjectElimination"] R7 --> C{"any rule changed the plan?"} C -- "yes" --> I C -- "no, or 10 iterations" --> J["cost_reorder_top (join reorder)"] J --> O["optimized plan"]

Source: src/plan/optimizer.rs, Optimizer::optimize, apply_rule.

optimize runs up to max_iterations (10) passes. In each pass every rule is applied once through apply_rule. apply_rule tries the rule at the current node; if the rule does not change that node, it recurses into the children, but only for Filter, Project, Join, Sort, Limit, Aggregate, Distinct and Union. It stops at the first change. A pass that changes nothing ends the loop (source: src/plan/optimizer.rs, Optimizer::optimize, apply_rule).

Because apply_rule does not descend into LimitWithTies, LockRows, Alias, Intersect, Except, LateralJoin, RecursiveCTE, Explain or any DML node, nothing below those nodes is rewritten. A derived table (Alias) or a SELECT ... FOR UPDATE (LockRows at the top) is therefore executed as parsed (source: src/plan/optimizer.rs, apply_rule). This also means EXPLAIN shows an unoptimized plan (see EXPLAIN).

Rules in order

# Rule (name()) Rewrites Conditions
1 PredicatePushdown (predicate_pushdown) Filter{Project} to Project{Filter}; Filter{Join} to a join with the filter on one side through Project: the projection has no aggregate or window expression, and every predicate column is a column reference in the projection. Through Join: join type Inner or Cross, and all predicate columns come from one side (extract_plan_columns)
2 ProjectionPushdown adds narrower Project nodes below Filter and Join; sets Scan.columns skipped when the projection has an aggregate, window or wildcard. Below Filter: only if fewer columns are needed than the input has. Into Scan: columns: Some(needed), using bare column names (qualifier dropped)
3 ConstantFolding folds constant subexpressions in Filter predicates and Project expressions a predicate that folds to TRUE removes the Filter; one that folds to FALSE is kept as a Filter so the result still has its columns. See the table below
4 FilterMerge Filter{Filter} to one Filter with outer AND inner always
5 LimitPushdown Limit{Union} to Limit{Union{Limit left, Limit right}}; Limit{Limit} to one Limit union: offset is 0 and limit is Some(n). Merge: offset is the sum, limit is min(outer, inner - outer_offset). Never through Project (the code comment says the executor has no Project{Limit} fast path)
6 JoinElimination removes joins with an Empty side Inner, Cross or Semi with either side Empty becomes Empty; left side Empty with Right or Full becomes the right side; right side Empty with Left or Full becomes the left side
7 RedundantProjectElimination drops a Project that changes nothing every expression is an unqualified column, in exactly the order of the input's output names (ordered_output_names, known only through Project, Filter, Sort, Limit), with no duplicates. The earlier collapse of nested Project nodes was removed as unsound

(source: src/plan/optimizer.rs, PredicatePushdown, ProjectionPushdown, ConstantFolding, FilterMerge, LimitPushdown, JoinElimination, RedundantProjectElimination)

Tested by test_predicate_pushdown_through_project, test_constant_folding_arithmetic, test_constant_folding_boolean, test_constant_folding_comparison, test_filter_remove_true, test_filter_to_empty, test_filter_merge, test_limit_merge and test_empty_join_elimination in src/plan/optimizer.rs. ProjectionPushdown, predicate pushdown through joins, LimitPushdown over Union and RedundantProjectElimination have no unit test in that file.

Not verified: LimitPushdown also fires for UNION without ALL. Limiting each branch to n rows before duplicates are removed can return fewer than n distinct rows when a branch has duplicates in its first n rows. The rule also matches its own output (Limit{Union{...}}), so it reports a change on every pass and the loop runs to its 10-pass limit, nesting another Limit in each branch each time. No test covers either effect (source: src/plan/optimizer.rs, LimitPushdown).

Constant folding

Expression Folded?
integer +, -, * yes, with checked arithmetic (overflow leaves it unfolded)
integer / only when not in MySQL dialect, not a decimal division, divisor non-zero (checked_div)
integer % divisor non-zero (checked_rem)
float +, -, *, / yes; / only with a non-zero divisor
integer comparisons yes
string comparisons no, deliberately (collation-dependent)
string concatenation yes
boolean AND, OR, =, <> yes; AND/OR short-circuit on a constant side
bitwise &, \|, #, <<, >> yes; shift amount masked with 0x3f
NOT on a boolean, unary minus on int or float yes
CASE without operand the first WHEN that is constant TRUE replaces the expression with its THEN
upper, lower, abs, coalesce on constants yes
length, CAST no

(source: src/plan/optimizer.rs, fold_expr)

Join reorder

After the rule loop, cost_reorder_top may reorder inner joins. This is the only part of the optimizer that reads statistics (source: src/plan/optimizer.rs, cost_reorder_top, reorder_joins_in, try_reorder_inner_tree).

It runs only when all of these hold:

  • the top node is a Project with no wildcard (so the output column order cannot change);
  • the join subtree, reached through Filter and Join nodes, is made only of Inner joins over base relations, each a Scan or Filter{Scan};
  • there are at least two leaves and their table names are distinct;
  • every leaf has a row estimate, meaning global_statistics() holds a row_count > 0 for it, which only ANALYZE provides;
  • every join predicate is fully qualified (collect_pred_tables).

build_greedy then starts from the largest relation and repeatedly adds the connected relation that minimises running_rows * rows * selectivity; an unconnected relation is penalised by a factor of 1e6. Selectivity of a cross-table col = col equality is 1 / max(NDV of the two columns); any other predicate counts as 0.2. The result is a left-deep tree; each predicate is attached at the lowest join that covers its tables, and the rest go into a final Filter (source: src/plan/optimizer.rs, build_greedy, pred_selectivity, row_estimate).

The reorder reads crate::plan::statistics::global_statistics() directly, not the optimizer's stats_manager field (source: src/plan/optimizer.rs, row_estimate). Statistics lookup is by exact table name; see cost model and statistics.

Tested by cost_reorder_puts_smaller_relation_on_build_side, cost_reorder_skips_wildcard_projection and cost_reorder_multiway_chain_orders_and_attaches_predicates in src/plan/optimizer.rs.

Without ANALYZE, joins run in the order written (after promote_where_equijoins). The executor makes its own run-time choice of which side to run first, independent of the optimizer (see executor).

Code in src/plan/optimizer.rs that the live path does not use

Not wired: these items exist in src/plan/ but nothing outside src/plan/ calls them (source: src/plan/optimizer.rs):

Item What it would do
Optimizer::to_physical, to_physical_with_stats lower a logical plan to PhysicalPlan
JoinOrderOptimizer, JoinOrderingRule, with_join_ordering, with_full_optimization dynamic-programming and greedy join ordering as an optimizer rule
estimate_cardinality, should_use_index, select_best_index cost-based cardinality and index choice
AdaptiveQueryOptimizer, compare_plan_costs, estimate_physical_plan_cost feedback-driven plan choice

The cost model and statistics page covers CostModel, which the live optimizer constructs but does not consult.

Disagreements with other documents

  • The README and How it works describe a cost-based optimizer that chooses indexes, and the configuration reference says SYNERGYDB_OPTIMIZER=0 "disables the cost-based optimizer". The code is rule-based with a statistics-gated join reorder, and index choice is not made by the optimizer (source: src/plan/optimizer.rs, Optimizer::optimize; src/query/engine.rs, execute_table_scan).
  • A comment above optimizer_enabled calls the optimizer off by default and experimental; the function enables it unless the variable says otherwise (source: src/query/engine.rs, optimizer_enabled).
  • STATUS.md says a constant TRUE or FALSE filter is always simplified; ConstantFolding removes only TRUE filters and keeps FALSE ones (source: src/plan/optimizer.rs, ConstantFolding).