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 / graph-algorithms

Graph algorithms

The helix-graph-algorithms crate provides a storage-independent graph snapshot and a shared set of local graph algorithms. A client loads a complete, validated selection once, then uses the immutable snapshot for traversal, path, centrality, cycle, community, layout, and graph-structure operations without more database reads. See Graph computation and value semantics for the wider graph model and Value semantics for the rules that keep graph identities lossless across APIs.

Snapshot role

The crate sits between graph data loading and higher-level SDK graph APIs. It keeps storage, query planning, runtimes, and language bindings outside the algorithm core so the same graph rules apply in each supported SDK.

Loaded graph boundary

The graph boundary accepts node and edge rows from a normal query response. The loader checks row shape, identity mapping, endpoint membership, optional limits, metadata, and topology before it creates a Graph; an over-limit response fails instead of becoming a partial graph. GraphLoadSpec declares the graph kind and identity rules that give the rows their meaning.

flowchart LR
    A[Graph selection] --> B[One Helix read]
    B --> C[Validated node and edge rows]
    C --> D[Immutable Graph snapshot]
    D --> E[Local algorithms]
    E --> F[SDK graph results]

The Rust SDK follows this boundary through Client::graph in sdks/…/graph.rs. Other language SDKs use the native binding façade to create the same snapshot. Every later graph read and algorithm call uses that snapshot.

References: crates/…/lib.rs• L1-6 crates/…/loader.rs• L36-49 crates/…/loader.rs• L97-224 sdks/…/graph.rs• L313-325

Graph model

Graph is an immutable value with graph-level attributes, nodes, and edges. A node has an external identity, an optional label, and selected attributes. An edge has a stable identity, source and target identities, an optional Graphify key, an optional label, an optional non-negative weight, and selected attributes.

The graph kind states whether edge direction matters and whether parallel edges are allowed:

Graph kindDirectionParallel edges
GraphNoNo
DiGraphYesNo
MultiGraphNoYes
MultiDiGraphYesYes

Construction rejects duplicate node or edge identities, missing endpoints, invalid weights, and parallel edges that violate the declared kind. Nodes and edges have stable deterministic order, so result order does not depend on input row order.

References: crates/…/model.rs• L14-17 crates/…/model.rs• L168-192 crates/…/model.rs• L194-245 crates/…/model.rs• L427-545 crates/…/model.rs• L547-599

Identity contract

ExternalId is the public identity type for nodes and Graphify keys. It preserves the source value type instead of turning every value into a string. It supports null, booleans, arbitrary-size decimal integers, exact floating-point values, strings, bytes, tuples, and frozen sets.

Callers choose an identity source with IdentitySelection: the internal node ID, a scalar property, or a tagged property. Tagged values use a canonical JSON form. This contract prevents values such as integer 1 and string "1" from becoming the same graph node.

References: crates/…/identity.rs• L13-26 crates/…/identity.rs• L43-92 crates/…/identity.rs• L155-175 crates/…/identity.rs• L322-360 crates/…/loader.rs• L239-277

Algorithm API

The public API groups algorithms by the question they answer. Each method returns a typed result that keeps node or edge identity with the computed value, so a higher-level API can present the result without rebuilding the graph.

Traversal and local structure

traverse supports breadth-first and depth-first searches from one or more seeds. Options control maximum depth, direction, allowed edge labels, and whether high-degree non-seed nodes may expand. The result contains visits with depth and discovery order plus the edge that discovered each non-seed node.

The same graph object provides local structure queries. neighbors, successors, predecessors, edge-ID lookups, and endpoint checks expose directed or undirected adjacency. degree and degrees return both edge count and weighted degree; an edge without a weight counts as one for weighted degree.

References: crates/…/traversal.rs• L7-85 crates/…/traversal.rs• L87-155 crates/…/traversal.rs• L195-215 crates/…/traversal.rs• L321-372 crates/…/traversal.rs• L459-543

Path and centrality results

shortest_path finds an unweighted local path under a chosen direction, label set, and optional depth bound. Its result distinguishes a missing source, a missing target, no path, and a found path. A found path includes the ordered node IDs and the edge records between them.

Betweenness centrality computes scores for nodes or stable edge identities. Callers can use every node as a source, use a deterministic sample, or switch from exact to sampled mode at a graph-size threshold. They can also request normalized scores, endpoint-inclusive node scores, and weighted shortest paths. Weighted centrality requires positive edge weights; missing weights still have unit cost.

References: crates/…/traversal.rs• L157-193 crates/…/traversal.rs• L374-419 crates/…/centrality.rs• L10-79 crates/…/centrality.rs• L82-104 crates/…/centrality.rs• L143-249

Cycles and communities

simple_cycles enumerates simple cycles up to a required length bound. An optional output cap makes the result size bounded, and truncated tells callers when the cap stopped the search. Cycles use canonical node and edge order so rotations do not produce duplicate results; undirected reverse directions are also treated as one cycle.

louvain_communities and leiden find weighted communities in an explicit undirected graph view. Their results contain canonical communities and modularity. Louvain reports the number of levels, while Leiden also reports the winning trial. Both keep isolated nodes as singleton communities.

References: crates/…/cycles.rs• L9-35 crates/…/cycles.rs• L37-87 crates/…/louvain.rs• L8-50 crates/…/louvain.rs• L221-270 crates/…/leiden.rs• L13-55 crates/…/leiden.rs• L63-103

Layout results

spring_layout produces deterministic two-dimensional positions for each node. The caller can set the ideal distance, iteration count, seed, weight use, and some initial positions. The output is centered and rescaled to the range [-1, 1]; empty and single-node graphs have explicit results.

The layout is a visual aid rather than a graph query. Its value is that the same loaded graph and seed produce repeatable positions for SDK consumers that need to draw or inspect a graph.

References: crates/…/layout.rs• L8-45 crates/…/layout.rs• L47-79 crates/…/layout.rs• L82-157

Graph transformations

Graph transformations create new immutable graph values that can be passed to the same algorithm API. They let a caller change the view used for a computation without changing the loaded snapshot.

Topology views

to_directed materializes reverse traversal edges for an undirected graph. to_undirected changes traversal semantics for a directed graph and promotes the result to a multigraph when collapsing direction would create parallel endpoint pairs. Self-loops and graph attributes remain part of the resulting graph.

induced_subgraph keeps selected nodes and only edges whose two endpoints are selected. This is useful when a higher-level operation first computes a node set and then needs to run another algorithm on that smaller view.

References: crates/…/transform.rs• L5-127

Identity and composition views

relabel replaces external node identities and rewires edge endpoints without allowing two source nodes to merge. compose combines graphs of the same kind. Shared nodes and edges are merged by stable identity, with right-hand attributes taking precedence; conflicting endpoints are rejected.

These operations preserve the value model. A caller can copy or export graph parts for independent use, while the original graph remains unchanged.

References: crates/…/transform.rs• L129-245

SDK and binding use

The graph crate is the common computation layer for the Rust SDK and the Python, Node, and Go native graph surfaces. The binding layer converts the shared result types into FFI-safe records while keeping the same identity, topology, algorithm, and error contracts.

One-query SDK flow

The Rust GraphSelection describes the node and edge traversals, graph direction, selected properties, identity source, optional weight, and safety limits. It builds one read batch and passes its response to the shared loader. Full graph scans require explicit opt-in, and limits use an extra row as a truncation sentinel.

The resulting graph is a snapshot. A second call to Client::graph creates a new snapshot, while operations on the first graph do not query Helix again.

References: sdks/…/graph.rs• L60-105 sdks/…/graph.rs• L116-176 sdks/…/graph.rs• L226-281 sdks/…/graph.rs• L313-335

Cross-language result surface

NativeGraph exposes counts, entity access, local structure queries, algorithms, and graph transformations to the native SDKs. The Python, TypeScript, and Go wrappers present these results in language-appropriate forms, while the UniFFI façade keeps algorithm work in Rust. Event-loop SDK calls run the heavier operations on a blocking worker so local computation does not block the event loop.

The wrappers consume computed results rather than reimplementing graph logic. For example, a centrality call returns node or edge score records, a path call returns an explicit result state, and a community call returns canonical member lists with modularity diagnostics.

References: bindings/…/graph.rs• L398-418 bindings/…/graph.rs• L410-510 bindings/…/graph.rs• L761-1004 sdks/…/graph.ts• L177-355 sdks/…/graph.py• L471-815 sdks/…/graph.go• L365-447

Fixtures and benchmarks

The crate uses checked-in reference data and repeatable benchmark inputs to protect result compatibility and to show the cost of common graph workloads. These assets are part of the algorithm contract, not production graph data.

Compatibility fixtures

The NetworkX fixture checks node and edge betweenness plus bounded cycles on a diamond graph. The Leiden fixture records weighted community partitions and modularity against Graphify and its Python dependencies. Tests compare floating-point values with a tight tolerance and compare canonical structures directly.

These fixtures make changes to result scaling, cycle ordering, community selection, and default parameters visible before a binding or SDK can expose a changed result.

References: crates/…/networkx_golden.rs• L10-68 crates/…/leiden_golden.rs• L5-91 crates/…/networkx-3.4.2-diamond.json• L1-27 crates/…/graspologic-3.4.4-leiden.json• L1-69

Benchmark workloads

The Criterion benchmark covers graph construction at 1,000 and 10,000 nodes. It also measures representative work on a 1,000-node, 4,000-edge graph:

  • sampled node and edge betweenness
  • bounded cycle enumeration
  • Louvain communities
  • breadth-first traversal and shortest path
  • degree calculation and induced subgraph creation
  • a 500-node spring layout

The benchmark graph uses labels and weights so the measured workloads include the data fields used by weighted and filtered operations.

References: crates/…/graph_algorithms.rs• L10-35 crates/…/graph_algorithms.rs• L37-126

Change checklist

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

  • Keep GraphKind, loader topology checks, SDK direction mapping, and native binding graph-kind mapping aligned. A mismatch can change whether direction or parallel edges affect results.
  • Keep external-identity selection and canonical encoding aligned between identity.rs, the loader, UniFFI records, and each SDK wrapper. A change can merge or reject values across language boundaries.
  • Keep edge identity and reverse-generation rules aligned with path, cycle, edge-centrality, and transformation result types. A display string must not replace the structural edge identity.
  • Keep algorithm defaults and option validation aligned across Rust, UniFFI, Python, TypeScript, and Go. In particular, check sampling mode, seeds, weights, non-zero bounds, and community graph direction.
  • Update the NetworkX or Leiden golden inputs when a deliberate compatibility change alters score scaling, cycle canonicalization, community choice, or modularity.
  • Recheck benchmark workload sizes and bounded options when algorithm cost or graph construction behavior changes.

Important failure modes

TriggerConsequenceGuard
Node or edge selection exceeds its configured limitThe loader rejects the result instead of returning a partial graphQuery one extra row and handle IncompleteSelection
Two selected nodes decode to the same external identityGraph construction fails and no ambiguous graph is exposedChoose a lossless identity source and preserve canonical value types
An edge endpoint is outside the selected node setThe response is rejected as an invalid graph rowSelect nodes and edges from compatible graph scopes
A simple graph selection returns parallel endpoint pairsGraph construction fails with a topology errorUse a multigraph kind when parallel edges are valid
Louvain or Leiden receives a directed graphThe community operation returns an invalid-option errorCreate an explicit undirected view before community analysis
Weighted betweenness sees a zero-weight edgeCentrality returns an invalid-option errorUse positive weights or run unweighted centrality
Cycle output reaches its configured capThe result is incomplete but marked with truncatedTreat truncated as part of the result contract
A relabel mapping merges two nodes or composition changes an edge endpointThe transformation fails rather than silently changing topologyResolve identity collisions and endpoint conflicts before composing
Native bindings are unavailableSDK graph loading cannot create the native graph surfaceInstall and link the platform native graph package

Key files

FileWhy to read it
crates/…/lib.rsDefines the crate boundary and the public re-exports used by consumers.
crates/…/model.rsDefines the validated immutable graph model, topology kinds, records, and graph errors.
crates/…/identity.rsDefines lossless external identities and identity-selection rules.
crates/…/loader.rsDefines the response-validation boundary between graph query rows and a usable snapshot.
crates/…/traversal.rsDefines traversal, shortest path, degree, neighbor, and edge relation results.
crates/…/centrality.rsDefines node and edge betweenness options and score results.
crates/…/cycles.rsDefines bounded cycle output and canonical cycle behavior.
crates/…/louvain.rs and crates/…/leiden.rsDefine weighted community outputs and convergence diagnostics.
crates/…/layout.rsDefines deterministic graph layout inputs and position results.
crates/…/transform.rsDefines the immutable graph views used to prepare inputs for later algorithms.
sdks/…/graph.rsShows how one Helix read becomes a reusable graph snapshot.
bindings/…/graph.rsShows the shared native graph surface used by the non-Rust SDKs.
crates/…/networkx_golden.rs and crates/…/leiden_golden.rsShow compatibility checks against external algorithm baselines.
crates/…/graph_algorithms.rsShows the supported construction and algorithm benchmark workloads.