antfly-embedded 0.3.1

Safe Rust binding for local Antfly databases and inference via libantfly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
// Copyright 2026 Antfly, Inc.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The embedded Antfly database handle and its core operations.

use std::path::Path;

use antfly_embedded_sys::{self as sys, antfly_buffer, antfly_db, antfly_error_code, antfly_slice};

use crate::error::{Error, Result};
use crate::ffi::{
    HandleGate, borrow_slice, check, check_outcome, path_has_suffix, path_to_bytes,
    path_to_cstring, take_buffer,
};
use crate::options::{GraphDirection, OpenOptions, WriteIntent};

/// The resolved outcome of a write that failed with
/// [`Error::OutcomeUnknown`]; see [`Database::outcome_receipt_status`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutcomeReceiptStatus {
    /// The uncertain write applied.
    Applied,
    /// The uncertain write did not apply.
    NotApplied,
}

/// The Antfly C ABI version this binding expects.
pub const SUPPORTED_ABI_VERSION: u32 = 3;

/// The only threading mode libantfly provides: any thread may call any
/// method on a [`Database`] concurrently. See [`threading_mode`].
pub const THREADING_SERIALIZED: u32 = sys::ANTFLY_THREADING_SERIALIZED;

/// Minimum stack, in bytes, for any thread that calls into a [`Database`].
/// Rust's default for spawned threads is 2 MiB, which is not enough; spawn
/// callers with `std::thread::Builder::new().stack_size(MIN_THREAD_STACK_SIZE)`
/// (and size async runtimes' blocking pools the same way).
pub const MIN_THREAD_STACK_SIZE: usize = sys::ANTFLY_MIN_THREAD_STACK_SIZE;

/// Reports the loaded libantfly threading contract, like
/// `sqlite3_threadsafe()`.
pub fn threading_mode() -> u32 {
    unsafe { sys::antfly_threading_mode() }
}

/// Returns the loaded Antfly C ABI version.
pub fn abi_version() -> u32 {
    unsafe { sys::antfly_abi_version() }
}

/// Returns the loaded C ABI size of `antfly_open_options`.
pub fn open_options_size() -> u32 {
    unsafe { sys::antfly_open_options_size() }
}

fn compiled_open_options_size() -> u32 {
    std::mem::size_of::<sys::antfly_open_options>() as u32
}

/// Verifies that the loaded C library matches the header this binding was
/// compiled against. Every open function calls this first, like the Go
/// binding. A mismatch is reported as [`Error::Internal`]: it indicates a
/// build/deployment inconsistency (a `libantfly` built for a different ABI
/// generation), not a normal operational failure.
pub fn validate_abi() -> Result<()> {
    if abi_version() != SUPPORTED_ABI_VERSION {
        return Err(Error::Internal);
    }
    if open_options_size() != compiled_open_options_size() {
        return Err(Error::Internal);
    }
    Ok(())
}

/// An embedded Antfly database handle.
///
/// `Database` is safe for concurrent use from multiple threads, like
/// `*sql.DB` in the Go binding: libantfly runs in serialized threading mode
/// (see [`threading_mode`]). Lite calls queue on the connection and coordinate
/// with other connections to the same file. Streaming SQL readers keep their
/// pinned snapshots while other connections publish changes. Schema or index
/// changes wait for in-flight calls. [`Database::close`] (and
/// [`Drop`]) wait for in-flight calls to finish; calls made after close
/// return [`Error::InvalidArgument`].
pub struct Database {
    // See `HandleGate`: a writer-preferring reader/writer gate, not
    // `std::sync::RwLock`, so a steady stream of reads cannot starve
    // `close`. The actual write-vs-write serialization for concurrent
    // mutations happens inside libantfly itself, not in this gate.
    gate: HandleGate<antfly_db>,
}

// SAFETY: libantfly's only threading mode is "serialized" (see
// `antfly_threading_mode`, `ANTFLY_THREADING_SERIALIZED`, and
// zig/CAPI.md "Thread Safety"): any thread may call any exported function on
// any handle concurrently. Lite calls queue on their connection; managed
// owners coordinate reads, writes, and admin calls inside the engine.
// `HandleGate` above coordinates Rust close with in-flight calls; nothing
// about `*mut antfly_db` here is thread-affine.
unsafe impl Send for Database {}
unsafe impl Sync for Database {}

/// A document handle borrowing a table's owning database.
pub struct Table<'db> {
    database: Database,
    _owner: &'db Database,
}
impl std::ops::Deref for Table<'_> {
    type Target = Database;
    fn deref(&self) -> &Database {
        &self.database
    }
}

impl Database {
    fn from_handle(handle: *mut antfly_db) -> Database {
        Database {
            gate: HandleGate::new(handle),
        }
    }

    /// Opens a table-scoped document, schema, index, and enrichment handle.
    /// Close it before dropping the table. Closing the owner invalidates it.
    pub fn open_table(&self, name: &str) -> Result<Table<'_>> {
        self.with_handle(|handle| {
            let mut table = std::ptr::null_mut();
            check(unsafe {
                sys::antfly_db_open_table(handle, borrow_slice(name.as_bytes()), &mut table)
            })?;
            Ok(Table {
                database: Self::from_handle(table),
                _owner: self,
            })
        })
    }

    /// Runs `f` with the live handle, or returns [`Error::InvalidArgument`]
    /// if the database has already been closed. See [`HandleGate`].
    pub(crate) fn with_handle<T>(&self, f: impl FnOnce(*mut antfly_db) -> Result<T>) -> Result<T> {
        self.gate.with_handle(f)
    }

    pub(crate) fn read_buffer(
        &self,
        f: impl FnOnce(*mut antfly_db, *mut antfly_buffer) -> antfly_error_code,
    ) -> Result<Vec<u8>> {
        self.with_handle(|handle| {
            let mut out = antfly_buffer::default();
            check(f(handle, &mut out))?;
            Ok(unsafe { take_buffer(out) })
        })
    }

    pub(crate) fn with_input(
        &self,
        input: &[u8],
        f: impl FnOnce(*mut antfly_db, antfly_slice) -> antfly_error_code,
    ) -> Result<()> {
        self.with_handle(|handle| check(f(handle, borrow_slice(input))))
    }

    pub(crate) fn with_input_output(
        &self,
        input: &[u8],
        f: impl FnOnce(*mut antfly_db, antfly_slice, *mut antfly_buffer) -> antfly_error_code,
    ) -> Result<Vec<u8>> {
        self.with_handle(|handle| {
            let mut out = antfly_buffer::default();
            check(f(handle, borrow_slice(input), &mut out))?;
            Ok(unsafe { take_buffer(out) })
        })
    }

    fn graph_lookup(
        &self,
        index_name: &str,
        key: &str,
        edge_type: &str,
        direction: u8,
        f: impl FnOnce(
            *mut antfly_db,
            antfly_slice,
            antfly_slice,
            antfly_slice,
            u8,
            *mut antfly_buffer,
        ) -> antfly_error_code,
    ) -> Result<Vec<u8>> {
        self.with_handle(|handle| {
            let mut out = antfly_buffer::default();
            check(f(
                handle,
                borrow_slice(index_name.as_bytes()),
                borrow_slice(key.as_bytes()),
                borrow_slice(edge_type.as_bytes()),
                direction,
                &mut out,
            ))?;
            Ok(unsafe { take_buffer(out) })
        })
    }

    // -- Open / create ---------------------------------------------------

    /// Opens an existing Antfly Lite database using explicit options.
    pub fn open(path: impl AsRef<Path>, options: &OpenOptions) -> Result<Database> {
        Self::open_with(path.as_ref(), options, false)
    }

    /// Creates a new Antfly Lite database using explicit options.
    pub fn create(path: impl AsRef<Path>, options: &OpenOptions) -> Result<Database> {
        Self::open_with(path.as_ref(), options, true)
    }

    /// Opens an existing native Antfly Lite database file for writing
    /// (writer mode, native profile, no other options).
    pub fn open_default(path: impl AsRef<Path>) -> Result<Database> {
        Self::open(path, &OpenOptions::default())
    }

    /// Creates a new native Antfly Lite database file for writing (writer
    /// mode, native profile, no other options).
    pub fn create_default(path: impl AsRef<Path>) -> Result<Database> {
        Self::create(path, &OpenOptions::default())
    }

    /// Opens an existing Antfly Lite database file read-only.
    pub fn open_readonly(path: impl AsRef<Path>) -> Result<Database> {
        Self::open(
            path,
            &OpenOptions {
                mode: crate::options::OpenMode::Readonly,
                ..Default::default()
            },
        )
    }

    /// Opens enough of an Antfly Lite database to read status.
    pub fn open_status_only(path: impl AsRef<Path>) -> Result<Database> {
        Self::open(
            path,
            &OpenOptions {
                mode: crate::options::OpenMode::StatusOnly,
                ..Default::default()
            },
        )
    }

    /// Opens an existing Antfly Lite database in hosted/manual maintenance
    /// mode. In this profile callers drive pending work explicitly with
    /// [`Database::run_until_idle`].
    pub fn open_hosted(path: impl AsRef<Path>) -> Result<Database> {
        validate_abi()?;
        let c_path = path_to_cstring(path.as_ref())?;
        let mut handle: *mut antfly_db = std::ptr::null_mut();
        check(unsafe { sys::antfly_lite_open_hosted(c_path.as_ptr(), &mut handle) })?;
        Ok(Database::from_handle(handle))
    }

    /// Creates a new Antfly Lite database in hosted/manual maintenance
    /// mode. In this profile callers drive pending work explicitly with
    /// [`Database::run_until_idle`].
    pub fn create_hosted(path: impl AsRef<Path>) -> Result<Database> {
        validate_abi()?;
        let c_path = path_to_cstring(path.as_ref())?;
        let mut handle: *mut antfly_db = std::ptr::null_mut();
        check(unsafe { sys::antfly_lite_create_hosted(c_path.as_ptr(), &mut handle) })?;
        Ok(Database::from_handle(handle))
    }

    fn open_with(path: &Path, options: &OpenOptions, create: bool) -> Result<Database> {
        validate_abi()?;
        let c_path = path_to_cstring(path)?;

        let mut c_opts: sys::antfly_open_options = unsafe { std::mem::zeroed() };
        check(unsafe { sys::antfly_open_options_init(&mut c_opts) })?;

        c_opts.storage_kind = options.storage.as_u32();
        c_opts.open_mode = options.mode.as_u32();
        c_opts.profile = options.profile.as_u32();
        c_opts.map_size = options.map_size;
        if options.no_sync {
            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_NO_SYNC;
        }
        if options.remote_provider_configured {
            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_REMOTE_PROVIDER_CONFIGURED;
        }
        if options.local_runtime_configured {
            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_LOCAL_RUNTIME_CONFIGURED;
        }
        if options.generated_enrichment_replay {
            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_GENERATED_ENRICHMENT_REPLAY;
        }
        c_opts.inference_host_budget_mb = options.host_budget_mb;
        c_opts.inference_backend_budget_mb = options.backend_budget_mb;
        c_opts.inference_combined_budget_mb = options.combined_budget_mb;
        c_opts.inference_kv_budget_mb = options.kv_budget_mb;
        c_opts.inference_scratch_budget_mb = options.scratch_budget_mb;
        c_opts.inference_process_memory_budget_mb = options.process_memory_budget_mb;
        c_opts.busy_timeout_ms = options.busy_timeout_ms();
        let models_dir_bytes = options.models_dir.as_deref().map(path_to_bytes);
        if let Some(bytes) = &models_dir_bytes {
            c_opts.models_dir = borrow_slice(bytes);
        }

        if let Some(ttl) = &options.ttl_cleanup {
            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_TTL_CLEANUP;
            c_opts.ttl_cleanup_enabled = ttl.enabled;
            c_opts.ttl_cleanup_lease_owned = ttl.lease_owned;
            c_opts.ttl_cleanup_lease_ttl_ms = ttl.lease_ttl_ms;
            c_opts.ttl_cleanup_interval_ms = ttl.interval_ms;
            c_opts.ttl_cleanup_batch_size = ttl.batch_size;
            c_opts.ttl_cleanup_grace_period_ns = ttl.grace_period_ns;
            // `ttl.owner_id` outlives this call (borrowed from `options`,
            // which the caller keeps alive for the duration of `open_with`).
            c_opts.ttl_cleanup_owner_id = borrow_slice(ttl.owner_id.as_bytes());
        }

        let mut handle: *mut antfly_db = std::ptr::null_mut();
        let code = if create {
            unsafe { sys::antfly_db_create_with_options(c_path.as_ptr(), &c_opts, &mut handle) }
        } else {
            unsafe { sys::antfly_db_open_with_options(c_path.as_ptr(), &c_opts, &mut handle) }
        };
        check(code)?;
        Ok(Database::from_handle(handle))
    }

    // -- Close ------------------------------------------------------------

    /// Releases the embedded database handle, waiting for in-flight calls
    /// on other threads to finish first. Idempotent and safe to call
    /// concurrently with itself or from several threads at once (matching
    /// `antfly_db_close`'s contract), including through a shared
    /// `Arc<Database>` -- calls made after (or racing) `close` return
    /// [`Error::InvalidArgument`] rather than touching a freed handle.
    ///
    /// Takes `&self`, not `self`, specifically so it can be called on a
    /// `Database` shared across threads (e.g. `Arc<Database>`) without every
    /// other clone having to be dropped first; [`Drop`] still closes
    /// automatically once the last owner goes out of scope, for callers who
    /// never need to close early.
    pub fn close(&self) -> Result<()> {
        self.close_inner();
        Ok(())
    }

    fn close_inner(&self) {
        self.gate
            .close(|handle| unsafe { sys::antfly_db_close(handle) });
    }

    // -- Status / maintenance JSON -----------------------------------------

    pub fn status_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_status_json(h, out) })
    }

    pub fn capabilities_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_capabilities_json(h, out) })
    }

    pub fn replay_generated_enrichments_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe {
            sys::antfly_db_replay_generated_enrichments_json(h, out)
        })
    }

    /// Returns a portable Antfly backup archive (`.afb`) of this database,
    /// which restores or imports into either storage kind.
    pub fn backup(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_backup(h, out) })
    }

    /// Export with optional {"tables":[...]} scope; default is always included.
    /// Full backups fail closed if any table is unavailable.
    pub fn backup_json(&self, options: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(options.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_backup_json(h, input, out)
        })
    }

    /// Imports a portable Antfly backup archive into this empty database.
    /// [`Error::OutcomeUnknown`] means the live handle adopted the imported
    /// generation, but crash durability could not be confirmed; inspect the
    /// handle and do not retry automatically.
    pub fn import_backup(&self, backup: impl AsRef<[u8]>) -> Result<()> {
        self.with_input(backup.as_ref(), |h, input| unsafe {
            sys::antfly_db_import_backup(h, input)
        })
    }

    /// Runs Lite integrity checks and returns the JSON result.
    pub fn check_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_lite_check_json(h, out) })
    }

    /// Compacts free space and returns the JSON result.
    pub fn vacuum_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_lite_vacuum_json(h, out) })
    }

    /// Drains maintenance, compacts indexes, vacuums free space, and
    /// returns the JSON result.
    pub fn compact_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_lite_compact_json(h, out) })
    }

    /// Copies a stable Lite snapshot to `dest_path`, which must end in
    /// `.aflite`.
    pub fn copy_stable_snapshot_json(
        &self,
        dest_path: impl AsRef<Path>,
        replace: bool,
    ) -> Result<Vec<u8>> {
        let dest_path = dest_path.as_ref();
        if !path_has_suffix(dest_path, ".aflite") {
            return Err(Error::InvalidArgument);
        }
        let c_dest = path_to_cstring(dest_path)?;
        self.with_handle(|handle| {
            let mut out = antfly_buffer::default();
            check(unsafe {
                sys::antfly_lite_copy_stable_snapshot_json(
                    handle,
                    c_dest.as_ptr(),
                    replace,
                    &mut out,
                )
            })?;
            Ok(unsafe { take_buffer(out) })
        })
    }

    // -- Batch / documents --------------------------------------------------

    /// Applies write intents at `timestamp_ns`.
    pub fn batch(&self, writes: &[WriteIntent], timestamp_ns: u64) -> Result<()> {
        self.with_handle(|handle| {
            // Keep every borrowed antfly_slice's backing bytes alive for the
            // duration of the call by holding the WriteIntent Vecs (`writes`)
            // borrowed for the whole closure, and building the antfly_slice
            // array from them just before the call.
            let c_writes: Vec<sys::antfly_write_intent> = writes
                .iter()
                .map(|w| sys::antfly_write_intent {
                    key: borrow_slice(&w.key),
                    value: borrow_slice(&w.value),
                    is_delete: w.delete,
                })
                .collect();
            let ptr = if c_writes.is_empty() {
                std::ptr::null()
            } else {
                c_writes.as_ptr()
            };
            check_outcome(unsafe {
                sys::antfly_db_batch(
                    handle,
                    ptr,
                    c_writes.len(),
                    std::ptr::null(),
                    0,
                    timestamp_ns,
                    0,
                )
            })
        })
    }

    /// Applies a public Antfly batch request and returns the JSON result.
    /// An `OutcomeUnknown` failure carries its outcome receipt (see
    /// [`Error::outcome_receipt`]).
    pub fn batch_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let request = request.as_ref();
        self.with_handle(|handle| {
            let mut out = antfly_buffer::default();
            let code =
                unsafe { sys::antfly_db_batch_json(handle, borrow_slice(request), &mut out) };
            if let Err(error) = check_outcome(code) {
                unsafe { take_buffer(out) };
                return Err(error);
            }
            Ok(unsafe { take_buffer(out) })
        })
    }

    /// Resolves an outcome receipt from an `OutcomeUnknown` batch or
    /// autocommit SQL write, on any handle for the same database. Returns
    /// [`Error::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.
    pub fn outcome_receipt_status(&self, receipt: &str) -> Result<OutcomeReceiptStatus> {
        self.with_handle(|handle| {
            let mut status: u8 = 0;
            check(unsafe {
                sys::antfly_db_outcome_receipt_status(
                    handle,
                    borrow_slice(receipt.as_bytes()),
                    &mut status,
                )
            })?;
            match status {
                sys::ANTFLY_OUTCOME_RECEIPT_APPLIED => Ok(OutcomeReceiptStatus::Applied),
                sys::ANTFLY_OUTCOME_RECEIPT_NOT_APPLIED => Ok(OutcomeReceiptStatus::NotApplied),
                _ => Err(Error::Internal),
            }
        })
    }

    /// Removes a resolved receipt's durable marker; afterwards the receipt
    /// can no longer be resolved.
    pub fn forget_outcome_receipt(&self, receipt: &str) -> Result<()> {
        self.with_input(receipt.as_bytes(), |h, input| unsafe {
            sys::antfly_db_outcome_receipt_forget(h, input)
        })
    }

    /// Returns the JSON lookup result for `key`.
    pub fn lookup_json(&self, key: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(key.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_lookup_json(h, input, out)
        })
    }

    /// Returns the raw stored bytes for `key`.
    pub fn get_raw(&self, key: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(key.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_get_raw(h, input, out)
        })
    }

    // -- Schema / indexes / enrichments -------------------------------------

    pub fn schema_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_get_schema_json(h, out) })
    }

    pub fn set_schema_json(&self, schema: impl AsRef<[u8]>) -> Result<()> {
        self.with_input(schema.as_ref(), |h, input| unsafe {
            sys::antfly_db_set_schema_json(h, input)
        })
    }

    /// Drains pending enrichment and index work.
    pub fn run_until_idle(&self) -> Result<()> {
        self.with_handle(|handle| check(unsafe { sys::antfly_db_run_until_idle(handle) }))
    }

    /// Drains pending enrichment and index work and returns the post-drain
    /// pending work stats JSON.
    pub fn run_until_idle_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_run_until_idle_json(h, out) })
    }

    pub fn pending_work_stats_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_pending_work_stats_json(h, out) })
    }

    pub fn indexes_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_list_indexes_json(h, out) })
    }

    /// Render the durable template and follow key aliases, without writes or ANN search.
    pub fn render_resolver_key_json(
        &self,
        resolver: &str,
        mention: impl AsRef<[u8]>,
    ) -> Result<Vec<u8>> {
        self.with_input_output(mention.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_render_resolver_key_json(
                h,
                borrow_slice(resolver.as_bytes()),
                input,
                out,
            )
        })
    }

    /// Resolve text or extraction mentions, including aliases and ANN, without writes.
    /// Execute native memory policy without an HTTP server or extension.
    pub fn memory_json(&self, space: &str, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_memory_json(h, borrow_slice(space.as_bytes()), input, out)
        })
    }

    pub fn resolve_query_json(&self, resolver: &str, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_resolve_query_json(h, borrow_slice(resolver.as_bytes()), input, out)
        })
    }

    /// Persist a {"key","target"} redirect. Drain to re-key existing resolution edges.
    pub fn merge_resolver_keys_json(
        &self,
        resolver: &str,
        request: impl AsRef<[u8]>,
    ) -> Result<()> {
        self.with_input(request.as_ref(), |h, input| unsafe {
            sys::antfly_db_merge_resolver_keys_json(h, borrow_slice(resolver.as_bytes()), input)
        })
    }

    /// Undo a redirect, optionally pinning its former target distinct.
    pub fn unmerge_resolver_key_json(
        &self,
        resolver: &str,
        request: impl AsRef<[u8]>,
    ) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_unmerge_resolver_key_json(
                h,
                borrow_slice(resolver.as_bytes()),
                input,
                out,
            )
        })
    }

    /// Atomically add or remove runtime key and normalized-text suppressions.
    pub fn suppress_resolver_keys_json(
        &self,
        resolver: &str,
        request: impl AsRef<[u8]>,
    ) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_suppress_resolver_keys_json(
                h,
                borrow_slice(resolver.as_bytes()),
                input,
                out,
            )
        })
    }

    /// Remove runtime suppression of a key; declarative rules remain effective.
    pub fn unsuppress_resolver_key_json(
        &self,
        resolver: &str,
        request: impl AsRef<[u8]>,
    ) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_unsuppress_resolver_key_json(
                h,
                borrow_slice(resolver.as_bytes()),
                input,
                out,
            )
        })
    }

    /// Inspect one resolver's durable curation, or all identities for an empty name.
    pub fn resolver_curation_json(&self, resolver: &str) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe {
            sys::antfly_db_resolver_curation_json(h, borrow_slice(resolver.as_bytes()), out)
        })
    }

    /// Page reviews or submit a decision bound to the displayed artifact.
    pub fn resolver_reviews_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_resolver_reviews_json(h, input, out)
        })
    }

    /// Propose an entity correction; repeated action and keys retain the existing decision.
    pub fn propose_curation_json(&self, table: &str, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_propose_curation_json(h, borrow_slice(table.as_bytes()), input, out)
        })
    }

    /// List the persistent entity review queue with bounded keyset pagination.
    pub fn list_curation_proposals_json(
        &self,
        table: &str,
        request: impl AsRef<[u8]>,
    ) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_list_curation_proposals_json(
                h,
                borrow_slice(table.as_bytes()),
                input,
                out,
            )
        })
    }

    /// Inspect a persistent proposal by its stable identifier.
    pub fn get_curation_proposal_json(&self, table: &str, id: &str) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe {
            sys::antfly_db_get_curation_proposal_json(
                h,
                borrow_slice(table.as_bytes()),
                borrow_slice(id.as_bytes()),
                out,
            )
        })
    }

    /// Accept or reject a proposal; retry incomplete fanout to resume durable receipts.
    pub fn decide_curation_proposal_json(
        &self,
        table: &str,
        id: &str,
        request: impl AsRef<[u8]>,
    ) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_decide_curation_proposal_json(
                h,
                borrow_slice(table.as_bytes()),
                borrow_slice(id.as_bytes()),
                input,
                out,
            )
        })
    }

    /// Fan out a correction across resolver namespaces targeting this entity.
    pub fn curate_entity_json(
        &self,
        table: &str,
        key: &str,
        request: impl AsRef<[u8]>,
    ) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_curate_entity_json(
                h,
                borrow_slice(table.as_bytes()),
                borrow_slice(key.as_bytes()),
                input,
                out,
            )
        })
    }

    /// List active and retired identities, including durable merges.
    pub fn resolver_identities_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_list_resolver_identities_json(h, out) })
    }

    /// Discard retired identity metadata; artifacts and canonical rows remain.
    /// Delete source documents for artifact cleanup, then explicitly delete
    /// unused canonical rows. Busy is retryable.
    pub fn drop_resolver_identity(&self, name: &str) -> Result<bool> {
        self.with_handle(|handle| {
            let mut deleted = false;
            check(unsafe {
                sys::antfly_db_drop_resolver_identity(
                    handle,
                    borrow_slice(name.as_bytes()),
                    &mut deleted,
                )
            })?;
            Ok(deleted)
        })
    }

    /// Atomically reset or migrate resolver identities; drain afterward.
    /// Retry the identical request on Busy.
    pub fn set_resolver_namespace_json(
        &self,
        resolver: &str,
        request: impl AsRef<[u8]>,
    ) -> Result<()> {
        self.with_input(request.as_ref(), |h, input| unsafe {
            sys::antfly_db_set_resolver_namespace_json(h, borrow_slice(resolver.as_bytes()), input)
        })
    }

    /// Add or replace an index; retry the identical request on Busy.
    /// A graph replaces command registers a resumable background shadow. The
    /// old index serves until activation; absent old indexes behave like add.
    /// Optional wait:{timeout_ms:N} waits for activation. A deadline Busy leaves
    /// the accepted shadow running; pending work stats expose its progress.
    pub fn add_index_json(&self, config: impl AsRef<[u8]>) -> Result<()> {
        self.with_input(config.as_ref(), |h, input| unsafe {
            sys::antfly_db_add_index_json(h, input)
        })
    }

    /// Deletes an index by name and reports whether it existed.
    /// Retire an index, returning whether it existed. Busy is retryable.
    pub fn delete_index(&self, name: &str) -> Result<bool> {
        self.with_handle(|handle| {
            let mut deleted = false;
            check(unsafe {
                sys::antfly_db_delete_index(handle, borrow_slice(name.as_bytes()), &mut deleted)
            })?;
            Ok(deleted)
        })
    }

    /// Cancel a running or failed shadow by its new name; idempotent.
    pub fn cancel_replacement(&self, name: &str) -> Result<bool> {
        self.with_handle(|handle| {
            let mut deleted = false;
            check(unsafe {
                sys::antfly_db_cancel_replacement(
                    handle,
                    borrow_slice(name.as_bytes()),
                    &mut deleted,
                )
            })?;
            Ok(deleted)
        })
    }

    pub fn enrichments_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_list_enrichments_json(h, out) })
    }

    pub fn add_enrichment_json(&self, config: impl AsRef<[u8]>) -> Result<()> {
        self.with_input(config.as_ref(), |h, input| unsafe {
            sys::antfly_db_add_enrichment_json(h, input)
        })
    }

    /// Deletes an enrichment by kind and name and reports whether it
    /// existed.
    pub fn delete_enrichment(&self, kind: &str, name: &str) -> Result<bool> {
        self.with_handle(|handle| {
            let mut deleted = false;
            check(unsafe {
                sys::antfly_db_delete_enrichment(
                    handle,
                    borrow_slice(kind.as_bytes()),
                    borrow_slice(name.as_bytes()),
                    &mut deleted,
                )
            })?;
            Ok(deleted)
        })
    }

    // -- Scan / stats / search ----------------------------------------------

    pub fn scan_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_scan_json(h, input, out)
        })
    }

    pub fn stats_json(&self) -> Result<Vec<u8>> {
        self.read_buffer(|h, out| unsafe { sys::antfly_db_stats_json(h, out) })
    }

    pub fn search_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_search_json(h, input, out)
        })
    }

    /// Executes a packed dense-vector wire search request.
    pub fn dense_search_wire(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_search_dense_wire(h, input, out)
        })
    }

    /// Executes a packed text-match wire search request.
    pub fn text_match_wire(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_search_text_match_wire(h, input, out)
        })
    }

    /// Executes a packed text-term wire search request.
    pub fn text_term_wire(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_search_text_term_wire(h, input, out)
        })
    }

    /// Executes a packed text-match-phrase wire search request.
    pub fn text_match_phrase_wire(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_search_text_match_phrase_wire(h, input, out)
        })
    }

    /// Aggregates hits from a JSON request.
    pub fn aggregate_hits_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_aggregate_hits_json(h, input, out)
        })
    }

    /// Looks up an artifact by base64 artifact ID.
    pub fn lookup_artifact_json(&self, artifact_id_base64: &str) -> Result<Vec<u8>> {
        self.with_input_output(artifact_id_base64.as_bytes(), |h, input, out| unsafe {
            sys::antfly_db_lookup_artifact_json(h, input, out)
        })
    }

    pub fn extract_enrichments_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_extract_enrichments_json(h, input, out)
        })
    }

    pub fn compute_enrichments_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_compute_enrichments_json(h, input, out)
        })
    }

    // -- Graph ---------------------------------------------------------------

    /// Returns graph edges for `key` from a graph index. `edge_type` of
    /// `""` matches every edge type.
    pub fn edges_json(
        &self,
        index_name: &str,
        key: &str,
        edge_type: &str,
        direction: GraphDirection,
    ) -> Result<Vec<u8>> {
        self.graph_lookup(
            index_name,
            key,
            edge_type,
            direction.as_u8(),
            |h, i, k, e, d, out| unsafe { sys::antfly_db_get_edges_json(h, i, k, e, d, out) },
        )
    }

    pub fn traverse_edges_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_traverse_edges_json(h, input, out)
        })
    }

    pub fn execute_graph_queries_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_execute_graph_queries_json(h, input, out)
        })
    }

    /// Returns graph neighbors for `key` from a graph index. `edge_type` of
    /// `""` matches every edge type.
    pub fn neighbors_json(
        &self,
        index_name: &str,
        key: &str,
        edge_type: &str,
        direction: GraphDirection,
    ) -> Result<Vec<u8>> {
        self.graph_lookup(
            index_name,
            key,
            edge_type,
            direction.as_u8(),
            |h, i, k, e, d, out| unsafe { sys::antfly_db_get_neighbors_json(h, i, k, e, d, out) },
        )
    }

    pub fn find_shortest_path_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_find_shortest_path_json(h, input, out)
        })
    }

    pub fn find_k_shortest_paths_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_find_k_shortest_paths_json(h, input, out)
        })
    }

    pub fn match_pattern_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
            sys::antfly_db_match_pattern_json(h, input, out)
        })
    }
}

impl Drop for Database {
    fn drop(&mut self) {
        self.close_inner();
    }
}

impl std::fmt::Debug for Database {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Database")
            .field("open", &self.gate.is_open())
            .finish()
    }
}

/// Decodes a base64 artifact ID without opening a database.
pub fn decode_artifact_id_json(artifact_id_base64: &str) -> Result<Vec<u8>> {
    let mut out = antfly_buffer::default();
    check(unsafe {
        sys::antfly_decode_artifact_id_json(borrow_slice(artifact_id_base64.as_bytes()), &mut out)
    })?;
    Ok(unsafe { take_buffer(out) })
}