Introducing a new way to review your PRs.

Read the announcement

helixdb / helix-db

HelixDB is an OLTP graph database with native vector and full-text search built in Rust on Object Storage.

View on GitHub

27 documents · Updated Nov 23, 2026

docs / planner-optimizer

Planner and optimizer

The planner turns a validated query into an executable strategy. It combines query meaning, graph and row facts, storage estimates, resource limits, and runtime observations so the optimizer can choose access paths, graph traversal order, and row execution behavior. See Query planning and execution for the wider lifecycle, Query language and AST for the input shape, Cypher language frontend and SQL language frontend for query sources, and Interpreter execution for the runtime consumer.

Planning boundary

Planning inputs and outputs

The planning boundary accepts a read or write batch plus one immutable PlannerContext. It returns an executable plan, or a diagnostic result that includes planner work and selection data. The context gives the planner the request parameters, index catalog, base statistics, runtime feedback, storage cost profile, and work limits needed to make one reproducible choice.

The main planning path is:

  1. Convert the batch into a plan envelope and one or more logical roots.
  2. Explore equivalent logical expressions and retain physical alternatives.
  3. Select the best physical alternative for each root.
  4. Lower the selected alternatives and their memo children into executable IR.
  5. Build the executable DAG and attach trace and metric data.

The following diagram shows how a query moves from its source form to an execution strategy.

flowchart LR
    A[Query AST batch] --> B[Validated relational query]
    B --> C[Logical roots]
    C --> D[Predicate and property analysis]
    D --> E[Memo of equivalent expressions]
    E --> F[Physical alternatives]
    F --> G[Property and cost selection]
    G --> H[Executable IR]
    H --> I[Executable plan]

References: crates/…/mod.rs• L17-68 crates/…/executable.rs• L9-74 crates/…/planner.rs• L8-38 crates/…/planning.rs• L151-212

Validated relational query

The relational query is the planner’s language-neutral contract between a frontend and physical planning. A frontend resolves names into slots before it creates the query. The query then records bindings, graph patterns, row operators, return slots, read or write effect, and the schema contract between each operator.

Validation derives scope and layout from the operators. It checks expression shape, slot use, graph endpoints, paths, projections, windows, and mutation inputs before physical planning starts. Deserialization uses the same validation boundary, so serialized query data cannot replace derived effects or schemas.

References: crates/…/mod.rs• L1-5 crates/…/query.rs• L106-133 crates/…/query.rs• L196-219 crates/…/query.rs• L236-475

Logical roots and IR

The planner uses an intermediate representation (IR) to give query meaning a stable form before it chooses storage and execution details. Logical expressions describe what the query must do. They cover access sources, filters, ordering, distinct, windows, pipelines, projections, aggregates, variables, mutations, branches, repeats, shortest paths, and other root operations.

The relational layer supplies validated graph and row operators to these roots. Its expressions use slots rather than runtime names. This keeps frontend syntax separate from optimizer rules while preserving scope, value type, nullability, and effect boundaries.

The IR keeps validation and shape rules close to the plan contract. For example, runtime expressions carry validated names, and non-empty wrappers prevent invalid empty plan parts. This lets later analysis and rule passes work with trusted plan shapes instead of re-checking basic structure at every step.

References: crates/…/mod.rs• L5-26 crates/…/ir.rs• L6-36 crates/…/plan.rs• L7-21 crates/…/query.rs• L106-133 crates/…/expression.rs• L138-184

Physical plans and executable plans

A physical plan states how a logical operation will run. A PhysicalAlternative pairs a physical expression with the properties it delivers and its estimated cost. The selected physical form can represent a label scan, index access, point reads, set operations, graph expansion, a stream operator, a sort, a barrier, or a control-flow operation.

The physical layer is not yet the final runtime plan. After selection, the planner resolves the logical source and child groups that produced the choice, then reconstructs selected executable IR. This separation lets the optimizer compare strategies without making the execution layer part of every search step.

For relational graph and row work, the selected result becomes a RowPlan. It retains graph source choices, match steps, row-pipeline behavior, and a validated row program. A reference plan exists for diagnostics and correctness comparison; it uses full scans and materialized row operators rather than optimizer-selected access or fusion.

References: crates/…/expr.rs• L8-39 crates/…/access.rs• L5-38 crates/…/alternative.rs• L6-34 crates/…/mod.rs• L1-16 crates/…/planning.rs• L35-89 crates/…/reference.rs• L1-100

Analysis and property inference

Predicate analysis

Predicate analysis extracts facts that can change the access strategy without reading storage. It proves static tautologies and contradictions, checks whether a predicate is true for a known label, prunes impossible branches, and identifies equality or range shapes that may use a secondary index.

The analysis supplies safe predicate shapes to access rules. Those rules can turn an indexed source filter into index access instead of a row-by-row decision. They preserve unindexed conjuncts as residual filters and keep branches that cannot narrow a label as ordinary filters. This makes analysis a source of safe candidates rather than a promise that an index exists.

The relational planner can carry safe predicates across later filters and pass-through projections. It only does this when the intervening work cannot change which errors are seen or which rows remain. Optional boundaries, ordering, windows, distinct, aggregation, and non-total expressions stop this movement. These checks keep an early access choice equivalent to the written query.

References: crates/…/analysis.rs• L1-28 crates/…/analysis.rs• L30-91 crates/…/planning.rs• L987-1149 crates/…/mod.rs• L52-79 crates/…/translate.rs• L76-145

Expression facts and graph demands

Expression analysis supplies the facts needed by both planning and evaluation. It validates structural depth and arity, infers a broad value type, records referenced slots, and identifies the graph data that an expression may need. A fixed property demand can name keys, while a dynamic property operation can require all properties.

The planner uses these demands to separate graph access from scalar work. A graph value source prepares metadata and properties for the batch. Scalar evaluation then reads the prepared values without performing storage I/O. This allows access planning to avoid unnecessary hydration while still preserving errors for properties that are actually read.

References: crates/…/expression.rs• L183-251 crates/…/expression.rs• L253-335 crates/…/expression.rs• L641-685 crates/…/graph_values.rs• L1-28

Required and delivered properties

Physical property inference describes what a plan needs and what it produces. A required property can specify the element kind and row ordering. Delivered properties also describe cardinality bounds, streaming or materialized behavior, side effects, and key locality.

An alternative is eligible only when its delivered properties satisfy the consumer's requirements. Ordering can satisfy a required key prefix, while an unordered result cannot satisfy a specific order. Cardinality inference also carries exact or bounded row counts through limits, skips, and ranges. These contracts prevent a cheaper plan from being chosen when it cannot preserve the behavior required by its parent.

Relational row plans use the same idea for projections, selections, and windows. A projection reads all expressions from the incoming row and installs its destinations only after the full result succeeds. A selection keeps rows in input order and retains only true predicates. A window can reduce upstream demand only when no later operation can change the result or expose a new failure.

References: crates/…/delivered.rs• L7-53 crates/…/ordering.rs• L6-39 crates/…/cardinality.rs• L5-18 crates/…/kinds.rs• L13-56 crates/…/projection.rs• L15-95 crates/…/selection.rs• L25-85 crates/…/planning.rs• L123-148

Cost estimates

The cost model compares plans across several resource dimensions instead of reducing every choice to one number. It tracks critical-path latency, storage reads, authoritative graph reads, multi-get calls, range work, CPU work, bytes, peak memory, and parallel width.

Child costs compose with the parent cost during selection. Serial work adds its resource costs, while peak memory and parallel width use their maximum values. Storage costs and cardinality estimates come from the planning context, so the same logical query can choose a different strategy when its data or storage profile changes.

Graph patterns add source population, relationship fanout, index lookup selectivity, join work, and possible Cartesian products to this comparison. Estimates affect the chosen order and cost, not the set of graph data that a correct plan may return.

References: crates/…/vector.rs• L5-29 crates/…/vector.rs• L31-79 crates/…/rule.rs• L7-19 crates/…/config.rs• L9-26 crates/…/graph_order.rs• L219-342

Graph pattern order

Graph pattern planning chooses how a MATCH obtains and connects its bindings. It compares source scans, correlated equality lookups, relationship expansion in either direction, and property hash joins. It prefers an expansion from a bound endpoint and can use an index when a probe is already known.

The pattern order keeps semantic rules with the row operator. Relationship uniqueness, optional boundaries, correlations, and predicates remain part of the query contract. The optimizer changes traversal priority and access choice without changing those rules.

The following diagram shows the main graph-order choices.

flowchart TD
    A[Validated graph pattern] --> B{Bound endpoint?}
    B -->|Yes| C[Expand relationship]
    B -->|No| D{Bound indexed probe?}
    D -->|Yes| E[Correlated index lookup]
    D -->|No| F{Property equality?}
    F -->|Yes| G[Hash join]
    F -->|No| H[Source scan]
    C --> I[Next bound pattern state]
    E --> I
    G --> I
    H --> I

References: crates/…/graph_order.rs• L1-81 crates/…/graph_order.rs• L122-217 crates/…/graph_order.rs• L219-342 crates/…/planning.rs• L549-827

Evaluation and resource contracts

Scalar evaluation gives the selected row plan its value semantics. It evaluates resolved expressions over rows, parameters, prepared graph values, and optional groups. It preserves written evaluation order, short-circuit behavior, null rules, aggregate behavior, and the first error that the query can observe.

The evaluator admits owned temporaries before it creates them. One memory allowance tracks live siblings and can report the request-wide peak. Separate checks bound expression depth, list cardinality, aggregate state, and output size. This makes resource failure part of the plan contract rather than an uncontrolled allocator failure.

Aggregates update incremental state. Ordinary numeric aggregates use bounded state, while DISTINCT retains grouping keys and collect retains its output values. GroupingKey uses total value equality for grouping and distinctness, including normalized numeric values, null, and NaN. Failed transitions do not partially update the aggregate.

References: crates/…/evaluation.rs• L16-82 crates/…/evaluation.rs• L284-315 crates/…/evaluation.rs• L784-815 crates/…/memory.rs• L1-93 crates/…/aggregation.rs• L1-35 crates/…/aggregation.rs• L90-265 crates/…/value.rs• L280-437

Rule system

Logical exploration rules

Logical exploration rules add equivalent expressions to the same memo group. They simplify static predicates and pipelines, merge or push filters, normalize access filters, and combine compatible access sets. The access rules expose index-backed choices for equality, range, conjunction, and disjunction predicates.

An indexed filter over a broad source is treated as a required access rewrite when an index can serve a conjunct. Conjunctions use intersections of index sources. Disjunctions use unions when every branch narrows the label; branches with their own unindexed terms retain branch-local residual filters. A branch that cannot narrow the label remains a row filter because an index would not reduce the work safely.

The rewrite uses every eligible indexed conjunct in a conjunction. It does not drop an index because statistics are missing, stale, or small. A literal equality can also use a range index as a point lookup when no equality index exists; values that cannot form an exact point remain residual predicates.

Unique node keys have a narrower role. A non-null equality lookup on a unique index can drive the source because it produces at most one candidate per value. Other conjuncts then run on those candidates, even when another index could answer them. Sources that may repeat elements do not use set intersection; node membership checks preserve every repeated input instead.

The rules preserve query meaning while exposing choices such as early filtering, index access, range intersection, range union, contradiction elimination, and order or distinct elision. They return NotApplicable when a shape does not match and Rejected when a matching shape cannot be used safely.

References: crates/…/exploration.rs• L1-11 crates/…/access.rs• L25-42 crates/…/rule.rs• L37-57 crates/…/mod.rs• L24-89 crates/…/shared.rs• L108-176 crates/…/translate.rs• L76-145 crates/…/source_index.rs• L1-29

Physical implementation rules

Physical implementation rules turn logical expressions into executable strategies. They implement core operators, access paths, access pipelines, root operations, stream operators, cardinality programs, and control-flow operations.

The graph implementation rule turns a pattern into scan, lookup, expansion, or join alternatives. The row implementation rule chooses a pipeline mode and can use bounded input demand for safe windows. Each produced alternative includes delivered properties, a cost estimate, and rule provenance. Provenance records which rule made the choice, so traces and later plan inspection can explain why an alternative exists without changing the execution contract.

The access implementation path applies the required source-index rewrite before it offers a physical alternative. This keeps an indexed leading filter from falling back to a scan because of cost estimates or a stopped optional search. Pipeline simplification also removes a distinct after only filtering steps when the access source already guarantees unique elements, and removes an adjacent duplicate distinct.

References: crates/…/implementation.rs• L1-16 crates/…/access.rs• L25-42 crates/…/mod.rs• L1-21 crates/…/implementation.rs• L1-13 crates/…/alternative.rs• L6-34 crates/…/provenance.rs• L7-36 crates/…/graph_order.rs• L344-397 crates/…/planning.rs• L829-940 crates/…/distinct.rs• L7-47

Rule registry and schedule

The built-in seed registry defines the production rule set and validates that rule IDs are unique and complete. The optimizer compiles the ordered registry into candidate lists by expression and operation family. Exploration can then consider rules that match the current shape without scanning unrelated rules.

The registry order is part of the planner contract. Rule IDs also serve as trace and provenance keys, so missing, duplicate, or unexpected IDs are rejected before search begins.

Access-pipeline scheduling uses conservative candidate checks before it runs local simplification. The check admits empty sources and distinct patterns after filters or index-membership steps, plus adjacent distincts. It may admit extra work, but it must not miss a shape that the simplifier can rewrite.

References: crates/…/registry.rs• L9-25 crates/…/registry.rs• L65-126 crates/…/registry.rs• L8-24 crates/…/mod.rs• L1-79 crates/…/candidates.rs• L1-29

Cascades optimization

Memo exploration

The optimizer uses a Cascades-style memo. A memo is a shared store of equivalent logical expressions grouped by semantic alternatives. The search starts with one or more roots, adds logical effects to existing groups, and places new work on an exploration queue. Physical effects are retained against the group that they implement.

Multiple roots share one request-scoped memo, queue, metric set, and guardrail budget. This matters for batches and nested roots because shared child groups can be explored once and selected through their parent relationships.

Relational access roots and graph pattern roots enter this same memo. This lets source access choices and traversal order compete under one planning budget instead of being selected by unrelated searches.

References: crates/…/mod.rs• L1-29 crates/…/state.rs• L20-29 crates/…/state.rs• L31-105 crates/…/mod.rs• L37-56 crates/…/planning.rs• L214-243 crates/…/planning.rs• L829-837

Guardrails and partial results

Search is bounded by limits on memo groups, memo expressions, rule fires, retained alternatives, and elapsed planning time. A guardrail stops further exploration and is recorded in the optimization result. The planner can therefore report that a result is incomplete instead of allowing search work to grow without bound.

The result keeps the memo, retained physical alternatives, metrics, roots, and any stopping guardrail together. This gives selection and diagnostics the same view of the search that produced the candidate plans.

For relational access and graph order, a guardrail can use the validated seed implementation as a correctness-preserving fallback. The fallback gives a usable plan with less optimization rather than inventing an unplanned access path.

References: crates/…/limits.rs• L22-56 crates/…/exploration.rs• L21-68 crates/…/mod.rs• L26-100 crates/…/planning.rs• L839-878 crates/…/planning.rs• L909-940

Physical selection

Selection chooses one retained alternative for a group after it checks required properties and recursively selects the groups used by that alternative. The selected cost includes the alternative's own cost plus the serial cost of its selected children.

The first ordering key is the full cost vector. The physical alternative digest is the final tie-breaker, which makes equal-cost choices stable across process runs. A reusable selection session caches default choices for one optimization result and detects missing alternatives, unsatisfied properties, and recursive selection cycles.

References: crates/…/candidate.rs• L9-78 crates/…/cost.rs• L8-27 crates/…/ordering.rs• L5-26 crates/…/mod.rs• L16-40

Selected plan lowering

The selected-plan boundary maps the chosen physical alternative back to its source logical expression and recursively resolves its memo children. It then lowers the complete selected root into selected executable IR before the final executable-plan builder validates and assembles the DAG.

Child selection stays tied to the optimizer result that chose the parent. If a required child or physical alternative is missing, the planner reports an optimizer or unsupported-plan failure instead of starting an unrelated fallback search.

References: crates/…/session.rs• L13-35 crates/…/session.rs• L48-114 crates/…/mod.rs• L1-16 crates/…/executable.rs• L47-74

Feedback and plan identity

Runtime feedback

Runtime feedback is an immutable snapshot of observed row counts from earlier execution. It can describe node and edge label counts plus equality-index and range-index results for both nodes and edges.

The planner overlays this snapshot on the base statistics when it creates optimizer configuration. Feedback does not read storage or runtime counters during planning, and it does not mutate the base statistics. A zero-row observation is valid and can make an empty or more selective strategy preferable.

References: crates/…/feedback.rs• L14-18 crates/…/feedback.rs• L47-79 crates/…/feedback.rs• L152-185 crates/…/planner.rs• L98-124

Plan digests

A PlanDigest is a stable identity value for planner contracts. The planner computes it from serialized values with an explicit schema tag, then uses it for memo identity, selected-root cache keys, physical-alternative tie-breaking, and deterministic ordering.

Resolved relational values are part of this identity. Planner serialization preserves exact floating-point bits, including signed zero and NaN payloads, so distinct constants do not collapse into one memo key.

Digest lookup is only a fast first step. Memo and selected-root caches confirm full expression equality after a digest match, so a digest collision cannot cause an unrelated plan to be reused. Changing the tagged value or its contract shape changes the identity and can invalidate reuse by design.

References: crates/…/digest.rs• L3-55 crates/…/identity.rs• L8-22 crates/…/root.rs• L7-30 crates/…/cache.rs• L1-14 crates/…/value.rs• L58-92

Change checklist

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

  • Changes to logical expression shape, child order, or serialized fields can change memo identity and selected-root cache behavior. Review the digest tags and equality checks together.
  • Changes to delivered or required properties must be checked against every physical rule that creates or consumes those properties. A plan can become selectable or unselectable without a type error.
  • Changes to cost-vector fields or ordering must preserve recursive child-cost composition and the stable digest tie-breaker.
  • Changes to rule IDs or the built-in seed registry must preserve unique IDs, complete known-rule coverage, schedule routing, trace output, and provenance.
  • Changes to statistics or runtime feedback must keep the overlay immutable and must cover both label estimates and index estimates for nodes and edges.
  • Changes to optimizer guardrails must keep partial-result reporting aligned with root counts, retained alternatives, and planner diagnostics.
  • Changes to slot scopes, operator contracts, or row layouts must be checked against expression references, projection destinations, graph pattern endpoints, and the derived read or write effect.
  • Changes to graph lookup extraction or predicate movement must preserve totality checks and optional boundaries. An early lookup must not hide an error or remove a row that the query would keep.
  • Changes to access-index translation must preserve the required rewrite contract: indexed conjuncts cannot fall back to a scan, residuals stay attached to their own branches, and repeated sources do not lose duplicate rows.
  • Changes to unique-index handling must preserve the distinction between one-value keys, key lists, null values, and non-unique indexes. The chosen driver also controls which other predicates remain residual.
  • Changes to access-pipeline candidate checks must cover every shape that local simplification can rewrite. A false negative can leave redundant distinct work in the plan.
  • Changes to expression or value shape limits must preserve compile-time validation, runtime validation, collection limits, and memory admission as separate contracts.
  • Changes to grouping or aggregate state must keep total grouping equality aligned with hashing, DISTINCT, numeric aggregate behavior, and failed-update atomicity.

Important failure modes

TriggerConsequenceGuard
A required ordering or element kind is not delivered by an alternativeSelection rejects that alternative and may report unsatisfied required propertiesProperty satisfaction is checked before recursive cost comparison
A selected group has no retained physical alternativeThe root cannot lower to executable IRSelection returns NoPhysicalAlternatives and the planning boundary maps it to an explicit planner failure
Memo groups, expressions, rule fires, alternatives, or time exceed a limitExploration stops with a partial result and a recorded guardrailRequest-scoped optimizer limits are checked during seed, rule, and effect processing
A digest bucket contains a different logical expressionA cache hit could select the wrong plan if equality were not checkedCache reuse requires full logical-expression equality after digest lookup
The production rule registry has a duplicate, custom, or missing known rule IDScheduling and provenance keys are not trustedRegistry validation rejects the set before optimization
An indexed filter is left over a broad scanThe plan reads records row by row and can violate the required indexed-access contractThe source-index rule is required for matching implementations, including after optional exploration stops
A unique key is treated as a general set or a null match is treated as one candidateThe plan can do needless index work or miss rows with a missing propertyUnique driving accepts only non-null key shapes and keeps other predicates as candidate residuals
A repeated source is intersected with an index setRepeated input IDs collapse and the result changesRepeated sources use index membership rather than set-replacing access rewrites
An OR branch cannot narrow the label but is forced into an index unionThe plan can omit rows or attach a residual to an incomplete sourceSuch disjunctions remain row filters unless every branch has a safe narrowing source
A source filter has no index-served conjunctThe plan must scan and evaluate the filter per rowIndex derivation reports no applicable rewrite and the normal filter path remains available
A distinct candidate is missed after filters or index membershipRedundant distinct work remains in the access pipelineCandidate checks include empty sources, filter or membership prefixes, and adjacent distincts
Runtime feedback is applied as mutable shared stateLater requests could see stale or request-specific estimatesFeedback is overlaid into a fresh effective statistics snapshot
A row projection fails after an earlier destination is computedThe input row or output destinations can be left partly changedProjection evaluates against the immutable input and installs results only after success
An expression or aggregate exceeds depth, collection, or memory limitsPlanning or execution returns a classified resource error instead of producing an unbounded valueShape checks and admission run before cloning, allocation, or state mutation
A distinct aggregate admits a key before its numeric transition succeedsA later result can contain a key that the aggregate did not processAggregate transitions and distinct-key retention occur only after validation and admission

Key files

FileWhy to read it
crates/…/mod.rsPublic planning boundary for read and write batches
crates/…/planner.rsComplete immutable input snapshot and effective statistics behavior
crates/…/query.rsValidated slot-based query contract and operator scopes
crates/…/expression.rsShared expression shape, graph demands, and rewrite behavior
crates/…/mod.rsLogical expression families used as optimizer input
crates/…/alternative.rsContract for costed physical choices and delivered properties
crates/…/delivered.rsRequired-versus-delivered property checks
crates/…/analysis.rsPredicate facts that guide simplification and index candidates
crates/…/planning.rsRelational access selection, graph schedules, row plans, and guardrail fallback
crates/…/graph_order.rsGraph traversal order, correlated lookups, joins, and pattern alternatives
crates/…/mod.rsContract for required and partial property-index rewrites
crates/…/contracts.rsOutcomes that distinguish rewrites, unchanged sources, unique-key sources, and residual limits
crates/…/shared.rsShared index-source, unique-key, and source-combination behavior
crates/…/translate.rsBranch-level translation of mixed indexed and residual predicates
crates/…/source_index.rsRequired rewrite of leading source filters into index access
crates/…/distinct.rsSafe distinct simplification in access pipelines
crates/…/candidates.rsCandidate detection for local access-pipeline simplification
crates/…/index_served_sources.rsEnd-to-end guarantees for index-served source filters, unions, residuals, and stable plans
crates/…/unique_driver.rsEnd-to-end guarantees for unique-key-driven reads and writes
crates/…/registry.rsProduction rule families and registry completeness
crates/…/exploration.rsRequest-scoped rule exploration flow
crates/…/candidate.rsProperty filtering and best-candidate choice
crates/…/cost.rsRecursive composition of selected child costs
crates/…/evaluation.rsScalar semantics, graph reads, aggregate evaluation, and memory checks
crates/…/aggregation.rsIncremental aggregate state and resource admission
crates/…/value.rsQuery value limits, total grouping equality, and planner serialization
crates/…/feedback.rsRuntime row observations used to refine estimates
crates/…/digest.rsStable identity and deterministic tie-break behavior
crates/…/mod.rsBoundary from selected optimizer output to executable IR