Minigraf
v3.0.0 (unreleased)

Architecture

On this page

Module Structure#

Added in v3.0.0

Ordinary and window aggregates share exact numeric summation and the total value comparator. Ordinary sum/sum-distinct skip nonnumbers, and min/max compare every non-nil type. Distinct sum filters before retaining and charging members; count-distinct retains all non-nil types. Ordered grouping admits count/count-distinct/sum/avg, fixed-scalar extrema and Integer/nil distinct sums when the grouping and argument proofs below succeed.

src/
├── main.rs                     — binary entry point (interactive REPL)
├── lib.rs                      — public API exports
├── db.rs                       — public embedded API: Minigraf, OpenOptions (incl. read_only), WriteTransaction, OwnedWriteTransaction, IntegrityReport; execute / query / fact_log / prepare / begin_write / begin_write_owned / checkpoint / verify / rebuild_indexes; register_aggregate / register_predicate and their fallible try_ forms (UdfError, QRY-014) for UDFs
├── cursor.rs                   — Cursor / Batch: owned, Send cursor returned by Minigraf::query and PreparedQuery::query
├── fact_log.rs                 — FactLog / FactFilter / FactRecord / FactOrder: every fact version, streamed without Datalog
├── log_writer.rs               — LogWriter: builds a new file from FactRecords, keeping their tx and valid time
├── repl.rs                     — interactive Datalog REPL console
├── temporal.rs                 — UTC timestamp parsing (avoids chrono CVE GHSA-wcg3-cvx6-7396)
├── wal.rs                      — write-ahead log (version 2 header with base generation), CRC32 entries; not built for wasm32
├── error.rs                    — structured error codes: MinigrafError, ErrorCategory, ErrorCode registry (PRS/QRY/STG/WAL/API/INT); matches docs/ERROR_REFERENCE.md
├── browser/                    — browser WASM backend (`browser` feature)
│   ├── buffer.rs               — BrowserBufferBackend: in-memory pages with dirty-page tracking
│   ├── indexeddb.rs            — IndexedDB persistence on main thread and workers
│   ├── backend.rs              — buffer/OPFS backend dispatch
│   └── opfs.rs                 — dedicated-worker sync access handle; one .graph file and a 256-page cache
├── graph/
│   ├── types.rs                — Fact, Value, EntityId, Attribute, VALID_TIME_FOREVER
│   └── storage.rs              — FactStorage: in-memory EAV store with temporal query methods
├── query/datalog/              — parser, executor (transact/retract/rule commands; opens every query on the engine), matcher (EDN → value), evaluator (rule limits), aggregate (accumulators and window values the engine uses), stratification, rules, functions, optimizer, prepared, magic_sets, types; the optimizer reorders on every build, the `wasm` feature is a deprecated no-op
├── query/engine/               — streaming query engine, which runs every query: plan (the operator tree of a query), scan (one pattern over key ranges), join (index nested-loop and hash joins), filter (expressions, pseudo-attributes), anti (`not` / `not-join`, hashed or per row from a seed), union and distinct (`or` / `or-join`, plus optional `:distinct` final tuples after aggregates/windows and before sorting/pagination), aggregate, window, relation and recursive (rules), meter (query memory), project (ids → values using bounded UUID batch hints), cells, batches and ids
└── storage/
    ├── mod.rs                  — StorageBackend trait, CommittedReader trait, LegacyHeaderV7 (v7 migration only)
    ├── persistent_facts.rs     — PersistentFactStorage: v8 save/load, copy-on-write checkpoint, v7 → v8 migration
    ├── meta.rs                 — meta pages A/B: the only commit point
    ├── page.rs                 — 24-byte common page header (type, count, CRC32, page id, generation), page allocator
    ├── freelist.rs             — free-list chain of reusable pages
    ├── keys.rs                 — byte-comparable keys: FDB integers, value tags, tx↓, FOREVER; pure scalar decoders with Kani proofs; MAX_VALUE_BYTES, MAX_IDENT_BYTES
    ├── node.rs                 — prefix-compressed leaves and shortest-separator internal nodes
    ├── btree.rs                — on-disk B+tree over byte keys: build_btree, cow_insert, LeafCursor (seek), prefix_scan, get
    ├── dict.rs                 — DICT tree: entity and ident ids, tx timestamps, long values; batched UUID resolution from the pinned dictionary (dense leaf walks, sparse/small exact reads); checkpoint-time Encoder
    ├── value_pages.rs          — append-only pages for strings over 64 bytes
    ├── reader.rs               — OnDiskReader: covering reads of committed facts; net-assert on index keys
    ├── verify.rs               — integrity walk for Minigraf::verify and the source choice for rebuild_indexes
    ├── index.rs                — in-memory keys of the pending (uncheckpointed) EAVT/AEVT indexes
    ├── cache.rs                — LRU page cache: approximate-LRU, read-lock on hits
    ├── dir_sync.rs             — fsyncs the parent directory after creating or deleting a file
    ├── packed_pages.rs         — v7 fact pages, read only to migrate a v7 file
    └── backend/
        ├── file.rs             — FileBackend: single .graph file, cross-platform
        ├── memory.rs           — MemoryBackend: in-memory backend for testing
        └── fault_inject.rs     — FaultInjectingBackend: injects I/O errors for durability tests (test builds only)

The format-v8 scalar key decoders have Kani round-trip and bounded malformed-input proofs (#693). Differential tests compare their results, errors and cursor positions with the earlier reader, including string and set escape paths.

Added in v3.0.0

BrowserDb.openOpfs(name) uses the v8 copy-on-write commit directly on OPFS, without a WAL. close() releases its exclusive handle and invalidates dependents in every mode. Database <name> maps exactly to <name>.graph; its staging file <name>.graph-import cannot be addressed by any database name. Import admits an empty blob; a nonempty v8 image with a selectable meta and complete, verified contents (including an empty v8 image); or a supported v7 image that migrates completely. It stages a verified image before replacing anything, then publishes and copies it with old-or-new recovery. OPFS alone accepts a sole valid meta despite newer data pages; native STG-033 recovery is unchanged. See the browser durability contract.

Language bindings (separate repositories)#

The bindings moved out of this repository in #231. Each one has its own repository and release pipeline, and is rebuilt when a new minigraf crate is published.

RepositoryContents
minigraf-pythonUniFFI bindings, minigraf on PyPI
minigraf-javaUniFFI bindings, io.github.project-minigraf:minigraf-jvm on Maven Central
minigraf-androidUniFFI bindings, io.github.project-minigraf:minigraf-android on Maven Central
minigraf-swiftUniFFI bindings, MinigrafKit xcframework via Swift Package Manager
minigraf-nodenapi-rs bindings, minigraf on npm
minigraf-wasm@minigraf/browser and @minigraf/wasi on npm
minigraf-cC FFI (cdylib + staticlib, minigraf.h via cbindgen)

Data Model#

The unit of storage is a Fact — an Entity-Attribute-Value triple extended with bi-temporal metadata:

struct Fact {
    entity:    EntityId,   // Uuid
    attribute: Attribute,  // String, e.g. ":person/name"
    value:     Value,
    tx_id:     TxId,       // Uuid — transaction that asserted this fact
    tx_count:  u64,        // monotonic transaction counter (used for :as-of queries)
    valid_from: i64,       // Unix ms — when fact became valid in the real world
    valid_to:   i64,       // Unix ms — i64::MAX = open-ended (valid forever)
    asserted:  bool,       // true = assert, false = retract
}

enum Value {
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Ref(Uuid),        // reference to another entity
    Keyword(String),  // e.g. ":status/active"
    Null,
}
Added in v3.0.0

From v3.0.0 Value is #[non_exhaustive] and has an eighth variant, Set(ValueSet): a finite set of the scalar values above, never of sets, kept in Value's order with duplicates removed (#{...} in Datalog). A match on Value outside the crate needs a wildcard arm.

VALID_TIME_FOREVER = i64::MAX is the sentinel for open-ended valid time.


Storage Architecture#

Layered design#

┌─────────────────────────────────────┐
│  Minigraf / WriteTransaction (db.rs)│  ← public API
├─────────────────────────────────────┤
│  FactStorage (graph/storage.rs)     │  ← in-memory EAV + index-driven scans
│  PersistentFactStorage              │  ← persistence layer
├─────────────────────────────────────┤
│  PageCache (storage/cache.rs)       │  ← LRU page cache (default 256 pages = 1MB)
├─────────────────────────────────────┤
│  StorageBackend trait               │  ← platform-agnostic page I/O
│  FileBackend / MemoryBackend        │
└─────────────────────────────────────┘
       ↕ WAL sidecar (wal.rs)
Added in v3.0.0

Pending (uncheckpointed) facts live in memory, indexed by entity and by attribute. Committed facts live only in the on-disk covering indexes: every index entry is a whole fact, so a read touches index leaves, the dictionary pages that translate its ids, and a value page for a long string, all through the LRU cache (OnDiskReader, through the CommittedReader trait). Nothing is loaded at startup, and memory is O(cache pages), not O(facts).

Covering indexes#

Four Datomic-style covering indexes are maintained for each committed fact:

IndexSort orderBest for
EAVTentity → attribute → value → txentity lookups
AEVTattribute → entity → value → txattribute scans
AVETattribute → value → entity → txvalue equality lookups
VAETvalue → attribute → entity → txreverse ref lookups
Added in v3.0.0

Each index entry is the whole fact, as a byte-comparable key, so a query never reads a separate fact page. See File format (v8) for the key layout. Two values of one attribute written in the same transaction are separate keys, and an assertion and a retraction of the same value in one transaction stay apart.


Added in v3.0.0

File Format (v8)#

The .graph file is page-based (4KB pages), endian-safe, cross-platform. The design is in docs/superpowers/specs/2026-10-05-v8-storage-format-design.md (#374, #434, #388, #433).

Layout.

Page 0, 1   Meta pages A and B. Odd generations commit to page 0, even to page 1.
            magic "MGRF"/"META", version 8, CRC32 over the whole page, generation,
            page_count, fact_count, last_checkpointed_tx_count, five tree roots
            (EAVT, AEVT, AVET, VAET, DICT), free-list head and count, next_eid,
            next_iid, required_features. The only commit point.
Page 2+     Any mix of B+tree leaves (0x61) and internal nodes (0x62), value
            pages (0x51) and free-list pages (0x81). Each starts with a 24-byte
            header: type, count, CRC32, its own page id, the generation that
            wrote it. Every read checks all four.
Sidecar     <db>.wal, version 2: the header records the base generation.

Covering keys. Every index entry is a whole fact, encoded so that comparing bytes gives the logical order:

TreeKey
EAVTe a v tx↓ vf vt op
AEVTa e v tx↓ vf vt op
AVETa v e tx↓ vf vt op
VAETv a e tx↓ vf vt op (ref values only)
DICTUUID ↔ entity id, ident ↔ ident id, tx_count → tx_id, long-value dedup
  • Entities and idents (attribute names and keyword values) are sequential ids from the DICT tree, assigned at checkpoint. The query layer still sees UUIDs and strings.
  • Integers use the FoundationDB tuple encoding; tx↓ is the complemented tx_count, so the newest transaction comes first; vt = FOREVER is one byte.
  • Strings over 64 bytes are stored once (deduplicated) in value pages; the key holds a 32-byte prefix, a hash and a reference.
  • A set has value tag 0x08, after refs. Its key bytes are its elements' own key encodings, sorted: up to 64 bytes inline in the key, longer stored once in a value page as a long string is.
  • Leaves are prefix-compressed with restart points; internal nodes hold shortest separators. There are no leaf sibling pointers: scans use a cursor with a parent stack and a forward seek.
  • A query reads only index leaves, the DICT pages that translate its ids, and a value page for a long string. Committed results come back in id order.

Checkpoints are copy-on-write.

  • A checkpoint writes only:
    • new value pages;
    • the touched leaves and their paths to the root, in each of the five trees;
    • a few free-list pages;
    • the other meta page.
  • Pages freed by one checkpoint are reused by later ones. The free list is read only as far as it is needed, and new pages are pushed onto its head.
  • A crash or torn write at any point leaves the previous checkpoint intact. Open never rebuilds an index.
  • Cost follows the change:
Checkpoint10k facts100k facts1M facts
after 1 new fact3.0 ms3.3 ms6.1 ms

One new fact at 100k facts writes 16 pages.

Density. About 142 bytes per fact, history included, at 1.15M facts in #433's shape (about 10 attributes per entity, 20 % multi-valued, 10 % retracted and re-asserted). v7 used about 2 KB per fact as measured.

Integrity.

  • A damaged page fails the read or checkpoint that reaches it, with STG-029 (CRC), STG-030 (page id) or STG-031 (generation). It never returns wrong or fewer rows.
  • If the newest meta page is damaged after its WAL is gone, open fails with STG-033 rather than silently opening an older generation.
  • Unknown required_features bits fail with STG-034.
  • A file shorter than its meta page's page_count, such as an interrupted copy or a partial download, fails at open with STG-044, read-write and read-only, and is not modified. Open does not fall back to the other meta page: a valid newer meta means that checkpoint happened. verify() reports a page_count past the end of the file as STG-044 too.

Limits. String values up to 4,068 bytes; attribute names and keyword values up to 1,024 bytes; set values up to 4,068 bytes, counting each keyword element as 6 bytes and each ref as 10 (WAL-003).

Migration.

  • v7 files (v2.x) upgrade automatically, one way, on first open.
  • The upgrade is crash-safe, with a backup meta page. Old pages become free pages that later checkpoints reuse.
  • A v7 fact page whose type byte is damaged fails the upgrade with STG-014, and the file is left as v7. v7 fact pages have no checksum, so other damage inside a page is not always caught: keep a copy of a v7 file until it has opened under v3.
  • v1–v6 fail with STG-028: open them once with v2.x first.
  • Development builds of v3.0.0 from before this format fail with STG-032.

Checking a file. Minigraf::verify() walks every committed page and reports logical damage that page checksums cannot see: indexes that disagree (STG-038), keys out of order or a page reached twice (STG-039), dictionary maps that disagree (STG-040), and leaked or doubly used pages (STG-035). Minigraf::rebuild_indexes() rebuilds the four indexes from an intact one and commits like a checkpoint; if none can serve as the source it fails with STG-041 and writes nothing.

Added in v2.0.5

Short files. A file of 1 to 4,095 bytes holds no whole page. It opens as a new database only when its bytes are zeros or a prefix of what a new database writes first, which is what a crash during creation can leave. Anything else, such as a database cut short by an interrupted copy or an unrelated file at the path, fails with STG-045, read-write and read-only, and the file is not modified. A zero-length file is a new database (#506).


WAL (Write-Ahead Log)#

The WAL sidecar (<db>.wal) is present whenever there are uncommitted writes. It is replayed on open and deleted on checkpoint.

Added in v2.0.5

checkpoint() also removes a WAL whose entries are all in the file already, which a crash between a checkpoint's commit and its WAL delete leaves (#457). A handle opened with wal_checkpoint_threshold(usize::MAX) does not checkpoint at close: the WAL keeps its pending facts and the next open replays them (#476).

Added in v3.0.0
WAL file layout:
  Header (32 bytes): magic "MWAL", version u32 (2),
                     base_generation u64 (the meta generation the WAL extends), 16 reserved bytes
  Entries (repeated):
    checksum u32     — CRC32 of the rest of the entry
    tx_count u64     — transaction counter
    num_facts u64    — number of facts in this entry
    [ len u32 | postcard-bytes ]×num_facts

On open, the WAL is replayed only on top of the generation it was written against. A version 1 WAL from v2.x next to a file migrated from v7 is still replayed.

A WAL created after a later checkpoint than the file holds, as when a backup of the .graph is restored and the current WAL is left in place, fails at open with STG-047, read-write and read-only, and both files are left unmodified. Replaying it would apply the later transactions and silently miss the ones between the two checkpoints. A WAL with an older base generation, left by a crash between a checkpoint's commit and its WAL delete, replays as before.

Large transactions. transact and retract are read one fact at a time, so a statement's size never multiplies in memory while it is parsed. A transaction becomes large on a file database when its facts would pass one chunk (OpenOptions::transaction_chunk_facts, default 65,536 facts; smaller values hold less memory and take longer): a larger statement passed to execute, or the WriteTransaction statement that takes its staged facts past it. From then on it holds at most one chunk of facts in memory:

  • The WAL file is created, header only, before the transaction writes its first page; the transaction never writes a WAL entry.
  • Its facts go, a chunk at a time, into copy-on-write trees that start as the committed generation's, together with the uncheckpointed facts of earlier transactions. Readers keep reading the committed generation.
  • In a WriteTransaction each statement has a base: a rejected statement returns the trees to it, and the transaction stays usable. A later statement that writes a fact an earlier statement wrote replaces it (the last statement decides each fact, as in a small transaction).
  • Commit is a checkpoint: the next meta page is the commit point, then the WAL is deleted. The transaction's tx_id is the time it became large.
  • A crash before the commit point leaves the database as it was: the WAL says which generation to open, even on a new file. A rollback leaves the file as it was too; the next checkpoint, like the first one after a WAL is found at open, writes a meta page before it deletes the WAL.

Queries inside a WriteTransaction read the committed indexes and uncheckpointed facts with the transaction's staged facts, or, once it is large, its working trees; they do not copy the database.

CRC32-protected entries ensure partial writes (from crashes) are safely discarded. Every WAL write is followed by a flush to disk, controlled by OpenOptions::synchronous (see Performance Tuning):

  • SyncMode::Full (default) — fdatasync after every entry. Matches Minigraf's original always-fsync behavior; every committed transact/retract is durable immediately.
  • SyncMode::Normal — no per-write flush. Entries are still write_all()'d (safe across an ordinary process crash) but not forced to disk until the next checkpoint (auto-threshold, explicit checkpoint(), or clean close). Data written since the last checkpoint is lost only on OS crash or power loss, not process death. Intended for bulk loaders that can safely re-run from a checkpoint watermark.

checkpoint() itself always fsyncs the main .graph file regardless of synchronous — it remains the hard durability boundary in both modes.

Added in v3.0.0

The WAL writer keeps no mode: each entry is appended with its transaction's, which is OpenOptions::synchronous unless a WriteTransaction was begun with begin_write_with(TxOptions::new().synchronous(..)). One WAL can therefore hold synced and unsynced entries; a Full append syncs the whole file, earlier Normal entries included. A large transaction's WAL guard header is always synced.

Added in v2.0.5

Opening a database for writing cuts the WAL back to the end of its last valid entry, and syncs it, before anything is appended, so a new entry always lands where replay reaches it. After a failed WAL write or sync, later writes through that handle fail with WAL-007 until the database is reopened or a checkpoint() succeeds. The transaction whose write failed is not applied; after a reopen it is there in full or not at all.

Added in v3.0.0

A checkpoint that fails after it may have written (a failed write, a full disk, a failed fsync) is never retried on the same handle: after a failed fsync the kernel may have dropped the written pages, and the checkpoint's meta page may have reached the disk anyway. Every later write, checkpoint and index rebuild through the handle fails with STG-046, queries keep working, and the close-time checkpoint is skipped. Reopening recovers every committed transaction from the WAL.


Query Execution Pipeline#

  1. Parse — EDN string → DatalogQuery; not / not-join / Expr clauses safety-checked at this stage; regex patterns in matches? validated at parse time
  2. Plan — optimizer.rs selects an index hint and reorders join clauses by selectivity; Expr clauses are passed through unchanged (not reordered — ordering guaranteed by safety check)
Added in v3.0.0
  1. Execute — the streaming engine (below) runs the query: one tree of operators reading the covering indexes, with :as-of, net-assert (decided on the index keys, before any fact is decoded) and valid time applied while reading. The latest assertion's window is a fact's only current valid-time window; earlier windows stay visible through :as-of (#435). Rules are evaluated by the same engine. The executor's own query path is gone (#551).
Added in v3.0.0

Streaming engine#

Every query runs on a streaming engine (query/engine/): patterns, expression clauses, not / not-join, or / or-join and rule invocations in :where, plain variables, aggregates and window functions in :find. The executor's query path, its pattern matcher and its rule evaluators are gone (#551). Queries inside a WriteTransaction run on the engine too.

  • Plan. Clauses run in the optimizer's order. The first pattern's constant and bound positions choose the index range: EAVT for a known entity, AVET for an attribute and value ([?e :person/name "Alice"] reads only the entries for "Alice"), AEVT for an attribute alone.
  • Expressions. = and != resolve literal keywords to their entity UUIDs when their filter or binding operator is built, then reuse those resolutions across rows and rewinds. This includes nested expressions, rule bodies and substituted prepared slots. The cache contains only literals from that expression; dynamic row values never enlarge it. Keyword/ref equivalence and the types of returned values are unchanged (#774).
  • Joins. Each later pattern is an IndexNestedLoopJoin when its entity is a variable already bound (one entity's range per row, committed and uncheckpointed), or, with a constant attribute, when its value is (per row, the AVET ranges of the values that join-equal it and the uncheckpointed facts with those values, read once per query; a value that is an entity finds the keyword naming it only where the query made the entity from that keyword, and otherwise the join is a HashJoin). Any other join is a HashJoin (on the attribute position, or a cross product), whose table holds the side with the smaller estimate; for a cross product the outer side's estimate is the product of its patterns', so a chain of patterns that share no variable keeps each small inner pattern in the table, not the growing outer side. Join keys follow the join rules.
  • Pseudo-attributes. The parser names each per-fact pseudo-attribute's source pattern (pseudo-attributes); the source's scan or join fills a metadata column (valid from/to, tx count, tx id) from the fact's key, and the pseudo-attribute pattern binds or checks against it. A :db/valid-at pattern joins with every visible fact of its entity.
  • Negation. not and not-join are an AntiJoin: it keeps the rows for which the body has no row, and never removes duplicates. A body with the same rows for every outer row (its expressions and pseudo-attributes read only variables its own patterns bind) runs once, and its rows' values of the shared variables form a hash set. Any other body, and one whose first pattern's entity comes from the outer row, runs once per row from a one-row seed of the values it shares, and stops at its first row; an entity-bound body costs one index probe per row and holds nothing. Comparisons follow the join rules.
  • Disjunction. or and or-join are a Union followed by a Distinct. Each branch is planned as a negation body is: one with the same rows for every outer row runs once, into a table of its rows keyed on the values it shares with the outer row; any other runs once per outer row from a seed. Union extends each outer row by every row of every branch (when the branches bind nothing new, an outer row is returned once, from the first branch with a row), and Distinct keeps one row of each set of equal rows. Comparisons follow the branch rules.
  • Rules. Before the query body runs, the rules it calls are evaluated stratum by stratum into relations: per predicate, the facts its rules derive, kept once each. The first round runs every rule over all facts; each later round runs a rule once per call of its own stratum in its body, that call reading only the facts the previous round derived (semi-naive evaluation), until a round derives nothing. A rule that reads its own stratum another way (in an or branch, or through a pattern such as [?x :p ?y] or [?x ?a ?v]) runs over all facts every round. Scans read a relation's facts after the stored ones, so every pattern sees derived facts, which have no metadata. The query body is then planned as any query, a rule call read as a pattern of its relation.
  • In-memory ancestor joins. An eligible positive three-pattern recursive body can start from a small derived relation and probe the stored edge attribute by entity, avoiding a whole-attribute value map. The engine reconsiders this alternative each round with a bounded pending-index count, preserving the same semi-naive ranges and head bindings. Populated committed generations keep AVET value probes. General value joins keep their existing behavior; no storage index or configuration is added (#723).
  • Scan. Reads the committed index keys of that range, deciding net-assert on the keys, then the uncheckpointed facts of the same range; a triple with uncheckpointed records is decided by them alone. :as-of and valid time are applied while reading. An :as-of time is a bound on the transaction counter when transaction times rise with the counter, and otherwise keeps the versions of the transactions at or before that time.
  • Result order. At query open, a plain query can use an AVET attribute range, or its existing EAVT entity-and-attribute range, to omit sorting when the pinned reader proves the full ascending result order. The source range must have no uncheckpointed or staged records and its attribute's committed history must have one value kind (integer, float, or Boolean). Mixed types, internal dictionary-id order, unproved tie columns, order-changing operators, user callbacks and collect-set retain the original plan. With a proved order, :offset and :limit can stop reading early.
  • Grouping. A plain query can hold one active group and bounded batches, releasing completed groups. Count/count-distinct/sum/avg qualify with a proved ordered grouping key; min/max additionally require Integer/Float/Boolean/nil arguments, and sum-distinct requires Integer/nil. Argument proofs use constants, metadata or raw attribute history from the pinned reader, including retracted/future values, and reject pending/staged data in the argument attribute. A single Integer/Boolean/Float key qualifies, including mixed numeric groups that retain final numeric sorting. A longer effective tuple must reduce to one varying Integer/Boolean slot plus repetitions and proved Integer/Boolean/nil constants. Hidden :with keys participate in this tuple; any requested final Sort is retained for :with. All-constant tuples, arbitrary payload extrema, floating distinct sums, unproved origins, callbacks, collect-set, rules and aggregate+window queries retain full-input evaluation. Distinct members within one group still grow. Small selective grouped queries pay proof startup cost. Limits count emitted groups after min/max drops; long runs of dropped groups have no bounded startup guarantee, and a retained Sort drains its child. Common result-buffer QRY-012 failures may precede later unread source failures, as for ordered counts; aggregate-specific registered finalizer errors retain full-drain behavior (#781).
  • Windows. A plain query whose built-in windows share one proved nonconstant partition key can finish and release one partition at a time, using the same evaluator for each window’s own order, peers, frames and neighbors. The committed source must prove adjacency, with no uncheckpointed/staged records in its range: entity prefixes, numeric/Boolean value prefixes, and uniform Ref/Keyword dictionary prefixes can qualify. Dictionary order proves adjacency only; it cannot replace final sorting or aggregate group order. One partition plus bounded lookahead/output batches is retained, and transient DICT lookups are evicted at internal input and result-conversion boundaries. Memory still follows the largest partition, and surrounding Sort/Distinct can require more. Unpartitioned/incompatible windows, aggregate queries, callbacks and collect-set retain full-input evaluation. A limit can avoid later input, but completing one output batch can still encounter an allocation/read error. Small selective value-partition queries pay optional proof-seek startup cost. Windows preserve their chosen input order; row order across physical plans requires final :order-by (#641).
  • Batches. Operators pass columnar batches of up to 1,024 rows of entity and ident ids; ids become values only for the rows a query returns.
  • Memory. Every operator that keeps state counts what it holds on one meter per query: a HashJoin's table, a negation's or a branch's table, Distinct's set, an aggregate's groups (including the exact-sum heap state retained by ordinary sum and avg), a window's rows, the facts the rules derive, and the query's entity and ident ids. Each entry costs an estimate for its value and retained string or set contents (including each set element and its strings), and tables grow with try_reserve. Shared payloads are counted for each entry retaining them. Over OpenOptions::query_memory_limit (off by default), or when the allocator refuses memory, the query fails with QRY-012 and frees what it held. Batches passing between operators, parsed query text and resolved expression literals are not counted.
  • Cursors. A Cursor pulls one batch from the operators when it runs out of rows. This bounds the returned batch, not all retained query state: sorts, windows, joins and recursive relations can hold more, as described above. Closing or dropping the cursor stops the work and releases its query state. A read error that happens after some rows of a next_batch call were gathered is returned by the next call. execute reads every batch at once and returns the same rows.

The engine returns the rows the executor returned, as a bag, except where a v3.0.0 change says otherwise (the CHANGELOG's breaking changes): until the executor's query path was removed, the test suite ran every query on both and compared the answers, and the answers of the suites that relied on that comparison are recorded in the repository (tests/answers/).

Rule Registration#

register_rule calls stratify() after adding each rule. If the new rule creates a negative cycle in the dependency graph, stratify() returns Err and the rule is not registered. Non-recursive negation is always safe.


File Locking#

A .graph file is guarded by a kernel file lock taken on the file itself (std::fs::File::try_lock: flock on Unix, LockFileEx on Windows). The lock is released by the kernel whenever the holding process exits, however it exits, so a crashed holder never leaves the database unopenable. Because flock and OFD locks attach to the open file description rather than the process, a second open within one process is refused too.

There is no lock file. A .graph.lock sidecar left behind by versions before 2.0 is ignored and never deleted, since a still-running old process may depend on it. Running mixed versions against one file is not supported.

On a filesystem that cannot lock at all, open() fails rather than proceeding unprotected. OpenOptions::allow_unlocked(true) overrides this, and accepts the corruption risk that comes with it.

On Windows these locks are mandatory rather than advisory, and they exclude every handle but the one holding them — including another handle in the same process. While a database is open you cannot read its .graph file through a second handle, your own included; the attempt fails with os error 33, "another process has locked a portion of the file", even when that process is you. Close the database first. On Unix the lock is advisory and such a read succeeds.

A cross-process WouldBlock is retried with bounded backoff (10 attempts, 5ms doubling, capped at 50ms, ~375ms total) before being reported as a real conflict, to ride out the transient window where a forked-but-not-yet-exec'd subprocess holds a duplicate of someone else's lock — the same class of problem SQLite's busy_timeout solves. A same-process conflict is not retried; it fails immediately, since waiting could never help.

Added in v3.0.0

Read-only opens. OpenOptions::read_only(true) takes the lock in shared mode instead. Any number of read-only handles, in this process or others, can hold the file at once; they exclude a read-write open and it excludes them (STG-025 / STG-026). Nothing done through a read-only handle writes to the .graph file or its WAL: a WAL left by an earlier session is applied in memory only, a v7 file is read into memory instead of migrated, writes fail with API-014, and a missing file is STG-042.

One handle per file, per process. A second open on a file this process already has open is refused, naming the same-process case. This matters because each FileBackend caches its own header.page_count, allocates new pages from that count, and bounds-checks read_page against it — two handles on one file give two page tables that diverge, which surfaces as Page N out of bounds (total pages: M) and, past that, structural corruption. Minigraf is cheap to clone and all clones share one database, so cloning the existing handle is always the right move (#304).


Thread Safety#

Added in v2.0.11

Calling checkpoint, prepare or PreparedQuery::execute on a thread holding a WriteTransaction returns INT-001; commit or roll back the transaction first. The transaction stays usable after the refused call (#734).

Added in v3.0.0

Minigraf::begin_write_owned / begin_write_owned_with(TxOptions) return an OwnedWriteTransaction: Send + 'static, it keeps the database open and may begin on one thread and run, commit, roll back or be dropped on another; every language binding's transaction is one (#824). The write lock is a mutex over the write context plus a flag and condition variable: while an owned transaction holds it, every other writer (writes, checkpoints, verify, rebuild_indexes, begins) waits. Queries do not take it. The calls a WriteTransaction refuses on its thread are INT-001 on the owned transaction's begin thread (recorded per database) and on the thread running one of its statements, so a user function that calls back gets INT-001.

  • Concurrent reads via Arc<RwLock<FactStorage>>
  • Exclusive write via Mutex<WriteTransaction>
  • One live handle per file per process, enforced by the kernel file lock (see File Locking above)
  • Rule registry is independently Arc<RwLock<RuleRegistry>>
Added in v3.0.0
  • Function registry: Functions, a RwLock<Arc<FunctionRegistry>> shared by every handle of a database. A query takes a snapshot (an Arc clone) when it opens and reads every function from it, so it holds no lock while a user function runs and user functions may call back into the database. Registration (register_*, try_register_*) copies the registry, inserts the function and swaps the copy in (#180)
  • Page cache uses read-lock on hits, write-lock only on misses — minimises contention for read-heavy workloads
  • BrowserDb (wasm32-unknown-unknown) runs single-threaded — all Arc/RwLock/Mutex calls compile as single-threaded stubs under the browser feature; no WASM thread support
Added in v3.0.0
  • Cursor (from query()) and FactLog (from fact_log()) are owned and Send: they borrow nothing from the handle and can move to another thread. Each reads one snapshot of the database: the committed generation, pinned, and the uncheckpointed facts at open. Checkpoints keep running while one is open, but the pages they free from a pinned generation stay off the reuse list until the last cursor or log on it is dropped, so the file grows meanwhile. Pins live only in memory: after a crash or reopen those pages are free at once.
  • PreparedQuery holds Arc clones of FactStorage, RuleRegistry, and FunctionRegistry — each execute() call re-reads live store state (new facts visible) while the query plan is reused
How this page was assembled

This page is 39 fragments. Minigraf picked them from docs.graph with this query, where the version is a point on the valid-time axis:

(query [:find ?order ?blob ?added :valid-at "2003-01-01T00:00:00Z" :where [?f :frag/page "architecture"] [?f :frag/order ?order] [?f :frag/blob ?blob] [?f :frag/added-in ?added]])

Run it in the query console