a3s-vec 0.1.8

Native Rust in-process vector database with zvec-compatible capabilities
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
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_precision_loss,
    clippy::doc_markdown,
    clippy::float_cmp,
    clippy::items_after_statements,
    clippy::too_many_lines
)]

use a3s_vec::{
    Collection, CollectionOptions, CollectionSchema, DataType, Doc, Durability, FieldSchema,
    HnswQueryParams, IndexParams, IvfQueryParams, MetricType, SearchQuery,
};
use std::sync::{Arc, Barrier};
use std::thread;
use tempfile::tempdir;

const DOCUMENTS: usize = 8_400;
const ALLOWED_START: usize = DOCUMENTS / 2;
const TOPK: usize = 10;

fn options() -> CollectionOptions {
    let mut options = CollectionOptions::new().expect("collection options must be valid");
    options
        .set_durability(Durability::Manual)
        .expect("manual durability must be valid");
    options
}

fn schema(name: &str, indexed: bool) -> CollectionSchema {
    let mut scope =
        FieldSchema::new("scope", DataType::String, false, 0).expect("scope field must be valid");
    let mut shard =
        FieldSchema::new("shard", DataType::Int32, false, 0).expect("shard field must be valid");
    let mut embedding = FieldSchema::new("embedding", DataType::VectorFp32, false, 2)
        .expect("embedding field must be valid");
    if indexed {
        scope
            .set_index_params(
                &IndexParams::invert(false, false).expect("inverted descriptor must be valid"),
            )
            .expect("scope must support an inverted index");
        shard
            .set_index_params(
                &IndexParams::invert(false, false).expect("inverted descriptor must be valid"),
            )
            .expect("shard must support an inverted index");
        embedding
            .set_index_params(
                &IndexParams::ivf(MetricType::L2, 32, 5, false)
                    .expect("IVF descriptor must be valid"),
            )
            .expect("embedding must support IVF");
    }
    CollectionSchema::builder(name)
        .add_field(scope)
        .add_field(shard)
        .add_field(
            FieldSchema::new("tags", DataType::ArrayString, false, 0)
                .expect("tags field must be valid"),
        )
        .add_field(embedding)
        .build()
        .expect("collection schema must be valid")
}

fn document(index: usize) -> Doc {
    let mut doc =
        Doc::with_pk(format!("doc-{index:05}")).expect("document primary key must be valid");
    let allowed = index >= ALLOWED_START;
    doc.add_string("scope", if allowed { "allowed" } else { "excluded" })
        .expect("scope must be valid");
    doc.add_i32(
        "shard",
        i32::try_from(index % 2).expect("shard value fits i32"),
    )
    .expect("shard must be valid");
    let tags: &[&str] = if index % 100 == 0 {
        &["workspace"]
    } else {
        &["workspace", "target"]
    };
    doc.add_array_string("tags", tags)
        .expect("tags must be valid");
    let local = index % ALLOWED_START;
    let local = f32::from(u16::try_from(local).expect("fixture coordinate fits u16"));
    let offset = if allowed { 10_000.0 } else { 0.0 };
    doc.add_vector_f32("embedding", &[offset + local, local % 17.0])
        .expect("embedding must be valid");
    doc
}

fn insert_fixture(collection: &Collection) {
    let docs: Vec<Doc> = (0..DOCUMENTS).map(document).collect();
    let refs: Vec<&Doc> = docs.iter().collect();
    let result = collection
        .insert(&refs)
        .expect("fixture insert must succeed");
    assert_eq!(result.success_count, DOCUMENTS as u64);
}

fn exact_query(filter: &str) -> SearchQuery {
    let mut query = SearchQuery::new(
        "embedding",
        &[0.0, 0.0],
        i32::try_from(TOPK).expect("top-k fits i32"),
    )
    .expect("query must be valid");
    query
        .params
        .insert("metric".into(), serde_json::json!("l2"));
    query.set_filter(filter).expect("filter must be valid");
    query
}

fn indexed_query() -> SearchQuery {
    let mut query = exact_query("scope == 'allowed'");
    query
        .set_ivf_params(IvfQueryParams::new(2, true, 8.0))
        .expect("IVF controls must be valid");
    query
}

fn hnsw_query(filter: &str) -> SearchQuery {
    let mut query = exact_query(filter);
    query
        .set_hnsw_params(HnswQueryParams::new(64, 0.0, false, true))
        .expect("HNSW controls must be valid");
    query
}

fn comparable(docs: &[Doc]) -> Vec<(&str, f32)> {
    docs.iter()
        .map(|doc| {
            (
                doc.get_pk().expect("result must have a primary key"),
                doc.get_score(),
            )
        })
        .collect()
}

fn assert_filtered_query_matches_exact(indexed: &Collection, exact: &Collection) {
    let expected = exact
        .query(&exact_query("scope == 'allowed'"))
        .expect("exact filtered query must succeed");
    let before = indexed
        .stats_snapshot()
        .expect("statistics must be available");
    let actual = indexed
        .query(&indexed_query())
        .expect("filtered IVF query must succeed");
    let after = indexed
        .stats_snapshot()
        .expect("statistics must be available");

    assert_eq!(actual.len(), TOPK);
    assert_eq!(comparable(&actual), comparable(&expected));
    assert_eq!(after.ann_query_count - before.ann_query_count, 1);
    assert_eq!(
        after.scalar_index_query_count - before.scalar_index_query_count,
        1
    );
    assert!(after.candidates_scanned - before.candidates_scanned <= 80);
}

fn assert_filtered_hnsw_matches_exact(indexed: &Collection, exact: &Collection, filter: &str) {
    let expected = exact
        .query(&exact_query(filter))
        .expect("exact filtered query must succeed");
    let before = indexed
        .stats_snapshot()
        .expect("statistics must be available");
    let actual = indexed
        .query(&hnsw_query(filter))
        .expect("filtered HNSW query must succeed");
    let after = indexed
        .stats_snapshot()
        .expect("statistics must be available");

    assert_eq!(actual.len(), TOPK);
    assert_eq!(comparable(&actual), comparable(&expected));
    assert_eq!(after.ann_query_count - before.ann_query_count, 1);
    assert_eq!(
        after.scalar_index_query_count - before.scalar_index_query_count,
        1
    );
    assert!(after.candidates_scanned - before.candidates_scanned <= 64);
}

fn exercise_concurrent_filtered_generations(collection: &Collection) {
    const WRITES: usize = 32;
    const READS: usize = 64;
    const READERS: usize = 2;

    let started = Arc::new(Barrier::new(READERS + 1));
    thread::scope(|scope| {
        let writer_collection = collection.clone();
        let writer_started = Arc::clone(&started);
        let writer = scope.spawn(move || {
            writer_started.wait();
            for revision in 0..WRITES {
                let mut patch = Doc::with_pk("doc-00000").expect("patch must be valid");
                patch
                    .add_string(
                        "scope",
                        if revision % 2 == 0 {
                            "excluded"
                        } else {
                            "allowed"
                        },
                    )
                    .expect("scope patch must be valid");
                let result = writer_collection
                    .update(&[&patch])
                    .expect("concurrent scope update must succeed");
                assert_eq!(result.success_count, 1);
            }
        });

        let readers = (0..READERS)
            .map(|_| {
                let reader_collection = collection.clone();
                let reader_started = Arc::clone(&started);
                scope.spawn(move || {
                    reader_started.wait();
                    for _ in 0..READS {
                        let result = reader_collection
                            .query(&indexed_query())
                            .expect("concurrent filtered query must succeed");
                        assert_eq!(result.len(), TOPK);
                        assert!(result.iter().all(|doc| {
                            doc.get_string("scope").expect("scope must be readable")
                                == Some("allowed".into())
                        }));
                        assert!(matches!(
                            result[0].get_pk(),
                            Some("doc-00000" | "doc-04200")
                        ));
                    }
                })
            })
            .collect::<Vec<_>>();

        writer.join().expect("writer must not panic");
        for reader in readers {
            reader.join().expect("reader must not panic");
        }
    });
}

#[test]
fn filtered_ann_is_complete_generation_safe_and_durable() {
    let temporary = tempdir().expect("temporary directory must be available");
    let options = options();
    let indexed_path = temporary.path().join("indexed");
    let indexed = Collection::create(
        indexed_path.to_str().expect("temporary path must be UTF-8"),
        &schema("indexed", true),
        Some(&options),
    )
    .expect("indexed collection must be created");
    let exact = Collection::create(
        temporary
            .path()
            .join("exact")
            .to_str()
            .expect("temporary path must be UTF-8"),
        &schema("exact", false),
        Some(&options),
    )
    .expect("exact collection must be created");
    insert_fixture(&indexed);
    insert_fixture(&exact);

    assert_filtered_query_matches_exact(&indexed, &exact);

    let mut patch = Doc::with_pk("doc-00000").expect("patch must be valid");
    patch
        .add_string("scope", "allowed")
        .expect("scope patch must be valid");
    indexed
        .update(&[&patch])
        .expect("indexed scope update must succeed");
    exact
        .update(&[&patch])
        .expect("exact scope update must succeed");
    assert_filtered_query_matches_exact(&indexed, &exact);
    exercise_concurrent_filtered_generations(&indexed);
    assert_filtered_query_matches_exact(&indexed, &exact);

    indexed.flush().expect("indexed collection must flush");
    indexed.close().expect("indexed collection must close");
    let reopened = Collection::open(
        indexed_path.to_str().expect("temporary path must be UTF-8"),
        Some(&options),
    )
    .expect("indexed collection must reopen");
    assert_filtered_query_matches_exact(&reopened, &exact);

    reopened
        .create_index(
            "embedding",
            &IndexParams::hnsw(MetricType::L2, 12, 64).expect("HNSW descriptor must be valid"),
        )
        .expect("HNSW index must build");
    assert_filtered_hnsw_matches_exact(&reopened, &exact, "shard == 0");
    assert_filtered_hnsw_matches_exact(
        &reopened,
        &exact,
        "shard == 0 and tags contain_all ['target']",
    );
}

fn vamana_schema(name: &str) -> CollectionSchema {
    let mut scope =
        FieldSchema::new("scope", DataType::String, false, 0).expect("scope field must be valid");
    let mut embedding = FieldSchema::new("embedding", DataType::VectorFp32, false, 2)
        .expect("embedding field must be valid");
    scope
        .set_index_params(
            &IndexParams::invert(false, false).expect("inverted descriptor must be valid"),
        )
        .expect("scope must support an inverted index");
    embedding
        .set_index_params(
            &IndexParams::vamana(MetricType::L2, 16, 64, 1.2)
                .expect("Vamana descriptor must be valid"),
        )
        .expect("embedding must support Vamana");
    CollectionSchema::builder(name)
        .add_field(scope)
        .add_field(embedding)
        .build()
        .expect("collection schema must be valid")
}

/// Large scalar prefilter + Vamana must keep allow-list semantics vs exact Flat.
#[test]
fn filtered_vamana_matches_exact_on_large_allow_list() {
    let temporary = tempdir().expect("temporary directory must be available");
    let indexed = Collection::create(
        temporary
            .path()
            .join("filtered-vamana")
            .to_str()
            .expect("utf8"),
        &vamana_schema("filtered-vamana"),
        Some(&options()),
    )
    .expect("indexed");
    let mut exact_embedding =
        FieldSchema::new("embedding", DataType::VectorFp32, false, 2).expect("embedding");
    exact_embedding
        .set_index_params(&IndexParams::flat(MetricType::L2).expect("flat"))
        .expect("flat");
    let mut scope = FieldSchema::new("scope", DataType::String, false, 0).expect("scope");
    scope
        .set_index_params(&IndexParams::invert(false, false).expect("invert"))
        .expect("invert");
    let exact_schema = CollectionSchema::builder("filtered-vamana-exact")
        .add_field(scope)
        .add_field(exact_embedding)
        .build()
        .expect("schema");
    let exact = Collection::create(
        temporary
            .path()
            .join("filtered-vamana-exact")
            .to_str()
            .expect("utf8"),
        &exact_schema,
        Some(&options()),
    )
    .expect("exact");

    const N: usize = 8_400;
    let docs: Vec<Doc> = (0..N)
        .map(|index| {
            let mut doc = Doc::with_pk(format!("doc-{index:05}")).expect("pk");
            let allowed = index >= N / 2;
            doc.add_string("scope", if allowed { "allowed" } else { "excluded" })
                .expect("scope");
            let local = (index % (N / 2)) as f32;
            doc.add_vector_f32(
                "embedding",
                &[if allowed { 1_000.0 + local } else { local }, local % 13.0],
            )
            .expect("vector");
            doc
        })
        .collect();
    let refs: Vec<&Doc> = docs.iter().collect();
    indexed.insert(&refs).expect("insert");
    exact.insert(&refs).expect("insert");
    indexed.optimize().expect("optimize");
    exact.optimize().expect("optimize");

    let mut query = SearchQuery::new("embedding", &[1_050.0, 1.0], TOPK as i32).expect("query");
    query.set_filter("scope == \"allowed\"").expect("filter");
    let mut approx_query = query.clone();
    approx_query
        .set_diskann_params(a3s_vec::DiskannQueryParams::new(64))
        .expect("list_size");
    let approximate = indexed.query(&approx_query).expect("filtered Vamana");
    let truth = exact.query(&query).expect("filtered exact");
    assert_eq!(
        approximate
            .iter()
            .map(|doc| doc.get_pk().unwrap().to_string())
            .collect::<Vec<_>>(),
        truth
            .iter()
            .map(|doc| doc.get_pk().unwrap().to_string())
            .collect::<Vec<_>>()
    );
}

fn diskann_schema(name: &str) -> CollectionSchema {
    let mut scope =
        FieldSchema::new("scope", DataType::String, false, 0).expect("scope field must be valid");
    let mut embedding = FieldSchema::new("embedding", DataType::VectorFp32, false, 2)
        .expect("embedding field must be valid");
    scope
        .set_index_params(
            &IndexParams::invert(false, false).expect("inverted descriptor must be valid"),
        )
        .expect("scope must support an inverted index");
    embedding
        .set_index_params(
            &IndexParams::diskann(MetricType::L2, 16, 64, 0)
                .expect("DiskANN descriptor must be valid"),
        )
        .expect("embedding must support DiskANN");
    CollectionSchema::builder(name)
        .add_field(scope)
        .add_field(embedding)
        .build()
        .expect("collection schema must be valid")
}

#[test]
fn filtered_diskann_matches_exact_on_large_allow_list() {
    let temporary = tempdir().expect("temporary directory must be available");
    let indexed = Collection::create(
        temporary
            .path()
            .join("filtered-diskann")
            .to_str()
            .expect("utf8"),
        &diskann_schema("filtered-diskann"),
        Some(&options()),
    )
    .expect("indexed");
    let mut exact_embedding =
        FieldSchema::new("embedding", DataType::VectorFp32, false, 2).expect("embedding");
    exact_embedding
        .set_index_params(&IndexParams::flat(MetricType::L2).expect("flat"))
        .expect("flat");
    let mut scope = FieldSchema::new("scope", DataType::String, false, 0).expect("scope");
    scope
        .set_index_params(&IndexParams::invert(false, false).expect("invert"))
        .expect("invert");
    let exact_schema = CollectionSchema::builder("filtered-diskann-exact")
        .add_field(scope)
        .add_field(exact_embedding)
        .build()
        .expect("schema");
    let exact = Collection::create(
        temporary
            .path()
            .join("filtered-diskann-exact")
            .to_str()
            .expect("utf8"),
        &exact_schema,
        Some(&options()),
    )
    .expect("exact");

    const N: usize = 8_400;
    let docs: Vec<Doc> = (0..N)
        .map(|index| {
            let mut doc = Doc::with_pk(format!("doc-{index:05}")).expect("pk");
            let allowed = index >= N / 2;
            doc.add_string("scope", if allowed { "allowed" } else { "excluded" })
                .expect("scope");
            let local = (index % (N / 2)) as f32;
            doc.add_vector_f32(
                "embedding",
                &[if allowed { 1_000.0 + local } else { local }, local % 13.0],
            )
            .expect("vector");
            doc
        })
        .collect();
    let refs: Vec<&Doc> = docs.iter().collect();
    indexed.insert(&refs).expect("insert");
    exact.insert(&refs).expect("insert");
    indexed.optimize().expect("optimize");
    exact.optimize().expect("optimize");

    let mut query = SearchQuery::new("embedding", &[1_050.0, 1.0], TOPK as i32).expect("query");
    query.set_filter("scope == \"allowed\"").expect("filter");
    let mut approx_query = query.clone();
    approx_query
        .set_diskann_params(a3s_vec::DiskannQueryParams::new(64))
        .expect("list_size");
    let approximate = indexed.query(&approx_query).expect("filtered DiskANN");
    let truth = exact.query(&query).expect("filtered exact");
    assert_eq!(
        approximate
            .iter()
            .map(|doc| doc.get_pk().unwrap().to_string())
            .collect::<Vec<_>>(),
        truth
            .iter()
            .map(|doc| doc.get_pk().unwrap().to_string())
            .collect::<Vec<_>>()
    );
}

#[test]
fn filtered_diskann_with_large_list_size_exercises_ann_candidate_path() {
    let temporary = tempdir().expect("temp");
    let indexed = Collection::create(
        temporary
            .path()
            .join("filtered-diskann-wide")
            .to_str()
            .expect("utf8"),
        &diskann_schema("filtered-diskann-wide"),
        Some(&options()),
    )
    .expect("indexed");

    const N: usize = 8_400;
    let docs: Vec<Doc> = (0..N)
        .map(|index| {
            let mut doc = Doc::with_pk(format!("doc-{index:05}")).expect("pk");
            let allowed = index >= N / 2;
            doc.add_string("scope", if allowed { "allowed" } else { "excluded" })
                .expect("scope");
            let local = (index % (N / 2)) as f32;
            doc.add_vector_f32(
                "embedding",
                &[if allowed { 1_000.0 + local } else { local }, local % 13.0],
            )
            .expect("vector");
            doc
        })
        .collect();
    let refs: Vec<&Doc> = docs.iter().collect();
    indexed.insert(&refs).expect("insert");
    indexed.optimize().expect("optimize");

    let mut query = SearchQuery::new("embedding", &[1_050.0, 1.0], TOPK as i32).expect("query");
    query.set_filter("scope == \"allowed\"").expect("filter");
    // Large list_size keeps traversal below the full allow-list so DiskANN
    // filtered candidate planning runs instead of exact fallback.
    query
        .set_diskann_params(a3s_vec::DiskannQueryParams::new(512))
        .expect("list_size");
    let hits = indexed.query(&query).expect("filtered DiskANN wide");
    assert_eq!(hits.len(), TOPK);
    for hit in &hits {
        match hit.field("scope") {
            Some(a3s_vec::FieldValue::String(value)) => assert_eq!(value, "allowed"),
            other => panic!("expected allowed scope, got {other:?}"),
        }
    }
}

#[test]
fn large_scalar_and_conjunction_intersects_two_nonselective_bitmaps() {
    // Both sides exceed CONJUNCTION_EARLY_STOP (4096), so evaluation must
    // intersect rather than early-stop on a selective branch.
    let temporary = tempdir().expect("temp");
    let exact = Collection::create(
        temporary
            .path()
            .join("scalar-and-exact")
            .to_str()
            .expect("utf8"),
        &schema("scalar-and-exact", false),
        Some(&options()),
    )
    .expect("create exact");
    let indexed = Collection::create(
        temporary.path().join("scalar-and").to_str().expect("utf8"),
        &schema("scalar-and", true),
        Some(&options()),
    )
    .expect("create indexed");
    insert_fixture(&exact);
    insert_fixture(&indexed);

    // Query near the allowed cluster so filtered top-k is non-empty and stable.
    let filter = "scope == 'allowed' AND shard == 0";
    let mut query = SearchQuery::new("embedding", &[10_000.0, 0.0], TOPK as i32).expect("query");
    query
        .params
        .insert("metric".into(), serde_json::json!("l2"));
    query.set_filter(filter).expect("filter");
    let expected = exact.query(&query).expect("exact AND");
    // Exact scan on the indexed collection still evaluates inverted AND bitmaps.
    let actual = indexed.query(&query).expect("indexed AND");
    assert_eq!(comparable(&actual), comparable(&expected));
    assert_eq!(actual.len(), TOPK);
    for hit in &actual {
        match hit.field("scope") {
            Some(a3s_vec::FieldValue::String(value)) => assert_eq!(value, "allowed"),
            other => panic!("expected allowed scope, got {other:?}"),
        }
        match hit.field("shard") {
            Some(a3s_vec::FieldValue::Int32(0)) => {}
            other => panic!("expected shard 0, got {other:?}"),
        }
    }
}

#[test]
fn empty_scalar_and_branch_short_circuits_without_evaluating_right() {
    // Empty left bitmap must return immediately (CONJUNCTION early empty path).
    let temporary = tempdir().expect("temp");
    let indexed = Collection::create(
        temporary
            .path()
            .join("scalar-and-empty")
            .to_str()
            .expect("utf8"),
        &schema("scalar-and-empty", true),
        Some(&options()),
    )
    .expect("create");
    insert_fixture(&indexed);

    let mut empty_left =
        SearchQuery::new("embedding", &[10_000.0, 0.0], TOPK as i32).expect("query");
    empty_left
        .params
        .insert("metric".into(), serde_json::json!("l2"));
    empty_left
        .set_filter("scope == 'never-matches' AND shard == 0")
        .expect("filter");
    assert!(indexed.query(&empty_left).expect("empty left").is_empty());

    // Empty right after a non-selective left.
    let mut empty_right =
        SearchQuery::new("embedding", &[10_000.0, 0.0], TOPK as i32).expect("query");
    empty_right
        .params
        .insert("metric".into(), serde_json::json!("l2"));
    empty_right
        .set_filter("scope == 'allowed' AND scope == 'never-matches'")
        .expect("filter");
    assert!(indexed.query(&empty_right).expect("empty right").is_empty());

    // Indexed left with unindexed contain_all right falls back conservatively.
    let mut mixed = SearchQuery::new("embedding", &[10_000.0, 0.0], TOPK as i32).expect("query");
    mixed
        .params
        .insert("metric".into(), serde_json::json!("l2"));
    mixed
        .set_filter("scope == 'allowed' AND tags contain_all ['workspace']")
        .expect("filter");
    let hits = indexed.query(&mixed).expect("mixed AND");
    assert!(!hits.is_empty());
    for hit in &hits {
        match hit.field("scope") {
            Some(a3s_vec::FieldValue::String(value)) => assert_eq!(value, "allowed"),
            other => panic!("expected allowed scope, got {other:?}"),
        }
    }

    // Inexact large scalar prefilter is refined; a non-matching contain_all
    // shrinks the candidate set below the exact-scan threshold.
    let mut refined = SearchQuery::new("embedding", &[10_000.0, 0.0], TOPK as i32).expect("query");
    refined
        .params
        .insert("metric".into(), serde_json::json!("l2"));
    refined
        .set_filter("scope == 'allowed' AND tags contain_all ['no-such-tag']")
        .expect("filter");
    assert!(indexed.query(&refined).expect("refined empty").is_empty());
}