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
- func ABIVersion() uint32
- func CheckFileJSON(path string) ([]byte, error)
- func CopyStableSnapshotFileJSON(srcPath, destPath string, replace bool) ([]byte, error)
- func DecodeArtifactIDJSON(artifactIDBase64 string) ([]byte, error)
- func InferenceOptionsSize() uint32
- func LastErrorDetail() string
- func OpenOptionsSize() uint32
- func OutcomeReceiptOf(err error) (string, bool)
- func Restore(path string, backup []byte, opts RestoreOptions) error
- func RestoreFile(path, backupPath string, opts RestoreOptions) error
- func ThreadingMode() uint32
- func ValidateABI() error
- type Capabilities
- type CheckReport
- type CompactReport
- type DB
- func Create(path string) (*DB, error)
- func CreateHosted(path string) (*DB, error)
- func CreateWithOptions(path string, opts OpenOptions) (*DB, error)
- func Open(path string) (*DB, error)
- func OpenHosted(path string) (*DB, error)
- func OpenReadonly(path string) (*DB, error)
- func OpenStatusOnly(path string) (*DB, error)
- func OpenWithOptions(path string, opts OpenOptions) (*DB, error)
- func (db *DB) AddEnrichmentJSON(config []byte) error
- func (db *DB) AddIndexJSON(config []byte) error
- func (db *DB) AggregateHitsJSON(request []byte) ([]byte, error)
- func (db *DB) Backup() ([]byte, error)
- func (db *DB) BackupJSON(options []byte) ([]byte, error)
- func (db *DB) BackupToFile(path string) error
- func (db *DB) Batch(writes []WriteIntent, timestampNS uint64) error
- func (db *DB) BatchJSON(request []byte) ([]byte, error)
- func (db *DB) BeginTransaction(txnID TxnID, timestampNS uint64, participants []string) error
- func (db *DB) CancelReplacement(name string) (bool, error)
- func (db *DB) Capabilities() (*Capabilities, error)
- func (db *DB) CapabilitiesJSON() ([]byte, error)
- func (db *DB) Check() (*CheckReport, error)
- func (db *DB) CheckJSON() ([]byte, error)
- func (db *DB) Close() error
- func (db *DB) CommitVersion(txnID TxnID) (uint64, error)
- func (db *DB) Compact() (*CompactReport, error)
- func (db *DB) CompactJSON() ([]byte, error)
- func (db *DB) ComputeEnrichmentsJSON(request []byte) ([]byte, error)
- func (db *DB) CopyStableSnapshot(destPath string, replace bool) (*StableSnapshotReport, error)
- func (db *DB) CopyStableSnapshotJSON(destPath string, replace bool) ([]byte, error)
- func (db *DB) CreateTableJSON(name string, schema []byte) error
- func (db *DB) CurateEntityJSON(table, key string, request []byte) ([]byte, error)
- func (db *DB) CypherJSON(graph string, request []byte) ([]byte, error)
- func (db *DB) DeleteEnrichment(kind, name string) (bool, error)
- func (db *DB) DeleteIndex(name string) (bool, error)
- func (db *DB) DenseSearchWire(request []byte) ([]byte, error)
- func (db *DB) DropResolverIdentity(name string) (bool, error)
- func (db *DB) DropTable(name string) error
- func (db *DB) EdgesJSON(indexName, key, edgeType string, direction uint8) ([]byte, error)
- func (db *DB) EnrichmentsJSON() ([]byte, error)
- func (db *DB) ExecuteGraphQueriesJSON(request []byte) ([]byte, error)
- func (db *DB) ExtractEnrichmentsJSON(request []byte) ([]byte, error)
- func (db *DB) FindKShortestPathsJSON(request []byte) ([]byte, error)
- func (db *DB) FindShortestPathJSON(request []byte) ([]byte, error)
- func (db *DB) ForgetOutcomeReceipt(receipt string) error
- func (db *DB) GraphCatalogJSON(request []byte) ([]byte, error)
- func (db *DB) GraphWriteStatusJSON(transactionID string) ([]byte, error)
- func (db *DB) ImportBackup(backup []byte) error
- func (db *DB) IndexesJSON() ([]byte, error)
- func (db *DB) ListTablesJSON() ([]byte, error)
- func (db *DB) LookupArtifactJSON(artifactIDBase64 string) ([]byte, error)
- func (db *DB) LookupJSON(key string) ([]byte, error)
- func (db *DB) MatchPatternJSON(request []byte) ([]byte, error)
- func (db *DB) MemoryJSON(space string, request []byte) ([]byte, error)
- func (db *DB) MergeResolverKeysJSON(resolver string, request []byte) error
- func (db *DB) NeighborsJSON(indexName, key, edgeType string, direction uint8) ([]byte, error)
- func (db *DB) NewSQLSession() (*SQLSession, error)
- func (db *DB) OpenSQLCursorJSON(request []byte) (*SQLCursor, error)
- func (db *DB) OpenTable(name string) (*DB, error)
- func (db *DB) OutcomeReceiptStatus(receipt string) (OutcomeReceiptStatus, error)
- func (db *DB) PendingWorkStats() (*PendingWorkStatus, error)
- func (db *DB) PendingWorkStatsJSON() ([]byte, error)
- func (db *DB) Raw(key string) ([]byte, error)
- func (db *DB) RenderResolverKeyJSON(resolver string, mention []byte) ([]byte, error)
- func (db *DB) ReplayGeneratedEnrichments() (*ReplayGeneratedEnrichmentsResult, error)
- func (db *DB) ReplayGeneratedEnrichmentsJSON() ([]byte, error)
- func (db *DB) ResolveQueryJSON(resolver string, mention []byte) ([]byte, error)
- func (db *DB) ResolveTransaction(txnID TxnID, status TxnStatus, commitVersion uint64) error
- func (db *DB) ResolverCurationJSON(resolver string) ([]byte, error)
- func (db *DB) ResolverIdentitiesJSON() ([]byte, error)
- func (db *DB) ResolverReviewsJSON(request []byte) ([]byte, error)
- func (db *DB) RunUntilIdle() error
- func (db *DB) RunUntilIdleJSON() ([]byte, error)
- func (db *DB) RunUntilIdleStatus() (*PendingWorkStatus, error)
- func (db *DB) SQLJSON(request []byte) ([]byte, error)
- func (db *DB) ScanJSON(request []byte) ([]byte, error)
- func (db *DB) SchemaJSON() ([]byte, error)
- func (db *DB) SearchJSON(request []byte) ([]byte, error)
- func (db *DB) SetResolverNamespaceJSON(resolver string, request []byte) error
- func (db *DB) SetSchemaJSON(schema []byte) error
- func (db *DB) StatsJSON() ([]byte, error)
- func (db *DB) Status() (*Status, error)
- func (db *DB) StatusJSON() ([]byte, error)
- func (db *DB) SuppressResolverKeysJSON(resolver string, request []byte) ([]byte, error)
- func (db *DB) TextMatchPhraseWire(request []byte) ([]byte, error)
- func (db *DB) TextMatchWire(request []byte) ([]byte, error)
- func (db *DB) TextTermWire(request []byte) ([]byte, error)
- func (db *DB) TransactionStatus(txnID TxnID) (TxnStatus, error)
- func (db *DB) TraverseEdgesJSON(request []byte) ([]byte, error)
- func (db *DB) UnmergeResolverKeyJSON(resolver string, request []byte) ([]byte, error)
- func (db *DB) UnsuppressResolverKeyJSON(resolver string, request []byte) ([]byte, error)
- func (db *DB) Vacuum() (*VacuumReport, error)
- func (db *DB) VacuumJSON() ([]byte, error)
- func (db *DB) WriteTransaction(txnID TxnID, writes []WriteIntent) error
- type ErrorCode
- type GraphError
- type Inference
- func (inf *Inference) Chunk(request []byte) ([]byte, error)
- func (inf *Inference) Close() error
- func (inf *Inference) Decide(request []byte) ([]byte, error)
- func (inf *Inference) Embed(request []byte) ([]byte, error)
- func (inf *Inference) Extract(request []byte) ([]byte, error)
- func (inf *Inference) Generate(request []byte) ([]byte, error)
- func (inf *Inference) GenerateBatch(request []byte) ([]byte, error)
- func (inf *Inference) GenerateStream(ctx context.Context, request []byte, onChunk func(chunk []byte) bool) error
- func (inf *Inference) ListModels() ([]byte, error)
- func (inf *Inference) Pull(ctx context.Context, request []byte, progress func(PullProgress) bool) ([]byte, error)
- func (inf *Inference) Read(request []byte) ([]byte, error)
- func (inf *Inference) Rerank(request []byte) ([]byte, error)
- func (inf *Inference) Rewrite(request []byte) ([]byte, error)
- type InferenceAPIError
- type InferenceError
- type InferenceOptions
- type InferenceStatus
- type LiveByteAccounting
- type LiveByteCategory
- type MemoryAdmissionStats
- type NativeError
- type OpenMode
- type OpenOptions
- type OutcomeReceiptStatus
- type PendingWorkStatus
- type Profile
- type PullProgress
- type ReplayGeneratedEnrichmentsResult
- type RestoreOptions
- type SQLCursor
- type SQLError
- type SQLSession
- type StableSnapshotReport
- type Status
- type Storage
- type StorageStatus
- type TTLCleanupOptions
- type TxnID
- type TxnStatus
- type VacuumReport
- type WriteIntent
Constants ¶
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.
const SupportedABIVersion uint32 = 3
SupportedABIVersion is the Antfly C ABI version this binding expects.
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 CheckFileJSON ¶
CheckFileJSON runs Lite integrity checks for path without opening a database handle and returns the JSON result.
func CopyStableSnapshotFileJSON ¶
CopyStableSnapshotFileJSON opens srcPath read-only, copies a stable Lite snapshot to destPath, and returns the JSON result.
func DecodeArtifactIDJSON ¶
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 ¶
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 CreateHosted ¶
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 OpenHosted ¶
OpenHosted opens an existing Antfly Lite database in hosted/manual maintenance mode. In this profile callers drive pending work explicitly with RunUntilIdle.
func OpenReadonly ¶
OpenReadonly opens an existing Antfly Lite database file read-only.
func OpenStatusOnly ¶
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 ¶
AddEnrichmentJSON adds an enrichment from its JSON configuration.
func (*DB) AddIndexJSON ¶
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 ¶
AggregateHitsJSON aggregates hits from a JSON request.
func (*DB) Backup ¶
Backup returns a portable Antfly backup archive (.afb) of this database, which restores or imports into either storage kind.
func (*DB) BackupJSON ¶
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 ¶
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 ¶
BatchJSON applies a public Antfly batch request and returns the JSON result. An OutcomeUnknown failure carries an outcome receipt (see OutcomeReceiptOf).
func (*DB) BeginTransaction ¶
BeginTransaction starts a local transaction with an explicit transaction ID.
func (*DB) CancelReplacement ¶
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 ¶
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) Close ¶
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 ¶
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 ¶
CompactJSON drains maintenance, compacts indexes, vacuums free space, and returns the JSON result.
func (*DB) ComputeEnrichmentsJSON ¶
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 ¶
CopyStableSnapshotJSON copies a stable Lite snapshot to destPath.
func (*DB) CurateEntityJSON ¶
CurateEntityJSON applies an entity correction to every matching resolver namespace.
func (*DB) CypherJSON ¶
CypherJSON uses the hosted query contract and lossless tagged result values.
func (*DB) DeleteEnrichment ¶
DeleteEnrichment deletes an enrichment by kind and name and reports whether it existed.
func (*DB) DeleteIndex ¶
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 ¶
DenseSearchWire executes a packed dense-vector wire search request.
func (*DB) DropResolverIdentity ¶
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) EnrichmentsJSON ¶
EnrichmentsJSON returns configured enrichments as JSON.
func (*DB) ExecuteGraphQueriesJSON ¶
ExecuteGraphQueriesJSON executes a batch of JSON graph queries.
func (*DB) ExtractEnrichmentsJSON ¶
ExtractEnrichmentsJSON extracts enrichment outputs for a JSON request.
func (*DB) FindKShortestPathsJSON ¶
FindKShortestPathsJSON executes a JSON k-shortest-paths graph request.
func (*DB) FindShortestPathJSON ¶
FindShortestPathJSON executes a JSON shortest-path graph request.
func (*DB) ForgetOutcomeReceipt ¶
ForgetOutcomeReceipt removes a resolved receipt's durable marker. Afterwards the receipt can no longer be resolved.
func (*DB) GraphCatalogJSON ¶
GraphCatalogJSON gets/lists/puts/drops graphs. Updates require expected_revision.
func (*DB) GraphWriteStatusJSON ¶
GraphWriteStatusJSON resolves a receipt without replaying the graph statement.
func (*DB) ImportBackup ¶
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 ¶
IndexesJSON returns configured indexes as JSON.
func (*DB) ListTablesJSON ¶
func (*DB) LookupArtifactJSON ¶
LookupArtifactJSON looks up an artifact by base64 artifact ID.
func (*DB) LookupJSON ¶
LookupJSON returns the JSON lookup result for key.
func (*DB) MatchPatternJSON ¶
MatchPatternJSON executes a JSON graph pattern-match request.
func (*DB) MemoryJSON ¶
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 ¶
MergeResolverKeysJSON persists {"key","target"}; RunUntilIdle re-keys existing resolution edges.
func (*DB) NeighborsJSON ¶
NeighborsJSON returns graph neighbors for a key from a graph index.
func (*DB) NewSQLSession ¶
func (db *DB) NewSQLSession() (*SQLSession, error)
func (*DB) OpenTable ¶
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 ¶
PendingWorkStatsJSON returns pending index/enrichment work as JSON.
func (*DB) RenderResolverKeyJSON ¶
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 ¶
ReplayGeneratedEnrichmentsJSON replays generated enrichment work from stored documents and returns {"replayed":N}.
func (*DB) ResolveQueryJSON ¶
func (*DB) ResolveTransaction ¶
ResolveTransaction resolves transaction intents as committed or aborted.
func (*DB) ResolverCurationJSON ¶
ResolverCurationJSON inspects one resolver, or every identity for an empty name.
func (*DB) ResolverIdentitiesJSON ¶
ResolverIdentitiesJSON lists active and retired identities, including durable merges.
func (*DB) ResolverReviewsJSON ¶
ResolverReviewsJSON pages reviews or submits an artifact-bound decision.
func (*DB) RunUntilIdle ¶
RunUntilIdle drains pending enrichment and index work.
func (*DB) RunUntilIdleJSON ¶
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 ¶
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) SchemaJSON ¶
SchemaJSON returns the active schema JSON.
func (*DB) SearchJSON ¶
SearchJSON executes a JSON search request and returns the JSON result.
func (*DB) SetResolverNamespaceJSON ¶
SetResolverNamespaceJSON atomically resets or migrates resolver identities; drain afterward. Retry the identical request on Busy.
func (*DB) SetSchemaJSON ¶
SetSchemaJSON replaces the active schema JSON.
func (*DB) StatusJSON ¶
StatusJSON returns a JSON status document for the Lite database.
func (*DB) SuppressResolverKeysJSON ¶
SuppressResolverKeysJSON atomically updates runtime key and text suppressions.
func (*DB) TextMatchPhraseWire ¶
TextMatchPhraseWire executes a packed text-match-phrase wire search request.
func (*DB) TextMatchWire ¶
TextMatchWire executes a packed text-match wire search request.
func (*DB) TextTermWire ¶
TextTermWire executes a packed text-term wire search request.
func (*DB) TransactionStatus ¶
TransactionStatus returns the current transaction lifecycle state.
func (*DB) TraverseEdgesJSON ¶
TraverseEdgesJSON executes a JSON graph traversal request.
func (*DB) UnmergeResolverKeyJSON ¶
UnmergeResolverKeyJSON undoes a redirect and can pin its former target distinct.
func (*DB) UnsuppressResolverKeyJSON ¶
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 ¶
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 ¶
Description returns a short stable description 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) Close ¶
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 ¶
Decide answers named choice, ordinal score, and Boolean questions via the inference API's POST /ai/v1/decisions.
func (*Inference) Embed ¶
Embed returns embeddings for request, the JSON body of the inference API's POST /ai/v1/embed.
func (*Inference) Generate ¶
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 ¶
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 ¶
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 ¶
Read reads images, documents, or audio via the inference API's POST /ai/v1/read.
type InferenceAPIError ¶
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.
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.
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
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.
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 ¶
WriteIntent is a single key/value write or delete in a Lite batch.