antfly-embedded
Safe Rust binding for Antfly Lite, the embedded libantfly C ABI. It wraps
that ABI's antfly_db handle, so applications embed a live database
directly instead of talking to the network SDK (antfly-sdk) -- either a
single-file .aflite database (the default, [Storage::Lite]) or a normal
Antfly directory ([Storage::Directory]), selected on [OpenOptions].
This crate mirrors the reference Go binding (go/pkg/embedded) idiomatically:
[Database] is a Send + Sync handle safe for concurrent use from any
thread, most operations are exposed as *_json methods that take request
bytes and return response bytes (the same wire-level JSON contract shared
with the Antfly server API and the other language bindings), and a
default-on serde feature layers typed convenience wrappers (Status,
Capabilities, CheckReport, ...) on top.
Example
use ;
Every thread that calls into a Database needs at least
antfly_embedded::MIN_THREAD_STACK_SIZE (8 MiB) of stack. The main thread has
that on Linux and macOS, but Rust's spawned threads default to 2 MiB, so
size them explicitly:
# use Arc;
#
Async runtimes need the same for the threads that make these blocking
calls, for example Tokio's thread_stack_size on the runtime builder.
Building against libantfly
Install pkg-config, extract the Apache antfly-embedded release archive,
and add its lib/pkgconfig directory to PKG_CONFIG_PATH. Enable the
libantfly Cargo feature to link the combined database and inference library:
The sys crate tries an explicit ANTFLY_LIB_DIR first, then pkg-config,
then zig/zig-out/lib in a source checkout. The library must remain installed
when the app runs. Crate tests/examples receive runtime search paths;
downstream application binaries should install the library in the system
loader path or set LD_LIBRARY_PATH (Linux) / DYLD_LIBRARY_PATH (macOS)
to the archive's lib directory, or configure their own rpath.
No ELv2 server package is required. See the sys crate README for discovery
and cross-compilation details. Native archive targets are independent of the
Python/npm package matrix, which currently covers Linux x86-64 and ARM64
(glibc 2.28+) and macOS ARM64.
Source checkout tests:
&&
Outside the source tree, set ANTFLY_LIB_DIR to point at an installed
libantfly's lib directory.
Pkg-config resolves the archive's current installation directory when you
build. These crates' test/example binaries receive an absolute runtime search
path; downstream applications follow their own loader configuration. If a
binary uses the archive directory as its rpath, moving the archive afterward
requires rebuilding that binary or configuring the system loader. Distribution
packages should install the library into the final system prefix, remove the
-Wl,-rpath,${libdir} flag from libantfly.pc for C/Go consumers, and configure
application binaries according to the distribution's loader policy.
Embedded inference
libantfly always links the standalone inference runtime in-process, the
same as the antfly executable. Setting local_runtime_configured on
[OpenOptions] yields local_embedded behavior: an embedded model runtime
that runs chunker, embedder, and extractor producers configured with
"provider": "antfly" and no api_url locally instead of failing or
requiring a remote URL.
In-process, every backend. libantfly runs every inference backend,
including Metal, CUDA, and ONNX, in the calling process -- there is no
separate worker process, and ANTFLY_INFERENCE_WORKER is not used. The
antfly server instead runs those backends in a worker process it can kill
and restart, because a GPU driver call or an ONNX model load has no
per-call abort; a library cannot do that to its host program, so
libantfly accepts the trade SQLite makes: once a call reaches the device
or driver it runs to completion (call_timeout_ms/[InferenceOptions::call_timeout],
and closing a handle, take effect only when it returns; calls on CPU
backends still stop cooperatively), and a GPU driver fault terminates the
process. See zig/CAPI.md's "Inference In Process" section for the full
detail.
Embedded inference without a database
For typed decision requests and answer semantics, see the decision guide.
Database failures copy the native diagnostic into the returned Error, so it
survives subsequent calls. Error is Clone rather than Copy; use
error.kind() when matching stable variants and error.detail() for the
message. Equality and hashing compare the stable code, independent of detail.
[Inference] opens the same embedded inference runtime on its own, with no
database -- Inference::open/open_default (options: [InferenceOptions],
covering models directory, resource budgets, and a per-call timeout) and
close. It mirrors Database's handle-safety story (Send + Sync, close
waits for in-flight calls, idempotent, safe from any thread).
Each method mirrors one /ai/v1 route of the inference HTTP API and takes/
returns raw JSON bytes: embed, rerank, chunk, generate,
generate_batch, rewrite, decide, extract, read (OCR), transcribe, and
list_models. Unlike Database's *_json methods, these return
[InferenceResult<Vec<u8>>] on failure: [InferenceError] carries both the
mapped [Error] and the runtime's JSON error body
({"error":...,"message":...}), since antfly_inference_*_json calls are
documented to always leave one behind.
use ;
Streaming generation. generate always returns a complete response --
a request with "stream": true fails with Error::InvalidArgument. Use
Inference::generate_stream to stream instead: it sets "stream": true
for you and calls on_chunk on the calling thread for each
chat.completion.chunk JSON chunk as the model produces tokens.
# use ;
#
on_chunk is a rendezvous -- generation waits for each call to return
before producing the next chunk -- so returning false always stops
generation at that chunk, and the call fails with Error::Cancelled
(wrapped in InferenceError). A pre-stream failure (for example a missing
model) fails like generate, with the JSON error attached; a mid-stream
failure fails with Error::Internal and a JSON body naming
"STREAM_FAILED".
Pulling models. Inference::pull downloads a model into the handle's
models directory (like antfly inference pull), with an optional progress
callback called synchronously on the calling thread as each file starts,
every 16 MiB, and as it completes:
# use ;
#
Returning false cancels the pull -- the call fails with Error::Cancelled
and the model is not installed. The progress callback is a rendezvous (the
download waits for each call to return before continuing), so cancellation
is always honored at the report where on_progress returns false, even
at the very last report of the last file. Completed files stay staged, so
pulling the same model again resumes rather than restarts. Inference::close
waits for a pull (or a stream) in progress; neither is cancelled by close
itself.
A panic inside on_chunk/on_progress is caught and does not unwind
across the C ABI boundary (unwinding through extern "C" is undefined
behavior): it cancels the call and is resumed once the underlying FFI call
returns.
Thread safety
Database is Send + Sync and safe for concurrent use from any thread,
like *sql.DB in Go: share one handle rather than opening one per thread.
libantfly runs in serialized threading mode
(threading_mode() == THREADING_SERIALIZED). Lite calls queue on a connection
and coordinate with other connections to the file. Streaming SQL cursors retain
their original snapshots while other connections publish new commits. Schema
or index changes wait for in-flight calls.
close takes &self, not self by value, specifically so it can be called
on a Database shared across threads (e.g. Arc<Database>) without every
other clone having to be dropped first -- calls made after (or racing) close
return Error::InvalidArgument rather than touching a freed handle.
Drop also closes, for callers who never need to close early. Both are
idempotent and safe to call concurrently or more than once.
Internally, Database gates calls through a small hand-rolled
reader/writer lock rather than std::sync::RwLock: std's RwLock makes
no fairness guarantees, and on platforms like macOS a steady stream of
readers can starve a pending writer indefinitely, which would make close
hang under sustained concurrent read load. The internal gate instead blocks
new reads once a close is requested (like Go's sync.RWMutex), guaranteeing
close completes in bounded time.
Multiple writable Lite connections may remain open, including across processes.
Connections queue within a process; a kernel writer lease serializes complete
native operations across processes. OpenOptions::busy_timeout waits for an
operation holding that lease, like sqlite3_busy_timeout. Closing a connection
does not close another connection to the same file.
API surface
Database::open/create(with [OpenOptions]), plusopen_default,create_default,open_readonly,open_status_only,open_hosted, andcreate_hostedconvenience constructors.- Raw
*_jsonmethods takeimpl AsRef<[u8]>and returnVec<u8>, matching the C ABI's JSON contract 1:1:batch_json,lookup_json,get_raw,scan_json,search_json, the packed wire search variants, schema/index/ enrichment administration, graph queries, transactions, and maintenance (backup/export/import, check, compact, vacuum, stable snapshots). - With the default
serdefeature, typed convenience methods (status,capabilities,check,vacuum,compact,copy_stable_snapshot,pending_work_stats, ...) parse those JSON payloads into typed structs, returningTypedResult<T>(an FFI error or a JSON decode error). restore/restore_filestage a portable.afbbackup into a new database, of the storage kindRestoreOptions::storageselects (a backup of either kind restores into either kind);Database::backup/backup_to_fileproduce one, andDatabase::import_backupimports one directly into an empty, already-open handle.Inference::open/open_default(with [InferenceOptions]) open an embedded inference runtime with no database;embed,rerank,chunk,generate,generate_batch,rewrite,decide,extract,read,transcribe,list_models, andpullmirror the/ai/v1inference HTTP API 1:1.generate_streamstreams a generate request chunk by chunk, and both it andpullaccept a callback that can cancel the call by returningfalse, surfaced asError::Cancelled. See "Embedded inference without a database" above.
See the crate's rustdoc for the full method list.
Testing
cargo test -p antfly-embedded(no feature) runs only pure, non-linking tests (tests/pure.rs) -- value types, error name/description tables, and a compile-timeDatabase: Send + Syncassertion. It needs no dylib.cargo test -p antfly-embedded --features libantflyadditionally runs:tests/errors.rs: cross-checksError's names/descriptions against the liveantfly_error_code_name/antfly_error_code_description, plus ABI validation and struct-size checks.tests/concurrency.rs: a handle shared by threads doing batch/search/ scan/lookup/stats/run-until-idle concurrently, close racing in-flight calls, andbusy_timeoutbehavior.tests/conformance.rs: runs every case underzig/pkg/antfly-embedded/capi-conformance/cases/*.json(see that directory's README), the same declarative suite every language binding runs, plus a standalone test that restores a backup into directory storage and reopens it.tests/inference.rs:Inference::open/open_default, chunk/embed/ generate/generate_stream/pull error mapping (including the JSON error body carried onInferenceErrorandError::Cancelledfrom a cancelledgenerate_stream/pull), use-after-close and double-close, plus preconditioned tests that skip rather than fail when unmet: embedding with a locally installedQwen/Qwen3-Embedding-0.6B-GGUF*model, streaming/cancelling generation with a locally installedggml-org/gemma-4-e2b-it-gguf*model, and pulling a real model from the network (including cancelling on the first progress report, which reliably fails withError::Cancelledand leaves the model uninstalled) whenANTFLY_INFERENCE_PULL_TEST_MODELis set.
Some conformance/concurrency cases (full-text search under concurrent write pressure) need substantially more native stack than a typical fixed-size OS thread gets by default; these tests run their bodies on an explicitly large-stack thread rather than relying on the test harness's default.
SQLx and multiple tables
Enable sqlx and libantfly for the SQLx 0.9 driver (Rust 1.94 or newer):
use ;
use ConnectOptions;
let mut connection = new.connect.await?;
.execute.await?;
.bind.bind.execute.await?;
let rows =
.fetch_all.await?;
SQLx can open independent connections alongside a Database used for
documents, search, or inference. Each path-opened SQLx connection owns a SQL
session and borrows the process storage owner for its canonical file path and
compatible open settings; its default busy timeout is five seconds. To use an
existing handle and its settings, pass
AntflyConnectOptions::new(path).with_database(Arc::clone(&database)).
Connections never explicitly close a shared handle.
Compatible independent connections share their catalog and index caches in process. An external commit or file replacement refreshes the shared generation under the kernel lease. Reclamation runs through the shared maintenance owner, so a foreground refresh does not publish an extra reclamation checkpoint. Connections with different storage settings retain separate owners and refresh after a different owner commits. To compare both modes with one and four connections, run the manual benchmark:
AntflyPool, transactions, nested savepoints, query, query_as, streaming,
prepare/describe, and SQLSTATE database errors use native SQL sessions.
Native work runs on a dedicated worker with the required native stack,
keeping FFI calls off Tokio executor threads. File owners are shared across
pooled connections. Idle pool health checks inspect the worker lifetime without
entering the native database fence. Pending rollback cleanup still completes
before reuse, so the default test_before_acquire(true) remains safe.
Integer bindings and decoding preserve signed 64-bit
values. Byte parameters represent UTF-8 text; JSON uses serde_json::Value.
The upstream query! macro does not register custom database drivers; use
runtime queries and the driver's describe support.
With serde, Database provides create_table_json, list_tables_json,
drop_table, and database-level sql_json. open_table returns a table
handle borrowing its database; existing document, schema, index, enrichment,
and search methods operate on that table. Close handles before dropping
their tables.
Portable .afb archives back up the entire database: its table catalog,
schemas, documents, indexes, enrichments, and constraint records. Call backup
on the database handle. Restore publishes all tables together into either
Lite or directory storage; import requires an empty database with no open
table handles, SQL sessions, or cursors. Table handles cannot export or import
backups.
See the native SQL contract for READ COMMITTED, transactional DDL restrictions, and commit outcomes.