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 / query-planning-and-execution

Query planning and execution

Helix turns a query request into a checked execution plan and runs that plan against one graph view. The path keeps language meaning, plan choices, storage access, and returned data separate so each stage can enforce its own rules.

Query lifecycle

The query lifecycle moves from a public operation tree to a resolved relational query, then to planner facts, a costed executable graph, and finally to graph results. The query service is the main boundary for this path; transports should not repeat its validation or result handling.

flowchart LR
    A[Query request] --> B[Validated batch and parameters]
    B --> C[Planner context]
    C --> D[Logical form and query facts]
    D --> E[Optimized physical alternatives]
    E --> F[Validated executable DAG]
    F --> G[Interpreter stages]
    G --> H[Graph reads or writes]
    H --> I[Returns and diagnostics]

The request kind stays attached to the batch from intake through execution. This lets the system reject a read request that contains a write and lets the runtime select the correct storage and transaction behavior.

Request intake

The request boundary accepts a QueryRequest with a read or write batch, optional name, and runtime parameters. It validates the wire shape before planning, including agreement between the request tag and the closed batch variant; typed parameters must also match their declared value shapes. The full request contract is defined in crates/…/query.rs.

The query service in crates/…/query_service.rs then converts the request into a validated batch and planner parameter bindings. It also applies the selected mode, storage scope, and execution control before it allows planning to start.

References: crates/…/query.rs• L211-283 crates/…/query.rs• L470-535 crates/…/query_service.rs• L175-199 crates/…/query_service.rs• L323-378

Planner context

The planner context is an immutable snapshot of the facts that may affect one plan. It joins request parameters with the available index catalog, statistics, runtime feedback, storage cost profile, and planning limits.

The database builds this context for the request scope. A prepared context also couples the catalog observation and read view used for planning to execution, so a plan does not silently use a different index state from the one it was based on.

References: crates/…/planner.rs• L8-38 crates/…/config.rs• L9-39 crates/…/lib.rs• L1519-1592

AST conversion

The Helix query representation is an operation tree. Each traversal step wraps the prior input, while a batch groups named queries, conditions, for_each bodies, and the variables to return. This representation preserves the nesting and order that later planning must honor.

The planner converts batch entries into logical roots. It handles recursive branches, repeats, mutations, terminals, and pipeline children through the same selected-planning boundary instead of treating them as unrelated top-level requests.

For more detail about the public representation, see Query language AST.

References: crates/…/lib.rs• L1-12 crates/…/batch.rs• L18-44 crates/…/traversal.rs• L115-142 crates/…/mod.rs• L1-6

Resolved query contract

The resolved relational query is the language-neutral contract between a frontend and the planner. It represents graph patterns, row operators, expressions, bindings, return slots, and read or write effect without retaining frontend syntax. Bindings use stable slots, so later stages can track scope and value type without resolving names again.

Construction derives the row schema and operator contracts while it checks input scope, graph pattern shape, expression shape, output slots, and effect. This makes validation the trust boundary for physical planning and execution. Shared selection and projection programs preserve input order, output order, and failure order for frontend adapters.

For the language-facing representation, see Query language AST. For the frontend that creates this resolved form, see Cypher language frontend.

References: crates/…/query.rs• L106-133 crates/…/query.rs• L196-220 crates/…/query.rs• L236-475 crates/…/projection.rs• L15-95 crates/…/selection.rs• L25-84

Query analysis

Analysis extracts safe facts from predicates before the planner chooses an access path. These facts include label scope, constant tautologies or contradictions, branches that can be removed, and equality or range forms that may use a secondary index.

Analysis is a shape proof, not a storage lookup. The later access rules still check the catalog and full predicate coverage. This separation allows cheap rewrites without claiming that an index exists or that a scan is unnecessary.

References: crates/…/analysis.rs• L1-10 crates/…/analysis.rs• L30-45 crates/…/analysis.rs• L67-91

Logical and physical planning

Logical planning describes what the query must do without fixing one storage method. The relational planner turns validated graph patterns and row operators into shared planning inputs, then explores physical alternatives that can satisfy that logical work, such as different graph access paths, stream operations, terminals, and control-flow forms.

The Cascades optimizer keeps alternatives in a memo and selects a best plan under the request context. Required source-index rules first turn index-served source filters into index access, leaving only non-indexed conjuncts as residual filters. Conjunctions become index intersections and disjunctions become unions when each branch can be narrowed; a unique key drives a broad source and leaves the other checks on its candidates. These rewrites are required for matching source filters, while repeat-capable sources stay row-preserving instead of using a set intersection. The optimizer then compares source scans, index lookups, relationship expansions, hash joins, and traversal orders while preserving predicate and optional-match semantics. Its choice can use index metadata, cardinality facts, request values, storage costs, and configured guardrails. Selected roots retain provenance so the next stage can reconstruct their children from the same optimizer result.

Local access-pipeline rules also remove redundant work when the access source already guarantees distinct results, or when adjacent distinct operations repeat the same guarantee. The candidate check is conservative so a simplification rule is not skipped, but it does not change pipelines that contain an order-sensitive operation such as a limit before distinct.

See Planner optimizer for the decisions and cost model behind this stage.

References: crates/…/planning.rs• L44-61 crates/…/planning.rs• L151-212 crates/…/graph_order.rs• L219-333 crates/…/mod.rs• L5-26 crates/…/physical.rs• L1-22 crates/…/optimizer.rs• L1-28 crates/…/session.rs• L13-23 crates/…/session.rs• L44-63 crates/…/source_index.rs• L1-29 crates/…/shared.rs• L108-176 crates/…/translate.rs• L76-145 crates/…/distinct.rs• L7-47 crates/…/candidates.rs• L10-29

Executable plan construction

The selected physical result becomes an ExecutablePlan: a validated directed acyclic graph of executable steps with a root, return shapes, trace, and planner metrics. The plan is the contract shared by the planner and interpreter; it contains the access and control choices needed at runtime.

Construction validates dependency reachability, local step rules, return bindings, and the root. It also derives deterministic execution stages. Independent non-barrier steps can form a parallel stage, while barriers and dependent work stay in order.

References: crates/…/mod.rs• L17-68 crates/…/top_level.rs• L12-58 crates/…/validation.rs• L1-14 crates/…/order.rs• L1-10

Runtime execution

The interpreter consumes the executable plan directly. It does not choose access paths or rewrite predicates; it schedules validated steps, passes dependency values between them, and dispatches each operation to graph, search, stream, control-flow, or mutation behavior.

Relational operators evaluate expressions over materialized rows and use a batch-local graph view for labels, properties, keys, and entity metadata. Scalar evaluation applies null, comparison, function, aggregation, and graph-value rules without doing storage I/O itself. Projection evaluates all outputs against the incoming row before installing them, while selection retains only rows whose predicate is true.

Each request owns a stable read view. Reader requests use an immutable snapshot and may run isolated read stages in parallel. Writer-side reads use a snapshot transaction, so the runtime keeps stages serial. Graph writes use one request transaction and commit only after all steps succeed. Expression temporaries, retained row values, collections, and aggregation state share query resource limits, so evaluation can stop before an allocation or a result becomes unsafe.

See Interpreter execution for row state, step scheduling, operation behavior, and transaction boundaries.

References: crates/…/evaluation.rs• L16-25 crates/…/evaluation.rs• L84-115 crates/…/evaluation.rs• L300-315 crates/…/projection.rs• L81-108 crates/…/selection.rs• L68-99 crates/…/graph_values.rs• L5-28 crates/…/aggregation.rs• L31-40 crates/…/memory.rs• L7-26 crates/…/mod.rs• L1-6 crates/…/mod.rs• L58-181 crates/…/scheduler.rs• L16-46 crates/…/read_view.rs• L1-5

Result materialization

Execution produces named variables and requested returns as typed runtime values. The service converts those values into the public response shape, preserving the difference between streams, scalars, counts, booleans, empty lists, and absent object results.

Planner diagnostics travel beside the result rather than inside the public return object. This lets transports expose plan insights without changing the query data or leaking request literals into diagnostic output.

References: crates/…/types.rs• L324-355 crates/…/state.rs• L12-55 crates/…/query_service.rs• L380-441 crates/…/query_service.rs• L443-571

Request modes

The same planning and execution path supports read queries, graph writes, and index operations. The request mode controls which storage authority the interpreter may open and which side effects the validated plan may contain.

ModeAllowed workRuntime boundary
ReadGraph reads and read-only control flowOne stable read view; no persistent mutation
Graph writeGraph mutations and their dependent readsOne request-owned write transaction
Index operationIndex create, drop, retry, or abort workOperation-owned index lifecycle handling

The runtime derives this mode from both the declared plan kind and all reachable operations. A nested operation cannot hide a mutation or combine graph mutation with index DDL without causing an invariant failure.

References: crates/…/mod.rs• L184-301 crates/…/dispatch.rs• L22-33

Cross-stage contracts

The most important contracts are the boundaries where one stage can silently change the meaning expected by the next. Engineers changing one side should trace the matching contract rather than assume that a type or enum change is local.

Representation contract

The AST, batch kind, parameter bindings, and return names define the meaning that planning must preserve. Read-only validation occurs before planning, while the planner resolves output shapes and dependency relationships for the executable plan.

References: crates/…/batch.rs• L46-103 crates/…/batch.rs• L173-203 crates/…/top_level.rs• L127-165

Resolved relational contract

The validated relational query defines slot scope, value domains, graph-pattern shape, row effects, and the operator boundaries used by both optimization and execution. Frontends must provide this contract before physical planning; runtime adapters must keep its expression, projection, and selection semantics.

References: crates/…/mod.rs• L1-5 crates/…/query.rs• L196-220 crates/…/types.rs• L6-22 crates/…/expression.rs• L138-184

Plan contract

The executable DAG is the only plan form that crosses into the interpreter. Its step dependencies, conditions, output bindings, execution order, and root must remain consistent because the scheduler and dispatcher trust this contract at runtime.

References: crates/…/operation.rs• L7-77 crates/…/top_level.rs• L37-58 crates/…/order.rs• L53-82

Storage-view contract

Planning and execution must agree on the catalog and data view used for access decisions. Prepared query execution carries that authority forward; ordinary physical-plan execution remains conservative and can refresh its runtime catalog before use.

References: crates/…/lib.rs• L1538-1592 crates/…/lib.rs• L1634-1652 crates/…/read_view.rs• L248-343

Error contract

Query errors carry a stable category, phase, detail, message, and optional source span. Compile errors describe invalid query or plan input; runtime errors describe failures while reading graph values, evaluating expressions, or enforcing a request limit. Transports pass the machine-readable code through without needing to know every future detail.

References: crates/…/mod.rs• L56-136 crates/…/codes.rs• L1-59 crates/…/evaluation.rs• L874-882

Change checklist

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

  • AST node, batch, or parameter changes: trace request validation, native AST lowering, return-shape inference, and the public query-language page together.
  • Relational query, binding, value type, expression, projection, or selection changes: trace frontend resolution, operator contracts, graph hydration demands, runtime evaluation, and result materialization together.
  • Logical or physical alternative changes: trace selected-root provenance, child reconstruction, executable lowering, and the optimizer page together.
  • Graph pattern access or order changes: trace index totality checks, scan fallback, lookup correlation, relationship direction, and optional-match behavior together.
  • Source-filter or access-pipeline rewrite changes: trace index coverage, unique-key driving, residual placement, repeat preservation, branch ordering, and distinct simplification together.
  • Executable operation or stage changes: trace plan validation, derived execution order, dispatcher routing, and request transaction-mode checks.
  • Evaluation, aggregation, or value changes: trace null and equality semantics, memory admission, collection limits, grouping keys, and runtime error codes together.
  • Catalog or cost-context changes: trace prepared planning authority, access selection, fallback behavior, and tenant or storage scope handling.
  • Runtime value or return-shape changes: trace variable conditions, row annotations, property hydration, result materialization, and transport diagnostics.

Important failure modes

TriggerConsequenceGuard
A read envelope carries a write batch or mutation traversalThe request is rejected before planningClosed read and write batch types plus request-tag agreement checks
A resolved expression uses an unbound slot, invalid value type, or invalid graph patternPlanning cannot safely infer the row contractRelational query construction validates scope, shape, types, and pattern endpoints
A predicate looks indexable but the catalog cannot prove a usable indexThe optimizer uses another valid access path or reports a planning failureAnalysis only marks candidates; access rules perform catalog and coverage checks
A source filter leaves an indexed conjunct as a row filterThe plan can scan or read records that the index could have narrowed without preserving the required source-filter contractRequired source-index rewriting removes indexed conjuncts from the residual and keeps only unsupported checks per row
A unique-key lookup is intersected with other index setsThe plan performs broad reads even though the key has at most one candidate per valueUnique-key driving selects the narrow key source and evaluates the remaining predicate on its candidates
An index rewrite intersects a source that may repeat elementsDuplicate input rows collapse and the query result changesRepeat-capable sources avoid set rewrites and use row-preserving membership or filtering
A distinct is removed before an order-sensitive pipeline operationA later limit can observe a different row order or row countDistinct simplification only removes a post-filter distinct on duplicate-free access or an adjacent duplicate
A graph lookup could skip a stored-value error or an optional rowThe optimized result could differ from a scanTotality and error-preserving lookup checks keep unsafe probes out of the plan
An executable plan has a missing dependency, cycle, invalid root, or bad return bindingThe plan cannot cross the planner/interpreter boundaryExecutable-plan construction validates the DAG and derives execution stages
An expression or aggregate exceeds the depth, collection, or memory budgetEvaluation stops with a resource error before unsafe growthShape checks and request-owned memory admission cover temporaries and retained state
A graph value is not prepared or a requested stored property is invalidThe specific graph read fails instead of becoming an empty valueThe graph-value boundary returns entity and stored-value errors on access
A write plan contains both graph mutation and index DDL side effectsRuntime transaction ownership is ambiguousReachable side effects are classified before any request transaction opens
A request deadline expires during a writeThe request aborts without committing the request transactionDeadline checks run before and during step execution and before commit
Planning and execution use unrelated catalog authorityAn index choice may not match the active catalogPrepared execution verifies the catalog proof; unverified execution refreshes conservatively

Key files

FileWhy to read it
crates/…/query.rsPublic request, parameter, and read/write wire contract
crates/…/batch.rsBatch entries, conditions, returns, and read-only validation
crates/…/traversal.rsOperation-tree query representation and traversal states
crates/…/query_service.rsRequest intake, planner-to-runtime handoff, and response shaping
crates/…/lib.rsPlanner-context creation and prepared or ordinary plan execution entry points
crates/…/query.rsValidated frontend-neutral query, bindings, row contracts, and effects
crates/…/expression.rsShared expression shape, graph requirements, and safe traversal boundaries
crates/…/planning.rsRelational access selection, graph schedules, and row-plan assembly
crates/…/graph_order.rsGraph source, expansion, lookup, join, and traversal-order choices
crates/…/evaluation.rsRuntime scalar, function, predicate, and aggregate evaluation
crates/…/aggregation.rsIncremental aggregate state, distinct handling, and resource checks
crates/…/graph_values.rsGraph hydration boundary used by expression evaluation
crates/…/codes.rsStable query error categories and detail codes
crates/…/analysis.rsPredicate facts used to simplify work and find index candidates
crates/…/source_index.rsRequired lowering of source filters into index access before physical implementation
crates/…/shared.rsShared index-source, unique-key, intersection, union, and residual rules
crates/…/translate.rsPredicate branch translation for partial index coverage and residual evaluation
crates/…/node.rsNode index behavior, including unique-key source detection
crates/…/edge.rsEdge index behavior and non-unique access-source construction
crates/…/distinct.rsSafe distinct removal in access pipelines
crates/…/candidates.rsConservative detection of local access-pipeline simplification candidates
crates/…/mod.rsPublic planning entry points for read and write batches
crates/…/session.rsRequest-scoped optimizer search, selection, caching, and provenance
crates/…/executable.rsConversion from selected roots to a validated executable plan
crates/…/top_level.rsExecutable DAG, root, returns, trace, and execution-order contract
crates/…/mod.rsInterpreter lifecycle and request storage mode
crates/…/scheduler.rsStage order, safe parallel work, and dependency-output handling
crates/…/dispatch.rsMapping from executable operations to runtime behavior
crates/…/read_view.rsStable read snapshots and catalog-view coupling