project-minigraf/minigraf
Über uns
Embedded graph memory for AI agents, mobile apps, and the browser.
Web- und App-EntwicklungGemessener Sternzuwachs
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- +1
- in 1 month
- Verlauf wird gesammelt
Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.
README.md
OriginalMinigraf
Minigraf is an embedded graph database written in Rust. It stores a graph and its history in a local .graph file, and you query it with Datalog.
Try it in your browser — no install needed →
Open the visualizer → Change the selected transaction or valid time to see the graph change.
What Minigraf does
Minigraf is a single-file embedded graph database that lets you:
- ✅ Query relationships with Datalog - Follow relationships across multiple hops with recursive rules
- ✅ Query both timelines - Filter by when a fact applied (valid time) and when it was recorded (transaction time)
- ✅ Window functions -
sum/count/min/max/avg/rank/row-number/lag/lead :over (partition-by … :order-by …)in:findclauses - ✅ Bounded and ordered results -
:limit Nreturns at most N rows and stops the work once it has them;:order-by [?score :desc] :limit 10keeps only the top ten as it reads, and:offsetpages through an ordered answer - ✅ Prepared statements - Parse a query with
$slotparameters once, then run it with different values - ✅ Run inside your application - See supported platforms
- ✅ Zero configuration - Open a local database with
Minigraf::open("data.graph"); no database server or config file is needed
For example, (lag ?salary :over (:partition-by ?dept :order-by ?hire-date)) reads the preceding employee's salary within each department; the first row gets nil. lead reads the following row.
What's new in v3
- Format v8 fixes same-transaction multi-valued facts, adds covering indexes and crash-atomic checkpoints, and automatically upgrades v2.x files.
- Streaming queries and large transactions process data in batches, with configurable memory limits for queries.
- More query options: ordering and pagination, explicit
:distinct, set values and membership predicates, ordinaryavg,lag/lead, and sliding row windows. - Expanded APIs: query cursors, fact logs, bounded incoming-reference lookup, and prepared queries and user functions across bindings.
- Browser storage: OPFS in a dedicated worker, alongside IndexedDB, with explicit write transactions in both modes.
See the CHANGELOG for breaking changes, fixes and performance improvements. Back up v2.x databases before upgrading; follow the upgrade guide.
Why Datalog?
With Datalog, you can describe how to follow a link once and let a recursive rule repeat that step. In the Quick Start, the two reachable rules find friends by following one or more :friend links.
A fact can link two entities, as in [:alice :friend :bob], or store a value on one entity, as in [:alice :person/name "Alice"]. The Quick Start below inserts both facts with transact. Queries can match either kind of fact and filter the results by valid time or transaction time.
Installation
3.0.0-alpha is a prerelease. v2.x users should keep minigraf = "2" until 3.0.0 final.
[dependencies]
minigraf = "3.0.0-alpha"
Or via cargo:
cargo add [email protected]
Requires Rust 1.89 or newer (the minimum supported Rust version, set in Cargo.toml).
Known issues
v3.0.0 prereleases
Open issues are tracked in the core v3.0.0 milestone. Binding-specific issues use the v3.0.0 milestone in each binding repository. Fixes arrive in the next prerelease; earlier prereleases do not receive patches.
v2.x
The pinned v2.x known issues list records affected versions, workarounds and fixes. In particular, two values of one entity's attribute written in a single transact (or retracted in a single retract) can read back as one value (#371). Write or retract each value in its own call. v3 fixes this with format v8.
v2.x gets all bug fixes, including data-integrity and security fixes, but no new features, until 12 months after v3.0.0 final ships. Prereleases do not start that clock. See the support policy.
Quick Start
use minigraf::{FactFilter, LogWriter, Minigraf, OpenOptions};
// Open or create a file-backed database
let db = OpenOptions::new().path("myapp.graph").open()?;
// Add facts
db.execute(r#"(transact [[:alice :person/name "Alice"]
[:alice :person/age 30]
[:alice :friend :bob]
[:bob :person/name "Bob"]])"#)?;
// Query with Datalog
let results = db.execute(r#"
(query [:find ?friend-name
:where [:alice :friend ?friend]
[?friend :person/name ?friend-name]])
"#)?;
// Cursor — read a large answer in batches; the answer is fixed at open
let mut cursor = db.query("(query [:find ?name :where [?e :person/name ?name]])")?;
while let Some(batch) = cursor.next_batch(1000)? {
for row in batch.rows() { /* row[0] is ?name */ }
}
// Fact log — every assertion and retraction, in transaction order, without Datalog
let mut log = db.fact_log(&FactFilter::new().attribute_prefix(":person/"))?;
while let Some(batch) = log.next_batch(1000)? {
for rec in batch { /* rec.tx_count, rec.entity, rec.attribute, rec.value, rec.asserted */ }
}
// Read-only open — for backups and offline tools. Read-only handles share a file;
// a read-write handle (like `db` on myapp.graph) excludes them.
let archive = Minigraf::open_with_options("archive.graph", OpenOptions::new().read_only(true))?;
// Log writer — copy records into a new file with their transactions and valid-time
// windows kept; leave records out to purge them
let mut out = LogWriter::create("archive-clean.graph", OpenOptions::new())?;
for rec in archive.fact_log(&FactFilter::new())? {
let rec = rec?;
if rec.attribute != ":person/ssn" { out.append(&rec)?; }
}
out.advance_tx_count(archive.current_tx_count())?;
out.finish()?;
// Explicit transaction — all-or-nothing
let mut tx = db.begin_write()?;
tx.execute(r#"(transact [[:alice :person/age 31]])"#)?;
tx.commit()?;
// v3: bounded incoming scalar Ref links, including future/expired assertions.
// Require Complete before staging a cascading delete; Exhausted has no links.
use minigraf::{IncomingRefLimits, IncomingRefs};
let mut tx = db.begin_write()?;
let target = minigraf::EntityId::nil();
match tx.incoming_refs(target, IncomingRefLimits::new(100, 10_000))? {
IncomingRefs::Complete { links, .. } => { /* inspect every link before deleting */ }
IncomingRefs::Exhausted { budget, .. } => { /* retry or abandon the delete */ }
_ => { /* future outcomes */ }
}
tx.rollback();
// Owned transaction — Send + 'static, so it can live in an object or move to
// another thread; every language binding's transaction is one
let mut tx = db.begin_write_owned()?;
tx.execute(r#"(transact [[:alice :person/age 32]])"#)?;
std::thread::spawn(move || tx.commit()).join().unwrap()?;
// Time travel — query as of past transaction counter
db.execute("(query [:find ?age :as-of 1 :where [:alice :person/age ?age]])")?;
// Recursive rule — register each clause with a separate execute() call
db.execute("(rule [(reachable ?a ?b) [?a :friend ?b]])")?;
db.execute("(rule [(reachable ?a ?b) [?a :friend ?m] (reachable ?m ?b)])")?;
db.execute("(query [:find ?friend :where (reachable :alice ?friend)])")?;
// Parse once, then execute with different bind values
use minigraf::{BindValue, EntityId};
// Keywords map to UUIDv5 IDs in the OID namespace, including the leading colon.
let alice_id = EntityId::new_v5(&EntityId::NAMESPACE_OID, b":alice");
let bob_id = EntityId::new_v5(&EntityId::NAMESPACE_OID, b":bob");
let pq = db.prepare("(query [:find ?name :as-of $tx :where [$entity :person/name ?name]])")?;
let r1 = pq.execute(&[("tx", BindValue::TxCount(1)), ("entity", BindValue::Entity(alice_id))])?;
let r2 = pq.execute(&[("tx", BindValue::TxCount(2)), ("entity", BindValue::Entity(bob_id))])?;
cargo run # interactive Datalog REPL
cargo test # run the test suite
cargo run < demos/demo_recursive.txt # recursive rules demo
Storage key encoding and scalar decoding have Kani proofs; see test coverage for their scope and how to run them.
Queries without aggregates return one row per matching binding, including repeated :find tuples.
Add the bare :distinct flag to remove repeated
output tuples: (query [:find ?name :where [?e :person/name ?name] :distinct]).
It runs after aggregates and windows, before ordering and pagination (#493).
Demo
See a working implementation of temporal reasoning with Minigraf at github.com/project-minigraf/temporal_reasoning — an AI agent that uses Minigraf's bi-temporal model to store, correct, and audit beliefs.
The time travel visualizer runs Minigraf in your browser and draws its history. Step through transactions, move the valid-time cursor, and see each fact version on a bitemporal map. It opens .graph files too. For example, see a salary that was recorded wrong and then corrected.
See the Datalog Reference for the complete syntax.
Why Minigraf?
Here is how Minigraf compares with a few other databases:
| Feature | Minigraf | XTDB | Cozo | Neo4j | SQLite |
|---|---|---|---|---|---|
| Query Language | Datalog | Datalog | Datalog | Cypher | SQL |
| Single File | ✅ Yes | ❌ No | ❌ No | ❌ No | ✅ Yes |
| Bi-temporal | ✅ Yes | ✅ Yes | ⚠️ Time travel | ❌ No | ❌ No |
| Embedded | ✅ Yes | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes |
| Rust | ✅ Yes | ❌ Clojure | ✅ Yes | ❌ Java | ❌ C |
| WebAssembly support | ✅ Yes (browser + WASI) | ❌ No | ⚠️ Limited | ❌ No | ✅ Yes |
Platform support
| Platform | Tier | Package | Install |
|---|---|---|---|
| Rust (native) | 1 | minigraf on crates.io |
cargo add [email protected] |
| Python | 1 | minigraf on PyPI |
pip install --pre minigraf==3.0.0a0 |
| Browser WASM | 1 (from v3.0.0) | @minigraf/browser on npm |
npm install @minigraf/browser@next |
| WASI | 2 (experimental) | @minigraf/wasi on npm |
npm install @minigraf/wasi@next |
| Node.js | 2 (experimental) | minigraf on npm |
npm install minigraf@next |
| Java/JVM | 2 (experimental) | io.github.project-minigraf:minigraf-jvm on Maven Central |
see docs |
| Android | 2 (experimental) | io.github.project-minigraf:minigraf-android (.aar) on Maven Central |
see docs |
| iOS / macOS | 2 (experimental) | .xcframework via Swift Package Manager (minigraf-swift) |
see docs |
| C / FFI | 2 (experimental) | header + tarball on minigraf-c releases | see docs |
All bindings, including Tier 2, publish for each core release. Their versions match the core version, using each package registry’s version spelling for prereleases. A binding that cannot publish blocks the release. Tier 1 bindings are fully tested. Tier 2 bindings are experimental, built and smoke-tested in their own repos. The Rust crate and Python are Tier 1; browser WASM joins them from v3.0.0. A binding moves to Tier 1 when real users need it, including the project's own published tools. Tier 1 operating systems and filesystems are Linux (ext4, xfs), macOS (APFS) and Windows (NTFS) on local disk; NFSv4 is supported with caveats, and NFSv3 nolock is unsupported for multiple writers. Details: support tiers.
Language Bindings
| Language | Package | Repo |
|---|---|---|
| Python | minigraf on PyPI |
minigraf-python |
| Node.js | minigraf on npm |
minigraf-node |
| Browser WASM | @minigraf/browser on npm |
minigraf-wasm |
| WASI | @minigraf/wasi on npm |
minigraf-wasm |
| Java | io.github.project-minigraf:minigraf-jvm on Maven Central |
minigraf-java |
| Android | io.github.project-minigraf:minigraf-android on Maven Central |
minigraf-android |
| iOS/macOS | Swift bindings | minigraf-swift |
| C | C bindings | minigraf-c |
See the Comparison page for detailed analysis including temporal vs. time-series databases.
For AI Agents
Record the facts an agent uses to make a decision. If a fact is corrected later, query by transaction time to see what the database had recorded when the agent made the decision. Use valid time to choose the time those facts describe.
If you use a vector store to find similar items, use Minigraf to store facts about those items and query how they are connected.
See it in the visualizer: what an agent believed when it made a recommendation, and the correction that followed (press → to step forward).
For Mobile Apps
Offline-first storage with retroactive corrections — the bi-temporal model lets you correct a mis-entered value while preserving the original record (see a correction in the visualizer). Native Kotlin and Swift bindings ship as an Android .aar (Maven Central) and an iOS .xcframework (Swift Package Manager) via UniFFI. No Rust required.
// Android (Kotlin)
val db = MiniGrafDb.open(context.filesDir.absolutePath + "/myapp.graph")
db.execute("""(transact [[:alice :person/name "Alice"] [:alice :person/age 30]])""")
val json = db.execute("(query [:find ?name :where [?e :person/name ?name]])")
// iOS (Swift)
let db = try MiniGrafDb.open(path: docsURL.appendingPathComponent("myapp.graph").path)
try db.execute(datalog: #"(transact [[:alice :person/name "Alice"] [:alice :person/age 30]])"#)
let json = try db.execute(datalog: "(query [:find ?name :where [?e :person/name ?name]])")
See the Mobile Integration section for full setup and usage docs (Gradle config, SPM integration, error handling, threading).
For WASM / Browser
Published as @minigraf/browser on npm (wasm-pack). BrowserDb.open(name) uses IndexedDB on the main thread or in a worker. From v3.0.0, await BrowserDb.openOpfs(name) uses one <name>.graph file in OPFS, in a dedicated worker on HTTPS or localhost, with a 256-page cache instead of a whole-file memory buffer. OPFS starts at Tier 2 inside the Tier 1 browser binding; the modes have separate namespaces and never fall back to each other. close() is synchronous and releases the database and its lock in every mode. See the complete module-worker example and browser durability contract. BrowserDb.beginWrite() opens a write transaction (from v3.0.0): execute stages and reads back, await tx.commit() stores it in IndexedDB or flushes it to OPFS, rollback() discards it, and the database's other calls throw [INT-001] until it ends. tx.incomingRefs(target, maxLinks, maxRecords) synchronously returns {status: 'complete', links, recordsExamined} or {status: 'exhausted', budget: 'links' | 'records', recordsExamined} without partial links. Both budgets are integer JS numbers in 0..=4294967295; invalid inputs throw [API-017], finished/closed handles [API-018], and callback reentry [INT-001]. It includes earlier staged statements and only scalar Ref values (not Keywords, strings or sets), ignoring valid time. Require complete before deleting; retry or abandon on exhausted, which leaves earlier writes staged. The WASI package is the REPL: each command commits on its own, with no explicit transactions or incoming-reference lookup. The WASI REPL (wasm32-wasip1) runs in memory; install @minigraf/wasi from npm or build it from source for a WASI runtime such as Wasmtime or Wasmer. See the Use Cases. The playground and the time travel visualizer are both built on @minigraf/browser.
For Python / Node.js / Java / C
Language bindings ship as minigraf on PyPI, minigraf on npm (Node.js native addon), io.github.project-minigraf:minigraf-jvm on Maven Central, and a C header + prebuilt shared library on GitHub Releases. See the Use Cases.
Scope
Minigraf runs as:
- ✅ An embedded library
- ✅ A standalone binary (interactive REPL)
- ✅ Browser WASM —
@minigraf/browser(IndexedDB or OPFS in a dedicated worker,wasm-pack; OPFS starts at Tier 2 in v3.0.0) - ✅ Server-side WASM —
wasm32-wasip1/ WASI (Wasmtime, Wasmer, Cloudflare Workers) - ✅ Android, iOS, Python, Node.js, Java, C — via UniFFI / napi-rs / cbindgen
Minigraf will not be (by design):
- Distributed — no clustering, no sharding, no replication; each agent instance owns its own
.graphfile - Client-server — no network protocol in core
- Billion-node scale — optimised for <1M nodes (like SQLite)
- A time-series database — Minigraf is a temporal database; see Comparison
Roadmap
See ROADMAP.md for planned work and current direction.
Performance
Performance measurements for the v3.0.0-alpha release (format v8), refreshed on 2026-11-30 at bcd74572b with Rust 1.99.1, up to 10M facts on an otherwise idle dedicated benchmark server pinned to one NUMA node (see BENCHMARKS.md for every shape, RSS and the method):
| Workload | 100K facts | 1M facts | 10M facts |
|---|---|---|---|
Point lookup (bound entity + attribute, incl. :as-of / :valid-at), p50 / p99 |
20–23 µs / 30–34 µs | 17–19 µs / 32–34 µs | 17–19 µs / 32–35 µs |
| Entity with 1,000 versions, p50 / p99 | 0.24 / 0.28–0.29 ms | 0.22 / 0.24–0.25 ms | 0.22 / 0.25 ms |
| Open a file (RSS after open: 3 MiB) | 0.144 ms | 0.255 ms | 0.409 ms |
| Checkpoint after 1 new fact, p50 / p99 | 0.712 / 1.22 ms | 0.942 / 1.97 ms | 1.09 / 3.30 ms |
| Attribute scan (N/6 rows) drained in batches of 1,000, p50 | 10.79 ms | 0.117 s | 1.18 s |
| Selective 2-clause join (1 row), p50 | 43 µs | 34 µs | 35 µs |
| Rule query with a constant (magic sets, 5–7 rows), p50 | 1.07 ms | 1.35 ms | 1.81 ms |
The table above is the #942 alpha snapshot. Changes since the previous snapshot compares it with #551 and the later partial #530 measurements, including the slower file open and tail latencies at 10M.
Point lookups, time travel on one entity, and joins and rule queries that a constant makes selective stay flat at every tested size. Queries that read a whole attribute (scans, aggregates, joins with nothing selective) grow linearly with the facts they read, in bounded memory: the 1.67M-row scan at 10M facts holds one batch, 7 MiB. Windows and whole transitive closures hold their rows, and OpenOptions::query_memory_limit stops a query that passes it with QRY-012. Graphs over 10M facts are not tested.
File-backed databases limit string values to 4,068 bytes (WAL-003). In-memory databases have no limit.
Durability tuning: every write is fsync'd immediately by default (SyncMode::Full). Bulk loaders/migrations that can safely re-run from a checkpoint watermark on failure can trade that for throughput with OpenOptions::new().synchronous(SyncMode::Normal), or for one transaction with db.begin_write_with(TxOptions::new().synchronous(SyncMode::Normal)) on an otherwise Full database — checkpoint() still fsyncs unconditionally in both modes, and a later Full commit also makes earlier Normal ones durable. See the Performance Tuning for the full tradeoff and the write-batching pattern that pairs with it.
Configuration: docs/CONFIGURATION.md lists every OpenOptions setting, which ones query text can override, and how OpenOptions::allow_overrides lets the embedder refuse those keywords (API-025, #869).
Running Minigraf where data loss matters: docs/DURABILITY.md covers what survives a process crash and a power loss, recovery on open, supported filesystems and containers, backups and restores, verify() and rebuild_indexes(), upgrading from v2.x, and which errors mean retry, reopen or restore.
Contributing
This is a solo-maintained project with a long-term vision. Read PHILOSOPHY.md and ROADMAP.md before proposing features.
See CONTRIBUTING.md for development setup, code standards, and the PR process.
The deterministic storage schedule suite (#760) documents the native/MSRV CI checks, replay commands and coverage limits.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
Ähnliche Projekte entdecken
Wird geladen…