antfly-embedded 0.3.5

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
// 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.

//! Runs the shared libantfly conformance cases (see
//! `zig/pkg/antfly-embedded/capi-conformance/README.md`) through this crate's public
//! API, porting `go/pkg/embedded/conformance_cgo_test.go`'s semantics exactly.
//! Requires linking against the real library (`--features libantfly`).

use std::path::{Path, PathBuf};

use antfly_embedded::{
    Database, Error, GraphDirection, OpenMode, OpenOptions, Profile, RestoreOptions, Storage,
    TxnId, TxnStatus, WriteIntent,
};
use serde::Deserialize;
use serde_json::Value;

#[test]
fn conformance_cases() {
    // Run on a thread with exactly the documented minimum stack: the test
    // harness's own threads are smaller, and running at the minimum turns
    // any stack growth in libantfly into a test failure.
    std::thread::Builder::new()
        .stack_size(antfly_embedded::MIN_THREAD_STACK_SIZE)
        .spawn(conformance_cases_inner)
        .expect("spawn thread")
        .join()
        .unwrap_or_else(|payload| std::panic::resume_unwind(payload));
}

/// Beyond the shared conformance suite: a `.aflite` backup restores into a
/// normal Antfly directory (`RestoreOptions { storage: Storage::Directory,
/// .. }`), and the resulting directory database survives a close/reopen
/// cycle with its documents intact. See `zig/pkg/antfly-embedded/capi-conformance/
/// cases/directory_storage.json` and `backup_across_storage.json` for the
/// declarative cases this exercises via other bindings too; this test adds
/// an explicit reopen after the restore, which the shared cases do not.
#[test]
fn restore_into_directory_storage_and_reopen() {
    std::thread::Builder::new()
        .stack_size(antfly_embedded::MIN_THREAD_STACK_SIZE)
        .spawn(restore_into_directory_storage_and_reopen_inner)
        .expect("spawn thread")
        .join()
        .unwrap_or_else(|payload| std::panic::resume_unwind(payload));
}

fn restore_into_directory_storage_and_reopen_inner() {
    let tmp_dir = std::env::temp_dir().join(format!(
        "antfly-embedded-restore-directory-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or_default()
    ));
    std::fs::create_dir_all(&tmp_dir).expect("create temp dir");

    // Build a small .aflite source database and take a portable backup.
    let source_path = tmp_dir.join("source.aflite");
    let source = Database::create(&source_path, &OpenOptions::new().no_sync(true))
        .expect("create source .aflite database");
    source
        .batch(
            &[WriteIntent::put(
                "doc:restore-directory",
                r#"{"title":"restored into a directory"}"#,
            )],
            1,
        )
        .expect("batch");
    source.run_until_idle().expect("run until idle");
    let backup = source.backup().expect("backup");
    source.close().expect("close source");

    // Restore the backup into a directory-storage destination.
    let dest_path = tmp_dir.join("restored-dir");
    antfly_embedded::restore(
        &dest_path,
        &backup,
        &RestoreOptions {
            storage: Storage::Directory,
            replace: false,
        },
    )
    .expect("restore into directory storage");

    // The restored directory database opens directly (Restore leaves it
    // ready to open, matching the conformance `restore_open` step) and
    // contains the document.
    let restored = Database::open(&dest_path, &OpenOptions::new().storage(Storage::Directory))
        .expect("open restored directory database");
    let doc = restored
        .lookup_json("doc:restore-directory")
        .expect("lookup after restore");
    assert!(
        String::from_utf8_lossy(&doc).contains("restored into a directory"),
        "lookup after restore = {}",
        String::from_utf8_lossy(&doc)
    );
    let status = restored.status_json().expect("status");
    assert!(
        String::from_utf8_lossy(&status).contains(r#""format":"directory""#),
        "status after restore = {}",
        String::from_utf8_lossy(&status)
    );
    restored.close().expect("close restored");

    // Reopening the same directory (a plain Database::open, since directory
    // storage is opened rather than created) still has the document.
    let reopened = Database::open(&dest_path, &OpenOptions::new().storage(Storage::Directory))
        .expect("reopen restored directory database");
    let doc = reopened
        .lookup_json("doc:restore-directory")
        .expect("lookup after reopen");
    assert!(
        String::from_utf8_lossy(&doc).contains("restored into a directory"),
        "lookup after reopen = {}",
        String::from_utf8_lossy(&doc)
    );
    reopened.close().expect("close reopened");
}

fn conformance_cases_inner() {
    let cases_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../../zig/pkg/antfly-embedded/capi-conformance/cases");
    let mut files: Vec<PathBuf> = std::fs::read_dir(&cases_dir)
        .unwrap_or_else(|e| panic!("read_dir {}: {e}", cases_dir.display()))
        .filter_map(|entry| entry.ok().map(|e| e.path()))
        .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("json"))
        .collect();
    files.sort();
    assert!(
        !files.is_empty(),
        "no conformance cases in {}",
        cases_dir.display()
    );

    let mut failures = Vec::new();
    for file in &files {
        let raw = std::fs::read_to_string(file).unwrap_or_else(|e| panic!("read {file:?}: {e}"));
        let case: ConformanceCase =
            serde_json::from_str(&raw).unwrap_or_else(|e| panic!("parse {file:?}: {e}"));

        let tmp_dir = std::env::temp_dir().join(format!(
            "antfly-embedded-conformance-{}-{}-{}",
            case.name,
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or_default()
        ));
        std::fs::create_dir_all(&tmp_dir).expect("create temp dir");

        let mut runner = Runner {
            dir: tmp_dir,
            db: None,
            path: PathBuf::new(),
            backup: Vec::new(),
        };
        if let Err(e) = runner.open_current(&case.open) {
            failures.push(format!("{}: open: {e}", case.name));
            continue;
        }
        for (i, step) in case.steps.iter().enumerate() {
            if let Err(e) = runner.run_step(step) {
                failures.push(format!("{}: step {i} ({}): {e}", case.name, step.op));
                break;
            }
        }
        runner.close_current();
    }

    assert!(
        failures.is_empty(),
        "conformance failures:\n{}",
        failures.join("\n")
    );
}

#[derive(Debug, Deserialize)]
struct ConformanceCase {
    name: String,
    #[serde(default)]
    open: ConformanceOpen,
    #[serde(default)]
    steps: Vec<ConformanceStep>,
}

#[derive(Debug, Default, Deserialize)]
struct ConformanceOpen {
    #[serde(default)]
    storage: String,
    #[serde(default)]
    create: bool,
    #[serde(default)]
    mode: String,
    #[serde(default)]
    profile: String,
    #[serde(default)]
    no_sync: bool,
    #[serde(default)]
    busy_timeout_ms: u64,
    #[serde(default)]
    path: String,
}

#[derive(Debug, Default, Deserialize)]
struct ConformanceWrite {
    key: String,
    #[serde(default)]
    value: Value,
    #[serde(default)]
    delete: bool,
}

#[derive(Debug, Default, Deserialize)]
struct ConformanceStep {
    #[serde(flatten)]
    open: ConformanceOpen,
    op: String,
    #[serde(default)]
    writes: Vec<ConformanceWrite>,
    #[serde(default)]
    timestamp: u64,
    #[serde(default)]
    key: String,
    #[serde(default)]
    request: Value,
    #[serde(default)]
    config: Value,
    #[serde(default)]
    schema: Value,
    #[serde(default)]
    name: String,
    #[serde(default)]
    kind: String,
    #[serde(default)]
    txn_id: String,
    #[serde(default)]
    status: String,
    #[serde(default)]
    commit_version: u64,
    #[serde(default)]
    index: String,
    #[serde(default)]
    edge_type: String,
    #[serde(default)]
    direction: String,
    #[serde(default)]
    expect: Option<ConformanceExpect>,
}

#[derive(Debug, Default, Deserialize)]
struct ConformanceExpect {
    #[serde(default)]
    error: String,
    #[serde(default)]
    json_subset: Option<Value>,
    #[serde(default)]
    contains: Vec<String>,
    #[serde(default)]
    not_contains: Vec<String>,
    #[serde(default)]
    equals: Option<Value>,
}

/// The result of executing one step, in enough of a typed shape to render
/// as the "result text" the README's expectation table describes.
enum StepOutput {
    None,
    Json(Vec<u8>),
    Bool(bool),
    U64(u64),
    Str(String),
}

impl StepOutput {
    fn as_text(&self) -> String {
        match self {
            StepOutput::None => String::new(),
            StepOutput::Json(bytes) => String::from_utf8_lossy(bytes).into_owned(),
            StepOutput::Bool(b) => b.to_string(),
            StepOutput::U64(n) => n.to_string(),
            // json.Marshal on a Go string quotes it; serde_json does the same.
            StepOutput::Str(s) => serde_json::to_string(s).expect("string always serializes"),
        }
    }
}

struct Runner {
    dir: PathBuf,
    db: Option<Database>,
    path: PathBuf,
    backup: Vec<u8>,
}

impl Runner {
    fn resolve_path(&self, name: &str) -> PathBuf {
        let name = if name.is_empty() { "db.aflite" } else { name };
        self.dir.join(name)
    }

    fn open_options(o: &ConformanceOpen) -> Result<OpenOptions, ExecError> {
        let storage = parse_storage(&o.storage)?;
        let mode = match o.mode.as_str() {
            "" | "writer" => OpenMode::Writer,
            "readonly" => OpenMode::Readonly,
            "status_only" => OpenMode::StatusOnly,
            other => return Err(ExecError::Other(format!("unknown mode {other:?}"))),
        };
        let profile = match o.profile.as_str() {
            "" | "native" => Profile::Native,
            "hosted" => Profile::Hosted,
            other => return Err(ExecError::Other(format!("unknown profile {other:?}"))),
        };
        let mut opts = OpenOptions::new()
            .storage(storage)
            .mode(mode)
            .profile(profile)
            .no_sync(o.no_sync);
        if o.busy_timeout_ms > 0 {
            opts = opts.busy_timeout(std::time::Duration::from_millis(o.busy_timeout_ms));
        }
        Ok(opts)
    }

    fn open_db(&self, path: &Path, o: &ConformanceOpen) -> Result<Database, ExecError> {
        let opts = Self::open_options(o)?;
        let db = if o.create {
            Database::create(path, &opts)?
        } else {
            Database::open(path, &opts)?
        };
        Ok(db)
    }

    fn open_current(&mut self, o: &ConformanceOpen) -> Result<(), ExecError> {
        let path = self.resolve_path(&o.path);
        let db = self.open_db(&path, o)?;
        self.db = Some(db);
        self.path = path;
        Ok(())
    }

    fn close_current(&mut self) {
        if let Some(db) = self.db.take() {
            let _ = db.close();
        }
    }

    fn run_step(&mut self, step: &ConformanceStep) -> Result<(), String> {
        let result = self.execute(step);
        let Some(expect) = &step.expect else {
            return result.map(|_| ()).map_err(|e| e.to_string());
        };
        check_step(result, expect)
    }
}

fn check_step(
    result: Result<StepOutput, ExecError>,
    expect: &ConformanceExpect,
) -> Result<(), String> {
    if !expect.error.is_empty() {
        return match result {
            Ok(_) => Err(format!("succeeded, want {}", expect.error)),
            Err(ExecError::Ffi(err)) if err.name() == expect.error => Ok(()),
            Err(ExecError::Ffi(err)) => Err(format!(
                "error {} ({}), want {}",
                err.name(),
                err,
                expect.error
            )),
            Err(other) => Err(format!("error {other}, want {}", expect.error)),
        };
    }
    let output = result.map_err(|e| e.to_string())?;
    check_result(&output, expect)
}

impl Runner {
    fn execute(&mut self, step: &ConformanceStep) -> Result<StepOutput, ExecError> {
        match step.op.as_str() {
            "batch" => {
                let writes: Vec<WriteIntent> = step
                    .writes
                    .iter()
                    .map(|w| {
                        if w.delete {
                            WriteIntent::delete(w.key.as_bytes())
                        } else {
                            WriteIntent::put(w.key.as_bytes(), value_bytes(&w.value))
                        }
                    })
                    .collect();
                self.db()?.batch(&writes, step.timestamp)?;
                Ok(StepOutput::None)
            }
            "batch_json" => Ok(StepOutput::Json(
                self.db()?.batch_json(value_bytes(&step.request))?,
            )),
            "lookup" => Ok(StepOutput::Json(
                self.db()?.lookup_json(step.key.as_bytes())?,
            )),
            "scan" => Ok(StepOutput::Json(
                self.db()?.scan_json(value_bytes(&step.request))?,
            )),
            "search" => Ok(StepOutput::Json(
                self.db()?.search_json(value_bytes(&step.request))?,
            )),
            "stats" => Ok(StepOutput::Json(self.db()?.stats_json()?)),
            "status" => Ok(StepOutput::Json(self.db()?.status_json()?)),
            "capabilities" => Ok(StepOutput::Json(self.db()?.capabilities_json()?)),
            "check" => Ok(StepOutput::Json(self.db()?.check_json()?)),
            "pending_work_stats" => Ok(StepOutput::Json(self.db()?.pending_work_stats_json()?)),
            "run_until_idle" => {
                self.db()?.run_until_idle()?;
                Ok(StepOutput::None)
            }
            "get_schema" => Ok(StepOutput::Json(self.db()?.schema_json()?)),
            "set_schema" => {
                self.db()?.set_schema_json(value_bytes(&step.schema))?;
                Ok(StepOutput::None)
            }
            "list_indexes" => Ok(StepOutput::Json(self.db()?.indexes_json()?)),
            "add_index" => {
                self.db()?.add_index_json(value_bytes(&step.config))?;
                Ok(StepOutput::None)
            }
            "delete_index" => Ok(StepOutput::Bool(self.db()?.delete_index(&step.name)?)),
            "get_edges" => {
                let direction = parse_direction(&step.direction)?;
                Ok(StepOutput::Json(self.db()?.edges_json(
                    &step.index,
                    &step.key,
                    &step.edge_type,
                    direction,
                )?))
            }
            "list_enrichments" => Ok(StepOutput::Json(self.db()?.enrichments_json()?)),
            "add_enrichment" => {
                self.db()?.add_enrichment_json(value_bytes(&step.config))?;
                Ok(StepOutput::None)
            }
            "delete_enrichment" => Ok(StepOutput::Bool(
                self.db()?.delete_enrichment(&step.kind, &step.name)?,
            )),
            "begin_transaction"
            | "write_transaction"
            | "resolve_transaction"
            | "transaction_status"
            | "commit_version" => self.execute_transaction(step),
            "backup" => {
                let backup = self.db()?.backup()?;
                self.backup = backup;
                Ok(StepOutput::None)
            }
            "import_backup" => {
                self.db()?.import_backup(&self.backup)?;
                Ok(StepOutput::None)
            }
            "restore_open" => {
                let path = self.resolve_path(&step.open.path);
                let storage = parse_storage(&step.open.storage)?;
                antfly_embedded::restore(
                    &path,
                    &self.backup,
                    &RestoreOptions {
                        storage,
                        replace: false,
                    },
                )?;
                self.close_current();
                self.open_current(&step.open)?;
                Ok(StepOutput::None)
            }
            "reopen" => {
                self.close_current();
                let mut o = ConformanceOpen {
                    path: step.open.path.clone(),
                    ..copy_open(&step.open)
                };
                if o.path.is_empty() {
                    o.path = self
                        .path
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("db.aflite")
                        .to_string();
                }
                self.open_current(&o)?;
                Ok(StepOutput::None)
            }
            "open_second" => {
                let path = self.resolve_path(&step.open.path);
                let second = self.open_db(&path, &step.open)?;
                let _ = second.close();
                Ok(StepOutput::None)
            }
            "close" => {
                self.close_current();
                Ok(StepOutput::None)
            }
            other => Err(ExecError::Other(format!("unknown op {other:?}"))),
        }
    }

    fn execute_transaction(&mut self, step: &ConformanceStep) -> Result<StepOutput, ExecError> {
        let id = parse_txn_id(&step.txn_id)?;
        match step.op.as_str() {
            "begin_transaction" => {
                self.db()?.begin_transaction(id, step.timestamp, &[])?;
                Ok(StepOutput::None)
            }
            "write_transaction" => {
                let writes: Vec<WriteIntent> = step
                    .writes
                    .iter()
                    .map(|w| {
                        if w.delete {
                            WriteIntent::delete(w.key.as_bytes())
                        } else {
                            WriteIntent::put(w.key.as_bytes(), value_bytes(&w.value))
                        }
                    })
                    .collect();
                self.db()?.write_transaction(id, &writes)?;
                Ok(StepOutput::None)
            }
            "resolve_transaction" => {
                let status = match step.status.as_str() {
                    "committed" => TxnStatus::Committed,
                    "aborted" => TxnStatus::Aborted,
                    other => return Err(ExecError::Other(format!("unknown status {other:?}"))),
                };
                self.db()?
                    .resolve_transaction(id, status, step.commit_version)?;
                Ok(StepOutput::None)
            }
            "transaction_status" => {
                let status = self.db()?.transaction_status(id)?;
                let name = match status {
                    TxnStatus::Pending => "pending",
                    TxnStatus::Committed => "committed",
                    TxnStatus::Aborted => "aborted",
                };
                Ok(StepOutput::Str(name.to_string()))
            }
            _ => Ok(StepOutput::U64(self.db()?.commit_version(id)?)),
        }
    }

    fn db(&self) -> Result<&Database, ExecError> {
        self.db
            .as_ref()
            .ok_or_else(|| ExecError::Other("no open database".to_string()))
    }
}

fn copy_open(o: &ConformanceOpen) -> ConformanceOpen {
    ConformanceOpen {
        storage: o.storage.clone(),
        create: o.create,
        mode: o.mode.clone(),
        profile: o.profile.clone(),
        no_sync: o.no_sync,
        busy_timeout_ms: o.busy_timeout_ms,
        path: o.path.clone(),
    }
}

fn parse_storage(s: &str) -> Result<Storage, ExecError> {
    match s {
        "" | "lite" => Ok(Storage::Lite),
        "directory" => Ok(Storage::Directory),
        other => Err(ExecError::Other(format!("unknown storage {other:?}"))),
    }
}

fn parse_direction(s: &str) -> Result<GraphDirection, ExecError> {
    match s {
        "" | "out" => Ok(GraphDirection::Out),
        "in" => Ok(GraphDirection::In),
        "both" => Ok(GraphDirection::Both),
        other => Err(ExecError::Other(format!("unknown direction {other:?}"))),
    }
}

fn parse_txn_id(hex_id: &str) -> Result<TxnId, ExecError> {
    if hex_id.len() != 32 {
        return Err(ExecError::Other(format!(
            "txn_id {hex_id:?} must be 32 hex characters"
        )));
    }
    let mut id = [0u8; 16];
    for i in 0..16 {
        let byte = u8::from_str_radix(&hex_id[i * 2..i * 2 + 2], 16)
            .map_err(|e| ExecError::Other(format!("txn_id {hex_id:?}: {e}")))?;
        id[i] = byte;
    }
    Ok(id)
}

/// Serializes a JSON case value to the bytes a C ABI call would receive.
/// `Value::Null` (an absent field in the case file) becomes an empty
/// payload, matching Go's `json.RawMessage` zero value.
fn value_bytes(v: &Value) -> Vec<u8> {
    if v.is_null() {
        Vec::new()
    } else {
        serde_json::to_vec(v).expect("case JSON always re-serializes")
    }
}

#[derive(Debug)]
enum ExecError {
    Ffi(Error),
    Other(String),
}

impl From<Error> for ExecError {
    fn from(err: Error) -> Self {
        ExecError::Ffi(err)
    }
}

impl std::fmt::Display for ExecError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExecError::Ffi(err) => write!(f, "{err}"),
            ExecError::Other(msg) => write!(f, "{msg}"),
        }
    }
}

fn check_result(output: &StepOutput, expect: &ConformanceExpect) -> Result<(), String> {
    let text = output.as_text();
    if let Some(want) = &expect.json_subset {
        let got: Value =
            serde_json::from_str(&text).map_err(|e| format!("result is not JSON: {e}: {text}"))?;
        if !json_subset(want, &got) {
            return Err(format!("result {text} does not contain {want}"));
        }
    }
    for s in &expect.contains {
        if !text.contains(s.as_str()) {
            return Err(format!("result {text} does not contain {s:?}"));
        }
    }
    for s in &expect.not_contains {
        if text.contains(s.as_str()) {
            return Err(format!("result {text} unexpectedly contains {s:?}"));
        }
    }
    if let Some(want) = &expect.equals {
        let got: Value = serde_json::from_str(&text)
            .map_err(|e| format!("scalar result {text:?} is not JSON: {e}"))?;
        if want != &got {
            return Err(format!("result {got}, want {want}"));
        }
    }
    Ok(())
}

fn json_subset(want: &Value, got: &Value) -> bool {
    match want {
        Value::Object(want_map) => match got {
            Value::Object(got_map) => want_map
                .iter()
                .all(|(k, wv)| got_map.get(k).is_some_and(|gv| json_subset(wv, gv))),
            _ => false,
        },
        Value::Array(want_arr) => match got {
            Value::Array(got_arr) if got_arr.len() == want_arr.len() => want_arr
                .iter()
                .zip(got_arr.iter())
                .all(|(w, g)| json_subset(w, g)),
            _ => false,
        },
        other => other == got,
    }
}

#[test]
fn resolver_identity_management() {
    std::thread::Builder::new()
        .stack_size(antfly_embedded::MIN_THREAD_STACK_SIZE)
        .spawn(|| {
            let path = std::env::temp_dir().join(format!("antfly-identities-{}-{}.aflite",std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
            let db = Database::create(&path, &OpenOptions::new().no_sync(true)).unwrap();
            assert!(!db.cancel_replacement("missing").unwrap());
            assert!(!db.backup_json(br#"{"tables":["default"]}"#).unwrap().is_empty());

            db.add_index_json(br#"{"name":"knowledge","type":"graph","source":{"artifact":"kg","format":"extraction_graph","mention_edge_type":"mentions"},"artifact":{"name":"kg","kind":"asset","source":{"type":"field","value":"kg"},"content_type":"application/json"},"edge_types":[{"name":"mentions"}],"resolvers":[{"name":"concepts","table":"default","source_artifact":"kg","resolution_artifact":"resolved","key_template":"entity/{{ uslug _entity.text }}","promote":false}]}"#).unwrap();
            let active: Value = serde_json::from_slice(&db.resolver_identities_json().unwrap()).unwrap();
            assert_eq!(active[0]["config"]["name"], "concepts");
            assert!(db.drop_resolver_identity("concepts").is_err());
            assert!(db.delete_index("knowledge").unwrap());
            let retired: Value = serde_json::from_slice(&db.resolver_identities_json().unwrap()).unwrap();
            assert_eq!(retired[0]["config"]["retired"], true);
            assert!(db.drop_resolver_identity("concepts").unwrap());
            assert!(!db.drop_resolver_identity("concepts").unwrap());
            db.close().unwrap();
            std::fs::remove_file(path).unwrap();
        }).unwrap().join().unwrap();
}