embedded

package module
v0.0.0-...-c1b2574 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

Antfly Embedded Go Binding

go/pkg/embedded is the first language binding above the stable Zig APIs and the libantfly C ABI. It exposes local databases and database-free inference from the same ABI. Applications can embed .aflite or directory storage without talking to the network SDK.

The Go module includes the matching antfly.h header. Install pkg-config and extract the Apache antfly-embedded release archive for your platform. Keep its lib/ and include/ directories together; lib/pkgconfig/libantfly.pc is relocatable and supplies the library, header, and runtime search paths. No database server or CLI package is required.

export PKG_CONFIG_PATH="/path/to/antfly-embedded/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
go build ./...

The binding uses #cgo pkg-config: libantfly, so this works after go get without paths into the monorepo. If you install into a standard system prefix, your system pkg-config and loader configuration may already find it. The native library must remain installed when running the compiled application.

From a source checkout:

cd zig
zig build capi
export PKG_CONFIG_PATH="$PWD/zig-out/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
cd ../go/pkg/embedded
go test -tags libantfly ./...

Native release libraries are available for Linux and macOS targets in the release archive matrix. Python/npm prebuilt packages currently support Linux x86-64 and ARM64 (glibc 2.28+), and macOS ARM64. Go links native archives directly; it does not install a Python/npm platform package.

The archive relocates before compilation: pkg-config resolves its current installation directory when you build. The resulting runtime search path is absolute, so moving the archive afterward requires rebuilding the application or configuring the system loader. For distribution packages, install the library into the final system prefix and remove the -Wl,-rpath,${libdir} flag from libantfly.pc; use the distribution's loader policy instead.

go vet, gopls, and golangci-lint also run cgo and therefore need pkg-config and the same PKG_CONFIG_PATH configuration as go build. Set that environment in your editor's launch environment as well as your shell. Native builds and tests that link the binding require the actual library. Repository CI's declaration-only vet check generates temporary pkg-config metadata without a library; that setup cannot run or link an application.

Embedded inference

libantfly always links the inference runtime and executes it in-process (see zig/COMPILATION.md's "C API composition" section and zig/LITE.md's "Local Embedded Inference" section). Setting LocalRuntimeConfigured (below) 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 -- with the standard library and no extra link flags. This makes libantfly a much larger shared library than before inference was embedded by default; there is no smaller inference-free variant to link against instead.

Normal go test ./... does not run the C ABI smoke test. The libantfly build tag means "a built libantfly is available to link"; it is not Lite-specific, because the C ABI itself is storage-neutral. Without it, test binaries would fail at link time, but cgo still requires pkg-config metadata during compilation. Tests that exercise native calls require the actual library.

The open helpers call ValidateABI before filling C option structures or creating handles. Applications can call ValidateABI at startup to fail fast when the loaded libantfly ABI version or antfly_open_options size does not match the header used to build the Go binding.

The binding exposes raw JSON methods such as StatusJSON and CapabilitiesJSON for parity with the C ABI. It also exposes typed Status and Capabilities helpers for stable Lite control fields, including storage identity, inference mode, caller-supplied artifact support, and distributed-only capability flags. Use constants such as InferenceModeCallerSuppliedArtifacts, InferenceModeManualMaintenance, and InferenceModeDisabledDeferred when branching on inference status or capabilities. Typed PendingWorkStats, RunUntilIdleStatus, Check, Compact, Vacuum, CopyStableSnapshot, and CopyStableSnapshotFile helpers cover the stable Lite maintenance reports while keeping the raw JSON methods available. ReplayGeneratedEnrichments recreates generated enrichment work from stored documents after a manual-maintenance or restore pause. Use CheckFile or CheckFileJSON to inspect an invalid, truncated, or corrupted .aflite file without opening a database handle.

Use Create for a new native .aflite writer database and Open for an existing native .aflite writer database. Open does not create missing files or upgrade pre-release Lite layouts; unknown or invalid files fail explicitly. Every Create* variant provisions the default full_text_index_v0 full-text index, matching the server's table-create behavior, so AddIndexJSON is only needed for indexes beyond that default. Use OpenReadonly for read-only query handles and OpenStatusOnly for inspection. Use CreateHosted for a new hosted/manual-maintenance database and OpenHosted for an existing hosted/manual-maintenance database when the application will call RunUntilIdle itself. Use RunUntilIdleStatus when the application also wants the typed post-drain pending-work readiness document. Use CreateWithOptions and OpenWithOptions for advanced settings such as map size, native-profile TTL cleanup, and explicit inference status reporting. Set RemoteProviderConfigured when the embedding producer is backed by a configured remote provider so Status().Inference reports remote_provider instead of the default caller-supplied/deferred mode. Set LocalRuntimeConfigured when the application requests a local inference runtime; Lite reports local_embedded whenever the loaded build advertises LocalInferenceRuntime, which is true by default for the standard libantfly (see "Embedded inference" above).

In-process execution. libantfly runs inference in-process on every backend, including Metal, CUDA, and ONNX -- there is no separate worker process, and ANTFLY_INFERENCE_WORKER is not used by libantfly. A call that has already reached a GPU driver cannot be interrupted: a call_timeout_ms deadline or a Close only takes effect once the call returns on its own, and a driver fault terminates the process (unlike the antfly server, which runs models in a separate, restartable worker process it can kill). Size InferenceOptions/OpenOptions resource budgets and keep concurrent calls bounded accordingly. See zig/LITE.md's "Local Embedded Inference" section for the full rationale.

Embedded inference without a database

Database failures retain an owned native diagnostic in NativeError. Use errors.Is(err, lite.InvalidArgument) (or another stable ErrorCode) to classify failures. The copied detail remains valid after later native calls; Go keeps each native call and diagnostic read on the same OS thread.

When Batch, BatchJSON, or an autocommit SQL write fails with OutcomeUnknown, the error may carry an outcome receipt (NativeError.OutcomeReceipt or SQLError.OutcomeReceipt; read either with lite.OutcomeReceiptOf(err)). Resolve it later on any handle for the same database with db.OutcomeReceiptStatus(receipt), which returns OutcomeReceiptApplied or OutcomeReceiptNotApplied, or Stalled while the uncertain commit is not reconciled yet (Lite: retry; directory database: close the issuing handle and reopen first). Call db.ForgetOutcomeReceipt(receipt) once resolved; afterwards the receipt can no longer be resolved.

OpenInference opens a standalone *Inference handle that runs models with no DB attached -- models load on first use and stay cached until Close. Each method sends and receives the JSON of the matching /ai/v1 route of the Antfly inference HTTP API (see specs/openapi/inference/api.yaml): Embed, Rerank, Chunk, Generate, GenerateBatch, Rewrite, Extract, Read (documents, images, or audio), and ListModels. Generate always returns a complete response; a request with "stream": true fails with InvalidArgument. Use GenerateStream to stream chunks instead.

inf, err := lite.OpenInference(&lite.InferenceOptions{ModelsDir: "/path/to/models"})
if err != nil {
    // Unsupported means this build does not link the inference runtime, or
    // it failed to start.
}
defer inf.Close()

body, err := inf.Chunk([]byte(`{"input":"Ants live in colonies."}`))

Like DB, an *Inference is safe for concurrent use by multiple goroutines, and Close waits for in-flight calls before releasing the handle; calls made after Close return InvalidArgument.

On failure, every JSON method still returns the runtime's JSON error body ({"error": ..., "message": ...}) wrapped in an *InferenceError, alongside the mapped stable ErrorCode (an HTTP 404, such as a model that is not installed, maps to NotFound; 4xx to InvalidArgument; 429/503/504 or an elapsed call timeout to Busy; 501/507, meaning the model does not fit the configured memory budgets, to Unsupported; a Pull or GenerateStream callback returning false, or its ctx becoming done, to Cancelled). Use errors.As for the API error code (e.g. "MODEL_NOT_FOUND") and message, or errors.Is(err, lite.NotFound) for the stable code:

_, err := inf.Embed(request)
var infErr *lite.InferenceError
if errors.As(err, &infErr) {
    log.Printf("inference call failed: %s: %s", infErr.API.Code, infErr.API.Message)
}

Models are not downloaded automatically. Use Pull to fetch a model from the Hugging Face Hub into the handle's models directory, like antfly inference pull. The optional progress callback runs synchronously on the calling goroutine as each file starts, every 16 MiB, and as each file completes:

_, err := inf.Pull(ctx, []byte(`{"model":"owner/name"}`), func(p lite.PullProgress) bool {
    log.Printf("%s: %s %d/%d bytes (cached=%v)", p.Model, p.File, p.BytesDownloaded, p.TotalBytes, p.Cached)
    return true // false stops the pull
})

Pull and GenerateStream both take a context.Context (nil is treated as context.Background()) alongside their own callback-return-value mechanism for stopping early -- the callback returning false, or ctx being done at the point a callback fires, both stop the call, and either way the call returns lite.Cancelled (the ANTFLY_CANCELLED C ABI code). Each progress report is a rendezvous: the call waits for the callback to return before continuing, so cancellation takes effect exactly at the report where the callback returns false (or ctx is observed done) -- for Pull, that can be each file start, every 16 MiB, or each file end (ctx itself is only checked when a report fires, not continuously); for GenerateStream, each streamed chunk. For Pull, files already fully downloaded before cancellation stay staged, so pulling the same model again resumes rather than restarts.

err := inf.GenerateStream(ctx, request, func(chunk []byte) bool {
    // chunk is a "chat.completion.chunk" JSON document; it is only valid
    // during this call, so copy it before returning if you need to keep it.
    return true // false stops generation
})
Concurrency

A *DB is safe for concurrent use by multiple goroutines, like *sql.DB; share one handle rather than opening one per goroutine. libantfly runs in serialized threading mode (ThreadingMode() == ThreadingSerialized). 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 waits for in-flight calls; calls after it return InvalidArgument. See zig/CAPI.md "Thread Safety" for the full contract.

Multiple writable Lite connections may remain open, including across processes. Native operations queue within a process and take a kernel writer lease across processes. OpenOptions.BusyTimeout retries admission while another process holds the writer lease or advances the allocator checkpoint. This admission retry never replays a mutation body. Connection lifetimes are independent.

Use BeginTransaction, WriteTransaction, ResolveTransaction, TransactionStatus, and CommitVersion when an embedded application needs the local transaction/OCC path exposed by the Antfly C ABI.

OpenOptions.Storage selects a .aflite file (StorageLite, the default) or a normal Antfly directory (StorageDirectory); every method works on either. CreateWithOptions only creates .aflite files; open a missing directory path to create one.

Use Backup or BackupToFile to write a portable .afb archive of the entire database. Use Restore or RestoreFile to create a new database from one without publishing a partial target on failure; RestoreOptions.Storage selects a .aflite file (the default) or a directory, and a backup of either kind restores into either kind. ImportBackup imports into an empty open database. Use CopyStableSnapshot or CopyStableSnapshotFile when you want a physical .aflite database snapshot rather than a portable .afb backup archive.

From the repository’s zig directory, zig build libantfly builds the Lite CLI and libantfly. Run zig build lite-test for the Lite checks, including the Go binding tests against the built library.

SQL and multiple tables

Importing this package registers the antfly driver with database/sql:

db, err := sql.Open("antfly", "file:/path/app.aflite")
if err != nil { return err }
defer db.Close()
_, err = db.Exec("CREATE TABLE people (id BIGINT PRIMARY KEY, name TEXT)")
_, err = db.Exec("INSERT INTO people (id,name) VALUES ($1,$2)", int64(1), "Ada")
rows, err := db.Query("SELECT id,name FROM people")

Pooled connections have independent SQL sessions. Compatible connections to the same canonical file path share a process storage owner, caches, and maintenance worker. Native operations coordinate writer ownership; busy_timeout_ms in the DSN defaults to 5000. BeginTx uses READ COMMITTED; stronger isolation returns an error. Rows use native streaming cursors, so queries continue beyond 128 rows. Signed 64-bit integers remain int64; SQL NULL becomes nil. JSON parameters can use json.RawMessage, JSON results use []byte, and byte parameters represent UTF-8 text. Errors expose SQLState() and an optional transaction receipt.

The document API uses the same catalog: CreateTableJSON, ListTablesJSON, OpenTable, and DropTable. A table handle supports the existing document, schema, search, index, and enrichment methods. Close table handles before dropping them. Closing the database invalidates its table handles.

Portable .afb archives back up the entire database: its table catalog, schemas, documents, indexes, enrichments, durable resolver merges, 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 transaction, savepoint, result-size, and commit-outcome behavior.

Cypher and SQL graph composition

GraphCatalogJSON, CypherJSON, and GraphWriteStatusJSON expose durable named graphs, Cypher queries and mutations, and transaction receipts through libantfly. Catalog requests use action (put, get, list, drop), a graph name, and a definition for puts. Replacement and drop require the current decimal-string expected_revision.

Queries use the same request contract as the server: query, parameters or lossless typed_parameters, optional limits, and write_request_id. Results contain tagged graph values; integer values are decimal strings. Native writes return a commit receipt. Retain the request ID and resolve an unknown outcome through the status method instead of replaying the query. *GraphError preserves the diagnostic code, span, outcome, and transaction ID when available.

Local SQL supports GRAPH_TABLE over these catalogs, including ordinary-table joins and staged SQL rows in an explicit transaction. Graph definitions pin local table and graph-index identities across reopen. Raw embedded calls reject protected tables; authenticated principal queries use the server API.

See the Cypher contract for grammar, mapping, value, mutation, and deployment semantics.

The real local synonym/ANN regression is opt-in with ANTFLY_LITE_EMBEDDING_MODELS_DIR=/path/to/inference/models. It uses that explicit model root (containing Qwen/Qwen3-Embedding-0.6B-GGUF), rather than searching the user's home directory. The Zig CI gate separately downloads the pinned GLiNER base bundle and runs real extraction, promotion, and a public direction: "both" PageRank query. It also downloads the pinned Qwen bundle for a required public Python embedding/promotion/drain/ANN test; Unicode resolver tests run in the ordinary lib-test gate.

Documentation

Overview

Package embedded provides Go bindings for local Antfly databases and database-free inference through libantfly.

The package is backed by the stable Antfly C ABI. The Go module carries the matching antfly.h header; build or install libantfly before running cgo-backed tests or binaries. Install pkg-config and add the Apache antfly-embedded archive's lib/pkgconfig to PKG_CONFIG_PATH.

Index

Constants

View Source
const (
	InferenceModeCallerSuppliedOrDisabled = C.ANTFLY_INFERENCE_MODE_CALLER_SUPPLIED_OR_DISABLED
	InferenceModeCallerSuppliedArtifacts  = C.ANTFLY_INFERENCE_MODE_CALLER_SUPPLIED_ARTIFACTS
	InferenceModeRemoteProvider           = C.ANTFLY_INFERENCE_MODE_REMOTE_PROVIDER
	InferenceModeLocalEmbedded            = C.ANTFLY_INFERENCE_MODE_LOCAL_EMBEDDED
	InferenceModeManualMaintenance        = C.ANTFLY_INFERENCE_MODE_MANUAL_MAINTENANCE
	InferenceModeDisabledDeferred         = C.ANTFLY_INFERENCE_MODE_DISABLED_DEFERRED
)

Inference mode strings returned by Lite status and capabilities.

View Source
const SupportedABIVersion uint32 = 3

SupportedABIVersion is the Antfly C ABI version this binding expects.

View Source
const ThreadingSerialized uint32 = C.ANTFLY_THREADING_SERIALIZED

ThreadingSerialized is the only threading mode libantfly provides: any goroutine may call any method on a DB concurrently.

Variables

This section is empty.

Functions

func ABIVersion

func ABIVersion() uint32

ABIVersion returns the loaded Antfly C ABI version.

func CheckFileJSON

func CheckFileJSON(path string) ([]byte, error)

CheckFileJSON runs Lite integrity checks for path without opening a database handle and returns the JSON result.

func CopyStableSnapshotFileJSON

func CopyStableSnapshotFileJSON(srcPath, destPath string, replace bool) ([]byte, error)

CopyStableSnapshotFileJSON opens srcPath read-only, copies a stable Lite snapshot to destPath, and returns the JSON result.

func DecodeArtifactIDJSON

func DecodeArtifactIDJSON(artifactIDBase64 string) ([]byte, error)

DecodeArtifactIDJSON decodes a base64 artifact ID without opening a database.

func InferenceOptionsSize

func InferenceOptionsSize() uint32

InferenceOptionsSize returns the loaded C ABI size of antfly_inference_options.

func LastErrorDetail

func LastErrorDetail() string

LastErrorDetail returns the native validation error for the current OS thread. Call immediately after failure while runtime.LockOSThread is held across both the operation and this accessor.

func OpenOptionsSize

func OpenOptionsSize() uint32

OpenOptionsSize returns the loaded C ABI size of antfly_open_options.

func OutcomeReceiptOf

func OutcomeReceiptOf(err error) (string, bool)

OutcomeReceiptOf returns the outcome receipt carried by err, if any. It recognizes *NativeError and *SQLError anywhere in err's chain.

func Restore

func Restore(path string, backup []byte, opts RestoreOptions) error

Restore creates a database at path from a portable Antfly backup archive, of the storage kind opts.Storage selects. A backup of either kind restores into either kind. OutcomeUnknown means the destination was published but crash durability could not be confirmed; inspect it and do not retry automatically.

func RestoreFile

func RestoreFile(path, backupPath string, opts RestoreOptions) error

RestoreFile is Restore reading the archive from backupPath. For .aflite destinations it streams with bounded memory use. Busy means the source changed during streaming or the source/destination is concurrently locked; retry after the files are stable and no writer is active. Unsupported means the source filesystem lacks required advisory locking; copy the archive to a supported local filesystem.

func ThreadingMode

func ThreadingMode() uint32

ThreadingMode reports the loaded libantfly threading contract, like sqlite3_threadsafe().

func ValidateABI

func ValidateABI() error

ValidateABI verifies that the loaded C library matches the header used to compile this Go binding.

Types

type Capabilities

type Capabilities struct {
	FreestandingBuild                  bool     `json:"freestanding_build"`
	Threading                          string   `json:"threading"`
	HostedProfile                      bool     `json:"hosted_profile"`
	ManualMaintenance                  bool     `json:"manual_maintenance"`
	BackgroundEnrichmentRuntime        bool     `json:"background_enrichment_runtime"`
	TTLCleanupRuntime                  bool     `json:"ttl_cleanup_runtime"`
	TransactionRecoveryRuntime         bool     `json:"transaction_recovery_runtime"`
	LocalTemplateRendering             bool     `json:"local_template_rendering"`
	RemoteTemplateRendering            bool     `json:"remote_template_rendering"`
	RemoteTemplateHostCallbacks        bool     `json:"remote_template_host_callbacks"`
	InferenceMode                      string   `json:"inference_mode"`
	SupportedInferenceModes            []string `json:"supported_inference_modes"`
	AvailableInferenceModes            []string `json:"available_inference_modes"`
	InferenceRequired                  bool     `json:"inference_required"`
	NoInferenceConfiguredOK            bool     `json:"no_inference_configured_ok"`
	CallerSuppliedArtifacts            bool     `json:"caller_supplied_artifacts"`
	CallerSuppliedEmbeddings           bool     `json:"caller_supplied_embeddings"`
	RemoteInferenceProviders           bool     `json:"remote_inference_providers"`
	LocalInferenceRuntime              bool     `json:"local_inference_runtime"`
	GeneratedEnrichmentPlanning        bool     `json:"generated_enrichment_planning"`
	TextSearch                         bool     `json:"text_search"`
	DenseVectorSearch                  bool     `json:"dense_vector_search"`
	SparseVectorSearch                 bool     `json:"sparse_vector_search"`
	HybridSearch                       bool     `json:"hybrid_search"`
	GraphSearch                        bool     `json:"graph_search"`
	DistributedShardOwnership          bool     `json:"distributed_shard_ownership"`
	RaftReplication                    bool     `json:"raft_replication"`
	ClusterPlacement                   bool     `json:"cluster_placement"`
	CrossNodeJoins                     bool     `json:"cross_node_joins"`
	RemoteShardFanout                  bool     `json:"remote_shard_fanout"`
	DistributedTransactionCoordination bool     `json:"distributed_transaction_coordination"`
	ClusterHeartbeatStatusAggregation  bool     `json:"cluster_heartbeat_status_aggregation"`
	ServerSideAutoscaling              bool     `json:"server_side_autoscaling"`
	KubernetesOperator                 bool     `json:"kubernetes_operator"`
	ObjectStoragePrimary               bool     `json:"object_storage_primary"`
}

Capabilities describes the Lite feature contract advertised by a handle.

type CheckReport

type CheckReport struct {
	LiveAccounting   *LiveByteAccounting `json:"live_accounting,omitempty"`
	Valid            bool                `json:"valid"`
	FileSize         uint64              `json:"file_size"`
	ValidPrefixSize  uint64              `json:"valid_prefix_size"`
	TailBytes        uint64              `json:"tail_bytes"`
	RecordCount      uint64              `json:"record_count"`
	LiveFileCount    uint64              `json:"live_file_count"`
	LiveBytes        uint64              `json:"live_bytes"`
	CompactSize      uint64              `json:"compact_size"`
	ReclaimableBytes uint64              `json:"reclaimable_bytes"`
	Issue            *string             `json:"issue,omitempty"`
}

CheckReport is the typed form of CheckJSON.

func CheckFile

func CheckFile(path string) (*CheckReport, error)

CheckFile runs Lite integrity checks for path without opening a database handle and returns the typed result.

type CompactReport

type CompactReport struct {
	Compacted bool         `json:"compacted"`
	Vacuum    VacuumReport `json:"vacuum"`
}

CompactReport is the typed form of CompactJSON.

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is an embedded Antfly database handle.

A DB is safe for concurrent use by multiple goroutines, like *sql.DB. libantfly runs in serialized threading mode (see ThreadingMode): reads run in parallel, writes on one handle queue behind each other instead of failing with Busy, and schema or index changes wait for in-flight calls. Close waits for in-flight calls to finish; calls made after Close return InvalidArgument.

func Create

func Create(path string) (*DB, error)

Create creates a new native Antfly Lite database file for writing.

func CreateHosted

func CreateHosted(path string) (*DB, error)

CreateHosted creates a new Antfly Lite database in hosted/manual maintenance mode. In this profile callers drive pending work explicitly with RunUntilIdle.

func CreateWithOptions

func CreateWithOptions(path string, opts OpenOptions) (*DB, error)

CreateWithOptions creates an Antfly Lite database using explicit C ABI options.

func Open

func Open(path string) (*DB, error)

Open opens an existing native Antfly Lite database file for writing.

func OpenHosted

func OpenHosted(path string) (*DB, error)

OpenHosted opens an existing Antfly Lite database in hosted/manual maintenance mode. In this profile callers drive pending work explicitly with RunUntilIdle.

func OpenReadonly

func OpenReadonly(path string) (*DB, error)

OpenReadonly opens an existing Antfly Lite database file read-only.

func OpenStatusOnly

func OpenStatusOnly(path string) (*DB, error)

OpenStatusOnly opens enough of an Antfly Lite database to read status.

func OpenWithOptions

func OpenWithOptions(path string, opts OpenOptions) (*DB, error)

OpenWithOptions opens an Antfly Lite database using explicit C ABI options.

func (*DB) AddEnrichmentJSON

func (db *DB) AddEnrichmentJSON(config []byte) error

AddEnrichmentJSON adds an enrichment from its JSON configuration.

func (*DB) AddIndexJSON

func (db *DB) AddIndexJSON(config []byte) error

AddIndexJSON adds or replaces an index. Retry the identical request on Busy. A graph replaces command registers a resumable background shadow; the old index serves until activation. It also works when the old index is absent. Optional wait:{timeout_ms:N} waits for activation. Deadline Busy leaves the accepted shadow running; PendingWorkStatsJSON reports progress and last error.

func (*DB) AggregateHitsJSON

func (db *DB) AggregateHitsJSON(request []byte) ([]byte, error)

AggregateHitsJSON aggregates hits from a JSON request.

func (*DB) Backup

func (db *DB) Backup() ([]byte, error)

Backup returns a portable Antfly backup archive (.afb) of this database, which restores or imports into either storage kind.

func (*DB) BackupJSON

func (db *DB) BackupJSON(options []byte) ([]byte, error)

BackupJSON exports a portable archive with an explicit optional table scope. Default is always included. Full backups never silently omit unavailable tables.

func (*DB) BackupToFile

func (db *DB) BackupToFile(path string) error

BackupToFile writes a portable Antfly backup archive (.afb) of this database.

func (*DB) Batch

func (db *DB) Batch(writes []WriteIntent, timestampNS uint64) error

Batch applies write intents at timestampNS.

func (*DB) BatchJSON

func (db *DB) BatchJSON(request []byte) ([]byte, error)

BatchJSON applies a public Antfly batch request and returns the JSON result. An OutcomeUnknown failure carries an outcome receipt (see OutcomeReceiptOf).

func (*DB) BeginTransaction

func (db *DB) BeginTransaction(txnID TxnID, timestampNS uint64, participants []string) error

BeginTransaction starts a local transaction with an explicit transaction ID.

func (*DB) CancelReplacement

func (db *DB) CancelReplacement(name string) (bool, error)

CancelReplacement cancels a running or failed shadow by its new name.

func (*DB) Capabilities

func (db *DB) Capabilities() (*Capabilities, error)

Capabilities returns the typed Lite capability document for the database.

func (*DB) CapabilitiesJSON

func (db *DB) CapabilitiesJSON() ([]byte, error)

CapabilitiesJSON returns the database's Lite capability document.

func (*DB) Check

func (db *DB) Check() (*CheckReport, error)

Check runs Lite integrity checks and returns the typed result.

func (*DB) CheckJSON

func (db *DB) CheckJSON() ([]byte, error)

CheckJSON runs Lite integrity checks and returns the JSON result.

func (*DB) Close

func (db *DB) Close() error

Close releases the embedded database handle, waiting for in-flight calls on other goroutines to finish first. It is safe to call more than once and concurrently.

func (*DB) CommitVersion

func (db *DB) CommitVersion(txnID TxnID) (uint64, error)

CommitVersion returns the commit version recorded for a committed transaction.

func (*DB) Compact

func (db *DB) Compact() (*CompactReport, error)

Compact drains maintenance, compacts indexes, vacuums free space, and returns the typed result.

func (*DB) CompactJSON

func (db *DB) CompactJSON() ([]byte, error)

CompactJSON drains maintenance, compacts indexes, vacuums free space, and returns the JSON result.

func (*DB) ComputeEnrichmentsJSON

func (db *DB) ComputeEnrichmentsJSON(request []byte) ([]byte, error)

ComputeEnrichmentsJSON computes enrichment outputs for a JSON request.

func (*DB) CopyStableSnapshot

func (db *DB) CopyStableSnapshot(destPath string, replace bool) (*StableSnapshotReport, error)

CopyStableSnapshot copies a stable Lite snapshot to destPath and returns the typed result.

func (*DB) CopyStableSnapshotJSON

func (db *DB) CopyStableSnapshotJSON(destPath string, replace bool) ([]byte, error)

CopyStableSnapshotJSON copies a stable Lite snapshot to destPath.

func (*DB) CreateTableJSON

func (db *DB) CreateTableJSON(name string, schema []byte) error

func (*DB) CurateEntityJSON

func (db *DB) CurateEntityJSON(table, key string, request []byte) ([]byte, error)

CurateEntityJSON applies an entity correction to every matching resolver namespace.

func (*DB) CypherJSON

func (db *DB) CypherJSON(graph string, request []byte) ([]byte, error)

CypherJSON uses the hosted query contract and lossless tagged result values.

func (*DB) DeleteEnrichment

func (db *DB) DeleteEnrichment(kind, name string) (bool, error)

DeleteEnrichment deletes an enrichment by kind and name and reports whether it existed.

func (*DB) DeleteIndex

func (db *DB) DeleteIndex(name string) (bool, error)

DeleteIndex deletes an index by name and reports whether it existed. DeleteIndex retires an index; retry on Busy. Returns whether the index existed.

func (*DB) DenseSearchWire

func (db *DB) DenseSearchWire(request []byte) ([]byte, error)

DenseSearchWire executes a packed dense-vector wire search request.

func (*DB) DropResolverIdentity

func (db *DB) DropResolverIdentity(name string) (bool, error)

DropResolverIdentity deletes retired identity metadata; artifacts and canonical rows remain. Retry on Busy. Delete source documents for artifact cleanup; explicitly delete unused canonical rows.

func (*DB) DropTable

func (db *DB) DropTable(name string) error

func (*DB) EdgesJSON

func (db *DB) EdgesJSON(indexName, key, edgeType string, direction uint8) ([]byte, error)

EdgesJSON returns graph edges for a key from a graph index.

func (*DB) EnrichmentsJSON

func (db *DB) EnrichmentsJSON() ([]byte, error)

EnrichmentsJSON returns configured enrichments as JSON.

func (*DB) ExecuteGraphQueriesJSON

func (db *DB) ExecuteGraphQueriesJSON(request []byte) ([]byte, error)

ExecuteGraphQueriesJSON executes a batch of JSON graph queries.

func (*DB) ExtractEnrichmentsJSON

func (db *DB) ExtractEnrichmentsJSON(request []byte) ([]byte, error)

ExtractEnrichmentsJSON extracts enrichment outputs for a JSON request.

func (*DB) FindKShortestPathsJSON

func (db *DB) FindKShortestPathsJSON(request []byte) ([]byte, error)

FindKShortestPathsJSON executes a JSON k-shortest-paths graph request.

func (*DB) FindShortestPathJSON

func (db *DB) FindShortestPathJSON(request []byte) ([]byte, error)

FindShortestPathJSON executes a JSON shortest-path graph request.

func (*DB) ForgetOutcomeReceipt

func (db *DB) ForgetOutcomeReceipt(receipt string) error

ForgetOutcomeReceipt removes a resolved receipt's durable marker. Afterwards the receipt can no longer be resolved.

func (*DB) GraphCatalogJSON

func (db *DB) GraphCatalogJSON(request []byte) ([]byte, error)

GraphCatalogJSON gets/lists/puts/drops graphs. Updates require expected_revision.

func (*DB) GraphWriteStatusJSON

func (db *DB) GraphWriteStatusJSON(transactionID string) ([]byte, error)

GraphWriteStatusJSON resolves a receipt without replaying the graph statement.

func (*DB) ImportBackup

func (db *DB) ImportBackup(backup []byte) error

ImportBackup imports a portable Antfly backup archive into this empty database. OutcomeUnknown means the live handle adopted the imported generation, but crash durability could not be confirmed; inspect the handle and do not retry automatically.

func (*DB) IndexesJSON

func (db *DB) IndexesJSON() ([]byte, error)

IndexesJSON returns configured indexes as JSON.

func (*DB) ListTablesJSON

func (db *DB) ListTablesJSON() ([]byte, error)

func (*DB) LookupArtifactJSON

func (db *DB) LookupArtifactJSON(artifactIDBase64 string) ([]byte, error)

LookupArtifactJSON looks up an artifact by base64 artifact ID.

func (*DB) LookupJSON

func (db *DB) LookupJSON(key string) ([]byte, error)

LookupJSON returns the JSON lookup result for key.

func (*DB) MatchPatternJSON

func (db *DB) MatchPatternJSON(request []byte) ([]byte, error)

MatchPatternJSON executes a JSON graph pattern-match request.

func (*DB) MemoryJSON

func (db *DB) MemoryJSON(space string, request []byte) ([]byte, error)

ResolveQueryJSON extracts text or resolves supplied extraction mentions, including ANN, without writes. MemoryJSON executes the native memory service against a named local space.

func (*DB) MergeResolverKeysJSON

func (db *DB) MergeResolverKeysJSON(resolver string, request []byte) error

MergeResolverKeysJSON persists {"key","target"}; RunUntilIdle re-keys existing resolution edges.

func (*DB) NeighborsJSON

func (db *DB) NeighborsJSON(indexName, key, edgeType string, direction uint8) ([]byte, error)

NeighborsJSON returns graph neighbors for a key from a graph index.

func (*DB) NewSQLSession

func (db *DB) NewSQLSession() (*SQLSession, error)

func (*DB) OpenSQLCursorJSON

func (db *DB) OpenSQLCursorJSON(request []byte) (*SQLCursor, error)

func (*DB) OpenTable

func (db *DB) OpenTable(name string) (*DB, error)

OpenTable returns a handle scoped to a catalog table. Existing document, schema, index, enrichment, and search methods operate on that table. Close the table before DropTable. Database Close invalidates table handles.

func (*DB) OutcomeReceiptStatus

func (db *DB) OutcomeReceiptStatus(receipt string) (OutcomeReceiptStatus, error)

OutcomeReceiptStatus resolves an outcome receipt from an OutcomeUnknown batch or autocommit SQL write, on any handle for the same database. It returns Stalled while the uncertain commit is not reconciled yet: retry on a Lite database; for a directory database, close the issuing handle and reopen first.

func (*DB) PendingWorkStats

func (db *DB) PendingWorkStats() (*PendingWorkStatus, error)

PendingWorkStats returns the typed Lite pending-work readiness document.

func (*DB) PendingWorkStatsJSON

func (db *DB) PendingWorkStatsJSON() ([]byte, error)

PendingWorkStatsJSON returns pending index/enrichment work as JSON.

func (*DB) Raw

func (db *DB) Raw(key string) ([]byte, error)

Raw returns the raw stored bytes for key.

func (*DB) RenderResolverKeyJSON

func (db *DB) RenderResolverKeyJSON(resolver string, mention []byte) ([]byte, error)

RenderResolverKeyJSON renders the durable resolver template and follows key aliases, without writes or ANN search.

func (*DB) ReplayGeneratedEnrichments

func (db *DB) ReplayGeneratedEnrichments() (*ReplayGeneratedEnrichmentsResult, error)

ReplayGeneratedEnrichments recreates generated enrichment work from stored documents and returns the replay count.

func (*DB) ReplayGeneratedEnrichmentsJSON

func (db *DB) ReplayGeneratedEnrichmentsJSON() ([]byte, error)

ReplayGeneratedEnrichmentsJSON replays generated enrichment work from stored documents and returns {"replayed":N}.

func (*DB) ResolveQueryJSON

func (db *DB) ResolveQueryJSON(resolver string, mention []byte) ([]byte, error)

func (*DB) ResolveTransaction

func (db *DB) ResolveTransaction(txnID TxnID, status TxnStatus, commitVersion uint64) error

ResolveTransaction resolves transaction intents as committed or aborted.

func (*DB) ResolverCurationJSON

func (db *DB) ResolverCurationJSON(resolver string) ([]byte, error)

ResolverCurationJSON inspects one resolver, or every identity for an empty name.

func (*DB) ResolverIdentitiesJSON

func (db *DB) ResolverIdentitiesJSON() ([]byte, error)

ResolverIdentitiesJSON lists active and retired identities, including durable merges.

func (*DB) ResolverReviewsJSON

func (db *DB) ResolverReviewsJSON(request []byte) ([]byte, error)

ResolverReviewsJSON pages reviews or submits an artifact-bound decision.

func (*DB) RunUntilIdle

func (db *DB) RunUntilIdle() error

RunUntilIdle drains pending enrichment and index work.

func (*DB) RunUntilIdleJSON

func (db *DB) RunUntilIdleJSON() ([]byte, error)

RunUntilIdleJSON drains pending enrichment and index work and returns the post-drain pending work stats JSON.

func (*DB) RunUntilIdleStatus

func (db *DB) RunUntilIdleStatus() (*PendingWorkStatus, error)

RunUntilIdleStatus drains pending enrichment and index work and returns the typed post-drain readiness document.

func (*DB) SQLJSON

func (db *DB) SQLJSON(request []byte) ([]byte, error)

SQLJSON executes SQL against the database catalog. The request contains statement, parameters and an optional result limit. The returned body includes SQLSTATE diagnostics on failure.

func (*DB) ScanJSON

func (db *DB) ScanJSON(request []byte) ([]byte, error)

ScanJSON executes a JSON scan request and returns the JSON result.

func (*DB) SchemaJSON

func (db *DB) SchemaJSON() ([]byte, error)

SchemaJSON returns the active schema JSON.

func (*DB) SearchJSON

func (db *DB) SearchJSON(request []byte) ([]byte, error)

SearchJSON executes a JSON search request and returns the JSON result.

func (*DB) SetResolverNamespaceJSON

func (db *DB) SetResolverNamespaceJSON(resolver string, request []byte) error

SetResolverNamespaceJSON atomically resets or migrates resolver identities; drain afterward. Retry the identical request on Busy.

func (*DB) SetSchemaJSON

func (db *DB) SetSchemaJSON(schema []byte) error

SetSchemaJSON replaces the active schema JSON.

func (*DB) StatsJSON

func (db *DB) StatsJSON() ([]byte, error)

StatsJSON returns database stats as JSON.

func (*DB) Status

func (db *DB) Status() (*Status, error)

Status returns the typed Lite status document for the database.

func (*DB) StatusJSON

func (db *DB) StatusJSON() ([]byte, error)

StatusJSON returns a JSON status document for the Lite database.

func (*DB) SuppressResolverKeysJSON

func (db *DB) SuppressResolverKeysJSON(resolver string, request []byte) ([]byte, error)

SuppressResolverKeysJSON atomically updates runtime key and text suppressions.

func (*DB) TextMatchPhraseWire

func (db *DB) TextMatchPhraseWire(request []byte) ([]byte, error)

TextMatchPhraseWire executes a packed text-match-phrase wire search request.

func (*DB) TextMatchWire

func (db *DB) TextMatchWire(request []byte) ([]byte, error)

TextMatchWire executes a packed text-match wire search request.

func (*DB) TextTermWire

func (db *DB) TextTermWire(request []byte) ([]byte, error)

TextTermWire executes a packed text-term wire search request.

func (*DB) TransactionStatus

func (db *DB) TransactionStatus(txnID TxnID) (TxnStatus, error)

TransactionStatus returns the current transaction lifecycle state.

func (*DB) TraverseEdgesJSON

func (db *DB) TraverseEdgesJSON(request []byte) ([]byte, error)

TraverseEdgesJSON executes a JSON graph traversal request.

func (*DB) UnmergeResolverKeyJSON

func (db *DB) UnmergeResolverKeyJSON(resolver string, request []byte) ([]byte, error)

UnmergeResolverKeyJSON undoes a redirect and can pin its former target distinct.

func (*DB) UnsuppressResolverKeyJSON

func (db *DB) UnsuppressResolverKeyJSON(resolver string, request []byte) ([]byte, error)

UnsuppressResolverKeyJSON removes runtime suppression while preserving declarative rules.

func (*DB) Vacuum

func (db *DB) Vacuum() (*VacuumReport, error)

Vacuum compacts free space and returns the typed result.

func (*DB) VacuumJSON

func (db *DB) VacuumJSON() ([]byte, error)

VacuumJSON compacts free space and returns the JSON result.

func (*DB) WriteTransaction

func (db *DB) WriteTransaction(txnID TxnID, writes []WriteIntent) error

WriteTransaction appends write intents to an open local transaction.

type ErrorCode

type ErrorCode uint32

ErrorCode is a stable Antfly C ABI error code.

const (
	OK              ErrorCode = 0
	InvalidArgument ErrorCode = 1
	NotFound        ErrorCode = 2
	VersionConflict ErrorCode = 3
	IntentConflict  ErrorCode = 4
	TxnNotFound     ErrorCode = 5
	Busy            ErrorCode = 6
	// OutcomeUnknown means the operation may have taken effect: either it
	// was published but crash durability could not be confirmed, or a failure
	// left it unknown whether it applied at all. Inspect the affected data
	// and do not retry the operation automatically.
	OutcomeUnknown ErrorCode = 7
	// Unsupported means the operation requires a platform or filesystem
	// capability that is unavailable. Retrying unchanged will not succeed.
	Unsupported ErrorCode = 8
	// Stalled reports stalled derived work or a failed derived worker. Inspect
	// pending-work diagnostics and repair or reopen the database. A batch may
	// already have committed: inspect its error detail and do not replay it
	// when reported as committed.
	Stalled ErrorCode = 9
	// Cancelled means the operation was cancelled, including cancellation
	// of a pending replacement or a false progress/stream callback result
	// (see Inference.Pull and Inference.GenerateStream).
	Cancelled                        ErrorCode = 10
	ReplacementFailed                ErrorCode = 11
	ReplacementPending               ErrorCode = 12
	ReplacementConfigurationMismatch ErrorCode = 13
	Internal                         ErrorCode = 255
)

func (ErrorCode) Description

func (code ErrorCode) Description() string

Description returns a short stable description for code.

func (ErrorCode) Error

func (code ErrorCode) Error() string

func (ErrorCode) Name

func (code ErrorCode) Name() string

Name returns the stable symbolic C ABI name for code.

type GraphError

type GraphError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Span    *struct {
		Start int `json:"start"`
		End   int `json:"end"`
	} `json:"span,omitempty"`
	WriteOutcome  string `json:"write_outcome,omitempty"`
	TransactionID string `json:"transaction_id,omitempty"`
	Cause         error  `json:"-"`
}

GraphError retains the native Cypher diagnostic and write delivery outcome.

func (*GraphError) Error

func (e *GraphError) Error() string

func (*GraphError) Unwrap

func (e *GraphError) Unwrap() error

type Inference

type Inference struct {
	// contains filtered or unexported fields
}

Inference is an embedded Antfly inference runtime handle with no database attached: models load on first use and stay cached until Close.

Like DB, an *Inference is safe for concurrent use by multiple goroutines. Close waits for in-flight calls to finish; calls made after Close return InvalidArgument. Models run in the calling process on every backend, including Metal, CUDA, and ONNX: once a call reaches the device or driver it cannot be interrupted, so CallTimeout and Close only take effect when the call returns on its own, and a driver fault terminates the process.

func OpenInference

func OpenInference(opts *InferenceOptions) (*Inference, error)

OpenInference opens an embedded inference runtime handle with no database attached. opts may be nil to use the runtime's defaults. OpenInference returns Unsupported when this build does not link the inference runtime or the runtime cannot start.

func (*Inference) Chunk

func (inf *Inference) Chunk(request []byte) ([]byte, error)

Chunk splits request's input per the inference API's POST /ai/v1/chunk.

func (*Inference) Close

func (inf *Inference) Close() error

Close releases the inference handle, waiting for in-flight calls on other goroutines to finish first. It is safe to call more than once and concurrently.

func (*Inference) Decide

func (inf *Inference) Decide(request []byte) ([]byte, error)

Decide answers named choice, ordinal score, and Boolean questions via the inference API's POST /ai/v1/decisions.

func (*Inference) Embed

func (inf *Inference) Embed(request []byte) ([]byte, error)

Embed returns embeddings for request, the JSON body of the inference API's POST /ai/v1/embed.

func (*Inference) Extract

func (inf *Inference) Extract(request []byte) ([]byte, error)

Extract runs the inference API's POST /ai/v1/extract.

func (*Inference) Generate

func (inf *Inference) Generate(request []byte) ([]byte, error)

Generate runs the inference API's POST /ai/v1/generate. A request with "stream": true fails with InvalidArgument: responses are always complete. Use GenerateStream to stream chunks instead.

func (*Inference) GenerateBatch

func (inf *Inference) GenerateBatch(request []byte) ([]byte, error)

GenerateBatch runs up to 128 non-streaming generate requests in one call (POST /ai/v1/generate/batch); per-item failures are reported in the response rather than as a Go error.

func (*Inference) GenerateStream

func (inf *Inference) GenerateStream(ctx context.Context, request []byte, onChunk func(chunk []byte) bool) error

GenerateStream streams a generate request: request is the same JSON body Generate takes, minus "stream" (antfly_inference_generate_stream_json sets it for you). onChunk is called synchronously on the calling goroutine for each "chat.completion.chunk" JSON chunk as the model produces tokens; the chunk is only valid during the callback, so GenerateStream copies it before calling onChunk. onChunk must be non-nil.

ctx is checked before each callback; if it is done, or onChunk returns false, generation stops and GenerateStream returns Cancelled. A nil ctx is treated as context.Background() (no cancellation via ctx).

A request rejected before generation starts (such as a missing model) fails like Generate, with the JSON error available via errors.As(err, &InferenceError{}); a failure mid-stream returns Internal with API code "STREAM_FAILED".

func (*Inference) ListModels

func (inf *Inference) ListModels() ([]byte, error)

ListModels returns the installed models, as returned by the inference API's GET /ai/v1/models.

func (*Inference) Pull

func (inf *Inference) Pull(ctx context.Context, request []byte, progress func(PullProgress) bool) ([]byte, error)

Pull downloads a model from the Hugging Face Hub into the handle's models directory, like `antfly inference pull`. request is the JSON body documented on antfly_inference_pull_json in antfly.h, e.g. {"model": "owner/name[:variant]"}.

progress, if non-nil, is called synchronously on the calling goroutine as each file starts, every 16 MiB, and as each file completes. ctx is checked at the same points; if it is done, or progress returns false, the download stops and Pull returns Cancelled. Completed files stay staged, so a later Pull for the same model resumes rather than restarts. A nil ctx is treated as context.Background() (no cancellation via ctx).

func (*Inference) Read

func (inf *Inference) Read(request []byte) ([]byte, error)

Read reads images, documents, or audio via the inference API's POST /ai/v1/read.

func (*Inference) Rerank

func (inf *Inference) Rerank(request []byte) ([]byte, error)

Rerank scores request against the inference API's POST /ai/v1/rerank.

func (*Inference) Rewrite

func (inf *Inference) Rewrite(request []byte) ([]byte, error)

Rewrite runs the inference API's POST /ai/v1/rewrite.

type InferenceAPIError

type InferenceAPIError struct {
	Code    string `json:"error"`
	Message string `json:"message"`
}

InferenceAPIError is the JSON error body an Antfly inference call returns on failure: {"error": "...", "message": "..."}. Code is a stable string such as "MODEL_NOT_FOUND"; either field may be empty when the body was not present or not in this shape.

type InferenceError

type InferenceError struct {
	// ErrorCode is the C ABI error code mapped from the call's HTTP-shaped
	// failure (see antfly.h's "Embedded inference without a database").
	ErrorCode ErrorCode
	// API is the parsed JSON error body, when the body was valid JSON in the
	// {"error":..., "message":...} shape.
	API InferenceAPIError
	// Body is the raw JSON error body returned by the call, if any.
	Body []byte
}

InferenceError is returned by failed Inference JSON calls. It carries the stable C ABI error code (see ErrorCode) plus the inference runtime's JSON error body, when one was returned. errors.Is(err, code) and errors.As(err, &inferenceErr) both work against it.

func (*InferenceError) Error

func (e *InferenceError) Error() string

func (*InferenceError) Unwrap

func (e *InferenceError) Unwrap() error

Unwrap exposes the underlying stable ErrorCode for errors.Is/errors.As.

type InferenceOptions

type InferenceOptions struct {
	// ModelsDir overrides the models directory. Empty uses
	// $ANTFLY_INFERENCE_MODELS_DIR, else ~/.antfly/inference/models.
	ModelsDir string
	// HostBudgetMB, BackendBudgetMB, ProcessMemoryBudgetMB, CombinedBudgetMB,
	// KVBudgetMB, and ScratchBudgetMB are explicit resource-budget overrides
	// in MiB; 0 means automatic. These mirror OpenOptions' inference budget
	// fields and the antfly CLI's --inference-*-budget-mb flags.
	HostBudgetMB          uint32
	BackendBudgetMB       uint32
	ProcessMemoryBudgetMB uint32
	CombinedBudgetMB      uint32
	KVBudgetMB            uint32
	ScratchBudgetMB       uint32
	// CallTimeout bounds each call; the C ABI takes whole milliseconds and
	// CallTimeout is rounded up to the nearest millisecond. Zero means no
	// deadline. Because models run in the calling process, a call that has
	// already reached a GPU driver cannot be interrupted: the timeout takes
	// effect only when the call returns.
	CallTimeout time.Duration
}

InferenceOptions configures OpenInference. The zero value uses the runtime's own defaults for every field (see antfly_inference_options_init in antfly.h); a nil *InferenceOptions passed to OpenInference does the same.

type InferenceStatus

type InferenceStatus struct {
	Mode                     string                `json:"mode"`
	AvailableModes           []string              `json:"available_modes"`
	Configured               bool                  `json:"configured"`
	RemoteProviderConfigured bool                  `json:"remote_provider_configured"`
	LocalRuntimeConfigured   bool                  `json:"local_runtime_configured"`
	LocalRuntimeAvailable    bool                  `json:"local_runtime_available"`
	CallerSuppliedArtifacts  bool                  `json:"caller_supplied_artifacts"`
	NoInferenceConfiguredOK  bool                  `json:"no_inference_configured_ok"`
	HostBudgetMB             uint32                `json:"host_budget_mb"`
	BackendBudgetMB          uint32                `json:"backend_budget_mb"`
	CombinedBudgetMB         uint32                `json:"combined_budget_mb"`
	KVBudgetMB               uint32                `json:"kv_budget_mb"`
	ScratchBudgetMB          uint32                `json:"scratch_budget_mb"`
	ProcessMemoryBudgetMB    uint32                `json:"process_memory_budget_mb"`
	ProcessMemoryLimitBytes  uint64                `json:"process_memory_limit_bytes"`
	ProcessMemoryLimitSource string                `json:"process_memory_limit_source"`
	MemoryAdmission          *MemoryAdmissionStats `json:"memory_admission,omitempty"`
}

InferenceStatus reports the configured inference execution mode for a Lite handle. A fresh core Lite database normally reports Configured=false and NoInferenceConfiguredOK=true.

HostBudgetMB, BackendBudgetMB, CombinedBudgetMB, KVBudgetMB, ScratchBudgetMB, and ProcessMemoryBudgetMB initially echo the OpenOptions resource-budget overrides requested for the local embedded runtime (0 meaning the embedded node's own host-clamped default, not automatic/ unbounded). Once a local runtime actually starts, all six are overwritten with the resolved effective values the node installed -- either the explicit override, or the host-clamped default from antfly's inference_provider.zig (default_host_budget_mb and friends) -- so none of the five generation-budget fields read 0 for a started local runtime. ProcessMemoryLimitBytes and ProcessMemoryLimitSource report the process memory envelope the embedded node resolved: either the explicit ProcessMemoryBudgetMB override, or the same host/cgroup-detected policy `antfly inference run` and `antfly standalone` report at startup. All of these stay at their zero-value/"automatic" defaults until a local runtime is actually started.

type LiveByteAccounting

type LiveByteAccounting struct {
	MetadataCatalog  LiveByteCategory `json:"metadata_catalog"`
	IndexCatalog     LiveByteCategory `json:"index_catalog"`
	ControlDocuments LiveByteCategory `json:"control_documents"`
	Documents        LiveByteCategory `json:"documents"`
}

LiveByteAccounting attributes the logical payload visited by integrity checks.

type LiveByteCategory

type LiveByteCategory struct {
	Records    uint64 `json:"records"`
	KeyBytes   uint64 `json:"key_bytes"`
	ValueBytes uint64 `json:"value_bytes"`
}

LiveByteCategory counts logical key/value payload, excluding physical headers.

type MemoryAdmissionStats

type MemoryAdmissionStats struct {
	Pressure              string `json:"pressure"`
	DeniedCount           uint64 `json:"denied_count"`
	LastDeniedNS          uint64 `json:"last_denied_ns"`
	RequestCount          uint64 `json:"request_count"`
	RequestedHostBytes    uint64 `json:"requested_host_bytes"`
	RequestedBackendBytes uint64 `json:"requested_backend_bytes"`
	RequestedKVBytes      uint64 `json:"requested_kv_bytes"`
	RequestedScratchBytes uint64 `json:"requested_scratch_bytes"`
	AdmittedHostBytes     uint64 `json:"admitted_host_bytes"`
	AdmittedBackendBytes  uint64 `json:"admitted_backend_bytes"`
	HostLimitBytes        uint64 `json:"host_limit_bytes"`
	BackendLimitBytes     uint64 `json:"backend_limit_bytes"`
	CombinedLimitBytes    uint64 `json:"combined_limit_bytes"`
	AvailableMemoryBytes  uint64 `json:"available_memory_bytes"`
}

MemoryAdmissionStats is the historical snapshot of the local runtime's last denied memory admission. LastDeniedNS uses the process monotonic clock.

type NativeError

type NativeError struct {
	Code   ErrorCode
	Detail string
	// OutcomeReceipt is set when an autocommit SQL write or a batch failed
	// with OutcomeUnknown and the database issued a receipt for it. Resolve
	// it later with DB.OutcomeReceiptStatus.
	OutcomeReceipt string
}

NativeError owns the diagnostic captured from one failed native call. errors.Is(err, ErrorCode) continues to classify the stable code.

func (*NativeError) Error

func (e *NativeError) Error() string

func (*NativeError) Unwrap

func (e *NativeError) Unwrap() error

type OpenMode

type OpenMode uint32

OpenMode controls how an Antfly Lite file is opened.

const (
	OpenModeWriter     OpenMode = C.ANTFLY_OPEN_MODE_WRITER
	OpenModeReadonly   OpenMode = C.ANTFLY_OPEN_MODE_READONLY
	OpenModeStatusOnly OpenMode = C.ANTFLY_OPEN_MODE_STATUS_ONLY
)

type OpenOptions

type OpenOptions struct {
	// ModelsDir selects models used by database enrichments. Empty uses default.
	ModelsDir string
	// Storage selects a .aflite file (the default) or a directory. Directory
	// storage is created by opening a missing path; CreateWithOptions only
	// creates .aflite files.
	Storage                   Storage
	Mode                      OpenMode
	Profile                   Profile
	NoSync                    bool
	RemoteProviderConfigured  bool
	LocalRuntimeConfigured    bool
	GeneratedEnrichmentReplay bool
	MapSize                   uint64
	TTLCleanup                *TTLCleanupOptions
	HostBudgetMB              uint32
	BackendBudgetMB           uint32
	CombinedBudgetMB          uint32
	KVBudgetMB                uint32
	ScratchBudgetMB           uint32
	ProcessMemoryBudgetMB     uint32
	BusyTimeout               time.Duration
}

OpenOptions configures OpenWithOptions and CreateWithOptions.

BusyTimeout, like sqlite3_busy_timeout, retries Lite admission while another process holds the writer lease or advances the allocator checkpoint. Mutation bodies are never replayed by this admission retry. Zero fails immediately with Busy. The C ABI takes whole milliseconds.

HostBudgetMB, BackendBudgetMB, CombinedBudgetMB, KVBudgetMB, ScratchBudgetMB, and ProcessMemoryBudgetMB are explicit resource-budget overrides for the local embedded inference runtime (0 means the embedded node's own host-clamped default, not the previous automatic/zero-bytes policy -- see antfly's inference_provider.zig default_*_budget_mb constants). They are only consulted when LocalRuntimeConfigured is set, and mirror the antfly CLI's --inference-host-budget-mb/ --inference-backend-budget-mb/--inference-combined-budget-mb/ --inference-kv-budget-mb/--inference-scratch-budget-mb/ --process-memory-budget-mb flags.

type OutcomeReceiptStatus

type OutcomeReceiptStatus uint8

OutcomeReceiptStatus is the resolved outcome of an OutcomeUnknown write.

const (
	// OutcomeReceiptApplied means the uncertain write applied.
	OutcomeReceiptApplied OutcomeReceiptStatus = 1
	// OutcomeReceiptNotApplied means the uncertain write did not apply.
	OutcomeReceiptNotApplied OutcomeReceiptStatus = 2
)

func (OutcomeReceiptStatus) String

func (status OutcomeReceiptStatus) String() string

type PendingWorkStatus

type PendingWorkStatus struct {
	BackgroundPublications              json.RawMessage   `json:"background_publications,omitempty"`
	DerivedTargetSequence               uint64            `json:"derived_target_sequence"`
	HasAsyncIndexes                     bool              `json:"has_async_indexes"`
	PortableImportPublicationInProgress bool              `json:"portable_import_publication_in_progress"`
	PortableImportRecoveryRequired      bool              `json:"portable_import_recovery_required"`
	PortableRuntimeActivationPending    bool              `json:"portable_runtime_activation_pending"`
	Enrichment                          json.RawMessage   `json:"enrichment"`
	Resolution                          json.RawMessage   `json:"resolution"`
	Promotion                           json.RawMessage   `json:"promotion"`
	TextMerge                           json.RawMessage   `json:"text_merge"`
	Replacements                        []json.RawMessage `json:"replacements,omitempty"`
}

PendingWorkStatus describes the stable Lite readiness fields for derived work. The nested maintenance telemetry is intentionally retained as raw JSON because it is operational detail rather than control-plane contract.

type Profile

type Profile uint32

Profile selects the Lite runtime profile.

const (
	ProfileNative Profile = C.ANTFLY_PROFILE_NATIVE
	ProfileHosted Profile = C.ANTFLY_PROFILE_HOSTED
)

type PullProgress

type PullProgress struct {
	// Model is the model reference being pulled (one per requested variant).
	Model           string
	File            string
	BytesDownloaded uint64
	// TotalBytes is 0 when unknown.
	TotalBytes uint64
	FilesDone  uint64
	FilesTotal uint64
	// Cached reports that File was already present and verified; nothing was
	// downloaded for it.
	Cached bool
}

PullProgress reports one file's download progress for a Pull call.

type ReplayGeneratedEnrichmentsResult

type ReplayGeneratedEnrichmentsResult struct {
	Replayed uint64 `json:"replayed"`
}

ReplayGeneratedEnrichmentsResult reports how many generated enrichment references were recreated from stored documents.

type RestoreOptions

type RestoreOptions struct {
	// Storage selects the kind of database created at the destination: a
	// .aflite file (the default) or a directory.
	Storage Storage
	// Replace atomically replaces an existing destination.
	Replace bool
}

RestoreOptions configures Restore and RestoreFile.

type SQLCursor

type SQLCursor struct {
	ID uint64
	// contains filtered or unexported fields
}

SQLCursor streams native result pages without imposing a SQL row limit.

func (*SQLCursor) Close

func (c *SQLCursor) Close() error

func (*SQLCursor) FetchJSON

func (c *SQLCursor) FetchJSON(rows uint32) ([]byte, error)

type SQLError

type SQLError struct {
	TransactionID string `json:"transaction_id,omitempty"`
	Code          string `json:"code"`
	Message       string `json:"message"`
	Hint          string `json:"hint"`
	Retryable     bool   `json:"retryable"`
	// OutcomeReceipt is set when an autocommit SQL write ended with
	// OutcomeUnknown and the database issued a receipt for it. Resolve it
	// later with DB.OutcomeReceiptStatus.
	OutcomeReceipt string `json:"-"`
}

SQLError includes the engine's SQLSTATE diagnostic.

func (*SQLError) Error

func (e *SQLError) Error() string

func (*SQLError) SQLState

func (e *SQLError) SQLState() string

type SQLSession

type SQLSession struct {
	ID uint64
	// contains filtered or unexported fields
}

SQLSession is a connection-local SQL transaction owner. Close rolls back staged writes and closes its cursors. A database may own multiple sessions.

func (*SQLSession) Close

func (s *SQLSession) Close() error

func (*SQLSession) SQLJSON

func (s *SQLSession) SQLJSON(request []byte) ([]byte, error)

type StableSnapshotReport

type StableSnapshotReport struct {
	SourceSize         uint64 `json:"source_size"`
	SnapshotSize       uint64 `json:"snapshot_size"`
	CheckpointSequence uint64 `json:"checkpoint_sequence"`
	PageCount          uint64 `json:"page_count"`
	TailBytes          uint64 `json:"tail_bytes"`
}

StableSnapshotReport is the typed form of CopyStableSnapshotJSON.

func CopyStableSnapshotFile

func CopyStableSnapshotFile(srcPath, destPath string, replace bool) (*StableSnapshotReport, error)

CopyStableSnapshotFile opens srcPath read-only, copies a stable physical .aflite snapshot to destPath, and returns the typed snapshot report.

type Status

type Status struct {
	Storage      StorageStatus     `json:"storage"`
	Stats        json.RawMessage   `json:"stats"`
	PendingWork  PendingWorkStatus `json:"pending_work"`
	Inference    InferenceStatus   `json:"inference"`
	Capabilities Capabilities      `json:"capabilities"`
}

Status is the typed form of StatusJSON. Stats is retained as raw JSON because its internal shape is broader than the stable Lite control fields bindings need for feature branching.

type Storage

type Storage uint32

Storage selects how a database is stored. The zero value is a single-file .aflite database.

const (
	// StorageLite is a single-file .aflite database.
	StorageLite Storage = iota
	// StorageDirectory is a normal single-node Antfly directory.
	StorageDirectory
)

type StorageStatus

type StorageStatus struct {
	Format             string  `json:"format"`
	Engine             string  `json:"engine"`
	PrimaryLayout      string  `json:"primary_layout"`
	ReplayLayout       string  `json:"replay_layout"`
	IndexLayout        string  `json:"index_layout"`
	IndexNamespace     *string `json:"index_namespace,omitempty"`
	FormatVersion      *uint32 `json:"format_version,omitempty"`
	PageSize           *uint32 `json:"page_size,omitempty"`
	ActiveCheckpoint   *uint8  `json:"active_checkpoint,omitempty"`
	CheckpointSequence *uint64 `json:"checkpoint_sequence,omitempty"`
	PageCount          *uint64 `json:"page_count,omitempty"`
}

StorageStatus describes the physical Lite database file backing a handle.

type TTLCleanupOptions

type TTLCleanupOptions struct {
	Enabled       bool
	LeaseOwned    bool
	OwnerID       string
	LeaseTTLMS    uint64
	IntervalMS    uint64
	BatchSize     uint32
	GracePeriodNS uint64
}

TTLCleanupOptions configures the optional Lite TTL cleanup runtime.

type TxnID

type TxnID [16]byte

TxnID is the stable 16-byte transaction identifier used by the C ABI.

type TxnStatus

type TxnStatus uint8

TxnStatus is a transaction intent lifecycle state.

const (
	TxnPending   TxnStatus = C.ANTFLY_TXN_PENDING
	TxnCommitted TxnStatus = C.ANTFLY_TXN_COMMITTED
	TxnAborted   TxnStatus = C.ANTFLY_TXN_ABORTED
)

type VacuumReport

type VacuumReport struct {
	BeforeSize     uint64 `json:"before_size"`
	AfterSize      uint64 `json:"after_size"`
	ReclaimedBytes uint64 `json:"reclaimed_bytes"`
	LiveFileCount  uint64 `json:"live_file_count"`
	LiveBytes      uint64 `json:"live_bytes"`
}

VacuumReport is the typed form of VacuumJSON.

type WriteIntent

type WriteIntent struct {
	Key    string
	Value  []byte
	Delete bool
}

WriteIntent is a single key/value write or delete in a Lite batch.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL