Use Minigraf in an Android app. Store data in an embedded, single-file graph database and query it with bi-temporal Datalog.
This guide uses the 3.x API. For a working 2.x dependency and imports, follow the stable guide.
Use the exact version in the snippet b 10BC8 elow once it is published in Maven Central. Until then, follow the stable guide.
dependencies {
implementation("io.github.project-minigraf:minigraf-android:3.0.0-alpha")
}Minimum SDK: 24 (Android 7.0). Supports arm64-v8a, armeabi-v7a, x86_64.
import io.github.project_minigraf.minigraf.MiniGrafDb
val db = MiniGrafDb.openInMemory()
val result = db.execute("""(transact [[:alice :name "Alice"]])""")
println(result) // {"transacted":<tx id>}In 3.x, import classes from io.github.project_minigraf.minigraf, the same
package as minigraf-jvm.
In 2.x, import from uniffi.minigraf_ffi instead.
import io.github.project_minigraf.minigraf.*
// Read-only: shared lock, nothing written; writes throw MiniGrafException (API-014).
val src = MiniGrafDb.openWithOptions(path, OpenOptions(readOnly = true, pageCacheSize = 4096))
// A cursor's answer is fixed when it opens. Each batch is a JSON array of rows,
// encoded like execute()'s "results"; null at the end.
src.query("(query [:find ?n :where [?e :name ?n]])").use { cursor ->
while (true) {
val batch = cursor.nextBatch(1000) ?: break
// parse batch
}
}
// Copy every fact version, keeping tx and valid-time bounds, into a new file.
MiniGrafLogWriter.create(newPath, OpenOptions()).use { out ->
src.factLog(FactFilter()).use { log ->
while (true) {
val records = log.nextBatch(1000) ?: break
out.appendBatch(records.filter { !it.attribute.startsWith(":secret/") })
}
}
out.advanceTxCount(src.currentTxCount())
out.finish()
} // closing without finish() abandons the build and leaves no fileUniFFI objects are AutoCloseable: close() (or use) frees the native object.
The binding also provides explicit close methods: release() for cursors and
fact logs, and abandon() for log writers. A record's value is a MiniGrafValue
(Text, Int64, Float64, Bool, Ref, Keyword, Null); a validTo of
Long.MAX_VALUE means forever. walCheckpointThreshold = Long.MAX_VALUE turns off automatic
checkpoints and the checkpoint on close. Error messages start with their code, such as [API-015].
OpenOptions(queryMemoryLimit = bytes) limits the bytes one query may hold in join build
sides, negation and or tables, distinct sets, aggregate groups, window rows, and
rule-derived facts. These operators count memory per entry. A query that exceeds
the limit frees its temporary state and throws MiniGrafException.Query with
QRY-012. The default and Long.MAX_VALUE mean no limit. Cursor output rows do
not count, so use query() to read a large answer.
Query text may override some settings with keywords such as :max-derived-facts 1000.
OpenOptions(allowOverrides = ...) lists the Overridable keywords it may use
(MAX_DERIVED_FACTS, MAX_RESULTS, QUERY_MEMORY_LIMIT, MAX_ITERATIONS). Left null,
the defaults apply: OVERRIDABLE_DEFAULTS, read from the core library (today
MAX_DERIVED_FACTS, MAX_RESULTS and MAX_ITERATIONS). A list replaces the defaults, it
does not add to them, and emptyList() refuses every keyword: a query that uses one
throws MiniGrafException.Api with [API-025] from execute, query and prepare.
val db = MiniGrafDb.openWithOptions(path, OpenOptions(
allowOverrides = OVERRIDABLE_DEFAULTS + Overridable.QUERY_MEMORY_LIMIT,
maxIterations = 10_000, // rounds per stratum of a rule query, else INT-020
transactionChunkFacts = 16_384, // facts staged before a large transaction is chunked
))maxIterations defaults to 1,000,000 and Long.MAX_VALUE is no limit;
transactionChunkFacts defaults to 65,536 and is clamped to 1..=1,000,000. A negative
count is [API-017].
db.prepare(text) parses a query once; run it with its $slots bound (names without
the $). Each run reads the database as it is then, and a prepared query keeps its
database open until both are closed.
val pq = db.prepare("(query [:find ?n :where [?e :age \$age] [?e :name ?n]])")
val thirty = pq.execute("age" to 30)
pq.query("age" to 40).use { cursor -> /* nextBatch() */ }Boolean, Byte/Short/Int/Long, Float/Double, String, null and
java.util.UUID (an entity, which also fits value slots as a ref) bind as they are.
For the other kinds pass a MiniGrafValue (Keyword, Ref, a whole-number Float64)
or a MiniGrafBindValue (Entity, TxCount or Timestamp for :as-of,
AnyValidTime for :valid-at). Any other type throws IllegalArgumentException. A
missing slot is MiniGrafException.Api with [API-022], a slot in an attribute
position [API-023], and a value of the wrong kind [API-024].
A Set binds a set value, for in? and the other set predicates or a set-valued
attribute: pq.execute("ids" to setOf(1, 2, 3)). Its elements are the plain values above
or a MiniGrafValue (MiniGrafValue.Keyword(":role/admin")), and a UUID element is a
ref. A set inside a set is MiniGrafException.Api with [API-021]; another kind of
element, or a List, throws IllegalArgumentException. Set values come back as JSON
arrays from execute and as MiniGrafValue.Set in fact records.
Errors are MiniGrafException.Parse, .Query, .Storage, .Api (a bad argument, a
closed object, an invalid query binding) or .Other.
withMaxDerivedFacts(n), withQueryMemoryLimit(bytes) and withMaxIterations(n) each
return a new prepared query with that limit; the one they are called on is unchanged.
allowOverrides does not restrict these setters. A permitted override in the
query text still takes precedence. Long.MAX_VALUE means no limit and a
negative value is [API-017]. A derived query keeps its database open, as any prepared
query does.
val reach = db.prepare("(query [:find ?x ?y :where (reach ?x ?y)])")
val small = reach.withMaxDerivedFacts(10_000).withQueryMemoryLimit(16L shl 20)
small.execute() // INT-020 or QRY-012 past a limit; reach is unchangedA predicate implements MiniGrafPredicate (test(value): Boolean) and is called in
Datalog as [(name ?v)]. An aggregate implements MiniGrafAggregate; its
accumulator() returns a new MiniGrafAccumulator (step(value), finish(count)) for
each group or window partition, and it is used as (name ?v) in :find or with
:over. Values arrive as MiniGrafValue (Int64, Text, …, with the value in
value), and finish returns one.
object Adult : MiniGrafPredicate {
override fun test(value: MiniGrafValue): Boolean = when (value) {
is MiniGrafValue.Int64 -> value.value >= 18
else -> throw MiniGrafUdfException.Failed("age is not an integer")
}
}
object Product : MiniGrafAggregate {
override fun accumulator(): MiniGrafAccumulator = object : MiniGrafAccumulator {
private var product = 1L
override fun step(value: MiniGrafValue) { product *= (value as MiniGrafValue.Int64).value }
override fun finish(count: Long): MiniGrafValue = MiniGrafValue.Int64(product) // count: values stepped
}
}
db.registerPredicate("adult?", Adult)
db.registerAggregate("product", Product)
db.execute("(query [:find ?n :where [?e :age ?a] [(adult? ?a)] [?e :name ?n]])")
db.execute("(query [:find ?g (product ?a) :where [?e :group ?g] [?e :age ?a]])")
db.execute("(query [:find ?a (product ?a :over (:order-by ?a)) :where [?e :age ?a]])")- Failures. A callback that throws stops the query with
QRY-014, raised asMiniGrafException.Query; it is never read asfalseor a missing value. ThrowMiniGrafUdfException.Failed(msg)to choose the message. Any other exception also fails the call, with its first line (class and message, such asjava.lang.IllegalArgumentException: bad) as the message. AMiniGrafValue.Reffromfinishwhose value is not a UUID is a failing call too. - Lifecycle. The database keeps a strong reference to each registered object until
the database and every cursor and prepared query opened from it are closed. There is
no unregister. Predicates and aggregates have separate names, and registering a name
twice in either is an error (
INT-040). A query sees the functions registered when it opened; a prepared query, those registered when each run starts. - Threading. A callback runs on the thread that calls
execute(of the database or a prepared query) or a cursor'snextBatch, including a prepared query's cursor. Queries on different threads may call the same object at once, so it must be thread-safe. One accumulator is used by one query on one thread at a time. Keep callbacks short: a query on the main thread blocks it for as long as they run. - Cost. Each call crosses the FFI once: one JNA call per value.
- Re-entry. A callback may query the same database, open a cursor or register another
function. Inside a write transaction, the restrictions in Write transactions
still apply and the listed calls return
INT-001.
A write transaction stages several transact, retract and query statements, with
queries seeing what it staged, and then commits them as one transaction or rolls them
back (minigraf#824). Available in the pinned, unreleased v3 core (commit
38b10383), which also provides incoming references.
val db = MiniGrafDb.open("bank.graph")
db.execute("(transact [[:alice :balance 100] [:bob :balance 50]])")
// use { } closes the transaction on exit, which rolls it back unless it was
// committed, also when an exception leaves the block.
db.beginWrite(TxOptions(chunkFacts = 10_000)).use { tx ->
tx.execute("(transact [[:alice :balance 70] [:bob :balance 80]])")
tx.execute("(retract [[:alice :balance 100] [:bob :balance 50]])")
val staged = tx.execute("(query [:find ?b :where [:alice :balance ?b]])")
if (!staged.contains("-")) tx.commit()
}-
db.beginWrite()uses the database's options;db.beginWrite(options)takesTxOptions(synchronous = ..., chunkFacts = ...). Anulloption uses the database default.synchronous(SyncMode.FULL/NORMAL) controls how this transaction syncs the WAL.chunkFactssets how many facts a file-backed transaction stages before writing in chunks. A negative value throws API-017. Read-only databases throw API-014. -
tx.execute(datalog)returns whatdb.executereturns; a staged write returns{"ok":true}. A statement that fails stages nothing and leaves the transaction open. There are no cursors or prepared queries inside a transaction. -
tx.commit()applies the staged changes as one transaction. An error can occur after the changes are applied: automatic checkpointing can fail, or WAL cleanup can fail after a large transaction commits. If the database rejects writes with STG-046 after a failed checkpoint, reopen it first. Check whether the changes were applied and retry only if they were not. Once the binding takes the transaction for commit, the transaction is finished even if commit returns an error. A call refused from inside its own statement callback does not reach that point.tx.rollback()discards staged changes in an open transaction; it does not undo an applied commit. Once the transaction is finished,execute,incomingRefsandcommitthrow API-018, androllbackdoes nothing. -
Commit is always explicit.
close()(anduse { }) frees the transaction and rolls it back unless it committed; afterclose()the object cannot be used. The garbage collector may never free an abandoned one, so do not rely on it. -
An open transaction holds the database's write lock until it finishes, so end every transaction explicitly or through
use { }. On the thread that began it, database calls (execute,query,prepare,factLog,checkpoint, anotherbeginWrite, prepared queries) fail with INT-001, and so do user functions its statements run. A callback that calls its own transaction'sexecute,incomingRefs,commit, orrollbackalso gets INT-001.On other threads, writes and attempts to begin a transaction wait until the open transaction ends. Queries still read committed data. Use the transaction on the thread that began it: if another thread uses that handle then writes directly to the database, its write waits on the same transaction.
-
Rules registered inside a transaction stay registered after a rollback.
-
The transaction keeps its database open until it is closed.
tx.incomingRefs(target: String, maxLinks: Long, maxRecords: Long): IncomingRefs
matches the API in minigraf-java: the package, method, and result types
(Complete and Exhausted) are the same.
import io.github.project_minigraf.minigraf.*
db.beginWrite().use { tx ->
when (val result = tx.incomingRefs("82958a33-8334-5ef8-ae38-de39ce3fab69", 100, 10_000)) {
is IncomingRefs.Complete -> {
val links = result.links.map { it.source to it.attribute }
val examined = result.recordsExamined
// Plan any deletes using the complete set, then stage and commit them.
}
is IncomingRefs.Exhausted -> {
val budget = result.budget // IncomingRefBudget.LINKS or .RECORDS
val examined = result.recordsExamined
// Retry with larger budgets or abandon the delete.
}
}
}The lookup sees earlier writes in this transaction without staging anything.
A complete result contains IncomingRef records with canonical
lowercase UUID source strings and attribute strings; order is unspecified.
A Complete result can contain zero links. An Exhausted result has no
partial link list. Look up references before staging deletes and require
Complete before deleting. On Exhausted, retry with higher budgets or abandon the deletion.
Earlier writes stay staged and can still be committed.
- Both budgets are required. Each is an exact cap, with no unlimited value. The accepted
range is
0..=min(i64::MAX, usize::MAX):2^63-1on 64-bit targets and2^32-1on 32-bit targets (including Android's 32-bit ABIs). A zero budget allows no links or examined records, depending on which budget is zero. With both at zero, the lookup returnsCompletewith zero links only if no records need inspection. Large budgets do not allocate proportional memory up front. - The links budget caps distinct
(source, attribute)pairs. The records budget caps fact versions examined across all layers, including superseded versions, retractions and lookahead. The returned record count never exceeds that budget; checkpointing can change the count without changing the links. - Only stored scalar Ref values count. Keywords (even an alias of the target), UUID-looking Strings, refs inside sets and rule-derived facts are excluded. Valid time is ignored: future and expired assertions count. The newest assertion or retraction decides whether a link is live.
- Invalid UUIDs and negative or unrepresentable budgets give
API-017. A finished transaction givesAPI-018before argument validation. A callback that calls its own transaction getsINT-001before locking or argument validation. Storage and decoding failures remain errors. ACompleteresult, anExhaustedresult, or invalid arguments (API-017) leave the transaction open for more statements, retry, commit, or rollback.
Requires Rust stable toolchain, Android NDK, and JDK 17.
cargo install cargo-ndk --locked
cargo ndk -t arm64-v8a -t armeabi-v7a -t x86_64 build --release
for pair in arm64-v8a:aarch64-linux-android armeabi-v7a:armv7-linux-androideabi x86_64:x86_64-linux-android; do
mkdir -p "android/jniLibs/${pair%%:*}"
cp "target/${pair#*:}/release/libminigraf_ffi.so" "android/jniLibs/${pair%%:*}/"
done
cargo run --bin uniffi-bindgen -- generate \
--library target/aarch64-linux-android/release/libminigraf_ffi.so \
--language kotlin \
--out-dir android/src/main/java/
cd android && ./gradlew assembleReleaseRun the default branch's release workflow for production. It builds and
fast-forwards main for a v3.* tag and v2.x for a v2.* tag. A missing branch
or unsupported version stops the run; it does not try another branch. The core
dispatch sends the full tag in client_payload.version and no other input.
The workflow uses the exact crates.io version of the core dependency. It keeps
the enabled features and checks the resolved dependencies against Cargo.lock.
It updates the README's Maven version, including 3.0.0-alpha. The package is
io.github.project-minigraf:minigraf-android, with JNA 5.14.0 as an AAR
dependency. When moving from 2.x to the alpha, change Kotlin imports from
uniffi.minigraf_ffi to io.github.project_minigraf.minigraf. The package
checks the namespace for the selected branch and all three ABIs. The consumer
tests on Android API 24 and 34 verify the version Gradle resolved and run that
branch's API tests.
To recover, run gh workflow run release.yml --ref main -f version=v3.0.0-alpha
(or use the required 2.x tag). Do not delete or move the binding tag. A retry
uses its original prepared commit and authenticated tested artifacts, even if the
branch has moved.
- If all expected Maven files are public and each SHA-256 matches the tested copy, the workflow skips Portal queries, rebuilding and uploading.
- If publication is missing or incomplete, it checks Central Portal for an existing matching deployment rather than submitting it again. If some files are public but no matching deployment can be recovered, the workflow stops. If no files are public and no matching deployment exists, it rebuilds from the original native and Kotlin inputs. Every unsigned AAR, POM and module file must match the tested copies, including the unsigned files inside the final signed upload bundle.
- A conflict or missing original evidence stops recovery. Evidence is retained for 90 days. If it expires or is deleted, automatic recovery cannot continue. Every successful recovery installs and tests the exact version from Maven Central, even if no upload was needed.
- Java and Android share a Portal namespace. If the artifact for a deployment is not yet known, the workflow checks up to 20 times, 15 seconds apart plus request time. It ignores a deployment only after identifying a different coordinate. If a deployment stays unidentified or disappears before it can be identified, the workflow stops and prints its ID. Check Central Portal before retrying. API errors stop the workflow immediately; they do not mean a deployment is missing.
- A user-managed
VALIDATEDdeployment may still need its original manual publish action. Runs for the same tag are serialized. If GitHub replaces a queued run, dispatch the replaced run again.
When public files are missing or incomplete, a matching FAILED deployment stops
recovery with its ID before downloading deployment files.
Inspect that deployment's validation errors in Central Portal and preserve its
files if requesting Sonatype support. Automation never drops it or resubmits it.
An operator may remove only the confirmed failed, unpublished deployment after
resolving its cause, following Sonatype's recovery guidance,
then retry the same tag using the retained tested artifacts. Never remove public
artifacts or change the tested unsigned bytes to force recovery; a required byte
change needs a separately tested release. An identified FAILED deployment for
the other artifact is ignored.
To rehearse the current default workflow, set rehearsal=true and omit
source_alias. For 3.x, use version=v3.0.0-alpha and
candidate=<full core SHA>. For 2.x, use version=v2.0.12 and no candidate.
Before the move in #937, those runs used source_alias=v3 and
source_alias=main, respectively.
A rehearsal runs the same preparation, checks of source and artifacts, packaging and consumer tests. It reports the candidate's actual crate version separately from the alpha label. It does not change public refs, tags, registry entries, releases or issues. The workflow saves the prepared commit in a Git bundle rather than pushing a temporary ref. The summary lists the workflow, source and prepared commits, the dependency's source, checksums and consumer results. Core #937 tracks post-move routing checks, and #929 tracks production publication.
MIT OR Apache-2.0