Metadata-Version: 2.4
Name: leangraph
Version: 0.1.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Topic :: Database
Classifier: Topic :: Database :: Database Engines/Servers
Classifier: Development Status :: 4 - Beta
Requires-Dist: pandas ; extra == 'all'
Requires-Dist: numpy ; extra == 'all'
Requires-Dist: pyarrow ; extra == 'all'
Requires-Dist: polars ; extra == 'all'
Requires-Dist: pyarrow ; extra == 'arrow'
Requires-Dist: kuzu==0.11.3 ; extra == 'bench'
Requires-Dist: pandas ; extra == 'bench'
Requires-Dist: numpy ; extra == 'bench'
Requires-Dist: grpcio>=1.82.1 ; python_full_version >= '3.10' and extra == 'grpc'
Requires-Dist: protobuf>=7.35.0,<8 ; python_full_version >= '3.10' and extra == 'grpc'
Requires-Dist: kuzu==0.11.3 ; extra == 'oracle'
Requires-Dist: pandas ; extra == 'pandas'
Requires-Dist: numpy ; extra == 'pandas'
Requires-Dist: polars ; extra == 'polars'
Requires-Dist: pyarrow ; extra == 'polars'
Requires-Dist: fastapi>=0.110 ; extra == 'server'
Requires-Dist: uvicorn[standard]>=0.29 ; extra == 'server'
Requires-Dist: pydantic>=2.8 ; extra == 'server'
Requires-Dist: orjson>=3.9 ; extra == 'server'
Requires-Dist: pytest>=7.0 ; extra == 'test'
Requires-Dist: pandas ; extra == 'test'
Requires-Dist: numpy ; extra == 'test'
Requires-Dist: pyarrow ; extra == 'test'
Requires-Dist: fastapi>=0.110 ; extra == 'test'
Requires-Dist: uvicorn[standard]>=0.29 ; extra == 'test'
Requires-Dist: pydantic>=2.8 ; extra == 'test'
Requires-Dist: orjson>=3.9 ; extra == 'test'
Requires-Dist: httpx>=0.27 ; extra == 'test'
Requires-Dist: grpcio>=1.82.1 ; python_full_version >= '3.10' and extra == 'test'
Requires-Dist: grpcio-tools==1.82.1 ; python_full_version >= '3.10' and extra == 'test'
Requires-Dist: protobuf>=7.35.0,<8 ; python_full_version >= '3.10' and extra == 'test'
Provides-Extra: all
Provides-Extra: arrow
Provides-Extra: bench
Provides-Extra: grpc
Provides-Extra: oracle
Provides-Extra: pandas
Provides-Extra: polars
Provides-Extra: server
Provides-Extra: test
License-File: LICENSE
Summary: Embeddable property-graph database with a Kuzu-compatible Python API and a Rust core
Keywords: graph,database,cypher,property-graph,embedded,kuzu
Author: cnmoro
License: MIT
Requires-Python: >=3.8
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://github.com/cnmoro/LeanGraph#readme
Project-URL: Issues, https://github.com/cnmoro/LeanGraph/issues
Project-URL: Repository, https://github.com/cnmoro/LeanGraph

# LeanGraph

LeanGraph is an embeddable property-graph database for Python. The core is written in
Rust. The Python API and the Cypher dialect follow [Kuzu](https://kuzudb.com) 0.11.3, so
most Kuzu programs run unchanged after `import leangraph as kuzu`.

A database is a directory (or memory only). There is no server. Queries run inside your
process, in parallel, on memory-mapped column files.

* Same API as `kuzu`: `Database`, `Connection`, `QueryResult`, `PreparedStatement`, the
  same exception names, `get_as_df()` / `get_as_arrow()` / `get_as_pl()` /
  `get_as_networkx()`.
* Checked against Kuzu: a differential test suite runs ~560 generated queries and write
  sequences on both engines and compares the results row by row. The few places where
  LeanGraph deliberately differs are listed under [Differences from Kuzu](#differences-from-kuzu).
* Crash-safe: CRC-framed write-ahead log, atomic checkpoints, verified files, fail-closed
  open. See [docs/RECOVERY.md](docs/RECOVERY.md).
* Faster and smaller than Kuzu on the benchmark in [docs/BENCHMARKS.md](docs/BENCHMARKS.md).

## Contents

- [Install](#install)
- [Quick start](#quick-start)
- [Python API](#python-api)
- [Cypher](#cypher)
- [Types](#types)
- [Transactions](#transactions)
- [Durability and recovery](#durability-and-recovery)
- [Threads, processes and fork](#threads-processes-and-fork)
- [Environment variables](#environment-variables)
- [Network servers](#network-servers)
- [Performance](#performance)
- [Differences from Kuzu](#differences-from-kuzu)
- [Limitations](#limitations)
- [Development](#development)

## Install

```bash
pip install leangraph                 # core, no Python dependencies
pip install "leangraph[pandas]"       # + get_as_df(), COPY FROM a DataFrame
pip install "leangraph[arrow]"        # + get_as_arrow()
pip install "leangraph[polars]"       # + get_as_pl()
pip install "leangraph[all]"
```

Wheels are abi3 (CPython 3.8+). To build from source you need a Rust toolchain and
[maturin](https://www.maturin.rs):

```bash
pip install maturin
maturin develop --release        # or: maturin build --release
```

## Quick start

```python
import leangraph

db = leangraph.Database("./social")          # a directory; created if missing
conn = leangraph.Connection(db)

conn.execute("CREATE NODE TABLE Person(id INT64, name STRING, age INT64, PRIMARY KEY(id))")
conn.execute("CREATE REL TABLE Knows(FROM Person TO Person, since INT64)")

conn.execute("CREATE (:Person {id: 1, name: 'Ann', age: 34})")
conn.execute("CREATE (:Person {id: 2, name: 'Bob', age: 29})")
conn.execute("""
    MATCH (a:Person {id: 1}), (b:Person {id: 2})
    CREATE (a)-[:Knows {since: 2015}]->(b)
""")

res = conn.execute(
    "MATCH (a:Person)-[k:Knows]->(b:Person) WHERE a.age > $min RETURN a.name, b.name, k.since",
    {"min": 30},
)
while res.has_next():
    print(res.get_next())                     # ['Ann', 'Bob', 2015]

# Bulk load
conn.execute("COPY Person FROM 'persons.csv' (HEADER=true)")

db.close()                                    # also runs at interpreter exit
```

`Database` and `Connection` are context managers:

```python
with leangraph.Database(":memory:") as db:
    conn = leangraph.Connection(db)
    print(conn.execute("RETURN 1 + 1 AS two").get_all())   # [[2]]
```

## Python API

### `leangraph.Database(database_path=None, *, read_only=False, sync_interval_ms=None, lock_timeout_ms=None, auto_vacuum=None, checkpoint_threshold=-1, auto_checkpoint=True, max_num_threads=0, **kuzu_options)`

* `database_path`: a directory. `None`, `""` or `":memory:"` gives an in-memory database.
* `read_only`: open an existing database for reading. Other processes may keep writing; a
  read-only handle picks their commits up before each query.
* `sync_interval_ms`: WAL group-commit window, default 250. `0` fsyncs every commit.
* `lock_timeout_ms`: how long `Database()` waits for the writer lock held by another
  process, default 5000. After that it raises `StorageError`.
* `auto_vacuum`: background compaction of relationship storage after deletes, default on.
* `checkpoint_threshold`: WAL size in bytes that triggers an automatic checkpoint.
  `auto_checkpoint=False` turns automatic checkpoints off.
* `max_num_threads`: default query parallelism for new connections (0 = all cores).
* Kuzu options without a LeanGraph meaning (`buffer_pool_size`, `compression`, `lazy_init`,
  `max_db_size`, …) are accepted and ignored. LeanGraph maps files instead of using a
  buffer pool.

Methods: `close()`, `is_closed`, `read_only`, `checkpoint()`, `vacuum()`,
`vacuum_errors()`, `wait_background()`, `verify_integrity()` (list of problems, empty when
healthy), `stats()`, `init_database()` (no-op, for Kuzu compatibility).

`close()` checkpoints and releases the files and locks. It is idempotent. If a write
transaction is still open on one of the database's connections, `close()` waits up to
`LEANGRAPH_CLOSE_TIMEOUT_MS` (30 s) and then raises. The database then stays open, so you
can roll the transaction back and call `close()` again.

### `leangraph.Connection(database, num_threads=None)`

* `execute(query, parameters=None)`: runs one or more `;`-separated statements and returns a
  `QueryResult` (a list of them for several statements). `query` may also be a
  `PreparedStatement`.
* `prepare(query, parameters=None)`: returns a `PreparedStatement` (`is_success()`,
  `get_error_message()`). The query is parsed, and read-only statements are bound against
  the schema (unknown tables, properties, variables and functions are reported), without
  executing anything. Executing a failed prepared statement raises its error.
* `set_max_threads_for_exec(n)`, `close()`.
* `set_query_timeout(ms)` is accepted but not enforced, and `interrupt()` is not supported.

A connection is thread-safe (its statements are serialized). Use one connection per thread
for parallel queries.

Parameters are passed as a dict: `conn.execute("MATCH (n) WHERE n.id = $id RETURN n", {"id": 7})`.
As in Kuzu, passing a parameter that the query does not use is an error, a parameter the
query uses but the call does not supply is NULL, and a Python `int` outside the INT64
range is refused (`QueryRuntimeError`).

### `QueryResult`

`has_next()`, `get_next()`, `get_n(k)`, `get_all()`, `rows_as_dict()`, `get_num_tuples()`,
`get_column_names()`, `get_column_data_types()`, `get_schema()`, `reset_iterator()`,
`get_compiling_time()`, `get_execution_time()`, `close()`, and the converters
`get_as_df()` (pandas), `get_as_arrow(chunk_size=None)` (pyarrow), `get_as_pl()` (polars),
`get_as_networkx(directed=True)`. A result is also iterable.

* `rows_as_dict(state=True)` returns the result itself, switched to rows as
  `{column: value}` dicts (`state=False` switches back), as in Kuzu.
* `get_next()` past the last row raises `QueryRuntimeError` (a `RuntimeError`).
* `get_as_df()` uses Kuzu's dtypes. Integer columns keep their declared width (`int32`,
  `uint8`, …) and become `float64` (NaN) when they hold NULLs. `FLOAT` is `float32`.
  `BOOL` is `bool`, or `object` with NULLs. `DATE` and `TIMESTAMP` are `datetime64[us]`.
  Other NULLs are NaN.
* `get_as_arrow()` uses Kuzu's types and names. Integer widths are kept, `FLOAT` is
  `float32`, `DATE` is `date32` and `TIMESTAMP` is `timestamp[us]`. List children are named
  after the column, and nodes are structs with `_ID` and `_LABEL` first, followed by the
  table's properties in their declared types.

Nodes and relationships come back as dicts, like Kuzu's:
`{'_id': {'table': 0, 'offset': 3}, '_label': 'Person', 'id': 1, 'name': 'Ann', ...}`.
Paths (recursive relationships) come back as `{'_nodes': [...], '_rels': [...]}`.

### Exceptions

All errors derive from `leangraph.Error`, which is a `RuntimeError`, so `except RuntimeError`
code written for Kuzu still works.

| Exception | Raised for |
|---|---|
| `ParserError` | Invalid Cypher syntax |
| `BinderError` | Unknown variables, properties, type errors |
| `CatalogError` | Unknown tables or functions, duplicate tables |
| `QueryRuntimeError` | Errors while running (overflow, division by zero, out-of-range index, …) |
| `TransactionError` | Misuse of `BEGIN`/`COMMIT`/`ROLLBACK` |
| `CopyError` | `COPY`/`LOAD FROM` input problems |
| `StorageError` | I/O and durability errors, lock timeouts |
| `CorruptionError` (a `StorageError`) | On-disk damage; the database refuses to open |
| `ClosedError` | Use of a closed database, connection or result |
| `InternalError` | A bug in LeanGraph (caught panic). Please report it. |

## Cypher

LeanGraph implements the Kuzu dialect of openCypher.

### Schema (DDL)

```cypher
CREATE NODE TABLE [IF NOT EXISTS] Person(id INT64, name STRING, tags STRING[], PRIMARY KEY(id))
CREATE NODE TABLE Doc(id SERIAL, body STRING, PRIMARY KEY(id))
CREATE REL TABLE [IF NOT EXISTS] Knows(FROM Person TO Person, since INT64 [, MANY_MANY | ONE_MANY | MANY_ONE | ONE_ONE])
CREATE REL TABLE Likes(FROM Person TO Doc, FROM Person TO Person)      -- several FROM/TO pairs
DROP TABLE [IF EXISTS] Knows
ALTER TABLE Person ADD [IF NOT EXISTS] email STRING [DEFAULT 'x']
ALTER TABLE Person DROP [IF EXISTS] email
ALTER TABLE Person RENAME name TO full_name
ALTER TABLE Person RENAME TO People
COMMENT ON TABLE Person IS 'people'
```

### Queries

* `MATCH`, `OPTIONAL MATCH`, `WHERE`, `WITH`, `UNWIND`, `RETURN [DISTINCT]`, `ORDER BY …
  [ASC|DESC]`, `SKIP`, `LIMIT`, `UNION [ALL]`, `RETURN *`, `RETURN n.*` (every property of
  `n` as a column).
* Patterns: node and relationship labels (including multi-label `:A:B`, which matches
  either table, and unlabelled nodes and relationships), property maps, either direction or undirected,
  comma-separated patterns, named paths `p = (...)`.
* Variable-length relationships: `[:Knows*1..3]`, `[*..2]`, `[*2]`, with the Kuzu path
  semantics `WALK` (default), `TRAIL` and `ACYCLIC`, `SHORTEST` / `ALL SHORTEST`, and
  filters on the relationships and nodes inside the path: `[:Knows*1..3 (r, n | WHERE r.since > 2000)]`.
* Subqueries: `EXISTS { MATCH … }`, `COUNT { MATCH … }`, pattern predicates.
* Expressions: arithmetic, comparison, `AND/OR/XOR/NOT`, `IN`, `STARTS WITH`, `ENDS WITH`,
  `CONTAINS`, `=~` (regex), `IS [NOT] NULL`, `CASE`, list literals, indexing `l[i]` and
  slicing `l[a:b]`, map and struct literals, `CAST(x AS TYPE)`, parameters `$p`.
* Quantifiers: `all/any/none/single(x IN list WHERE pred)`.
* Lambdas: `list_transform(l, x -> …)`, `list_filter`, `list_reduce`.
* Aggregates: `count(*)`, `count`, `sum`, `avg`, `min`, `max`, `collect`, `stddev_samp`,
  `stddev_pop`, `product`, each with `DISTINCT`.
* Path functions: `nodes(p)`, `rels(p)`, `length(p)`, `properties(list, 'key')`,
  `is_trail(p)`, `is_acyclic(p)`. Graph functions: `id(n)`, `label(n)`, `offset(id)`,
  `start_node(r)`, `end_node(r)`.
* Scalar functions: string (`lower`, `upper`, `trim`, `substring`, `string_split`,
  `regexp_*`, `levenshtein`, `lpad`, …), math (`abs`, `round`, `sqrt`, `pow`, `log`, trig,
  …), casts (`to_int64`, `to_double`, `to_string`, …), dates (`date`, `timestamp`,
  `interval`, `date_part`, `date_trunc`, `make_date`, …), lists (`range`, `list_*`,
  `size`), maps and structs (`map`, `map_extract`, `struct_extract`, …), and `coalesce`,
  `typeof`, `hash`. The full list is `SCALAR_FUNCS` in `src/exec/scalar.rs`.

### Writes

`CREATE`, `MERGE … ON CREATE SET … ON MATCH SET …`, `SET n.p = v`, `SET n = {map}`,
`DELETE`, `DETACH DELETE`. Writes may be combined with reads and `RETURN` in one statement.

### Import, export and procedures

```cypher
COPY Person FROM 'persons.csv' (HEADER=true, DELIM=',')
COPY Person FROM 'part_*.csv'                       -- glob
COPY Person FROM $df                                 -- pandas DataFrame / dict of columns / list of rows
COPY Knows FROM 'knows.csv' (HEADER=true)            -- first two columns: FROM and TO primary keys
LOAD FROM 'file.csv' (HEADER=true) RETURN *          -- query a CSV without loading it
COPY (MATCH (p:Person) RETURN p.id, p.name) TO 'out.csv'
CALL show_tables() RETURN *
CALL table_info('Person') RETURN *
CALL show_connection('Knows') RETURN *
CALL db_version() RETURN *
EXPLAIN MATCH (n) RETURN count(n)
CHECKPOINT
```

**Windows paths:** a backslash in a Cypher string starts an escape (`'C:\temp'` contains a
tab), as in Kuzu. Write paths with forward slashes, which Windows accepts
(`COPY P FROM 'C:/data/p.csv'`, or `pathlib.Path(...).as_posix()` from Python), or double
the backslashes.

CSV options: `HEADER`, `DELIM`/`DELIMITER`/`SEP`, `QUOTE`, `ESCAPE`, `SKIP`,
`IGNORE_ERRORS`, `PARALLEL`, `AUTODETECT`. As in Kuzu, an empty CSV field (quoted or not)
is read as NULL.

### Not supported

* Parquet, JSON and NumPy files in `COPY`/`LOAD FROM` (CSV, DataFrames and Python rows only).
* Several things Kuzu 0.11.3 rejects are rejected too: list comprehensions
  `[x IN l WHERE … | …]`, `REMOVE`, `SET n += {…}`, `WALK` as an explicit keyword,
  2-argument `substring`. LeanGraph is not strictly parity on rejections, though; see
  [Extensions](#extensions-accepted-here-rejected-by-kuzu).
* Kuzu extensions (`INSTALL`/`LOAD EXTENSION`: full-text search, vector index, algo, …),
  `ATTACH`, `EXPORT/IMPORT DATABASE`, macros, user-defined functions, `CALL` procedures
  other than those listed above.
* Query timeouts and `interrupt()`.

## Types

`BOOL`, `INT8/16/32/64`, `UINT8/16/32/64`, `INT128`, `SERIAL`, `FLOAT`, `DOUBLE`,
`STRING`, `BLOB`, `DATE`, `TIMESTAMP`, `INTERVAL`, `LIST` (`T[]`), `MAP(K, V)`,
`STRUCT(a T, …)`, plus `NODE`, `REL`, `RECURSIVE_REL` and `INTERNAL_ID` in results.

Python mapping: `int`, `float`, `str`, `bool`, `bytes`, `datetime.date`,
`datetime.datetime`, `datetime.timedelta`, `list`, `dict`, `None`. `sum()` over integers
returns an `int`. Kuzu returns a `Decimal` there, because it sums integers as `INT128`. Integer columns are
stored at the narrowest width that holds their values, so storage does not depend on the
declared width.

## Transactions

* Every statement outside `BEGIN … COMMIT` is its own transaction (auto-commit).
* `BEGIN TRANSACTION` … `COMMIT` / `ROLLBACK` groups statements on one connection.
  `BEGIN TRANSACTION READ ONLY` gives a read-only transaction. All its statements see the
  same snapshot.
* Readers never block and never see uncommitted data. Every query reads a consistent
  snapshot.
* One write transaction at a time per database. A second writer (another connection or
  thread) waits up to `LEANGRAPH_WRITE_LOCK_TIMEOUT_MS` (60 s).
* As in Kuzu, an error inside an explicit transaction rolls the whole transaction back.
* DDL and `COPY` are transactional too. `COPY` commits by writing a checkpoint.

## Durability and recovery

Commits are appended to a CRC-framed write-ahead log and fsynced by a group-commit flusher
within `sync_interval_ms` (default 250 ms). Use `sync_interval_ms=0` for an fsync per
commit. Checkpoints write new column files and publish them atomically. A statement that
raised an error is never visible after a reopen. On open, every file is checked against the
manifest. A torn WAL tail (an interrupted, unacknowledged commit) is truncated, and real
damage makes the open fail with `CorruptionError` without modifying anything.

[docs/RECOVERY.md](docs/RECOVERY.md) covers the file layout, the exact guarantees, and what
to do when a database refuses to open (including salvage with `LEANGRAPH_ALLOW_WAL_SKIP=1`).

## Threads, processes and fork

* **Threads:** share one `Database`. Give each thread its own `Connection`. Queries run in
  parallel; writes are serialized.
* **Processes:** one **writer** process per directory, enforced by an `flock` on
  `.writer_lock`. A second `Database(path)` in another process waits `lock_timeout_ms`, then
  raises `StorageError`. Any number of processes may open the same directory with
  `read_only=True` while the writer runs. They see each commit before their next query, and
  never see uncommitted data. When the writer closes or dies (even by SIGKILL), its lock is
  released and another process can become the writer.
* **fork():** a forked child must not use database objects inherited from the parent.
  LeanGraph detaches them in the child, so the parent's files and locks are never touched,
  and the child should open its own `Database`. `multiprocessing` with the `spawn` or
  `forkserver` start method needs nothing special.
* Network file systems are not supported (they do not give reliable `flock`/`fsync`).

## Environment variables

| Variable | Default | Effect |
|---|---|---|
| `LEANGRAPH_NUM_THREADS` | all cores | Query worker threads |
| `LEANGRAPH_WAL_SYNC_MS` | 250 | Group-commit window; `0` = fsync each commit |
| `LEANGRAPH_WAL_FLUSHER_TICK_MS` | 20 | Flusher wake-up interval |
| `LEANGRAPH_CHECKPOINT_THRESHOLD_BYTES` | automatic | WAL size that triggers a checkpoint |
| `LEANGRAPH_CHECKPOINT_ON_CLOSE` | 1 | Checkpoint in `close()` |
| `LEANGRAPH_MAX_WAL_BYTES` | 16 GiB | Refuse to replay a larger WAL |
| `LEANGRAPH_VERIFY_ON_OPEN` | 1 | CRC-check every data file on open |
| `LEANGRAPH_ALLOW_WAL_SKIP` | 0 | Salvage: open past mid-log damage, **discarding** the rest of the log |
| `LEANGRAPH_LOCK_TIMEOUT_MS` | 5000 | Wait for another process's writer lock |
| `LEANGRAPH_WRITE_LOCK_TIMEOUT_MS` | 60000 | Wait for another write transaction in this process |
| `LEANGRAPH_CLOSE_TIMEOUT_MS` | 30000 | `close()` wait for an open write transaction |
| `LEANGRAPH_AUTO_VACUUM` | 1 | Background relationship compaction |
| `LEANGRAPH_VACUUM_RATIO` | 0.2 | Deleted fraction that triggers a vacuum |
| `LEANGRAPH_VACUUM_MIN_DELETED` | 256 | …and at least this many deleted relationships |
| `LEANGRAPH_VACUUM_FINISH_WAIT_S` | 60 | How long a vacuum waits to publish its result |
| `LEANGRAPH_COMPACT_MIN_DELTA` | 65536 | Adjacency delta size that triggers a CSR rebuild |
| `LEANGRAPH_QUERY_MEMORY_LIMIT` | half of the available RAM | Heap one query may add before it fails with "query exceeded its memory budget" (bytes; `0` disables) |
| `LEANGRAPH_MAX_STRING_BYTES` | 256 MiB | Largest string any function or `+` may build |
| `LEANGRAPH_MAX_LIST_ELEMENTS` | 16 Mi | Largest list any function or `+` may build |
| `LEANGRAPH_FAIL_STAGE`, `LEANGRAPH_FAIL_MODE` | unset | Fault injection for tests (see RECOVERY.md) |

The network servers have their own variables; see [CLIENT.md](CLIENT.md).

## Network servers

`pip install "leangraph[server]"` adds a REST server (`leangraph-serve`, FastAPI).
`pip install "leangraph[grpc]"` adds a gRPC server (`leangraph-grpc`, Python ≥ 3.10).
Both ship in the wheel under `leangraph.server`, and `import leangraph` never loads them.

```bash
leangraph-serve --path ./social          # http://127.0.0.1:8005, POST /query {"query": ..., "parameters": {...}}
```

They bind loopback by default, need a bearer token (and TLS for gRPC) off loopback, refuse
`COPY`/`LOAD FROM` unless file access is enabled, cap request and response sizes by the
free memory, and return the same rows as the library. Every request uses its own
connection, so a transaction must begin and end within one request. See
[CLIENT.md](CLIENT.md) for the API, value encoding, errors, limits and security model.

## Performance

Median of 5 runs, 1M nodes / 10M relationships, 8 threads, both engines on default
settings (full table, method and caveats in [docs/BENCHMARKS.md](docs/BENCHMARKS.md)):

| Benchmark | LeanGraph | Kuzu 0.11.3 | Ratio |
|---|---:|---:|---:|
| COPY 1M nodes | 414 ms | 576 ms | 1.4x |
| COPY 10M rels | 1,597 ms | 2,739 ms | 1.7x |
| Disk size after load | 190 MB | 224 MB | 1.18x |
| Open time | 27.9 ms | 103 ms | 3.7x |
| PK lookup | 14.8 µs | 13,419 µs | 908x |
| One hop | 18.0 µs | 2,571 µs | 143x |
| Full-scan filter + aggregate | 0.61 ms | 2.03 ms | 3.3x |
| Group by string (100 groups) | 9.12 ms | 27.1 ms | 3.0x |
| Var-length `*1..3` count | 0.046 ms | 5.22 ms | 113x |
| Shortest path | 0.062 ms | 72.4 ms | 1,174x |
| Auto-commit CREATE, fsync per commit (`LEANGRAPH_WAL_SYNC_MS=0`) | 678 /s | 295 /s | 2.3x |
| Auto-commit CREATE, default group commit | 37,706 /s | 295 /s | 128x |
| Peak RSS | 962 MB | 2,335 MB | 2.4x |

The default auto-commit ratio comes mostly from group commit (fsync within 250 ms instead of
per commit). At equal durability the gain is about 2.3x–3.6x. Treat differences under
~1.5x as noise; docs/BENCHMARKS.md explains the run.

## Differences from Kuzu

LeanGraph returns the same rows, column names and errors as Kuzu 0.11.3 on the
differential suite, except in these places:

* **Kuzu 0.11.3 bugs that LeanGraph does not copy.** The differential suite marks these
  cases as expected failures. For the first three, it does so only after LeanGraph and Kuzu
  agree on a rewritten query that avoids the bug:
  * Variable-length patterns with lower bound 0 (`*0..k`): when the start node lies on a
    cycle, Kuzu drops the zero-length row and returns an extra copy of the cycle row.
    LeanGraph returns the zero-length row.
  * `ACYCLIC`: Kuzu's operator returns paths that repeat nodes (even `1→2→1→2`).
    LeanGraph returns paths whose nodes are all distinct, endpoints included. That is what
    Kuzu documents and what its own `is_acyclic(p)` checks.
  * Grouped aggregation: in Kuzu, a non-DISTINCT aggregate placed after a DISTINCT
    aggregate (`RETURN g, count(DISTINCT x), max(y)`) returns NULL, and small repros crash
    Kuzu with a heap-corruption assertion. LeanGraph returns the correct value.
  * `DETACH DELETE` in Kuzu can leave relationships of the deleted node behind. In the
    1M-node benchmark, after 3,000 deletes Kuzu still counts 38–41 relationships that the
    source data says are gone. In the differential suite, Kuzu's on-disk `count(*)` still
    counts a deleted self-loop. LeanGraph removes them.
  * Kuzu's in-memory mode (`Database(":memory:")`) can silently drop hash-join rows and
    segfaults on some queries that the on-disk mode answers correctly. The test suites run
    Kuzu crash-isolated, in a subprocess, for that reason.
* **Deliberate choices where Kuzu is inconsistent.**
  * `MATCH (p:P {id: 2.0})` and `WHERE p.id = 2.0` both find the node with integer key
    2. In Kuzu the first finds it and the second does not. `{id: 2.5}` finds nothing;
    Kuzu casts 2.5 to 2.
  * `SET` is applied row by row and item by item, as in Kuzu and openCypher, so the stored
    result is the same. A `RETURN` after `SET` shows the final values for every row
    (`6, 6, 6`); Kuzu shows each row's value as of its own update (`1, 3, 6`).
  * A parameter the query uses but the call does not supply is NULL, as in Kuzu. Kuzu
    0.11.3 then returns *every* row for `WHERE p.id = $missing`; LeanGraph returns none,
    because the comparison is NULL.
  * UINT64 arithmetic past 2^63 raises an overflow error. Kuzu promotes to INT128.
  * `COPY … (IGNORE_ERRORS=true)` skips rows that fail to cast, duplicate primary keys and
    rows with the wrong number of fields, and reports the count in the result message. Kuzu
    reports them through `CALL show_warnings()`, and rejects files with ragged rows even
    with `IGNORE_ERRORS`.
* **No Parquet/JSON/NumPy input** in `COPY` (see [Not supported](#not-supported)).
* **Storage:** no buffer pool. Files are memory-mapped, and buffer-pool options are ignored.
* **`sum()` of integers** returns a Python `int`, not a `Decimal`.
* `set_query_timeout()` is accepted but not enforced.

### Extensions (accepted here, rejected by Kuzu)

LeanGraph rejects what Kuzu 0.11.3 rejects for the statements the differential harness
lists as invalid (a test runs all of them), but it still accepts a few queries Kuzu rejects
with a binder or catalog error. Programs that use these will not run on Kuzu:

* aggregates and predicates over a bare `NULL`: `sum(NULL)`, `'a' IN [NULL]`;
* `toFloat(x)` (Kuzu has `to_double`), `greatest(a, b)` / `least(a, b)` with scalar
  arguments, `stddev_samp` of a constant;
* property access on a map literal: `{a: 1}.b` is NULL.

A non-BOOL `WHERE` (`WHERE n.age`) and integer division by zero fail when the first row
reaches them, not when the query is bound.

## Limitations

* Single machine, single writer process per database (see above). No server, replication or
  distributed execution.
* The working set is memory-mapped. Queries are fastest when the data fits in RAM, but the
  OS pages data in and out as needed.
* A large `UNWIND … CREATE` or `MERGE` statement builds its changes in memory before it
  commits. Load big data sets with `COPY`.
* Queries cannot be interrupted or timed out yet. Runaway queries fail with an error when
  they pass their memory budget (`LEANGRAPH_QUERY_MEMORY_LIMIT`) instead of taking the
  process down: cartesian products, `RETURN p` over long variable-length paths, chained
  `UNWIND`s (streamed in bounded batches), and huge lists or strings built by `+`,
  `list_concat`, `concat`, `string_split`, `range`, `repeat` and list lambdas (their size
  is charged before they are built). Under an address-space limit (`RLIMIT_AS`), the
  process's virtual size is checked as well. After a query fails on its budget, or grows
  memory a lot, freed memory is handed back to the OS.
* Expressions may nest at most 500 levels deep (parentheses, operator chains, `NOT`, lists,
  maps, `CASE`, function calls), and a query may have at most 500 relationship patterns and
  500 clauses; deeper queries are a `ParserError`. Nested parameter values are limited to
  500 levels too. Deep queries run with extra stack, so they work on small thread stacks
  (Windows threads have 1 MB). A query that is merely slow, such as `count(*)` over a 27-billion-row
  cartesian product, runs to the end.
* Primary keys are required on node tables (as in Kuzu), and one property is the key.
* No full-text, vector or spatial indexes yet. Lookups other than by primary key scan
  (in parallel).
* The on-disk format is version 1. A LeanGraph that finds a newer format version refuses
  to open the database with a clear error, instead of misreading it.

## Development

```bash
python -m venv venv && . venv/bin/activate
pip install maturin pytest kuzu==0.11.3 pandas numpy pyarrow   # kuzu is the test oracle
maturin develop --release
pytest tests                              # differential suite + robustness suites
python bench/bench_vs_kuzu.py --quick     # small benchmark; drop --quick for 1M nodes / 10M rels
```

`tests/difftest/harness.py` can replay a single differential case:
`python -m tests.difftest.harness --seed 1 --category varlen --index 1 --engine leangraph --show`.

License: MIT.

