Storage — the key encoding and the graph algebra¶
This is the theory of how the graph is stored. If you are going to add an index, change a property
type, or debug a traversal, start here. The encodings live in src/storage/key_encoding.zig (keys),
value_encoding.zig (values) and node_record.zig (node records); graph.zig maintains them, and
key_value_store.zig is the store over the storage engine.
The model: everything is a key¶
There are no tables and no schema. The storage engine (LMDB by default, or libmdbx with
-Dstorage-engine=mdbx; see the engines) keeps four B+trees in one file:
the main one holds every fact as a key: edges, indexes, edge properties, counters;
#nodesholds the node records, keyed by the node id as a native integer (an integer-key table);#relationshipsholds the relationship records (src | dst | type), keyed the same way by the relationship’s id;#changesholds the change log replicas follow, empty unless it is started (see the change log). No graph read sees it.
The engine iterates keys in lexicographic byte order, which is the whole trick: the layout is chosen so that the order you get for free is the order you want.
Two rules make that work:
All integers are big-endian and fixed-width (ids are
u64, 8 bytes). So byte order equals numeric order, and no id is ever a prefix of another.A
0x00byte separates variable-length parts (strings). A quoted openCypher name could contain0x00, so ZypherDB refuses labels, relationship types and property names that contain it, are empty or are longer than 1024 bytes (writes.zigrequireStorableName;ZYPHERDB_INVALID_NAMEin C,ValueErrorin Python), and the storage boundary asserts it (layout.assertName). A name with0x00in a key would end early:A\0Bwould read asA. (For the length, see Limits.)
The key layout¶
(| = concatenation; id = 8-byte big-endian u64.)
Key |
Meaning |
Answering |
|---|---|---|
|
the node record: labels and properties |
|
|
one stored direction of relationship |
|
|
the relationship’s record: |
|
|
a relationship property |
|
|
label index |
|
|
a schema definition: an index or a constraint |
|
|
property index number |
|
|
vector index number |
|
|
edge-type cardinality counter |
|
|
label cardinality counter (when absent, the label index is counted) |
|
|
the next node id to allocate |
|
|
the next relationship id to allocate |
|
|
the last property or vector index number handed out |
|
|
how many times the definitions changed |
plans and cached definitions know when to read them again |
|
the storage format’s version |
|
Every “index” is just more keys, maintained by the same put/del primitives. There is no
separate index structure — an index is a key range.
How to read the table: the first byte of a main-table key is a letter (e, f, h, i, l, p,
t, c) that says which kind of key it is, so every kind occupies its own range of the key
space; the rest of the key is the fields of that kind, one after another. Most index keys have an
empty value: the key itself is the fact.
A worked example¶
Take the smallest graph that uses every kind of key: two people and a relationship with a property, each property indexed.
CREATE INDEX FOR (p:Person) ON (p.name)
CREATE INDEX FOR ()-[k:KNOWS]-() ON (k.since)
CREATE (a:Person {name: 'Ana'})-[:KNOWS {since: 2020}]->(b:Person {name: 'Bob'})
Ana gets node id 0, Bob node id 1, and the relationship gets relationship id 0 (the two kinds of id
are counted apart). These are all the keys the database then holds, as the storage engine stores
them (bytes in hex, "…" for bytes that are text):
#nodes — one record per node
key 00 00 00 00 00 00 00 00 (id 0, as a native integer)
val 00 01 1 label
00 06 "Person" length 6, the label
00 00 00 01 1 property
00 04 "name" name length 4, the name
00 00 00 04 02 "Ana" value length 4: tag 02 (string), the bytes
key 01 00 00 00 00 00 00 00 (id 1)
val 00 01 00 06 "Person" 00 00 00 01 00 04 "name" 00 00 00 04 02 "Bob"
#relationships — one record per relationship
key 00 00 00 00 00 00 00 00 (relationship id 0)
val 00 00 00 00 00 00 00 00 src: node 0 (Ana)
00 00 00 00 00 00 00 01 dst: node 1 (Bob)
"KNOWS" type
main table, in the order the engine keeps it
"!" → 00 00 00 00 00 00 00 02 next node id: 2
"!format" → 00 00 00 01 format version 1
"!index_id" → 00 00 00 02 2 property indexes numbered so far
"!relationships" → 00 00 00 00 00 00 00 01 next relationship id: 1
"!schema" → 00 00 00 00 00 00 00 02 the definitions changed twice
"c" "Person" → 00 00 00 00 00 00 00 02 2 nodes are Person
"e" 00×8 "o" 00 "KNOWS" 00 00×7 01 00×8 Ana -KNOWS-> Bob, relationship 0, seen from Ana
→ 01 00 01 00 06 "Person" version 1, then Bob's labels
"e" 00×7 01 "i" 00 "KNOWS" 00 00×8 00×8 the same relationship, seen from Bob
→ 01 00 01 00 06 "Person" Ana's labels
"f" 00×8 "since" → 01 00 00 00 00 00 00 07 e4 relationship 0's since: tag 01 (integer), 2020
"i" "index_KNOWS_since" a definition: kind 01 (range), entity 01
→ 01 01 00 00 (relationships), no analyzer,
00 01 00 05 "KNOWS" 1 type, 1 property,
00 01 00 05 "since" index number 2
00 00 00 02
"i" "index_Person_name"
→ 01 00 00 00 00 01 00 06 "Person" 00 01 00 04 "name" 00 00 00 01
"l" "Person" 00 00×8 index: Person → node 0
"l" "Person" 00 00×7 01 index: Person → node 1
"p" 00 00 00 01 02 "Ana" 00 00×8 index 1: name = 'Ana' → node 0
"p" 00 00 00 01 02 "Bob" 00 00×7 01 index 1: name = 'Bob' → node 1
"p" 00 00 00 02 01 80 00 00 00 00 00 07 e4 00×8 index 2: since = 2020 → relationship 0
"t" "KNOWS" → 00 00 00 00 00 00 00 01 1 relationship is KNOWS
(00×8 is eight zero bytes: the id 0. The index keys have empty values. The #nodes and
#relationships keys are native integers, little-endian on the machine this ran on; the engine
orders them as numbers.)
A few things to see in it:
The record is the truth, the rest is derived. Ana’s labels and properties are in her record;
l,pandcsay the same things again, arranged for a different question, andponly for the properties anidefinition indexes. The integrity checker rebuilds them from the records and compares.The relationship is stored three times: its record (ends and type), and one
ekey from each end. Theekeys differ in the node they start with and in the direction byte (oout,iin).Index keys end with the id. In
p, the index number and the value come before the id, and a string value ends with a00, so every node withname = 'Ana'is under the prefixp 00 00 00 01 02 Ana 00, and'An'cannot match it. Each index has its keys apart, so a lookup in thePersonindex never meets another label’s nodes.Numbers in index keys are rewritten to sort. In
fthe integer 2020 is stored as it is (00 … 07 e4); in the index key its sign bit is flipped (80 … 07 e4), so that negative numbers sort before positive ones byte by byte.
And what each kind of question reads:
Query |
Plan (EXPLAIN) |
What the engine does |
|---|---|---|
|
|
Scans the prefix |
|
|
Seeks the prefix |
|
|
Seeks |
|
|
The same from the other end: the prefix |
|
|
Seeks the prefix |
|
|
Reads and increments |
Index-free adjacency (the core idea)¶
A graph database is traversed by following edges, not by joining tables, so the storage is arranged so that “give me the neighbours of X” is a single prefix scan:
Every directed, typed edge is stored twice — once keyed by its source (
'o') and once by its target ('i'). Both directions are therefore a prefix scan, with no reverse index to maintain separately.Because the neighbour id is the fixed-width field after the type, the prefix scan returns neighbours in ascending id order — the sort is free.
The relationship’s own id comes last. Two relationships of one type between the same nodes (parallel ones) are two keys that differ only there, so
e | a | 'o' | 0x00 | T | 0x00 | bis the prefix of every relationshipTfromatob(edgesBetween).
A traversal (a)-[:ACTED_IN]->(b) is literally: scan the range
e | a | 'o' | 0x00 | ACTED_IN | 0x00 and read the neighbour’s 8 bytes of each key. That is the
“index-free adjacency” (IFA) model — no pointer, no join, just locality in the key space.
Value encoding¶
A property Value is a one-byte tag + payload (src/storage/value_encoding.zig), integers
big-endian:
Tag |
Value |
Payload |
|---|---|---|
|
|
|
|
|
raw bytes |
|
|
one byte, |
|
|
IEEE 754 bits, |
|
date |
days since 1970-01-01, |
|
local time |
nanoseconds of the day, |
|
time |
nanoseconds of the day, |
|
local date-time |
seconds, |
|
date-time |
UTC seconds, |
|
duration |
months, days, seconds, |
|
list |
count, |
|
map |
count, |
|
null |
nothing (only inside a map) |
A list is stored only when its elements share one storable type (integers and floats count as one). A map — a document, a ZypherDB extension — holds any of these values, nested maps, lists of any elements, and nulls. A null on its own is never stored: setting a property to null removes it.
Index keys use the same encoding except that variable-length parts (strings, zone names) end in
0x00, so a lookup prefix for "X" can’t also match "XY", and list elements carry no length.
Numbers are indexed canonically: a float that equals an integer (2.0) is indexed as that
integer, so {x: 2} and {x: 2.0} find the same nodes, as = says they should. Numbers,
dates, times and date-times are written so that their bytes sort in their order:
integers, dates (a day count) and the counts in times and date-times with the sign bit flipped (i64);
floats with negatives inverted and positives with the sign bit set;
a time as its instant (nanoseconds since midnight UTC), then its offset; a date-time as its instant (seconds, nanoseconds), then its offset and zone. That is the order comparisons use.
A range of values is then a range of keys. Graph.nodesInRange reads a range of numbers as two
key ranges, integers and floats, from which NaN is excluded. It rounds fractional bounds
outwards, so it returns a superset of the matches, and the WHERE is still checked on each.
Strings, times and date-times are one key range each, from the lower bound’s index form to the
upper bound’s.
The storage format¶
The key !format holds the format’s version. When the C ABI or the Python package opens a
database, Graph.checkFormat stamps a new one with format 1, and refuses one written in a format
this build does not read (error.IncompatibleFormat; in Python, a StorageError). The formats:
1: the format of the first release.
2: 1 plus vector indexes. Creating the first vector index stamps it, in the same transaction, so a release that reads only format 1 refuses the database instead of misreading the index. The format is never lowered: dropping every vector index keeps 2.
A build reads every format up to its newest (Graph.newest_format), and writes the lowest that
holds what the database contains. The integrity checker reports a vector index in a database not
stamped 2.
A replica’s hello tells the newest format it reads. The master refuses one that reads only
formats older than its database’s, or one newer than the master writes; the replica then asks again
announcing one format less, down to 1, so a new replica follows an older master, and announces its
newest again once a master welcomed it. A master whose database rises past the format of a replica
it serves (the first vector index, while a 0.2.0 replica follows) ends that conversation before
sending the change set that raised it, or the copy: the replica comes back and its hello is
refused for good (storage_format).
Limits¶
The formats count lengths with fixed-width integers, and keys must fit the storage engine’s key size (about 2000 bytes with 4 KB pages, as on Linux and Windows). Writes past a limit are refused with an error; none is reached silently.
What |
Limit |
Why |
Error |
|---|---|---|---|
A label, relationship type, property name or index/constraint name |
1024 bytes |
names go into keys (label, edge and full-text keys) |
|
A document path in |
1024 bytes in all |
stored as one name |
|
Labels on one node |
65535 |
counted in a u16 in the record |
|
One stored value: a node with all its properties, or one property of a relationship |
64 MiB |
a replica holds each write whole while it applies it |
|
Properties of a full-text index |
256 |
postings number them with a u8 |
|
Labels or types, properties of an index or constraint |
65535 |
counted in a u16 in the definition |
|
Values have no limit of their own in indexes: an index entry keeps at most a value’s first 512 bytes, and every match is checked against the whole value. The full-text index skips words whose term is longer than 255 bytes.
These are ceilings, not targets. A node record is read and rewritten whole on every change to the node, and each relationship keeps a copy of its nodes’ labels: keep records to a few KB, and store large content (documents, images) outside the database, with a property that names it.
The indexes, one by one¶
Node records (a table of their own,
#nodes, keyed by the id as an integer). A node’s labels and properties are one value (node_record.zig): label count, then each label; property count, then each name and encoded value, both sorted. One B-tree search reads everything about a node, and a change rewrites the record. In a read transaction, three things make reading records cheaper:A reused cursor. Records are looked up through one cursor. When the next id is at most four records ahead, the cursor steps forward (a cursor
next) instead of searching. A scan’s nodes come in id order, so a scan reads records almost sequentially.A record cache (
RecordCache). It keeps the records found in the transaction as the engine’s views, which stay valid until the transaction ends. It is direct-mapped by id with 4096 slots, so a lookup or an insertion is one array access. A node reached many times (a team every member reaches) is searched for once, and a scan that reads each node once pays almost nothing for the cache.Generations. Starting a read transaction moves the cache to a new generation, which empties it without touching it.
Neighbour labels on edges. The value of each edge key is the labels of the node at the other end: a version byte, then the label section of that node’s record. An expansion such as
(g)<-[:MEMBER_OF]-(p:Person)checksPersonwithout readingp’s record.addEdgewrites the value.addLabelandremoveLabelrewrite it in every neighbour’s key, which costs O(degree).A value without the version byte (an empty one) means the labels are unknown, and the record is read.
Label index (
l). Answers “which nodes carry this label” (a prefix scan), maintained with the record.Property indexes (
p). Only the properties aCREATE INDEXnames are indexed, each index on one label (or relationship type) and one property or document path (property_indexes.zig). A key is the index’s number (u32, handed out at creation; the definitioni | namekeeps it), the value in its index form, then the node’s or relationship’s id. This is what turnsMATCH (p:Person {name: 'Keanu'})from a scan into a point lookup.Maintenance.
property_indexes.nodeChangedgets the record before and after every change (setProperty,removeProperty,addLabel,removeLabel,deleteNode) and updates the indexes it concerns;relationshipPropertyChangeddoes the same for relationships.CREATE INDEXfills a new index from the label (or type) in the same transaction (populate);DROP INDEXremoves its keys (clear).Document paths. An index on
n.a.bhas an entry only whenn.ais a map with a fieldbthat is not null (valueAt).Long values. A value whose index form is longer than 512 bytes is written as its first 512 bytes and a
ffbyte. Such keys only name candidates: every lookup checks the whole value in the record, as it does anyway.Relationships. A relationship index’s keys end with the relationship’s id, whose record gives its ends and type. It lets
MATCH (a)-[r:TYPE {weight: 5}]->(b)anchor on the edge itself when the endpoints carry no selectivity.Constraints. A uniqueness constraint owns an index on its first property: its checks read the candidates there and compare every property whole, and the planner uses it for lookups on that property.
Edge-type counter (
t). A per-type cardinality, bumped byaddEdgeand decremented on delete, used by the planner to cap a node’s cost estimate by the rarest incident edge type.
Full-text indexes¶
Every schema definition lives under i | name (fulltext.zig): its kind (a full-text index, a
declared range index, a uniqueness constraint, or a vector index), whether it is on nodes or
relationships, its analyzer (full-text only), its labels or types, its properties, and a vector
index’s dimensions and similarity. !schema counts the changes
to the definitions. Every mutation asks for it, to know whether any index or constraint must
follow the change, so inside a write transaction it is read once
(KeyValueStore.write_transaction_memo): only that transaction could change it, and when it does
it updates the memo too. A database without definitions pays one read per write transaction.
A uniqueness constraint (constraints.zig) is checked before a node’s new record is written
(setProperty, addLabel): the property index gives the other nodes with the first property’s
value, and one with the label and every other value equal is a violation
(error.ConstraintViolation, Graph.violationMessage). Every property is compared as the index
compares it, so 1 and 1.0 are one value. Checking before writing keeps a refused write from
changing anything, also outside a transaction; it is also stricter than checking at commit:
swapping two nodes’ values in one query fails.
The postings live in four key spaces of their own, each after a marker byte, the index’s name and a
0x00. An entity is a node’s or a relationship’s id (8 bytes; an index holds one kind).
Key |
Value |
|---|---|
|
the term’s occurrences in the entity, per property: its ordinal (u8), a count (u32), the positions (u32 each) |
|
the entity’s length in terms, per property (u32 each) |
|
how many entities have the term (u64): BM25’s document frequency, and the vocabulary that prefix and fuzzy queries expand over |
|
the index’s entities and terms (u64 each): BM25’s N and average length |
Each property is analyzed on its own. A change to one property touches only the postings of the terms of its old and new text, and their counts. The changes come from three places:
Nodes. The graph’s mutators (
setProperty,removeProperty,addLabel,removeLabel,deleteNode) handfulltext_postings.nodeChangedthe record before and after. The old record is copied first, since a write may move the page its view points into. The node enters or leaves an index as its labels do.Relationships.
setEdgeProperty,removeEdgePropertyanddeleteEdgereport each property’s old and new value.Schema commands.
CREATE FULLTEXT INDEXindexes what exists (populate), andDROP INDEXremoves every key of the index (clear).
The id counter¶
allocateNodeId does a read-modify-write on the ! key (8-byte counter): read, increment, write.
In a write transaction this is atomic with the rest of the query, so a CREATE that aborts rolls
the counter back too. addNode accepts an id chosen by the caller and moves the counter past it,
so the counter never hands out an id that is in use.
Relationship ids come from their own counter, !relationships. Inside a write transaction it is
read once and kept in KeyValueStore.write_transaction_memo; Graph.commitWrite writes it back
with the commit, so a query that creates many relationships writes the counter once, and an
aborted one leaves it as it was.
Transactions¶
Writes are atomic: the executor opens one write transaction per query (
beginWrite/commitWrite); everyput/del/get/scanPrefixinside it routes through that transaction and sees its uncommitted writes. An aborted query rolls everything back, including the id counter.Reads are batched: a read-only query opens one read transaction (an MVCC snapshot,
beginRead/commitRead) and all its reads run inside it — so a filtered scan is O(1) transactions, not one perget.Read transactions are not tied to a thread (LMDB’s
MDB_NOTLS, libmdbx’sMDBX_NOSTICKYTHREADS), so a single thread may hold several at once — the executor needs that to run a scan, then a neighbour scan inside it.An ended read transaction is reset and kept (up to four per database) for the next one to renew (
Environment.endRead): starting a read costs no allocation.A read transaction keeps the cursors of finished prefix scans (up to 16) for the next scans, last in, first out: a nested scan gets the cursor its depth used before, which is near where it starts now (the next node’s edges), so the engine repositions it without searching from the root.
An iterator returned by
scanPrefixborrows its transaction; it must bedeinit’d before the transaction ends (the cursor belongs to it). The executor scopes every iterator to the operator call that opened it, which is what makes this safe.
The change log¶
Replicas follow a database by applying, in order, what each of its write transactions changed
(change_log.zig). The log keeps the key-value writes themselves, not the queries that made them:
a query may not give the same result twice (randomUUID(), timestamp(), the order behind a
LIMIT), its writes do. Indexes, full-text postings, the schema and the id counters are keys like
any other, so they follow with no special case.
It is off until
KeyValueStore.startChangeLog, and then stays on for the database. Off, a write costs one branch more (and the first write transaction after opening reads whether it is on).On,
KeyValueStorerecords eachputand delete of a write transaction (on every table but#changes). At commit, the writes become the transaction’s change set, under the next log sequence number (LSN, from 1), in the same transaction: the log and the data never disagree. A transaction that changed nothing, or was aborted, takes no LSN.Keys of
#changes:lsn (u64) | chunk (u32), big-endian, for each part of a change set, which is cut into chunks of 1 MiB as it is written (a large transaction is never held in memory whole); and twelve0xffbytes for the log’s state (the next LSN, the oldest kept, the bytes kept).A change set is its writes in order:
0x01 | table | key length | key | value length | valuefor a put,0x02 | table | key length | keyfor a delete (lengths as u32, big-endian). Keys of the integer-key tables are native integers, so a replica must have the same byte order.The log keeps up to
change_log_limitbytes (512 MiB by default). Past it, the oldest change sets go at commit, whether or not a replica has read them, but never the newest one: a replica that missed one starts again from a copy of the database.
A replica applies its master’s change sets with KeyValueStore.applyChangeSet(lsn, bytes), each in
a write transaction of its own that also stores its LSN (key replica in #changes). A crash
therefore loses an applied change set whole or keeps it whole, and the replica resumes after the
last LSN it stored (appliedLsn):
a change set it has already applied (sent again after a reconnection) is skipped;
one that does not follow the last applied fails with
ChangeSetOutOfOrder, and so does one that is not a change set (MalformedChangeSet); either leaves the replica as it was;the first change set applied makes the database a replica, which refuses every other write (
ReadOnlyReplica), and a database whose log is started (a master) applies none.
A replica starts from a copy of its master: KeyValueStore.writeCopy(writer) writes, in one read
transaction (writers go on meanwhile), a header (the LSN of the last change set the copy holds and
the master’s id) and then every entry of every table but #changes, as the puts of a change set
(storage/copy.zig): records, not the engine’s pages, so any engine loads any engine’s copy. The
replica loads it as it comes, part by part (applyCopyPart), in one write transaction: the first
part empties its tables, the last stores the master’s id and, as its applied LSN, the copy’s.
Readers see the database as it was until then; a copy cut short changes nothing. The LSN comes from
the same read transaction as the entries, so nothing races with the writers. Starting
the log gives the master a random 16-byte id (databaseId, key database in #changes), which
its copies keep: a replica follows only the master it was copied from.
Nothing cached goes stale on a replica: the record cache lives one read transaction, the schema definitions are kept by schema version, and a prepared statement’s plan is checked against counts. The version and the counts are keys, so they change with the change sets.
Vector indexes¶
A vector index (vector_index.zig) is an HNSW graph (Malkov and Yashunin, 2016): every entity is
on level 0, about one in 16 also on level 1, one in 256 on level 2, and so on; on each level an
entity keeps a list of neighbours (32 on level 0, 16 above), chosen so that they point different
ways. A search starts at the entry point on the top level, walks down to the closest entity on
each level, then explores level 0 breadth-first, keeping the best 100 (or k) it has seen. The
algorithm (src/vector/hnsw.zig) is written once over a storage context (distances, levels,
lists, header), as std.HashMap is over its hash context; vector_index.zig is the context that
keeps it in the store, and the tests keep one in memory.
Its keys, after h and the index number (u32, big-endian); the graph’s keys are under a
generation (u8, see the rebuild below); the values are little-endian:
Key |
Value |
|---|---|
|
its state: 0 populating (generation 0), then the next id to look at and the entities looked at (u64 each); 1 online, then the generation searches read (u8) and, while it is rebuilt, the next id to look at (u64); 2 failed, then the entity (u64) and what is wrong with its value |
|
the header: the entry point (u64), the top level (u8), the live entities and the tombstones (u64 each) |
|
the entity’s level (u8), whether it is live (u8), its vector (f32 each) |
|
its neighbours on that level (u64 each) |
|
its version: the id of the write transaction that last wrote the generation (u64) |
An entity’s level comes from a hash of its id, so rebuilding gives the same levels. Writes keep it current as they keep the full-text postings, from the same mutators:
Checked before the write.
checkNodeandcheckRelationshipPropertyrefuse a value that is not a vector of the index’s length (error.ConstraintViolation), as uniqueness is checked: nothing is written.Insert: the entity’s record, then its lists on each of its levels, each a search from the entry point (breadth 100); each new neighbour adds it back, choosing again when it has one too many. About 8 KiB of lists per insert, plus the vector.
Update (a new vector): its old neighbours that link back to it choose again among their other neighbours and its own, then it is inserted anew under the same record.
Delete (property removed, label removed, entity deleted): the record becomes a tombstone. Its neighbours are repaired as for an update; other lists may still point at it, so it keeps routing searches, and is never returned. When tombstones outnumber live entities (past 1024), the delete marks the index for a rebuild (below); it does not rebuild it.
Each store (one per thread) keeps the records and lists it decoded across transactions
(vector_cache.zig), so an insert or a search does not read again the thousands of entities it
visits. A generation’s version says whether they are current: each write transaction that writes
a generation stores its own id there, and a store’s next look at the generation drops what it
kept if the version it sees is another. A write transaction that ends without its commit drops the
store’s cache (the engine may hand its id out again), and loading a copy gives each generation the
loading transaction’s id (the master’s ids mean nothing here). At most 64 MiB stays kept between
transactions, evicted by the clock algorithm; a transaction may go above it, as what it reads stays
valid until it ends. A store that searches while another writes the same index drops its entries
of that index at each write it sees.
Every key is written in the transaction of the change, so a reader sees the index as of its
snapshot. The change log does not carry these keys: a replica moves each entity in its own
indexes as it applies the write that changed it (replica_vector_indexes.zig), and the state is
each database’s own. A copy carries them as they are.
A new index is populated in the background (vector_population.zig): CREATE VECTOR INDEX (or a
replica applying it) stores the state populating and does a first batch; the builder thread of
the open database does the rest, one write transaction of about 20 ms per batch, which places
the next entities by id (from the label index, or the relationship table) and stores how far it
got, so a crash loses at most a batch. Writes keep the index meanwhile, ahead of that point too:
placing an entity is idempotent. Several processes share the work, each batch going on from the
state it reads. A value that is not a vector fails the index: its keys are removed but the state,
which names the entity and why; writes then leave it alone. The builder’s transactions write only
h keys, which a replica allows (KeyValueStore.beginLocalWrite). The integrity checker
requires a populating index to hold the entities below where it got to, and those above that
writes placed.
The same thread rebuilds an index without its tombstones (vector_rebuild.zig), so a delete
that crosses the threshold costs its transaction nothing more. Each batch takes the next live
records by id from the current generation and inserts them into the next one, storing how far
it got in the state; writes keep the current generation, and the next one below that point.
Searches read the current generation until the last batch makes the next one current; inserted
in id order with levels from the ids, the new graph is the one a rebuild in one go would make.
Keys no index needs any more are garbage, which the thread deletes first, about 20 ms of it per
batch: those of the old generation, of a dropped index (DROP INDEX deletes only the
definition) and of a failed one but its state. Index numbers are never reused, so garbage never
mixes with a new index’s keys. A rebuild only starts from an online index (a population that
ends with too many tombstones starts one). Copies carry it as they carry a population, and each
database rebuilds its own indexes. The checker checks both generations while a rebuild runs (the
next one holding exactly the live entities below where it got to) and accepts garbage as it is.
Checking integrity¶
Everything but the records is derived: the label index, the property indexes (from their
definitions: an index’s keys are rebuilt from the nodes or relationships it covers), both edge
keys of each relationship and the labels they keep, the counters, the full-text postings, the
vector indexes. The
integrity checker, zypherdb.integrity.check(graph, allocator) (src/storage/integrity.zig),
rebuilds each of them from the primary data — the node and relationship records, the relationship
properties (f), the schema definitions (i) — and compares them with what is stored. It also
checks that every uniqueness constraint holds, that the id counters are above every id in use,
that each record and value is well formed (layout.zig), and that the main table holds no key of
any other kind. An HNSW graph depends on the order of the writes that built it, so a vector index
is not rebuilt but checked: each entity it must hold has its record exactly (level, live, vector),
every other record is a tombstone, each record has a list on each of its levels naming recorded
entities once each and at most the level’s maximum, the header’s entry point and counts
agree, a generation with entries has a version, and what the store’s cache keeps of a
generation at the version it reads is what the generation holds. It returns a Report with the first problems found, described, and their count.
The same layout functions guard the storage boundary in Debug and ReleaseSafe builds: the writer asserts the bytes it is about to store, and the reader the bytes it is about to trust (pair assertions), so a malformed record stops the program where it appears. ReleaseFast compiles them out.
Users can run it too, as Database.check() in Python and zypherdb_check in C: a diagnostic for
a suspected bug, documented as such, not a routine call.
It runs in one read transaction, or in the active one (a write transaction is seen with its uncommitted changes), in O(database) time and memory. Two differences are not problems: a counter of something no longer there may stay at zero, and an edge key may keep a neighbour’s labels as an empty section or as a count of zero (both mean none).
The storage fuzzer checks the database with it after every commit and abort, and the fault and crash fuzzers after every failure and crash (see testing).
The storage engines¶
The rest of ZypherDB sees the engine only through src/storage/engine/contract.zig; the engine is
chosen at build time (zig build -Dstorage-engine=lmdb|mdbx), and both are kept until libmdbx
builds everywhere LMDB does:
LMDB (default) |
libmdbx ( |
|
|---|---|---|
Sources |
|
|
Files in the database directory |
|
|
File size |
grows as data is written, within a 1 TiB map; never shrinks |
grows in 16 MiB steps, up to 1 TiB; gives back free space at its end past 64 MiB |
A second open in one process |
not safe |
refused ( |
Builds |
every target |
every target but Windows on ARM64 |
Speed ( |
commits ~2x faster, point reads 5-15% faster, range-index scans 12-22% slower |
The two write different files, so a database belongs to the engine that created it.
Durability¶
KeyValueStore.openWithOptions takes a durability mode, mapped to each engine’s flags:
Mode |
LMDB flag |
libmdbx flag |
A commit returns when… |
|---|---|---|---|
|
none |
|
data and metadata are flushed ( |
|
|
|
data is flushed; the metadata page follows with the next commit |
|
|
|
the write is in the page cache; |
With libmdbx, every process that opens a database at once must agree on deferred: it refuses to
open a database in deferred mode that another process has open in full or relaxed, and the
reverse.
Both engines are copy-on-write and never overwrite live pages, so no mode can corrupt the database: a crash loses at most the commits that were not yet flushed, and the database opens at the last flushed one.
Why this way — and the alternatives¶
A key/value B+tree, not record files with pointers. Neo4j stores nodes and relationships in fixed-size records that point at each other, so following a relationship is one pointer, without a search. ZypherDB pays a B+tree search instead (O(log n), mostly in cached pages), and gets in return transactions, crash safety and readers that never wait from an engine it does not have to write, and every index in the same structure. Writing a storage engine of its own was considered and rejected.
LMDB or libmdbx, not an LSM tree (RocksDB). The project started on C++ and RocksDB. An LSM tree writes faster, but its reads go through several levels, and building it from source was most of the build time. A graph database reads far more than it writes, and LMDB’s reads were about six times faster; its one writer and many readers across processes is also the model ZypherDB offers.
Each relationship stored twice. Storing it once would halve the edge keys, but then one direction needs a separate reverse index, maintained the same way. Storing both directions makes either one a prefix scan.
Node records, not one key per property. A record per node makes reading a node one search, at the cost of rewriting the record on every change to it. Graph queries read nodes far more than they change them.
Neighbour labels on edge keys. They make
(a)-[:R]->(b:Person)checkPersonwithout readingb, and cost O(degree) when a label is added or removed. Labels change rarely; expansions run in almost every query.