Architecture¶
This is the entry point to the technical documentation: the design decisions, the components, how they interact, and how a query flows through them. It is for reading and maintaining the code. For the how to use it side, start with the tutorial; the deeper pages — storage, the language, planning & execution — grow out of this one.
Why it is shaped this way¶
ZypherDB is deliberately small and generic. Five decisions explain almost every file:
Zig, not C++. The project started as C++/RocksDB and pivoted. The reasons were pragmatic: embeddable in Python, real performance, fast builds on an 8 GB M1, and a single-binary toolchain (no CMake, no vcpkg, no Docker). Zig 0.17 is pre-1.0, but
comptimegenerics map cleanly onto the generic-programming style the project wants.No class hierarchies, no Visitor. The style is Stepanov/STL: data as concrete types, algorithms as free functions, errors as values (Zig
error unions, the analogue ofstd::expected). You will not findinterface/abstract classanywhere — the AST is not a tree ofNodesubclasses but a flat arena, and a plan is not a tree ofOperatorobjects but chains of operators, each a value of one tagged union, that free functions feed rows through.An arena AST. Nodes live in one
std.ArrayList, children are a separate index array, and strings are interned into the arena. No pointers, no inheritance, onedeinitfrees the whole tree. This is the same shape Zig itself uses for its AST.Regular types and generic algorithms.
Value,RelationshipandPathdefine equality, a total order (where meaningful) and a hash that obey their laws, checked by property tests. Algorithms that apply to more than one type — deduplication, pagination, sorting by key, grouping — are written once over those operations (sequence_algorithms.zig,aggregation.Grouping,projection.sortByKey), never copied per type.LMDB or libmdbx as the storage engine, behind a contract. A graph is traversed by following adjacencies, not by joining tables, so the storage is a key/value B+tree and “neighbours of X” is one prefix scan. Both engines are single-writer / multi-reader across processes, and their lexicographic key order is what the adjacency encoding exploits. The rest of ZypherDB sees the engine only through its contract (
storage/engine/contract.zig); the engine is chosen at build time (-Dstorage-engine=lmdb, the default, ormdbx), and another one would be a new file next toengine/lmdb.zigandengine/mdbx.zig. Every change goes through the write transaction of that contract, the one place a change log (for replication) would be taken.
The components¶
Three layers, one directory each, plus a few cross-cutting files and the two embeddings. Dependencies point one way: the embeddings use execution and storage, execution uses the query AST and storage, and nothing below reaches up.
flowchart TB
subgraph embed["Embeddings"]
CAPI["c_api.zig — C ABI (export fn)"]
PyNative["python/native/ — Python extension module"]
end
subgraph statement["statement/ — prepared statements"]
Prepared["Statement.zig + Cache.zig — planned once, run many times"]
end
subgraph query["query/ — text to AST"]
Lexer["lexer.zig — tokens"]
Parser["parser.zig + expression_parser.zig — grammar"]
AST["ast.zig — arena AST"]
Semantics["semantics.zig — static checks"]
end
subgraph planning["planning/ — AST to plan"]
Builder["builder.zig + patterns.zig — clauses and patterns to operators"]
PlanIR["Plan.zig — operators in chains"]
end
subgraph execution["execution/ — plan to rows"]
Executor["Executor.zig — state, run()"]
Steps["operators · pattern_matching · expressions · aggregation · projection · writes"]
end
subgraph storage["storage/ — graph on a key-value engine"]
Graph["graph.zig — graph operations and indexes"]
Keys["key_encoding.zig + node_record.zig — key and record layout"]
KV["key_value_store.zig — transactions, prefix scans"]
Engine["engine.zig + engine/ — the engine contract, LMDB, libmdbx, C bindings"]
Integrity["integrity.zig + layout.zig — the checker, the layout assertions"]
end
Shared["value.zig · temporal/ · text/ · sequence_algorithms.zig · diagnostics.zig"]
CAPI --> Prepared
CAPI --> Graph
PyNative --> Prepared
PyNative --> Graph
Prepared --> Parser
Prepared --> Executor
Integrity --> Graph
Semantics --> AST
Executor --> Builder
Builder --> PlanIR
Builder --> AST
Executor --> Steps
Steps --> PlanIR
Steps --> AST
Steps --> Graph
Parser --> Lexer
Parser --> AST
Graph --> Keys
Graph --> KV
KV --> Engine
File |
What it is |
|---|---|
|
|
|
Generic algorithms written once for any regular element type: |
|
|
|
What a storage engine provides: environment, read and write transactions, cursors, the three tables, and the rules every engine keeps (zero-copy reads, one writer, several processes). |
|
The engine chosen at build time ( |
|
The LMDB engine (the default): map size, durability flags, renewed read transactions. |
|
Hand-written C bindings for LMDB ( |
|
The libmdbx engine: file geometry, durability flags, renewed read transactions. |
|
An engine that wraps the chosen one and fails at the N-th operation, or kills the process at a chosen crash point; used only by the fault and crash tests and the fuzzers (see testing). |
|
Hand-written C bindings for libmdbx: |
|
|
|
The byte layout of every key (markers, node ids, edge keys, index keys). The only place that knows the key layout. |
|
How a property value is stored, and written in index keys. |
|
The node record: a node’s labels and properties in one stored value, read with one B-tree search. |
|
What a well-formed record, value, edge key and name are, as functions that say why some bytes are not; the checker reports with them, and the storage boundary asserts them in pairs (Debug and ReleaseSafe). |
|
The integrity checker: rebuilds every derived key from the records and compares (see storage). |
|
Uniqueness constraints, checked against the constraint’s own index before a write is made. |
|
The schema definitions ( |
|
Property indexes ( |
|
Full-text postings, entity lengths, term counts and index totals, and how graph mutations keep them current. |
|
A full-text query against the postings: boolean clauses, phrases, prefix and fuzzy expansions, BM25. |
|
Text for full-text search: Unicode tables generated from the Unicode Character Database ( |
|
|
|
|
|
The |
|
The expression grammar, by precedence. |
|
The arena AST: |
|
The CALL clause, and the schema commands ( |
|
The procedures’ signatures (arguments, columns and their kinds), shared by the semantic checks and the executor. |
|
Cypher text of an expression, a pattern or a clause’s items (EXPLAIN’s details). |
|
Static checks before a query runs: each variable is used as one kind (node, relationship or value), literal operands have types their operators accept, no aggregates inside comprehensions. |
|
The plan: operators (a tagged union) in chains, and each pattern’s planned nodes and edges. Built once, never changed while it runs. |
|
Builds the plan: each clause’s operators, the chains of subqueries and of patterns in expressions, the variables in scope. |
|
Pattern planning: predicate pushdown (seeks and ranges), the estimates, anchor choice, the pattern’s operators. |
|
The variables in scope at a point of a query, as the planner knows them. |
|
The query’s expressions compiled with its plan: one instruction per AST node (a constant’s value, a variable’s slot, a parameter’s index, a resolved function, a compiled constant regex). |
|
The label and relationship-type counts the planner reads, once per plan, recorded in the plan. |
|
A plan as EXPLAIN’s lines: the result first, inner chains one level deeper, with estimated rows. |
|
The executor’s state and |
|
EXPLAIN and PROFILE: plans (and runs) the query, measures each operator’s rows and exclusive time, returns the plan’s lines as rows. |
|
Runs a plan’s chains: |
|
The procedures CALL runs, and how their rows extend the query’s (YIELD, WHERE). |
|
The schema commands, each a statement of its own. |
|
What the writing clauses do to one row, and the null bindings of an unmatched OPTIONAL MATCH. |
|
The pattern operators ( |
|
|
|
Expression evaluation and operators, with three-valued null logic. |
|
Aggregate states and the generic |
|
WITH and RETURN: projection, DISTINCT, ORDER BY, SKIP, LIMIT ( |
|
The built-in functions, as one table. |
|
|
|
The temporal functions, components and arithmetic, on |
|
The calendar ( |
|
CREATE, MERGE, SET, REMOVE and DELETE; refuses names that cannot be stored (empty, or with a |
|
LOAD CSV: a CSV file’s records as rows, read only from the import directory the database was opened with (none: LOAD CSV is off). |
|
|
|
|
|
A prepared statement: parsed, checked and planned once; each run binds the parameters and plans again if the counts drifted. |
|
The statements |
|
The C ABI ( |
|
The Python extension module, on the limited C API: converts parameters and rows directly, runs queries with the GIL released. See the Python reference. |
|
Converts temporal values to and from Python’s |
|
The library root: re-exports the public surface. |
|
The test suite, through the public API only (see contributing). |
The lifecycle of a query¶
A query is text in, rows out, through five stages. Each stage is a separate file. A query sent as
text (zypherdb_query, Database.query) is first looked up in the database’s cache of prepared
statements (statement/Cache.zig, by text, 64 entries): a statement found there was parsed,
checked and planned before, so its run starts at stage 4, after reading the graph’s counts again
to see whether the plan must be built again.
sequenceDiagram
autonumber
participant C as caller (C ABI or Python)
participant T as statement/
participant P as query/
participant E as execution/ + planning/
participant G as storage/graph.zig
participant S as storage/key_value_store.zig
C->>T: "MATCH (p:Person)-[:ACTED_IN]->(m:Movie) RETURN m.title"
T->>T: cached statement for this text?
T->>P: (not cached) tokenize, recursive descent → arena AST
T->>E: (not cached) check, plan: choose anchors, pull seeks out of WHERE, chain operators
T->>E: run: bind parameters, open the transaction, replan if the counts drifted
loop scan / expand
E->>G: nodesWithLabel / neighbours / nodesByIndex
G->>S: scanPrefix(...)
S-->>G: iterator (engine cursor)
G-->>E: node ids
end
E->>E: WHERE / projection / aggregation
E-->>C: rows
Lex + parse —
tokenizeturns the text into a token array; the recursive-descentParserwalks it into the arena AST. See the language.Check —
Executor.checkrejects queries that are well-formed but meaningless:semantics.check(a node used as a relationship,1 IN true) andfunctions.checkCalls(an unknown function, a wrong number of arguments). Nothing has touched storage yet.Plan —
planning/builder.zigturns the checked AST into a plan: chains of operators, one or more per clause, with eachMATCHpattern planned (equalities and ranges of the WHERE as seeks, an anchor chosen from the graph’s counts). This is where the optimizations live. See planning & execution.Execute —
operators.feedpushes rows through the chains; each pattern operator is a graph operation (a scan or an expansion) backed by ascanPrefixiterator. See storage for what those operations mean.Return — rows are projected; before the transaction ends,
EntitySnapshot.capturereads the nodes and relationships the rows mention; then the rows are handed back, through the C ABI or the Python module.
The plan is built once per statement and does not change while it runs: what a run needs besides it (parameters, rows, the transaction) is the executor’s. A prepared statement keeps its plan between runs and builds it again only when the counts it was planned on have drifted. See planning & execution for its operators, and why there is no cost-based optimizer yet.