Pathrex is a Rust library and CLI tool for benchmarking queries on edge-labeled graphs constrained by regular languages and context-free languages. It uses SuiteSparse:GraphBLAS (via LAGraph) for sparse Boolean matrix operations and decomposes a graph by edge label into one Boolean adjacency matrix per label.
Paths below are relative to the Pathrex workspace root, not to the enclosing RPQ_bench repository.
.
├── Cargo.toml # Workspace, edition 2024, MSRV 1.90
├── pathrex/
│ ├── Cargo.toml # Rust API; optional bench feature enables the CLI
│ ├── src/
│ │ ├── lib.rs # Public modules and pathrex_sys re-export
│ │ ├── bin/pathrex.rs # CLI entry point (requires bench)
│ │ ├── cli/ # Arguments, loading, dispatch, benchmarking, output
│ │ ├── eval/mod.rs # Evaluator, PreparedEvaluator, ResultCount
│ │ ├── graph/
│ │ │ ├── mod.rs # Graph traits, backend handle, errors
│ │ │ ├── inmemory.rs # In-memory graph, CSR/CSC stores, metadata
│ │ │ └── wrappers.rs # Native RAII wrappers and initialization
│ │ ├── rpq/
│ │ │ ├── mod.rs # Endpoint, PathExpr, RpqQuery, errors
│ │ │ ├── nfarpq.rs # NFA evaluator
│ │ │ └── rpqmatrix/
│ │ │ ├── eval.rs # RPQMatrix preparation
│ │ │ ├── expr.rs # Query translation and native plan materialization
│ │ │ ├── plan.rs # RpqPlan language and rewrite rules
│ │ │ ├── optimize.rs # Strategy selection, EGraphOptimizer, extraction
│ │ │ ├── cost.rs # Cost models
│ │ │ ├── sampling.rs # Induced-subgraph sampling
│ │ │ ├── stats.rs # Count-vector statistics
│ │ │ └── result.rs # PreparedRpqMatrix and execution results
│ │ ├── sparql/mod.rs # SPARQL to RpqQuery
│ │ ├── formats/ # CSV, MatrixMarket, RDF sources
│ │ └── utils.rs # FFI error macros and test helpers
│ └── tests/ # Integration tests and Git LFS fixtures
├── pathrex-sys/
│ ├── Cargo.toml
│ ├── build.rs # Fetch/build GraphBLAS, build/link LAGraph
│ ├── src/
│ │ ├── lib.rs # Raw FFI API
│ │ └── lagraph_sys_generated.rs
│ └── deps/LAGraph/ # Native dependency submodule with RPQ extensions
└── .github/workflows/ # CI and release workflows
The local build guide is the canonical source of installation and build commands. Run them from this workspace root.
- MSRV: Rust 1.90, inherited by both crates from the workspace manifest.
Edition 2024 alone would require 1.85, but the current resolved dependency
set includes
ordered-float 5.5.0(MSRV 1.90) and RDF/SPARQL dependencies requiring 1.87. - Resolver 3 prefers dependency versions compatible with the declared MSRV.
- Native prerequisites: Git, CMake, a C/C++ compiler and an OpenMP runtime.
The documented Linux configuration uses GCC and
libgomp. - Git LFS is needed to obtain integration-test fixtures.
cargo build --workspacebuilds the libraries.cargo build --release --features benchalso buildstarget/release/pathrex. The CLI is not built withoutbench.pathrex-sys/build.rsfetches GraphBLAS atGRAPHBLAS_TAG(currentlyv10.3.1) and builds GraphBLAS and LAGraph statically. A system installation of either library andLD_LIBRARY_PATHare not required. The first native build requires network access; later builds reuse$OUT_DIR/graphblas-src/and CMake build artifacts.pathrex-sys/regenerate-bindingsis optional and requires Clang/libclang. It rewritespathrex-sys/src/lagraph_sys_generated.rsusing the bundled LAGraph headers and the just-built GraphBLAS headers. Ordinary builds use the checked-in bindings. Do not hand-edit them.DOCS_RSskips native building for rustdoc; it is not an option for building a runnable binary.Cargo.lockis currently ignored. Preserve it for experiments and use--lockedafter the initial resolution to retain the dependency set.
Edge is the universal currency between format parsers and graph
builders: { source: String, target: String, label: String }.
GraphSource<B> is implemented by any data source that knows how to
feed itself into a specific [GraphBuilder]:
apply_to(self, builder: B) -> Result<B, B::Error>— consumes the source and returns the populated builder.
Csv<R>, MatrixMarket, and Rdf
implement GraphSource<InMemoryBuilder> (see pathrex/src/graph/inmemory.rs), so they
can be passed to [GraphBuilder::load] and [Graph::try_from].
GraphBuilder accumulates edges and produces a
GraphDecomposition:
load<S: GraphSource<Self>>(self, source: S)— primary entry point; delegates toGraphSource::apply_to.build(self)— finalise into an immutable graph.
InMemoryBuilder also exposes lower-level helpers outside the trait:
push_edge(&mut self, edge: Edge)— ingest one edge.with_stream<I, E>(self, stream: I)— consume anIntoIterator<Item = Result<Edge, E>>.
The MatrixMarket loader uses crate-private extend_prebuilt,
extend_prebuilt_csc, and extend_metadata helpers to install already loaded
matrices and their statistics.
Backend associates a marker type with a concrete builder/graph pair:
pub trait Backend {
type Graph: GraphDecomposition;
type Builder: GraphBuilder<Graph = Self::Graph>;
}Graph<B> is a zero-sized handle parameterised by a Backend:
Graph::<InMemory>::builder()— returns a freshInMemoryBuilder.Graph::<InMemory>::try_from(source)— builds a graph from a single source in one call.
InMemory is the concrete backend marker type.
GraphDecomposition is the read-only query interface:
get_graph(label)— returnsArc<LagraphGraph>for a given edge label.get_node_id(string_id)/get_node_name(mapped_id)— bidirectional string ↔ integer dictionary.num_nodes()— total unique nodes.get_graph_with_storage(label, storage)— preferred CSR/CSC orientation, defaulting toget_graphfor backends without both.get_metadata()— optional cached matrix statistics.
pathrex/src/eval/mod.rs defines query-language-agnostic evaluator traits:
Evaluatoruses associated types forQuery,Result,Error, andPrepared. The graph backend stays a method-level generic (G: GraphDecomposition) so one evaluator type can run against any graph backend selected at the call site.PreparedEvaluatorrepresents prepared(query, graph)state that can be executed repeatedly, which is used by benchmark timing loops.ResultCountis separate fromEvaluator::Result; only CLI runners that need counts require this bound, leaving room for future evaluators with richer result types.
InMemoryBuilder is the primary GraphBuilder implementation.
It collects edges in RAM, then build() calls
GraphBLAS to create one GrB_Matrix per label via COO format, wraps each in an
LAGraph_Graph, and returns an InMemoryGraph.
Multiple CSV sources can be chained with repeated .load() calls; all edges are merged
into a single graph.
The MatrixMarket loader populates both CSR and CSC matrix stores, along with
GraphMetadata containing a MatrixMetadata per label: dimension, nonzero
count, and numbers of nonempty rows and columns. MatrixStatsMode::Basic
adds row/column count vectors; Extended also adds the MNC singleton-related
vectors. The CLI requests Extended for MNC and None for other strategies.
CSV/RDF loading does not populate these cached statistics or a separate CSC store;
consumers use matrix/statistics fallbacks when needed.
Node ID representation: Internally, InMemoryBuilder uses HashMap<usize, String> for
id_to_node (changed from Vec<String> to support sparse/pre-assigned IDs from MatrixMarket).
The set_node_map() method allows bulk-installing a node mapping,
which is used by the MatrixMarket loader.
Three data sources implement GraphSource<InMemoryBuilder> and can be passed to
GraphBuilder::load() (see pathrex/src/graph/inmemory.rs).
CSV and RDF provide edge streams; MatrixMarket loads matrices directly.
Csv<R> parses delimiter-separated edge files.
Configuration is via CsvConfig:
| Field | Default | Description |
|---|---|---|
source_column |
Index(0) |
Column for the source node (by index or name) |
target_column |
Index(1) |
Column for the target node |
label_column |
Index(2) |
Column for the edge label |
has_header |
true |
Whether the first row is a header |
delimiter |
b',' |
Field delimiter byte |
ColumnSpec is either Index(usize) or Name(String).
Name-based lookup requires has_header: true.
MatrixMarket loads an edge-labeled graph from a directory with:
vertices.txt— one line per node:<node_name> <1-based-index>on disk;get_node_idreturns the matching 0-based matrix indexedges.txt— one line per label:<label_name> <1-based-index>(selectsn.txt)<n>.txt— MatrixMarket adjacency matrix for label with indexn
Names in mapping files may be written with SPARQL-style angle brackets (e.g. <Article1>).
parse_index_map strips a single pair of surrounding </> so
dictionary keys match short labels (Article1), aligning with IRIs after
RpqQuery::strip_base on SPARQL-derived queries.
The loader uses LAGraph_MMRead to parse each .txt file into a
GrB_Matrix, then wraps it in an LAGraph_Graph. Vertex indices from vertices.txt are
converted to 0-based and installed via InMemoryBuilder::set_node_map().
Helper functions:
load_mm_file(path)— reads a single MatrixMarket file into aGraphblasMatrix; re-exported byformats::mm.parse_index_map(path)— parses<name> <index>lines; indices must be >= 1 and unique within the file.
MatrixMarket implements GraphSource<InMemoryBuilder> in pathrex/src/graph/inmemory.rs: vertices.txt maps are converted from 1-based file indices to 0-based matrix ids before set_node_map; edges.txt indices are unchanged for n.txt lookup.
Rdf is a unified parser for RDF formats using oxttl and oxrdf.
It supports both N-Triples (.nt) and Turtle (.ttl) formats via the RdfFormat enum.
Each triple (subject, predicate, object) becomes an Edge where:
source— subject IRI or blank-node ID (_:label).target— object IRI or blank-node ID; triples whose object is an RDF literal yieldErr(FormatError::LiteralAsNode)(callers may filter these out).label— full predicate IRI string (including fragment#…when present).
Constructor:
Rdf::from_path(path)— auto-detects format from file extension (.nt→ N-Triples,.ttl→ Turtle). Parses in parallel using memory-mapping and rayon.
Format detection via RdfFormat::from_path(path):
| Extension | Format |
|---|---|
.nt, .ntriples |
RdfFormat::NTriples |
.ttl, .turtle |
RdfFormat::Turtle |
Example usage:
use pathrex::formats::Rdf;
use pathrex::graph::{Graph, InMemory};
// Auto-detect from extension
let graph = Graph::<InMemory>::try_from(
Rdf::from_path("data.ttl")?
)?;The sparql module uses the spargebra
crate to parse SPARQL 1.1 query strings and build a pathrex-native RpqQuery
for RPQ evaluators.
Supported query form: SELECT queries with exactly one triple or property
path pattern in the WHERE clause. Relative IRIs such as <knows> require a
BASE declaration (or PREFIX / full IRIs). Example:
BASE <http://example.org/>
SELECT ?x ?y WHERE { ?x <knows>/<likes>* ?y . }Key public items:
parse_rpq(sparql)— parses a SPARQL string withSparqlParserand returns anRpqQuery.extract_rpq(query)— validates a parsed [spargebra::Query] is aSELECTwith a single path pattern and returns anRpqQuery. Use this when you construct a customSparqlParser(e.g. with prefix declarations) and callparse_queryyourself.ExtractError— error enum for extraction failures (NotSelect,NotSinglePath,UnsupportedSubject,UnsupportedObject,VariablePredicate). Converts toRpqError::Extractvia#[from].
Call RpqQuery::strip_base when graph edge labels are short names
and the parsed query contains full IRIs sharing a common prefix.
The module handles spargebra's desugaring of sequence paths (?x <a>/<b>/<c> ?y)
from a chain of BGP triples back into a single path expression.
The rpq module provides an abstraction for evaluating
Regular Path Queries (RPQs) over edge-labeled graphs using GraphBLAS/LAGraph.
Key public items:
Endpoint—Variable(String)orNamed(String)(IRI string).PathExpr—Label,Sequence,Alternative,ZeroOrMore,OneOrMore,ZeroOrOne.RpqQuery—{ subject, path, object }using the types above;strip_base(&mut self, base)removes a shared IRI prefix from named endpoints and labels.RpqEvaluator— marker subtrait overEvaluator<Query = RpqQuery, Error = RpqError>, preserving the RPQ-facing trait name while the generic evaluator hierarchy lives inpathrex/src/eval/.PreparedRpq— marker subtrait overPreparedEvaluator<Error = RpqError>.RpqError— unified error type for RPQ parsing and evaluation:Parse(SPARQL syntax),Extract(query extraction),UnsupportedPath,VertexNotFound, andGraph(wrapsGraphErrorfor label-not-found and GraphBLAS/LAGraph failures).
NfaRpqEvaluator implements [RpqEvaluator] by:
- Building a finite-state machine from
PathExprwithrustfstconcatenation, union, and closure operations inbuild_fst. - Removing ε-transitions with
rustfst::rm_epsilonand extracting anNfainNfa::from_path_expr. - Building one
LAGraph_Graphper NFA label transition (Nfa::build_lagraph_matrices()). - Calling [
LAGraph_RegularPathQuery] with the NFA matrices, data-graph matrices, start/final states, and source vertices.
type Result = NfaRpqResult ([GraphblasVector] of reachable targets).
Supported path operators match [PathExpr] variants above. Reverse and
NegatedPropertySet from SPARQL map to [RpqError::UnsupportedPath] when they
appear in extracted paths.
Subject/object resolution: [Endpoint::Variable] means "all vertices";
[Endpoint::Named] resolves to a single vertex via
GraphDecomposition::get_node_id().
The source constraint selects starting vertices; a fixed object filters the
reachable-target vector after the native call.
NfaRpqResult wraps a [GraphblasVector] of reachable target
vertices. When the subject is a variable, every vertex is used as a source and
LAGraph_RegularPathQuery returns the union of targets — individual (source, target)
pairs are not preserved.
The RPQMatrix module is a directory, not the
former rpqmatrix.rs file. Its pipeline is:
RpqMatrixEvaluator::prepareselects a storage orientation and translates the query withquery_to_expr.query_to_exprbuilds aRecExpr<RpqPlan>. A label is a Boolean adjacency matrix; sequence is Boolean multiplication; alternative is union; star is reflexive transitive closure. One-or-more is translated to a sequence with star. Zero-or-one is currently rejected by RPQMatrix.EGraphOptimizerimplements the internalRpqOptimizerinterface. Except forNoOpt, it expands equivalent expressions withegg::Runnerand the rules inplan.rs, then selects an expression withegg::Extractorand a cost model fromcost.rs. The cost model is used for extraction, not to execute the final query.materialize_with_storageturns the selected expression into a flatVec<RPQMatrixPlan>, borrowing graph matrices and creating owned endpoint-selector matrices.PreparedRpqMatrix::executecallsLAGraph_RPQMatrix, duplicates the result matrix and releases temporary plan results. It can be called repeatedly without rerunning optimization.
Fixed endpoints are supported and filter the result. For a path relation
R, a named vertex v is represented by a diagonal selector D_v with a
single true entry at (v, v):
| Subject / object | Matrix expression |
|---|---|
| variable / variable | R |
named u / variable |
D_u × R |
variable / named v |
R × D_v |
named u / named v |
D_u × R × D_v |
An unknown named vertex produces RpqError::VertexNotFound.
For a variable subject and fixed object, preparation requests CSC matrices;
other endpoint combinations request CSR. This changes storage, not query
semantics. The MatrixMarket loader stores both orientations.
Backends without a CSC copy may return their default matrix through
GraphDecomposition::get_graph_with_storage.
RpqMatrixResult contains the filtered
relation matrix and its pair count nnz. Its ResultCount implementation
reports the number of distinct reachable targets (nonempty columns), not the
pair count.
The implemented CLI strategies are none, join, metaac, mnc,
hybrid, pang-hybrid, and sampling. RandomOpt, Simple, and
Wander remain unsupported internal enum variants. Sampling evaluates
induced-subgraph matrices for estimates; the final selected plan executes on
the full graph.
Fixed-object and fixed-subject/object behavior is covered by
pathrex/tests/rpqmatrix_tests.rs;
eval.rs also tests optimized fixed-endpoint
queries.
With the bench feature enabled, pathrex/src/cli/dispatch.rs is the single
mapping from Algo variants to concrete evaluator types. dispatch_query
and dispatch_bench each perform one exhaustive match per requested algorithm, then call
generic runners (run_query_for_evaluator<E> and run_bench_for_evaluator<E>) that are
monomorphized for the selected evaluator.
Adding a new algorithm requires a new Algo variant, its Display arm, one dispatch_query
arm, one dispatch_bench arm, an impl Evaluator for the evaluator type, and an
impl ResultCount for any result type used by CLI count reporting.
lagraph_sys exposes raw C bindings for GraphBLAS and
LAGraph. The API is re-exported as pathrex::lagraph_sys by
pathrex/src/lib.rs. Rust RAII wrappers live in
graph::wrappers:
LagraphGraph— RAII wrapper aroundLAGraph_Graph(callsLAGraph_Deleteon drop). Also providesLagraphGraph::from_coo()to build directly from COO arrays.GraphblasVector— RAII wrapper aroundGrB_Vector(derivesDebug).GraphblasMatrix— RAII wrapper aroundGrB_Matrix(dup+freeon drop).ensure_grb_init()— internal one-timeLAGraph_Initviastd::sync::Once. Called automatically by RAII-wrapped constructors (LagraphGraph::from_coo,LagraphGraph::from_matrix,ThreadScope::enter) and byload_mm_file. Crate-private; no other code should call it.
Two #[macro_export] macros handle FFI error mapping:
grb_ok!(expr)— evaluates a GraphBLAS call insideunsafe, maps thei32return toResult<(), GraphError::GraphBlas(info)>.la_ok!(fn::path(args…))— evaluates a LAGraph call, automatically appending the required*mut i8message buffer, and maps failure toGraphError::LAGraph(info, msg).
A convenience function is also provided:
build_graph(edges)— builds anInMemoryGraphfrom a slice of(&str, &str, &str)triples (source, target, label). Used by integration tests.
- Rust edition 2024; MSRV 1.90.
- Error handling via
thiserrorderive macros; three main error enums:GraphError,FormatError, andRpqError. FormatErrorconverts intoGraphErrorvia#[from] FormatErroron theGraphError::Formatvariant.GraphErrorconverts intoRpqErrorvia#[from] GraphErroron theRpqError::Graphvariant, enabling?propagation in evaluators.- Raw FFI declarations live in
pathrex-sys. Native calls also occur in the graph wrappers, the in-memory loader, NFA evaluation, and RPQMatrix expression, statistics, sampling, and execution modules. Resource ownership and cleanup must be explicit; prefer the existing RAII wrappers. unsafe impl Send + Syncis provided forLagraphGraph,GraphblasVector, andGraphblasMatrixbecause GraphBLAS handles are thread-safe after init.- Unit tests live in
#[cfg(test)] mod testsblocks inside each module. Integration tests that need GraphBLAS live inpathrex/tests/inmemory_tests.rs,pathrex/tests/mm_tests.rs,pathrex/tests/nfarpq_tests.rs.
From the workspace root:
git lfs pull
cargo test --workspace --features bench
cargo clippy --workspace --all-targets --features bench -- -D warningsNo LD_LIBRARY_PATH is needed for the statically built GraphBLAS and LAGraph.
Native libraries are built automatically by the sys crate even when running
tests with Cargo. Integration fixtures are under
pathrex/tests/testdata/.
Focused regression checks for fixed endpoints:
cargo test -p pathrex --features bench --test rpqmatrix_tests test_bound
cargo test -p pathrex --features bench optimizers_preserve_resultsUse --locked when reproducing a previously resolved build.
The GitHub Actions workflow (.github/workflows/ci.yml)
runs on every push and PR across stable, beta, and nightly toolchains:
- Checks out with
submodules: recursiveandlfs: true. - Installs
cmake,libclang-dev,clangvia apt. cargo build --workspace --features pathrex-sys/regenerate-bindings—pathrex-sys/build.rsclones GraphBLAS at the pinned tag, builds it statically, builds LAGraph statically against it, and regenerates FFI bindings.cargo test --workspace --verbose— runs tests without the optional CLI feature; CLI tests require--features bench. NoLD_LIBRARY_PATHis needed because GraphBLAS and LAGraph are linked statically; only the OpenMP runtime (libgomp) is dynamic and is already on the default loader path.
Pushing a v*.*.* tag triggers .github/workflows/release.yml:
dockerjob — builds the image once and pushes the same tags ({version},{major}.{minor},{major},latest) to two registries:ghcr.io/sparselinearalgebra/pathrex(authenticated viaGITHUB_TOKEN, no extra setup needed).docker.io/vanyaglazunov/pathrex(authenticated viaDOCKERHUB_USERNAME+DOCKERHUB_TOKENrepository secrets).
publish-cratesjob — publishes both crates to crates.io in the correct order:- Reads
pathrex-sysversion viacargo metadata. - Skips publishing
pathrex-sysif that version is already on the registry (allows re-tagging when onlypathrexchanged). - Polls
cargo searchuntil the newpathrex-sysis indexed (up to 5 minutes), then publishespathrexagainst it. - Requires the
CARGO_REGISTRY_TOKENrepository secret.
- Reads
To verify the publish path without uploading:
cargo publish --dry-run -p pathrex-sys
# (pathrex dry-run requires pathrex-sys to be on crates.io first)