# KleeneGraph

<p align="center"><img src="docs/kleene-graph.webp" alt="KleeneGraph: a black moose" width="480"></p>

A sparse matrix based engine in pure Rust on DataFusion/Ballista.

On a 24-core machine a ten-hop query over 533 million edges takes 0.63 s; PuppyGraph
publishes 2.26 s on four nodes.

A search, a shortest path or a Datalog rule runs as a product over a semiring, as GraphBLAS
does. A derived fact carries its proof.

Query times in seconds, warm, median of 3, through `kleene-ballista` on 2.5 GbE: four
machines with six cores each, and one machine with 24 cores.

| graph | edges | machines × cores | ten hops | full search | weak components | PuppyGraph\* |
|---|---|---|---|---|---|---|
| rmat24 | 133 million | 4 × 6 | 0.14 | 0.14 | 0.21 | |
| | | 1 × 24 | 0.06 | 0.06 | 0.09 | |
| rmat26 | 533 million | 4 × 6 | 0.88 | 0.87 | 0.90 | 2.26 |
| | | 1 × 24 | 0.63† | 0.23 | 0.44 | |
| rmat28 | 2.1 billion | 4 × 6 | 2.50 | 2.44 | 3.65 | |
| | | 1 × 24 | 0.87 | 0.86 | 1.32 | |

\* Ten hops, as published by PuppyGraph: four nodes of unknown size, 600 million edges by
one of their pages. Not measured here.

† Its three runs: 0.84, 0.63 and 0.22 s.

How this was measured: [bench/distributed.md](bench/distributed.md),
[bench/puppygraph.md](bench/puppygraph.md).

A graph is read from tables at one version. Its matrices and indexes are built once and
kept, and a query runs on what is kept. Over machines each worker holds one part, and only
new border nodes travel.

<p align="center"><img src="docs/overview.svg" alt="Data at a version is loaded once: each worker reads its own part and keeps its sparse matrix and indexes; a Datalog or GQL query runs in rounds between the parts and gives an answer with its proof" width="1180"></p>

Over machines the workers read an X.gar set today. Reading an Iceberg snapshot there, and
the dashed path, work on one machine and are planned over machines. Every step is listed
at the end of Details, under "From tables to an answer".

## Details

The engine has two halves that are really one loop:

| Half | What it does | Kleene's idea |
|---|---|---|
| Sparse matrices | graph algorithms as sparse products over semirings, on CPU and GPU | the star: A* = I + A + A² + … is every path |
| Datalog | typed recursive rules, run until nothing changes, a proof for every fact | the least fixed point |

Each round of a recursive rule is a sparse matrix product; the fixed point it stops at is the
star of the relation. The name is Stephen Kleene's ("KLAY-nee").

```
reach(F) :- entry(F).
reach(G) :- reach(F), calls(F, G).
```

Two lines, and kleene answers "what can this program reach?" on a call graph of millions of
edges as a masked BFS, then tells you *why* for every row.

### Fast

Same machine, same threads, same answers, against SuiteSparse:GraphBLAS + LAGraph (ms; loki,
8 threads, 2026-12-01):

| | graph | kleene | LAGraph |
|---|---|---|---|
| strong components | rmat26 (533 M edges) | **1701** | 11503 |
| weak components | road2048 | **18** | 111 |
| weighted shortest paths | road2048 | **380** | 2226 |
| weighted shortest paths | rmat26 | **2589** | 3318 |
| strong components, GPU (RTX 5080) | rmat22 | **37** | 500 |

Where we still lose: PageRank on loki on every graph smaller than rmat24 (1.1-1.7x), and raw
products: `A²` on road2048 (1.1x, masked 1.2x on loki) and the full min-plus `mxv` on rmat22
(1.5x). All of it, with method and hosts: [BENCH.md](BENCH.md).

### Inside

| Crate | |
|---|---|
| `kleene-sparse` | CSR/CSC matrices and vectors over semirings on Arrow buffers, zero copy, masks |
| `kleene-graph` | BFS (direction-optimizing), components (Afforest), SCC (Multistep), delta-stepping, PageRank, Brandes, triangles, bounded walks, shortest paths as vertex lists |
| `kleene-cubecl` | the same backend on GPUs through CubeCL (Vulkan, Metal, DX12) |
| `kleene-plan` | relations and rules as values: joins, negation, aggregates, recursion, stratified |
| `kleene-datalog` | Datalog rules built in Rust as typed values, or written as text with `datalog!`; no parser at run time |
| `kleene-datalog-macros` | the `datalog!` macro: Datalog text turned into the typed builder's calls at build time |
| `kleene-gql` | ISO GQL read queries: `MATCH`, variable-length paths as graph walks (bounded `{m,n}` too), `WHERE` with `AND`/`OR`/`NOT`/`XOR`/`IN`, `ORDER BY`/`OFFSET`/`LIMIT`, edges either way, with no label or `:A|B`, edge properties, `count`/`min`/`max`/`sum`/`avg` grouped, path variables and `ANY`/`ALL SHORTEST`, `OPTIONAL MATCH`, `WITH`, `CALL { }` subqueries, `UNWIND`, arithmetic, `UNION [ALL]`, `CALL pagerank`/`wcc`/`scc`/`sssp`/`betweenness`/`triangleCount`/`harmonic`/`ktruss`/`mis`/`msf`/`maxflow`, the state machine of a graph with labels (`CALL machine.steps`/`states`/`starts`), `$name` parameters, property, name, kind and reach index lookups chosen by the plan (`--explain`); `kleene gql "<query>" <X.gar>` on the command line, a set's signed, float, boolean and string columns typed (nulls as null) |
| `kleene-gar` | GraphAr tables read in place through DataFusion |
| `kleene-iceberg` | steps 1 to 4 and 7 below (kleene as an in-memory sink of Knut's bifröst); `kleene gql --iceberg` (feature `iceberg`, off by default) |
| `kleene-index` | the indexes of the figure below; each as an external relation of rules (`relations`), and a set's catalog with its indexes (`catalog`, `indexed`) |
| `kleene-datafusion` | the hop and a part's local fixpoint as DataFusion execution operators (`HopExec`, `LocalFixpointExec`); not pulled in by the umbrella crate |
| `kleene` | the umbrella crate and the `kleene` CLI |
| `kleene-ballista` | steps 8 to 14 below, on Ballista (our fork, `nordisk/kleene`): kleene's operators and codec, a sweep in part order, scheduler, executor and client binaries; its own workspace, not in the default build (Ballista builds the C zstd) |

No C in the default build: even zstd is pure Rust (a shim on mzstd). The exceptions are the
optional Iceberg adapter (`kleene-iceberg`, not in the default build), whose parquet links
`ring`, and `kleene-ballista` (its own workspace), where Ballista turns on DataFusion's
default features and their async compression needs zstd's raw stream API, which the shim
lacks, so the C zstd compiles. Parallel work
runs on gatling.

```
cargo build --release -p kleene --features gpu
target/release/kleene benchmark <data-dir> --zox <X.gar set> --gpu
```

A build in this repository is for the CPU it runs on: `.cargo/config.toml` sets
`-C target-cpu=native`, so a binary copied to an older CPU stops with an illegal
instruction. `RUSTFLAGS="-C target-cpu=x86-64-v3"` builds one binary for every AVX2 machine
instead (RUSTFLAGS replaces the file's flags). A crate that depends on kleene does not read
that file: set RUSTFLAGS in its own build. Measured binaries come from
`cargo build --profile measured` (release with fat LTO and one codegen unit).

From crates.io or git, one C library comes along: DataFusion turns on arrow-ipc's zstd
codec, the `zstd` crate binds the C zstd, and a `[patch]` never travels with a dependency.
To keep your build free of C, patch `zstd` in your own root Cargo.toml with this
repository's two shims (arrow 60 asks for zstd 0.14, Avro and Iceberg for 0.13; no
mzstd-backed `zstd` is on crates.io). Taking kleene from git, take both from the same git
source and rev you take kleene from; the exact `version` is needed, as the repository holds two packages named
`zstd` (without it cargo stops: "resolved to more than one candidate"):

```toml
[patch.crates-io]
zstd = { git = "ssh://git@git.gunnar.rs:2222/nordisk/kleene", rev = "<rev>", version = "=0.13.99" }
zstd014 = { git = "ssh://git@git.gunnar.rs:2222/nordisk/kleene", rev = "<rev>", package = "zstd", version = "=0.14.99" }
```

Or copy the `shims/zstd` and `shims/zstd-014` folders into your workspace and patch by path:
`zstd = { path = "shims/zstd" }` and `zstd014 = { package = "zstd", path = "shims/zstd-014" }`.
`cargo tree | grep -c zstd-sys` is then 0.

### From tables to an answer

<p align="center"><img src="docs/flow.svg" alt="The flow from Iceberg tables or an X.gar set to an answer, on one machine and over machines" width="1180"></p>

Steps 1 to 7 run on one machine. Steps 8 to 14 are `kleene-ballista`'s, over machines:
the coordinator is the client and Ballista's scheduler together, and the machines read an
X.gar set at the same path on each.

1. A mapping file (bifröst's `MappingSpec`, RON or YAML) names per table its node labels,
   its edge labels and their columns.
2. `IcebergSet::snapshot` reads each table at its current snapshot, or at a snapshot id
   given. Only metadata is read to find the snapshot; nothing is copied or re-partitioned.
3. What a table gave at a snapshot is kept per (table, snapshot id): asked again, no data
   file is read. `keep_in` keeps it on disk as well.
4. The rows fill a catalog: a node label is its ids, an edge label a sparse matrix held by
   source and by target, a property a typed column. An X.gar set fills the same catalog
   through `kleene-gar`.
5. The indexes are built once and kept in `<set>.kix`, an Arrow IPC file per column,
   memory-mapped and keyed by the set's root hash.
6. A Datalog rule or a GQL query is planned against the catalog. A rule takes an index as
   a relation; a GQL plan picks one for an equality, a range, a name, a kind or a reach
   between pinned ends. The kernels run the rest as products over a semiring.
7. For the next version `IcebergSet::advance` reads only what changed and gives a `Delta`
   of the rows added and removed; `Engine::continue_with` continues the earlier run from
   it.
8. The split is by a hash of the node id (`hash:K`), by blocks of ids, or computed
   (`computed:K`): made once by `kleene split-report --save`, kept in the store and read by
   every machine.
9. A load job (`Cluster::prepare`) has each executor read only the rows of its own part,
   build its matrix in both directions and keep it for every later job.
10. Each part returns a summary: its node count and its border edges per neighbouring
    part. The client builds the central index from the summaries: the id ranges per part,
    the part graph with its reach index, and the placement of parts on machines. It holds
    no edges.
11. A query's sources are placed in their parts from the id ranges. Only the parts they can
    reach get a task, and the scheduler sends a part's tasks to the executor that holds
    it.
12. In a round each part searches inside itself until it finds nothing new, then sends only
    its new border nodes, combined and compact, a row per target part, through Ballista's
    Flight shuffle.
13. The job ends at the first round that sends nothing. A collect step returns each part's
    answer in the original node ids.
14. With no split every machine holds the whole graph: a level's edges are cut into slices
    by the machines' cores and only the new nodes travel; many searches are handed out
    whole.

Planned, not built: executors that read Iceberg at a snapshot id, and indexes kept current
from the changes between snapshots.

### Versions

All crates share one version; its tags are `v0.1.0` to `v0.5.0` ([CHANGELOG.md](CHANGELOG.md)).
The engine on one machine and the engine over machines also carry step names, each a git tag:

| Engine | Step | Tag | What it holds |
|---|---|---|---|
| One machine | v1.0 | `single-v1.0` (the commit of `v0.2.0`) | Datalog rules with a proof per fact, the sparse kernels on CPU and GPU, GQL read queries, the indexes |
| One machine | v1.1 | `single-v1.1` | the clients' logic in the core (the catalog of a set, the index choice, ordered output, several aggregates in a rule), full-operand products in place |
| Over machines | v1.0 | `distributed-v1.0` | the changes between two Iceberg snapshots, the hop as a DataFusion operator, the split with local-first rounds, the first run through Ballista |
| Over machines | v1.1 | `distributed-v1.1` | the whole graph on every machine, a search cut in slices, many searches at once, measured |

`main` is past both v1.1 steps.

## Licence

MIT or Apache-2.0, at your option.
