|
smollerGraph 0.20.2
A small graph database, from scratch
|
A small graph database, built from scratch in C++ on the YouTube series Building smollerGraph. Each step of each episode is a tag in this repository, so you can check out the code at any point in a video.
It keeps a graph in a folder of fixed-size records, in pages of 4 KiB that a buffer pool keeps in memory, with a B+ tree that finds a node by its name, and each node's and relationship's properties in a chain of records of their own. Labels and relationship types are tokens, numbers kept in place of their names, as in Neo4j, and each relationship is in two chains, one of the relationships that start at a node and one of those that end at it, so they can be followed either way. It loads facts written as Cypher patterns, one a line, with a label after a colon and properties in braces, such as (Rabbit:Animal {legs: 4}), walks relationships of one type from a node, and draws the graph in a browser.
You need CMake 3.28 or newer, Ninja and a C++20 compiler.
sg path finds a shortest path between two nodes, along relationships of one type followed either way, with a breadth-first search from both ends, which meet in the middle, and says how many nodes it reached and how many pages it read. Given a property's key, such as weight, it finds a cheapest path instead, whose weights add up to the least, with Dijkstra's algorithm, from both ends too.
sg embed gives each node an embedding, a vector of 256 numbers that stands for where it is in the graph, with FastRP, as Neo4j's Graph Data Science library computes them: a sparse random vector for each node, then rounds in which a node's vector becomes the sum of its neighbours' vectors. It keeps them in the graph's folder, a kibibyte for each node, and sg similar prints the nodes whose embeddings point most nearly the same way as a node's, by their cosine:
sg export writes a graph into a folder for programs outside the database, such as a script that trains a model on it: nodes.jsonl, a line of JSON for each node, with its id, name, label and properties, and relationships.csv, the ids of the nodes each relationship joins, and its type. tools/gnn.py trains a small graph neural network on it, a GraphSAGE of four layers in PyTorch, which learns which species are threatened from their weights and from what's known of their relatives, and writes the risk it gives the species it didn't learn from as facts, which sg load adds to the graph, for Cypher to ask about:
sg query answers a small subset of Cypher: a pattern of nodes, with a label and properties to match, joined by relationships of a type, or of any of a few with bars between them, -[:EATS|LIVES_IN]->, that go right, -[:EATS]->, left, <-[:EATS]-, or either way, -[:EATS]-, for one hop or *N, then an optional WHERE of comparisons joined by AND, such as b.weight_g < 1000, and RETURN [DISTINCT] properties of its variables. ‘MATCH p = shortestPath((a {name: 'Red fox’})-[:PARENT_TAXON*]-(b {name: 'Lion'})) finds a shortest path between two nodes, whichRETURN preturns, andlength(p)its length. MATCH p = (a {name: 'Person 1'})-[:KNOWS* WSHORTEST(weight)]-(b {name: 'Person 2'}), as Kùzu writes it, finds a cheapest path, andcost(p)returns what its weights add up to. The plan starts from the node that's cheapest to find, by its name in the index, then by its label, and expands from it both ways along the pattern, or for a shortest path, finds both its ends, andEXPLAIN` in front shows it.
data/wikidata.txt holds 21,834 taxa from Wikidata, which is under CC0: each species of mammal and bird that the IUCN has assessed, with its scientific name, its conservation status, its weight when Wikidata has one, and the genera, families, orders and classes above it, joined by PARENT_TAXON. tools/wikidata.py writes it from Wikidata's query service, in a few minutes:
data/company.txt is a made-up company's Active Directory, written by tools/company.py from two lists of names and a seeded random generator: 275 accounts, 277 computers and 9 groups, joined the way BloodHound draws them, each relationship pointing the way an attacker would go, with MemberOf, AdminTo, HasSession, ForceChangePassword and GenericAll. A shortest path along any of the five, from an account to Domain Admins, is an attack path:
sg serve serves a graph over HTTP, with a page that runs Cypher queries and draws what they return on a canvas, a path as its nodes and the relationships between them, laid out by D3's force simulation, up to 500 nodes at a time, with the rows in a table, the plan, and what the query cost on the server. A search finds a node by its name, clicking a node shows its record as it's kept on disk, with its chain of properties and its chains of relationships out and in, and double-clicking it draws the nodes at the other end of both. Its second button draws the ten nodes whose embeddings are most like its, each at a distance that grows as their cosine falls:
Then open http://localhost:8474. Or, with Docker, docker compose up loads the mammals and birds, gives them their embeddings and serves them there, and docker compose -f compose.yaml -f compose.friends.yaml up serves the friends from the benchmarks, with their weights, which the page draws on each relationship.
The UI also runs in a browser on its own, without a server. Built with Emscripten (brew install emscripten), the library is WebAssembly, and the page builds the graph of mammals and birds, with their embeddings, from the Wikidata facts each time it opens, in its own memory, and keeps nothing:
Then open http://localhost:8475, or http://localhost:8475/?graph=company for the made-up company's Active Directory, which opens on its attack paths. CI publishes it with the API docs, at nenuadrian.github.io/smollerGraph/explorer and the company's.
smollerGraph is a library too, which another CMake project can fetch, as it would fetch Abseil, and link. Fetched that way, it adds the library and sg, which that project builds by naming it, and leaves the build type and the C++ standard to the project, which needs C++20 or newer. Each release has a tag, v0.20.0 for episode 20:
The headers are in include/smollergraph, and Execute runs a query in one call:
smollerGraph declares Abseil as abseil, so a project that declares it first shares its copy. tests/consumer is a project like that, which CI builds on each change, on the code in hand, with -DFETCHCONTENT_SOURCE_DIR_SMOLLERGRAPH pointing at the checkout.
deploy.sh copies the committed code to a server over SSH, and builds and runs it there with Docker Compose. Caddy, in a container of its own, serves the page's files on port 8474 and passes /api/ requests on to sg serve, which isn't published:
The server needs Docker, with Compose. The UI answers anyone who can reach the port, and it reads the graph, so there's nothing to change through it.
The comments in the headers are the API docs. With Doxygen installed (brew install doxygen graphviz, or apt install doxygen graphviz), the docs target writes them to build/docs/html:
CI publishes them at nenuadrian.github.io/smollerGraph, from each push to the public repository's main.
Doxygen reads comments written its own ways, such as with three slashes, and ours start with two, as Google's style guide writes them, so the build passes each header through a filter that gives them their third.
Why smollerGraph is built the way it is, a short record for each choice that would be costly to undo, with what else was weighed and what it costs, is in docs/decisions, with how to propose one. The API docs publish them too.
make_friends writes a social graph of made-up people, who each know ten others, with a weight on each friendship in the facts, as LDBC's Social Network Benchmark weighs them in its cheapest path question: max(round(40 - sqrt(messages)), 1), for a number of messages the two have sent each other, from 1 to 1,600.
bench/compare.py loads a generated social graph into smollerGraph, Kùzu and Neo4j (in Docker), and asks each of them two questions in Cypher from a thousand people, three times over: how many people are two hops of KNOWS away, following them out of a person, and following them in. sg bench parses and plans each query as well as running it. It writes the medians to bench/results.json:
Episodes 3, 5 and 11 measured changes this way. From episode 12, the series stopped racing Neo4j and Kùzu, as decision 18 says, so compare.py and sg bench are as episode 11 left them.
bench/ui.py measures how many frames a second Chromium paints while the page's layout moves a made-up graph, from 500 nodes to 20,000, drawn with SVG, drawn on a canvas, and not drawn at all, with sg serve serving ui/bench.html, and writes them to bench/ui.json. It opens a window, as Chromium paints a canvas in software without one:
The same build and tests on a clean Ubuntu, as CI runs them on each push:
And the API docs, with the explorer in explorer/, as CI publishes them, written to site/:
MIT, see [LICENSE](LICENSE).