Physical plan and executor

The live engine does not build a physical plan. QueryEngine interprets the optimized logical plan directly, recursively, and every operator returns its whole result as a materialized QueryResult::Select { columns, rows }, where each cell is an Option<String>. There is no pull iterator, no push pipeline, no column batches and no spill to disk. A physical plan type and a separate QueryExecutor exist in src/plan/, but the engine reaches them only as a fallback for plans that read no table (source: src/query/engine.rs, execute_plan_inner, execute_select, execute_select_plan; src/plan/executor.rs, QueryExecutor).

Execution model

Property Live engine
Plan form LogicalPlan, interpreted node by node
Data flow each child is fully executed before its parent starts; results are Vec<Vec<Option<String>>>
Value representation text cells; operators that compare or compute parse cells to Value as needed (joins parse each row once with parse_string_to_value)
Batches, vectorization none
Streaming to the client none from the executor; wires receive a complete result. See cursors for how wires page it
Memory limit, spill none. No work_mem-style limit exists outside the unwired cost model
Parallelism none inside one query
Early exit LIMIT over an unfiltered scan stops the scan early (scan_first_rows); top-k for ORDER BY ... LIMIT

(source: src/query/engine.rs, execute_select_plan, scan_first_rows, try_typed_top_k)

check_timeout exists but has no caller, so a statement timeout does not interrupt an operator mid-way (source: src/query/engine.rs, check_timeout; see lifecycle).

Dispatch

execute_plan_inner matches on the top node: DDL, DML, cursor, transaction and session nodes have their own handlers; query nodes go to execute_select, which records aggregate argument types when the plan has an aggregate and then calls execute_select_plan (source: src/query/engine.rs, execute_plan_inner, execute_select).

execute_select_plan first applies a few rewrites, then matches the node:

  1. rewrite_correlated_exists: turns a correlated EXISTS into an IN where it can.
  2. PostgreSQL user resolution, functional-dependency widening of GROUP BY (a primary key in GROUP BY makes the table's other columns legal in the select list).
  3. Grouping checks: SQLSTATE 42803 (PostgreSQL) and MySQL errors 1140 and 1055.
  4. Column ambiguity and existence checks: 42702, 42703.

(source: src/query/engine.rs, execute_select_plan, rewrite_correlated_exists)

Node Handler
FROM-less Project over literals evaluated directly
Values evaluated directly
Scan execute_table_scan_inh with the needed columns, see access paths
TableFunction built-in set-returning functions
Filter over Scan filter passed into the scan
LimitWithTies, Limit see limits
Sort see sorting
Join see joins
LateralJoin right side executed once per left row after substitute_outer_columns
Aggregate see aggregation
Alias executes the input and renames columns
Distinct execute_distinct
Union, Intersect, Except execute_plan, then execute_set_op
RecursiveCTE execute_recursive_cte: iterates until the working set is empty
anything else fallback to logical_to_physical and QueryExecutor, see below

(source: src/query/engine.rs, execute_select_plan)

Before execution, pushdown_filters_into_scans moves single-table conjuncts of a WHERE into the Scan.filter of that table, through inner joins only, after promote_cross_joins (source: src/query/engine.rs, pushdown_filters_into_scans). Tested by test_left_join_filter_pushdown_keeps_outer_semantics.

Access paths

The table scan picks one access path from the scan's filter by trying each in a fixed order and taking the first that applies. Statistics are not consulted (source: src/query/engine.rs, execute_table_scan_self).

Order Path Applies when the filter has
0 HNSW candidate keys a vector-distance ORDER BY ... LIMIT staged by the Limit arm
1 primary-key point get (try_pk_equality_key) equality on the whole primary key
2 primary-key multi-get (try_pk_in_list_keys) pk IN (...)
3 unique index (try_unique_index_lookup) equality on a single-column UNIQUE
4 composite unique (try_composite_unique_index_lookup) equality on every column of a multi-column UNIQUE
5 secondary index equality (try_secondary_index_candidates) equality on an indexed column
6 secondary index range (try_secondary_range_candidates) a range on an indexed column
7 GIN (try_gin_candidates) a GIN-indexable operator
8 full-text (try_fts_candidates) a full-text match
9 primary-key integer range (try_pk_int_range) a range on an integer primary key
10 primary-key prefix ranges (try_pk_prefix_ranges) a prefix of a composite primary key
11 full scan (scan_prefiltered) anything else

(source: src/query/engine.rs, execute_table_scan_self)

Tested in part by test_pk_int_range_matches_full_scan and test_param_equality_on_indexed_column_skips_full_scan_aggregate. Index structures are described in index overview.

Limits

The Limit arm (source: src/query/engine.rs, execute_select_plan, try_typed_top_k, take_scan_row_cap, scan_first_rows):

  • LIMIT 0 returns only the column list (extract_columns_from_plan) without running the input, unless the input has an unresolved *.
  • Limit{Sort} first tries try_typed_top_k: a bounded heap over an integer sort key, stable for ties.
  • A vector-distance order is staged through try_hnsw_candidate_keys and vector_scan_restrict.
  • For an unfiltered scan, the engine records a row cap of limit + offset for that table; take_scan_row_cap hands it to the scan, which stops after that many rows (scan_first_rows). The cap is not used under SERIALIZABLE isolation or when the transaction has written in the table's key range.
  • Otherwise the input is fully executed and sliced.

LimitWithTies executes its sorted input and extends the cut past limit while the sort key equals the last row's. Not verified: no engine test runs WITH TIES.

Tested by test_mysql_cast_and_limit and test_for_update_skip_locked_then_limit.

Sorting

The Sort arm resolves uncorrelated subqueries in sort keys, expands *, checks ORDER BY ambiguity (not in MySQL dialect), resolves positional keys (ORDER BY 2), adds sort columns that are missing from the projection, executes the input and sorts in memory with Rust's stable sort_by (source: src/query/engine.rs, execute_select_plan, positional_sort_keys, add_order_by_columns_to_plan, check_order_by_ambiguity). There is no external sort. Tested by test_correlated_scalar_subquery_order_by_limit and test_order_by_ordinal_over_aggregate_and_cast_and_left_join_column.

Joins

Both join inputs are fully materialized. The arm decides at run time which side to run first and whether to shrink the other side with an IN list built from the first side's keys (source: src/query/engine.rs, execute_select_plan, reduce_right_by_left_keys, reduce_side_by_join_keys, right_never_matches).

flowchart TD J["Join node"] --> N{"ON has col = NULL (Inner/Left)?"} N -- "yes" --> E["right side = empty with its columns"] N -- "no" --> O{"LEFT join, or INNER with index-served left and non-indexed right?"} O -- "yes" --> L["run left, then right reduced by left keys"] O -- "no" --> R["run right, then left reduced by right keys (INNER only)"] L --> A{"equi pairs, Inner/Left, join opt enabled?"} R --> A A -- "yes" --> H["hash join: build right, probe left"] A -- "no" --> NL["nested loop"] H --> X{"RIGHT or FULL?"} NL --> X X -- "yes" --> U["extra pass for unmatched right rows"]

Source: src/query/engine.rs, execute_select_plan.

Details:

  • Key reduction. reduce_side_by_join_keys applies to INNER joins with a single qualified equality between two distinct base tables. It collects up to 512 distinct keys (MAX_KEYS), or 8192 (MAX_INDEXED_JOIN_KEYS) when the probed column is index-served; a non-indexed probed column requires integer keys. An empty driving side turns the other side into LIMIT 0 (source: src/query/engine.rs, reduce_side_by_join_keys). Tested by test_join_reduction_on_unindexed_integer_key and inner_join_drives_from_indexed_side.
  • Hash join. Used when the join has equi-join pairs, the type is Inner or Left, and join optimizations are enabled. Buckets are a HashMap<Vec<String>, Vec<usize>> keyed by join_bucket_key; rows with a NULL key are left out of the table. Every candidate pair is re-checked against the full ON condition with evaluate_join_condition_typed. A LEFT join emits unmatched left rows with NULLs (source: src/query/engine.rs, join_bucket_key, evaluate_join_condition_typed).
  • Nested loop. Used for every other case, including non-equi conditions, Cross, Right and Full. It is O(left × right) and skips pairs whose condition is false or NULL.
  • Right and full joins. After the main pass, a second O(left × right) pass emits right rows that matched nothing. Tested by test_join_order_by_qualified_and_lateral_projection (FULL OUTER JOIN) and star_over_using_and_natural_joins_shows_the_key_once.
  • Output columns are named table.column unless already qualified.
  • SYNERGYDB_DISABLE_JOIN_OPT (1 or true, read once) disables the hash join, both key reductions and pushdown_filters_into_scans (source: src/query/engine.rs, join_opt_disabled).

Merge join and index nested-loop join do not exist on the live path. The optimizer's join order, when statistics allow a reorder (see optimizer), decides which relation is the left input; the arm above then decides execution order independently.

Other join tests: test_join_multi_condition_on, test_join_using, test_comma_join_becomes_inner_join, test_self_correlated_and_cross_join_lateral, test_null_literal_through_join_projection.

Aggregation

The Aggregate arm tries two typed fast paths before the general one (source: src/query/engine.rs, try_typed_simple_aggregate, try_typed_join_aggregate, validate_aggregate_arg_columns):

Path Applies to
try_typed_simple_aggregate COUNT, SUM, MIN, MAX, AVG over integer columns of one table, no open transaction; i128 accumulators
try_typed_join_aggregate two-table integer equi-join with GROUP BY
general executes the input, validates aggregate argument columns (42703), groups in a HashMap while keeping first-seen group order; with grouping_sets, runs once per set

Tested by test_typed_join_group_by_matches_general_path, test_plain_join_and_groupby_not_regressed and test_grouping_ambiguity_and_cardinality_errors. Aggregates without GROUP BY stay in Project (see logical plan) and are evaluated there. Not verified: no engine test runs ROLLUP, CUBE or GROUPING SETS.

Distinct, set operations, recursive CTEs

execute_distinct removes duplicates in memory, keeping the first occurrence; DISTINCT ON keeps the first row per key of its sorted input (tested by test_distinct_on_first_per_group). execute_set_op materializes both inputs and combines them in memory. execute_recursive_cte evaluates the recursive term repeatedly until the working set is empty, deduplicating against all rows so far for UNION (not UNION ALL); after 100,000 iterations (MAX_ITERATIONS) it returns an internal error instead of looping forever; tested by test_recursive_cte_counter_union_all, test_recursive_cte_hierarchy_traversal and test_recursive_cte_union_vs_union_all (source: src/query/engine.rs, execute_distinct, execute_set_op, execute_recursive_cte).

The physical plan and QueryExecutor

src/plan/physical.rs defines PhysicalPlan with these operators: SeqScan, IndexScan, VectorIndexScan, FullTextScan, GinScan, NestedLoopJoin, HashJoin, MergeJoin, VectorJoin, HashAggregate, SortAggregate, Project, Filter, Sort, TopN, Limit, HashDistinct, UnionAll, GraphTraversal, Hybrid, Window, Intersect, Except, Values, Empty, Insert, Update, Delete, CreateTable, DropTable, CreateIndex, DropIndex (source: src/plan/physical.rs, PhysicalPlan). The file has no tests.

QueryExecutor in src/plan/executor.rs executes PhysicalPlan with an ExecutionContext { variables, max_rows, timeout_ms }. It holds storage: Option<...>; with_storage is never called outside src/plan/, so the engine's instance has no storage (source: src/plan/executor.rs, QueryExecutor, with_storage; src/query/engine.rs, QueryEngine::new).

The engine's fallback, logical_to_physical, maps Project, Filter, Scan (to SeqScan), Limit, Sort, Values, Join (always NestedLoopJoin), Aggregate (to HashAggregate) and Distinct (to HashDistinct); everything else becomes Empty. Values gets a single column named column0 (a TODO in the code) (source: src/query/engine.rs, logical_to_physical). Because the executor has no storage, any fallback plan that contains a SeqScan fails with "No storage engine available for scan" (source: src/plan/executor.rs, execute_seq_scan). The LimitPushdown rule avoids creating Project{Limit} for this reason (see optimizer).

Not wired: IndexScan, HashJoin, MergeJoin, SortAggregate, TopN, Window, the vector, graph, GIN and full-text operators, and the DML and DDL operators of QueryExecutor are never produced by logical_to_physical. AuthorizedExecutor has no caller outside src/plan/. Its tests (test_row_access, test_execute_values, test_nested_loop_right_join_null_extends_unmatched_right, test_nested_loop_full_join_null_extends_both_sides, test_nested_loop_join_null_keys_do_not_match, test_execute_limit) exercise it in isolation.

Debug logging

When SYNERGYDB_DEBUG_LOG is set, debug_log_open appends diagnostic lines (for example the first row of a join result) to a file under /tmp; one call site opens a relative path in the working directory instead (source: src/query/engine.rs, debug_log_open). The output includes row data, so it should not be enabled where query results are sensitive.