troupekit-store-sqlite 0.4.0

SQLite storage for Troupekit: checkpoints, memory logs, blobs, a job queue and a usage ledger in one file.
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
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
use serde_json::json;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::process::{Child, Command};
#[cfg(unix)]
use std::time::{Duration, Instant};
use troupekit_core::error::CoreError;
use troupekit_core::ids::RunId;
use troupekit_core::inmem::InMemVectors;
use troupekit_core::store::{
    BlobStore, Checkpoint, CheckpointStore, Filter, KeywordStore, Scored, VectorRecord, VectorStore,
};
use troupekit_store_sqlite::{
    HnswParams, IndexKind, Quantization, SqliteStore, SqliteVectors, VectorSettings,
};

const DIMS: usize = 8;
const CHILD_DB: &str = "TROUPEKIT_VECTORS_CHILD_DB";
#[cfg(unix)]
const DEADLINE: Duration = Duration::from_secs(30);

struct Temp {
    _dir: tempfile::TempDir,
    path: PathBuf,
}

fn temp() -> Temp {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("store.db");
    Temp { _dir: dir, path }
}

struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }

    fn vector(&mut self, dims: usize) -> Vec<f32> {
        (0..dims)
            .map(|_| (self.next() % 2001) as f32 / 1000.0 - 1.0)
            .collect()
    }
}

fn meta(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
    pairs
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect()
}

fn rec(id: &str, vector: Vec<f32>, text: &str, pairs: &[(&str, &str)]) -> VectorRecord {
    VectorRecord {
        id: id.into(),
        vector,
        text: text.into(),
        meta: meta(pairs),
    }
}

fn sourced(id: &str, rng: &mut Rng, scope: &str, source: &str) -> VectorRecord {
    rec(
        id,
        rng.vector(DIMS),
        &format!("text of {id}"),
        &[("scope", scope), ("source", source)],
    )
}

fn filter(pairs: &[(&str, &str)]) -> Filter {
    Filter(meta(pairs))
}

fn count(path: &Path, sql: &str) -> i64 {
    let conn = rusqlite::Connection::open(path).unwrap();
    conn.query_row(sql, [], |row| row.get(0)).unwrap()
}

fn ids(hits: &[Scored]) -> Vec<&str> {
    hits.iter().map(|h| h.id.as_str()).collect()
}

async fn docs(store: &SqliteStore) -> SqliteVectors {
    store
        .vectors("docs", VectorSettings::new(DIMS))
        .await
        .unwrap()
}

fn store_error(result: Result<impl std::fmt::Debug, CoreError>, needle: &str) {
    match result {
        Err(CoreError::Store(message)) => {
            assert!(message.contains(needle), "{message} lacks {needle}")
        }
        other => panic!("expected Store error with {needle}, got {other:?}"),
    }
}

#[tokio::test]
async fn upsert_then_search_matches_brute_force_in_memory() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = store
        .vectors("docs", VectorSettings::new(16))
        .await
        .unwrap();
    let oracle = InMemVectors::new(16);
    let mut rng = Rng(7);
    let records: Vec<VectorRecord> = (0..2000)
        .map(|i| {
            let group = (i % 5).to_string();
            rec(
                &format!("r{i:05}"),
                rng.vector(16),
                &format!("chunk {i}"),
                &[("group", &group)],
            )
        })
        .collect();
    for batch in records.chunks(500) {
        vectors.upsert(batch.to_vec()).await.unwrap();
        oracle.upsert(batch.to_vec()).await.unwrap();
    }
    for q in 0..20 {
        let query = rng.vector(16);
        for f in [filter(&[]), filter(&[("group", "2")])] {
            let got = vectors.search(&query, 10, &f).await.unwrap();
            let want = oracle.search(&query, 10, &f).await.unwrap();
            assert_eq!(ids(&got), ids(&want), "query {q}");
            for (g, w) in got.iter().zip(&want) {
                assert!(
                    (g.score - w.score).abs() < 1e-5,
                    "query {q}: {} vs {}",
                    g.score,
                    w.score
                );
                assert_eq!((&g.text, &g.meta), (&w.text, &w.meta));
            }
        }
    }
    assert_eq!(vectors.len().await.unwrap(), 2000);
    assert!(!vectors.is_empty().await.unwrap());
}

#[tokio::test]
async fn text_and_meta_round_trip() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let text = "Größe: 10 cm\n\t\"quoted\" 'single' \u{1F600} end";
    let pairs = [
        ("ключ", "значение"),
        ("empty", ""),
        ("quote", "x' OR '1'='1"),
    ];
    vectors
        .upsert(vec![rec("a", vec![1.0; DIMS], text, &pairs)])
        .await
        .unwrap();
    drop(vectors);
    drop(store);
    let store = SqliteStore::open(&t.path).await.unwrap();
    let hits = docs(&store)
        .await
        .search(&[1.0; DIMS], 1, &filter(&[]))
        .await
        .unwrap();
    assert_eq!(hits[0].text, text);
    assert_eq!(hits[0].meta, meta(&pairs));
}

#[tokio::test]
async fn dims_mismatch_on_reopen_is_refused() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let err = vectors
        .upsert(vec![rec("a", vec![1.0; 3], "t", &[])])
        .await
        .unwrap_err();
    assert_eq!(
        err,
        CoreError::DimensionMismatch {
            expected: DIMS,
            actual: 3
        }
    );
    let err = vectors
        .search(&[1.0; 9], 1, &filter(&[]))
        .await
        .unwrap_err();
    assert_eq!(
        err,
        CoreError::DimensionMismatch {
            expected: DIMS,
            actual: 9
        }
    );
    drop(vectors);
    drop(store);
    let store = SqliteStore::open(&t.path).await.unwrap();
    let err = store.vectors("docs", VectorSettings::new(16)).await.unwrap_err();
    assert_eq!(err, CoreError::DimensionMismatch { expected: DIMS, actual: 16 });
    let vectors = docs(&store).await;
    assert_eq!(vectors.len().await.unwrap(), 0);
    assert!(vectors.is_empty().await.unwrap());
}

#[tokio::test]
async fn upsert_is_atomic_across_rows_fts_and_pages() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = store
        .vectors("docs", VectorSettings::new(DIMS).with_max_text_bytes(8))
        .await
        .unwrap();
    vectors
        .upsert(vec![rec("keep", vec![1.0; DIMS], "kept", &[("k", "v")])])
        .await
        .unwrap();
    let batch = vec![
        rec("a", vec![0.5; DIMS], "short", &[("k", "v")]),
        rec("b", vec![0.5; DIMS], "far too long", &[("k", "v")]),
        rec("c", vec![0.5; DIMS], "short", &[("k", "v")]),
    ];
    store_error(vectors.upsert(batch).await, "max_text_bytes");
    let rows = |sql| count(&t.path, sql);
    assert_eq!(rows("SELECT COUNT(*) FROM chunk"), 1);
    assert_eq!(rows("SELECT COUNT(*) FROM chunk_fts_docsize"), 1);
    assert_eq!(rows("SELECT COUNT(*) FROM chunk_meta"), 1);
    assert_eq!(rows("SELECT COUNT(*) FROM index_page"), 0);
    assert_eq!(vectors.len().await.unwrap(), 1);

    {
        let conn = rusqlite::Connection::open(&t.path).unwrap();
        conn.execute_batch("CREATE TRIGGER block BEFORE UPDATE ON vector_index BEGIN SELECT RAISE(ABORT, 'blocked'); END;")
            .unwrap();
    }
    let loads = vectors.open_report().loads();
    store_error(
        vectors
            .upsert(vec![rec("late", vec![0.25; DIMS], "late", &[])])
            .await,
        "blocked",
    );
    assert_eq!(rows("SELECT COUNT(*) FROM chunk"), 1);
    {
        let conn = rusqlite::Connection::open(&t.path).unwrap();
        conn.execute_batch("DROP TRIGGER block").unwrap();
    }
    let hits = vectors
        .search(&[0.25; DIMS], 10, &filter(&[]))
        .await
        .unwrap();
    assert_eq!(ids(&hits), ["keep"]);
    assert_eq!(vectors.len().await.unwrap(), 1);
    assert_eq!(
        vectors.open_report().loads(),
        loads + 1,
        "a failed write reloads from the file"
    );
}

#[cfg(unix)]
struct Worker(Child);

#[cfg(unix)]
impl Drop for Worker {
    fn drop(&mut self) {
        if matches!(self.0.try_wait(), Ok(None)) {
            let _ = self.0.kill();
        }
        let _ = self.0.wait();
    }
}

#[cfg(unix)]
#[tokio::test]
async fn killed_mid_upsert_leaves_a_consistent_index() {
    let t = temp();
    drop(docs(&SqliteStore::open(&t.path).await.unwrap()).await);
    let mut worker = Worker(
        Command::new(std::env::current_exe().unwrap())
            .args([
                "--ignored",
                "--exact",
                "vectors::child_upserts_until_killed",
                "--test-threads=1",
                "--quiet",
            ])
            .env(CHILD_DB, &t.path)
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap(),
    );
    let start = Instant::now();
    while count(
        &t.path,
        "SELECT generation FROM vector_index WHERE name = 'docs'",
    ) < 3
    {
        assert!(start.elapsed() < DEADLINE, "child wrote no batches");
        assert!(
            matches!(worker.0.try_wait(), Ok(None)),
            "child exited early"
        );
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    let control = rusqlite::Connection::open(&t.path).unwrap();
    control.busy_timeout(DEADLINE).unwrap();
    control
        .execute_batch(
            "CREATE TRIGGER stall AFTER UPDATE ON vector_index BEGIN \
             SELECT 1 FROM chunk a, chunk b, chunk c WHERE a.key + b.key + c.key < 0; END;",
        )
        .unwrap();
    let committed = count(&t.path, "SELECT COUNT(*) FROM chunk");
    let generation = count(&t.path, "SELECT generation FROM vector_index WHERE name = 'docs'");
    control.busy_timeout(Duration::ZERO).unwrap();
    let mut held_since: Option<Instant> = None;
    while held_since.is_none_or(|since| since.elapsed() < Duration::from_secs(1)) {
        assert!(start.elapsed() < 2 * DEADLINE, "child never stalled inside a batch");
        assert!(matches!(worker.0.try_wait(), Ok(None)), "child exited early");
        match control.execute_batch("BEGIN IMMEDIATE; ROLLBACK;") {
            Err(e) if e.sqlite_error_code() == Some(rusqlite::ErrorCode::DatabaseBusy) => {
                held_since.get_or_insert_with(Instant::now);
            }
            Err(e) => panic!("{e}"),
            Ok(()) => held_since = None,
        }
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    worker.0.kill().unwrap();
    let status = worker.0.wait().unwrap();
    assert!(!status.success(), "a killed child does not exit cleanly");
    control.busy_timeout(DEADLINE).unwrap();
    control.execute_batch("DROP TRIGGER stall").unwrap();
    drop(control);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk"), committed, "the interrupted batch did not persist");
    assert_eq!(count(&t.path, "SELECT generation FROM vector_index WHERE name = 'docs'"), generation);
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let chunks = count(&t.path, "SELECT COUNT(*) FROM chunk");
    assert!(chunks >= 2 * 2000, "{chunks}");
    assert_eq!(chunks % 2000, 0, "only whole batches commit");
    assert_eq!(
        count(&t.path, "SELECT COUNT(*) FROM chunk_fts_docsize"),
        chunks
    );
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk_meta"), chunks);
    assert_eq!(vectors.len().await.unwrap() as i64, chunks);
    assert_eq!(vectors.open_report().rebuilds(), 0);
}

#[tokio::test]
#[ignore = "child process of killed_mid_upsert_leaves_a_consistent_index"]
async fn child_upserts_until_killed() {
    let Ok(path) = std::env::var(CHILD_DB) else {
        return;
    };
    let store = SqliteStore::open(&path).await.unwrap();
    let vectors = docs(&store).await;
    let mut rng = Rng(11);
    for batch in 0..10_000 {
        let records = (0..2000)
            .map(|i| {
                rec(
                    &format!("b{batch}-{i}"),
                    rng.vector(DIMS),
                    "child text to index",
                    &[("batch", "x")],
                )
            })
            .collect();
        vectors.upsert(records).await.unwrap();
    }
}

#[tokio::test]
async fn corrupt_page_rebuilds_on_open() {
    let t = temp();
    let mut rng = Rng(3);
    let query = rng.vector(DIMS);
    let before = {
        let store = SqliteStore::open(&t.path).await.unwrap();
        let vectors = docs(&store).await;
        let records = (0..50)
            .map(|i| rec(&format!("r{i}"), rng.vector(DIMS), "t", &[]))
            .collect();
        vectors.upsert(records).await.unwrap();
        vectors.search(&query, 5, &filter(&[])).await.unwrap()
    };
    {
        let conn = rusqlite::Connection::open(&t.path).unwrap();
        conn.execute(
            "INSERT INTO index_page (index_name, page, bytes) VALUES ('docs', 0, X'DEADBEEF')",
            [],
        )
        .unwrap();
    }
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    assert_eq!(vectors.open_report().rebuilds(), 1);
    assert_eq!(vectors.open_report().loads(), 1);
    assert_eq!(
        count(
            &t.path,
            "SELECT COUNT(*) FROM index_page WHERE index_name = 'docs'"
        ),
        0
    );
    assert_eq!(
        vectors.search(&query, 5, &filter(&[])).await.unwrap(),
        before
    );
    assert_eq!(vectors.len().await.unwrap(), 50);
}

#[tokio::test]
async fn switching_kind_rebuilds_and_keeps_results() {
    let t = temp();
    let mut rng = Rng(5);
    let queries: Vec<Vec<f32>> = (0..10).map(|_| rng.vector(DIMS)).collect();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let brute = docs(&store).await;
    let records = (0..200)
        .map(|i| rec(&format!("r{i:03}"), rng.vector(DIMS), "t", &[]))
        .collect();
    brute.upsert(records).await.unwrap();
    let mut exact = Vec::new();
    for q in &queries {
        exact.push(
            ids(&brute.search(q, 5, &filter(&[])).await.unwrap())
                .iter()
                .map(|s| s.to_string())
                .collect::<Vec<_>>(),
        );
    }
    let hnsw = store
        .vectors(
            "docs",
            VectorSettings::new(DIMS).with_kind(IndexKind::Hnsw(HnswParams::default())),
        )
        .await
        .unwrap();
    assert_eq!(
        count(
            &t.path,
            "SELECT COUNT(*) FROM vector_index WHERE kind = 'hnsw'"
        ),
        1
    );
    assert!(
        count(
            &t.path,
            "SELECT COUNT(*) FROM index_page WHERE index_name = 'docs'"
        ) > 0
    );
    assert_eq!(hnsw.len().await.unwrap(), 200);
    for (q, want) in queries.iter().zip(&exact) {
        assert_eq!(&ids(&hnsw.search(q, 5, &filter(&[])).await.unwrap()), want);
    }
    let back = docs(&store).await;
    assert_eq!(
        count(
            &t.path,
            "SELECT COUNT(*) FROM index_page WHERE index_name = 'docs'"
        ),
        0
    );
    for (q, want) in queries.iter().zip(&exact) {
        assert_eq!(&ids(&back.search(q, 5, &filter(&[])).await.unwrap()), want);
    }
}

#[tokio::test]
async fn failed_kind_switch_never_publishes_its_generation() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let brute = docs(&store).await;
    brute
        .upsert(vec![rec("first", vec![1.0; DIMS], "t", &[])])
        .await
        .unwrap();
    let before = count(
        &t.path,
        "SELECT generation FROM vector_index WHERE name = 'docs'",
    );
    rusqlite::Connection::open(&t.path)
        .unwrap()
        .execute_batch(
            "CREATE TRIGGER refuse_switch AFTER UPDATE OF generation ON vector_index WHEN NEW.kind = 'hnsw' \
             BEGIN SELECT RAISE(ABORT, 'switch refused'); END;",
        )
        .unwrap();
    let hnsw = VectorSettings::new(DIMS).with_kind(IndexKind::Hnsw(HnswParams::default()));
    assert!(store.vectors("docs", hnsw).await.is_err());
    assert_eq!(
        count(
            &t.path,
            "SELECT generation FROM vector_index WHERE name = 'docs'"
        ),
        before
    );
    assert_eq!(
        count(
            &t.path,
            "SELECT COUNT(*) FROM vector_index WHERE kind = 'brute_force'"
        ),
        1
    );
    let other = SqliteStore::open(&t.path).await.unwrap();
    let mut second = vec![0.0; DIMS];
    second[0] = 1.0;
    docs(&other)
        .await
        .upsert(vec![rec("second", second.clone(), "t", &[])])
        .await
        .unwrap();
    assert_eq!(
        count(
            &t.path,
            "SELECT generation FROM vector_index WHERE name = 'docs'"
        ),
        before + 1
    );
    assert_eq!(brute.len().await.unwrap(), 2);
    assert_eq!(
        ids(&brute.search(&second, 1, &filter(&[])).await.unwrap()),
        ["second"]
    );
}

#[tokio::test]
async fn replace_source_drops_orphans() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let mut rng = Rng(9);
    let first: Vec<VectorRecord> = (0..3)
        .map(|i| sourced(&format!("a{i}"), &mut rng, "docs", "a.md"))
        .collect();
    assert_eq!(
        vectors
            .replace_source("docs", "a.md", first, "h1")
            .await
            .unwrap(),
        3
    );
    let other: Vec<VectorRecord> = (0..2)
        .map(|i| sourced(&format!("b{i}"), &mut rng, "docs", "b.md"))
        .collect();
    vectors
        .replace_source("docs", "b.md", other, "hb")
        .await
        .unwrap();
    let shorter = vec![sourced("a0", &mut rng, "docs", "a.md")];
    assert_eq!(
        vectors
            .replace_source("docs", "a.md", shorter, "h2")
            .await
            .unwrap(),
        1
    );
    assert_eq!(vectors.len().await.unwrap(), 3);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk"), 3);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk_fts_docsize"), 3);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk_meta"), 6);
    let mut found = ids(&vectors
        .search(&rng.vector(DIMS), 10, &filter(&[]))
        .await
        .unwrap())
    .iter()
    .map(|s| s.to_string())
    .collect::<Vec<_>>();
    found.sort();
    assert_eq!(found, ["a0", "b0", "b1"]);
    assert_eq!(
        vectors
            .source_hash("docs", "a.md")
            .await
            .unwrap()
            .as_deref(),
        Some("h2")
    );
    assert_eq!(
        vectors
            .source_hash("docs", "b.md")
            .await
            .unwrap()
            .as_deref(),
        Some("hb")
    );
    assert_eq!(vectors.source_hash("docs", "c.md").await.unwrap(), None);
    assert_eq!(
        count(
            &t.path,
            "SELECT chunks FROM ingest_source WHERE source = 'a.md'"
        ),
        1
    );
}

#[tokio::test]
async fn replace_source_refuses_an_id_owned_by_another_source() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let mut rng = Rng(21);
    vectors
        .replace_source(
            "docs",
            "a.md",
            vec![sourced("intro", &mut rng, "docs", "a.md")],
            "ha",
        )
        .await
        .unwrap();
    let before = count(
        &t.path,
        "SELECT generation FROM vector_index WHERE name = 'docs'",
    );
    let stolen = vec![
        sourced("b0", &mut rng, "docs", "b.md"),
        sourced("intro", &mut rng, "docs", "b.md"),
    ];
    store_error(
        vectors.replace_source("docs", "b.md", stolen, "hb").await,
        "intro",
    );
    assert_eq!(
        count(
            &t.path,
            "SELECT generation FROM vector_index WHERE name = 'docs'"
        ),
        before
    );
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk"), 1);
    assert_eq!(vectors.source_hash("docs", "b.md").await.unwrap(), None);
    let hits = vectors
        .search(&rng.vector(DIMS), 10, &filter(&[("source", "a.md")]))
        .await
        .unwrap();
    assert_eq!(ids(&hits), ["intro"]);
    assert_eq!(vectors.len().await.unwrap(), 1);
    let own = vec![sourced("intro", &mut rng, "docs", "a.md")];
    assert_eq!(
        vectors
            .replace_source("docs", "a.md", own, "ha2")
            .await
            .unwrap(),
        1
    );
    assert_eq!(
        vectors
            .source_hash("docs", "a.md")
            .await
            .unwrap()
            .as_deref(),
        Some("ha2")
    );
}

#[tokio::test]
async fn remove_source_drops_rows_keywords_index_and_status() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let mut rng = Rng(23);
    let a: Vec<VectorRecord> = (0..3)
        .map(|i| sourced(&format!("a{i}"), &mut rng, "docs", "a.md"))
        .collect();
    vectors
        .replace_source("docs", "a.md", a, "ha")
        .await
        .unwrap();
    vectors
        .replace_source(
            "docs",
            "b.md",
            vec![sourced("b0", &mut rng, "docs", "b.md")],
            "hb",
        )
        .await
        .unwrap();
    vectors
        .record_failed_source("docs", "c.md", "bad bytes")
        .await
        .unwrap();
    assert_eq!(
        vectors.sources("docs").await.unwrap(),
        ["a.md", "b.md", "c.md"]
    );
    assert!(vectors.sources("other").await.unwrap().is_empty());
    assert_eq!(vectors.remove_source("docs", "a.md").await.unwrap(), 3);
    assert_eq!(vectors.remove_source("docs", "c.md").await.unwrap(), 0);
    assert_eq!(vectors.sources("docs").await.unwrap(), ["b.md"]);
    assert_eq!(vectors.source_hash("docs", "a.md").await.unwrap(), None);
    assert_eq!(vectors.len().await.unwrap(), 1);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk"), 1);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk_fts_docsize"), 1);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk_meta"), 2);
    assert_eq!(
        ids(&vectors
            .search(&rng.vector(DIMS), 10, &filter(&[]))
            .await
            .unwrap()),
        ["b0"]
    );
    let other = SqliteStore::open(&t.path).await.unwrap();
    assert_eq!(docs(&other).await.len().await.unwrap(), 1);
    assert_eq!(
        vectors.remove_source("docs", "missing.md").await.unwrap(),
        0
    );
    store_error(vectors.remove_source("", "a.md").await, "scope");
}

#[tokio::test]
async fn reopen_after_replace_source_does_not_rebuild() {
    for settings in [
        VectorSettings::new(DIMS),
        VectorSettings::new(DIMS).with_kind(IndexKind::Hnsw(HnswParams::default())),
    ] {
        let t = temp();
        let mut rng = Rng(13);
        {
            let store = SqliteStore::open(&t.path).await.unwrap();
            let vectors = store.vectors("docs", settings.clone()).await.unwrap();
            let first = (0..4)
                .map(|i| sourced(&format!("a{i}"), &mut rng, "docs", "a.md"))
                .collect();
            vectors
                .replace_source("docs", "a.md", first, "h1")
                .await
                .unwrap();
            vectors
                .replace_source(
                    "docs",
                    "a.md",
                    vec![sourced("a9", &mut rng, "docs", "a.md")],
                    "h2",
                )
                .await
                .unwrap();
        }
        let store = SqliteStore::open(&t.path).await.unwrap();
        let vectors = store.vectors("docs", settings.clone()).await.unwrap();
        assert_eq!(vectors.open_report().rebuilds(), 0, "{:?}", settings.kind());
        assert_eq!(vectors.len().await.unwrap(), 1);
    }
}

fn contains(haystack: &[u8], needle: &[u8]) -> bool {
    haystack.windows(needle.len()).any(|w| w == needle)
}

#[tokio::test]
async fn deleted_chunk_leaves_no_bytes_in_the_file() {
    const MARKER: &str = "zqxvelociraptormarker";
    let marked: Vec<f32> = (0..DIMS)
        .map(|i| 0.123_456_79 + i as f32 * 0.010_203)
        .collect();
    let pattern: Vec<u8> = marked.iter().flat_map(|x| x.to_le_bytes()).collect();
    for settings in [
        VectorSettings::new(DIMS),
        VectorSettings::new(DIMS).with_kind(IndexKind::Hnsw(HnswParams::default())),
    ] {
        let t = temp();
        let mut rng = Rng(29);
        {
            let store = SqliteStore::open(&t.path).await.unwrap();
            let vectors = store.vectors("docs", settings.clone()).await.unwrap();
            let mut records: Vec<VectorRecord> = (0..40)
                .map(|i| sourced(&format!("k{i}"), &mut rng, "docs", "a.md"))
                .collect();
            records.push(rec(
                "secret",
                marked.clone(),
                &format!("the {MARKER} plan"),
                &[("scope", "docs"), ("source", "a.md")],
            ));
            vectors
                .replace_source("docs", "a.md", records, "h1")
                .await
                .unwrap();
            assert_eq!(
                ids(&vectors.search_text(MARKER, 1, &filter(&[])).await.unwrap()),
                ["secret"]
            );
            let kept: Vec<VectorRecord> = (0..40)
                .map(|i| sourced(&format!("k{i}"), &mut rng, "docs", "a.md"))
                .collect();
            vectors
                .replace_source("docs", "a.md", kept, "h2")
                .await
                .unwrap();
            assert!(vectors
                .search_text(MARKER, 1, &filter(&[]))
                .await
                .unwrap()
                .is_empty());
        }
        let conn = rusqlite::Connection::open(&t.path).unwrap();
        conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
            row.get::<_, i64>(0)
        })
        .unwrap();
        drop(conn);
        let mut bytes = std::fs::read(&t.path).unwrap();
        bytes.extend(std::fs::read(t.path.with_extension("db-wal")).unwrap_or_default());
        assert!(
            !contains(&bytes, MARKER.as_bytes()),
            "marker text left in the file ({:?})",
            settings.kind()
        );
        assert!(
            !contains(&bytes, &pattern),
            "marked vector left in the file ({:?})",
            settings.kind()
        );
    }
}

#[tokio::test]
async fn replace_source_refuses_records_without_scope_and_source() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let mut rng = Rng(17);
    let missing = vec![
        sourced("a0", &mut rng, "docs", "a.md"),
        rec("a1", rng.vector(DIMS), "t", &[("scope", "docs")]),
    ];
    store_error(
        vectors.replace_source("docs", "a.md", missing, "h").await,
        "record 1",
    );
    let wrong_scope = vec![sourced("a0", &mut rng, "other", "a.md")];
    store_error(
        vectors
            .replace_source("docs", "a.md", wrong_scope, "h")
            .await,
        "record 0",
    );
    let wrong_source = vec![sourced("a0", &mut rng, "docs", "b.md")];
    store_error(
        vectors
            .replace_source("docs", "a.md", wrong_source, "h")
            .await,
        "record 0",
    );
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk"), 0);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM ingest_source"), 0);
    assert_eq!(vectors.len().await.unwrap(), 0);
}

#[tokio::test]
async fn failed_source_is_retried_and_cleared_by_replace() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let mut rng = Rng(19);
    let first = (0..2)
        .map(|i| sourced(&format!("a{i}"), &mut rng, "docs", "a.md"))
        .collect();
    vectors
        .replace_source("docs", "a.md", first, "h1")
        .await
        .unwrap();
    let long_error = "é".repeat(1500);
    vectors
        .record_failed_source("docs", "a.md", &long_error)
        .await
        .unwrap();
    assert_eq!(vectors.source_hash("docs", "a.md").await.unwrap(), None);
    assert_eq!(vectors.len().await.unwrap(), 2);
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk"), 2);
    assert_eq!(
        count(
            &t.path,
            "SELECT COUNT(*) FROM ingest_source WHERE status = 'failed'"
        ),
        1
    );
    let error_bytes = count(
        &t.path,
        "SELECT length(CAST(error AS BLOB)) FROM ingest_source",
    );
    assert!((1..=1024).contains(&error_bytes), "{error_bytes}");
    vectors
        .record_failed_source("docs", "new.md", "unreadable")
        .await
        .unwrap();
    assert_eq!(vectors.source_hash("docs", "new.md").await.unwrap(), None);
    let again = vec![sourced("a0", &mut rng, "docs", "a.md")];
    vectors
        .replace_source("docs", "a.md", again, "h2")
        .await
        .unwrap();
    assert_eq!(
        vectors
            .source_hash("docs", "a.md")
            .await
            .unwrap()
            .as_deref(),
        Some("h2")
    );
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM ingest_source WHERE source = 'a.md' AND status = 'done' AND error IS NULL"), 1);
}

#[tokio::test]
async fn filter_values_are_bound_not_spliced() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let hostile = "x' OR '1'='1";
    vectors
        .upsert(vec![
            rec("tenant_a", vec![1.0; DIMS], "a", &[("tenant", "a")]),
            rec("tenant_b", vec![1.0; DIMS], "b", &[("tenant", "b")]),
            rec("literal", vec![1.0; DIMS], "l", &[("tenant", hostile)]),
        ])
        .await
        .unwrap();
    let hits = vectors
        .search(&[1.0; DIMS], 10, &filter(&[("tenant", "x")]))
        .await
        .unwrap();
    assert!(hits.is_empty());
    let hits = vectors
        .search(&[1.0; DIMS], 10, &filter(&[("tenant", "x' OR '1'='1' --")]))
        .await
        .unwrap();
    assert!(hits.is_empty());
    let hits = vectors
        .search(&[1.0; DIMS], 10, &filter(&[("tenant", hostile)]))
        .await
        .unwrap();
    assert_eq!(ids(&hits), ["literal"]);
    let hits = vectors
        .search(&[1.0; DIMS], 10, &filter(&[("tenant\" OR 1=1 --", "a")]))
        .await
        .unwrap();
    assert!(hits.is_empty());
    let hits = vectors
        .search(&[1.0; DIMS], 10, &filter(&[("tenant", "a")]))
        .await
        .unwrap();
    assert_eq!(ids(&hits), ["tenant_a"]);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn search_never_mixes_two_versions_of_a_chunk() {
    let t = temp();
    let reader = SqliteStore::open(&t.path).await.unwrap();
    let writer = SqliteStore::open(&t.path).await.unwrap();
    let read = docs(&reader).await;
    let write = docs(&writer).await;
    let mut one = vec![0.0; DIMS];
    one[0] = 1.0;
    let mut two = vec![0.0; DIMS];
    two[1] = 1.0;
    write
        .upsert(vec![rec("x", one.clone(), "one", &[])])
        .await
        .unwrap();
    let flips = async {
        for i in 0..300 {
            let (vector, text) = if i % 2 == 0 {
                (two.clone(), "two")
            } else {
                (one.clone(), "one")
            };
            write
                .upsert(vec![rec("x", vector, text, &[])])
                .await
                .unwrap();
        }
    };
    let searches = async {
        for _ in 0..300 {
            for hit in read.search(&one, 1, &filter(&[])).await.unwrap() {
                assert_eq!(
                    hit.text == "one",
                    hit.score > 0.5,
                    "text {} came with score {}",
                    hit.text,
                    hit.score
                );
            }
        }
    };
    tokio::join!(flips, searches);
}

#[tokio::test]
async fn same_store_handles_share_one_index() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let a = docs(&store).await;
    let b = docs(&store.clone()).await;
    a.upsert(vec![rec("x", vec![1.0; DIMS], "t", &[])])
        .await
        .unwrap();
    assert_eq!(
        ids(&b.search(&[1.0; DIMS], 1, &filter(&[])).await.unwrap()),
        ["x"]
    );
    assert_eq!(a.open_report().loads(), 1);
    assert_eq!(b.open_report().loads(), 1);
    let other = store
        .vectors("other", VectorSettings::new(4))
        .await
        .unwrap();
    assert_eq!(other.len().await.unwrap(), 0);
    assert_eq!(other.dims(), 4);
}

#[tokio::test]
async fn other_connection_sees_new_records() {
    let t = temp();
    let first = SqliteStore::open(&t.path).await.unwrap();
    let second = SqliteStore::open(&t.path).await.unwrap();
    let mine = docs(&first).await;
    let theirs = docs(&second).await;
    assert!(mine
        .search(&[1.0; DIMS], 5, &filter(&[]))
        .await
        .unwrap()
        .is_empty());
    theirs
        .upsert(vec![rec("new", vec![1.0; DIMS], "t", &[])])
        .await
        .unwrap();
    assert_eq!(
        ids(&mine.search(&[1.0; DIMS], 5, &filter(&[])).await.unwrap()),
        ["new"]
    );
    assert_eq!(mine.open_report().loads(), 2);
    mine.upsert(vec![rec("mine", vec![0.5; DIMS], "t", &[])])
        .await
        .unwrap();
    assert_eq!(theirs.len().await.unwrap(), 2);
}

#[tokio::test]
async fn checkpoint_saves_do_not_reload_the_index() {
    let t = temp();
    let first = SqliteStore::open(&t.path).await.unwrap();
    let second = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&first).await;
    vectors
        .upsert(vec![rec("x", vec![1.0; DIMS], "t", &[])])
        .await
        .unwrap();
    let run = RunId::new();
    for step in 0..5 {
        second
            .save(Checkpoint {
                run_id: run,
                step,
                state: json!({ "step": step }),
            })
            .await
            .unwrap();
        second.put("blob", vec![step as u8]).await.unwrap();
        vectors.search(&[1.0; DIMS], 1, &filter(&[])).await.unwrap();
    }
    assert_eq!(vectors.open_report().loads(), 1);
}

#[tokio::test]
async fn every_bound_is_enforced() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    store_error(
        store.vectors("Bad-Name", VectorSettings::new(DIMS)).await,
        "name",
    );
    store_error(store.vectors("docs", VectorSettings::new(0)).await, "dims");
    store_error(
        store.vectors("docs", VectorSettings::new(65_537)).await,
        "dims",
    );
    store_error(
        store
            .vectors("docs", VectorSettings::new(DIMS).with_max_batch(0))
            .await,
        "max_batch",
    );
    let settings = VectorSettings::new(DIMS)
        .with_max_batch(2)
        .with_max_meta_pairs(1)
        .with_max_meta_key_bytes(3)
        .with_max_meta_value_bytes(3)
        .with_max_text_bytes(4);
    let v = store.vectors("docs", settings).await.unwrap();
    let one = |id: &str, text: &str, pairs: &[(&str, &str)]| rec(id, vec![1.0; DIMS], text, pairs);
    store_error(
        v.upsert(vec![
            one("a", "t", &[]),
            one("b", "t", &[]),
            one("c", "t", &[]),
        ])
        .await,
        "max_batch",
    );
    store_error(
        v.upsert(vec![one("a", "t", &[("k", "v"), ("l", "w")])])
            .await,
        "max_meta_pairs",
    );
    store_error(
        v.upsert(vec![one("a", "t", &[("long", "v")])]).await,
        "meta key",
    );
    store_error(
        v.upsert(vec![one("a", "t", &[("", "v")])]).await,
        "meta key",
    );
    store_error(
        v.upsert(vec![one("a", "t", &[("k", "long")])]).await,
        "meta value",
    );
    store_error(
        v.upsert(vec![one("a", "texts", &[])]).await,
        "max_text_bytes",
    );
    store_error(v.upsert(vec![one("", "t", &[])]).await, "id");
    store_error(v.upsert(vec![one(&"i".repeat(257), "t", &[])]).await, "id");
    let mut nan = vec![1.0; DIMS];
    nan[2] = f32::NAN;
    store_error(
        v.upsert(vec![rec("a", nan.clone(), "t", &[])]).await,
        "non-finite",
    );
    store_error(v.search(&nan, 1, &filter(&[])).await, "finite");
    store_error(v.search(&[1.0; DIMS], 1_001, &filter(&[])).await, "k");
    store_error(
        v.search(&[1.0; DIMS], 1, &filter(&[("a", "1"), ("b", "2")]))
            .await,
        "max_meta_pairs",
    );
    store_error(v.replace_source("", "a.md", vec![], "h").await, "scope");
    store_error(v.replace_source("d", "a", vec![], "").await, "content_hash");
    store_error(
        v.replace_source("d", "a.md", vec![], "h").await,
        "source must be 1 to 3 bytes",
    );
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk"), 0);
}

#[tokio::test]
async fn defaults_are_the_safe_values() {
    let s = VectorSettings::new(384);
    assert_eq!(s.dims(), 384);
    assert_eq!(s.kind(), &IndexKind::BruteForce);
    assert_eq!(s.quantization(), Quantization::F32);
    assert_eq!(s.max_text_bytes(), 1024 * 1024);
    assert_eq!(s.max_meta_pairs(), 64);
    assert_eq!(s.max_meta_key_bytes(), 256);
    assert_eq!(s.max_meta_value_bytes(), 4096);
    assert_eq!(s.max_batch(), 10_000);
    assert_eq!(s.max_query_terms(), 32);
    assert_eq!(s.max_query_chars(), 2_000);
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let v = store.vectors("docs", s).await.unwrap();
    assert_eq!(v.open_report().loads(), 1);
    assert_eq!(v.open_report().rebuilds(), 0);
    let conn = rusqlite::Connection::open(&t.path).unwrap();
    let row: String = conn
        .query_row(
            "SELECT kind || ':' || params_json || ':' || generation FROM vector_index",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(row, "brute_force:{}:0");
}

#[tokio::test]
async fn keyword_search_ranks_by_bm25() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    let other = store
        .vectors("other", VectorSettings::new(DIMS))
        .await
        .unwrap();
    vectors
        .upsert(vec![
            rec(
                "once",
                vec![1.0; DIMS],
                "a refund is paid once the parcel is back at the warehouse",
                &[],
            ),
            rec(
                "twice",
                vec![1.0; DIMS],
                "refund policy: refund in 14 days",
                &[],
            ),
            rec("none", vec![1.0; DIMS], "shipping takes two days", &[]),
            rec("résumé", vec![1.0; DIMS], "Résumé of the REFUND rules", &[]),
        ])
        .await
        .unwrap();
    let fillers = (0..8)
        .map(|i| {
            rec(
                &format!("filler{i}"),
                vec![1.0; DIMS],
                &format!("shipping note number {i}"),
                &[],
            )
        })
        .collect();
    vectors.upsert(fillers).await.unwrap();
    other
        .upsert(vec![rec(
            "elsewhere",
            vec![1.0; DIMS],
            "refund refund refund",
            &[],
        )])
        .await
        .unwrap();
    let hits = vectors
        .search_text("Refund", 10, &filter(&[]))
        .await
        .unwrap();
    let conn = rusqlite::Connection::open(&t.path).unwrap();
    let mut stmt = conn
        .prepare(
            "SELECT c.id, -bm25(chunk_fts) FROM chunk_fts JOIN chunk c ON c.key = chunk_fts.rowid \
             WHERE chunk_fts MATCH 'refund' AND c.index_name = 'docs' ORDER BY bm25(chunk_fts), c.id",
        )
        .unwrap();
    let want: Vec<(String, f64)> = stmt
        .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
        .unwrap()
        .map(Result::unwrap)
        .collect();
    assert_eq!(want.len(), 3);
    assert_eq!(
        ids(&hits),
        want.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>()
    );
    assert_eq!(hits[0].id, "twice");
    for (hit, (_, score)) in hits.iter().zip(&want) {
        assert!(hit.score > 0.0);
        assert!(
            (f64::from(hit.score) - score).abs() < 1e-4,
            "{} vs {score}",
            hit.score
        );
    }
    assert!(ids(&vectors.search_text("resume", 10, &filter(&[])).await.unwrap()).contains(&"résumé"));
    let decomposed = vectors.search_text("Re\u{301}sume\u{301}", 10, &filter(&[])).await.unwrap();
    assert_eq!(ids(&decomposed), ["résumé"]);
    assert_eq!(ids(&vectors.search_text("refund", 1, &filter(&[])).await.unwrap()), ["twice"]);
    assert!(vectors.search_text("refund", 0, &filter(&[])).await.unwrap().is_empty());
    assert!(vectors.search_text("absent", 10, &filter(&[])).await.unwrap().is_empty());
}

#[tokio::test]
async fn fts_operators_in_query_are_plain_text() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    vectors
        .upsert(vec![
            rec("a", vec![1.0; DIMS], "a near b and text secret", &[]),
            rec("b", vec![1.0; DIMS], "nothing to see", &[]),
        ])
        .await
        .unwrap();
    for query in [
        "NEAR(a b)",
        "a*",
        "text:secret",
        "\"",
        "AND OR NOT",
        "^a",
        "\"unclosed",
        "a + b - c",
        "{text}: a",
        "col:* OR",
        "(((",
        "'; DROP TABLE chunk; --",
        "",
    ] {
        let result = vectors.search_text(query, 10, &filter(&[])).await;
        assert!(result.is_ok(), "{query}: {result:?}");
    }
    assert_eq!(
        ids(&vectors
            .search_text("text:secret", 10, &filter(&[]))
            .await
            .unwrap()),
        ["a"]
    );
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM chunk"), 2);
}

#[tokio::test]
async fn keyword_filter_respects_scope() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    vectors
        .upsert(vec![
            rec(
                "a1",
                vec![1.0; DIMS],
                "refund policy",
                &[("scope", "tenant_a")],
            ),
            rec(
                "b1",
                vec![1.0; DIMS],
                "refund policy",
                &[("scope", "tenant_b")],
            ),
            rec(
                "b2",
                vec![1.0; DIMS],
                "refund refund policy",
                &[("scope", "tenant_b"), ("lang", "en")],
            ),
        ])
        .await
        .unwrap();
    assert_eq!(
        ids(&vectors
            .search_text("refund", 10, &filter(&[("scope", "tenant_a")]))
            .await
            .unwrap()),
        ["a1"]
    );
    let b = vectors
        .search_text("refund", 10, &filter(&[("scope", "tenant_b")]))
        .await
        .unwrap();
    assert_eq!(ids(&b), ["b2", "b1"]);
    let both = vectors
        .search_text(
            "refund",
            10,
            &filter(&[("scope", "tenant_b"), ("lang", "en")]),
        )
        .await
        .unwrap();
    assert_eq!(ids(&both), ["b2"]);
    assert!(vectors
        .search_text("refund", 10, &filter(&[("scope", "x' OR '1'='1")]))
        .await
        .unwrap()
        .is_empty());
}

#[tokio::test]
async fn query_term_and_length_caps() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let settings = VectorSettings::new(DIMS)
        .with_max_query_terms(3)
        .with_max_query_chars(20)
        .with_max_meta_pairs(1);
    let vectors = store.vectors("docs", settings).await.unwrap();
    vectors
        .upsert(vec![rec("a", vec![1.0; DIMS], "one two three", &[])])
        .await
        .unwrap();
    assert_eq!(
        ids(&vectors
            .search_text("one, two; three", 10, &filter(&[]))
            .await
            .unwrap()),
        ["a"]
    );
    store_error(
        vectors
            .search_text("one two three four", 10, &filter(&[]))
            .await,
        "max_query_terms",
    );
    store_error(
        vectors.search_text(&"x".repeat(21), 10, &filter(&[])).await,
        "max_query_chars",
    );
    assert!(vectors
        .search_text(&"é".repeat(20), 10, &filter(&[]))
        .await
        .is_ok());
    store_error(
        vectors.search_text("one", 1_001, &filter(&[])).await,
        "k must be",
    );
    store_error(
        vectors
            .search_text("one", 1, &filter(&[("a", "1"), ("b", "2")]))
            .await,
        "max_meta_pairs",
    );
    store_error(
        store
            .vectors("docs", VectorSettings::new(DIMS).with_max_query_terms(0))
            .await,
        "max_query_terms",
    );
}

#[tokio::test]
async fn failed_first_open_leaves_no_cache_entry() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let broken = VectorSettings::new(DIMS).with_kind(IndexKind::Hnsw(HnswParams::default().with_m(0)));
    assert!(store.vectors("fresh", broken).await.is_err());
    assert_eq!(count(&t.path, "SELECT COUNT(*) FROM vector_index WHERE name = 'fresh'"), 0);
    let wide = store.vectors("fresh", VectorSettings::new(2 * DIMS)).await.unwrap();
    wide.upsert(vec![rec("a", vec![0.5; 2 * DIMS], "text", &[])]).await.unwrap();
    assert_eq!(wide.len().await.unwrap(), 1);
}

#[tokio::test]
async fn failed_reconfigure_keeps_the_previous_settings() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let old = store.vectors("docs", VectorSettings::new(DIMS).with_max_text_bytes(8)).await.unwrap();
    let lowered = VectorSettings::new(DIMS)
        .with_max_text_bytes(4)
        .with_kind(IndexKind::Hnsw(HnswParams::default().with_m(0)));
    assert!(store.vectors("docs", lowered).await.is_err());
    old.upsert(vec![rec("six", vec![0.5; DIMS], "sixsix", &[])]).await.unwrap();
    assert_eq!(old.len().await.unwrap(), 1);
}

#[tokio::test]
async fn invalid_query_is_refused_before_an_empty_filter_result() {
    let t = temp();
    let store = SqliteStore::open(&t.path).await.unwrap();
    let vectors = docs(&store).await;
    vectors.upsert(vec![rec("a", vec![0.5; DIMS], "text", &[("scope", "here")])]).await.unwrap();
    let missing = filter(&[("scope", "missing")]);
    let mut nan = vec![0.5; DIMS];
    nan[0] = f32::NAN;
    store_error(vectors.search(&nan, 1, &missing).await, "finite");
    store_error(vectors.search(&[0.5; DIMS], 1_001, &missing).await, "k must be");
    assert!(vectors.search(&[0.5; DIMS], 1, &missing).await.unwrap().is_empty());
}

#[tokio::test]
async fn secure_delete_off_cannot_lower_a_file_that_has_it_on() {
    let t = temp();
    let on = SqliteStore::open(&t.path).await.unwrap();
    on.vectors("docs", VectorSettings::new(DIMS)).await.unwrap();
    let off = SqliteStore::builder(&t.path).secure_delete(false).open().await.unwrap();
    let err = off.vectors("docs", VectorSettings::new(DIMS)).await.unwrap_err();
    assert!(matches!(&err, CoreError::Store(m) if m.contains("secure-delete")), "{err:?}");
    on.vectors("docs", VectorSettings::new(DIMS)).await.unwrap();
}

#[tokio::test]
async fn secure_delete_on_may_raise_a_file_opened_with_it_off() {
    let t = temp();
    let off = SqliteStore::builder(&t.path).secure_delete(false).open().await.unwrap();
    off.vectors("docs", VectorSettings::new(DIMS)).await.unwrap();
    off.vectors("docs", VectorSettings::new(DIMS)).await.unwrap();
    let on = SqliteStore::open(&t.path).await.unwrap();
    on.vectors("docs", VectorSettings::new(DIMS)).await.unwrap();
    let err = off.vectors("docs", VectorSettings::new(DIMS)).await.unwrap_err();
    assert!(matches!(&err, CoreError::Store(m) if m.contains("secure-delete")), "{err:?}");
}