tinystore 0.12.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
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
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use std::sync::Barrier;
use std::thread::JoinHandle;

use serde::{Deserialize, Serialize};

use super::*;
use crate::ErrorKind;
use crate::search::document::{self, Analyzed};
use crate::search::fixture::{Fixture, Random, fixture, open};
use crate::search::read::{checked, forms};
use crate::search::score::{Part, average, idf, points, score};
use crate::search::settings::Settings;
use crate::search::{analyzer, maintain};

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
struct Article {
    title: String,
    body: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    category: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    price: Option<i64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    tags: Vec<String>,
}

fn article(title: &str, body: &str) -> Article {
    Article { title: title.to_owned(), body: body.to_owned(), ..Article::default() }
}

fn ids<T>(found: &Found<T>) -> Vec<&str> {
    found.hits.iter().map(|hit| hit.id.as_str()).collect()
}

fn search(index: &Index<Article>, text: &str) -> Found<Article> {
    checked(|| index.search(text).run()).unwrap()
}

#[test]
fn a_search_finds_documents_by_any_of_its_words_the_best_first() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("a", &article("Sourdough bread", "flour, water and salt")).unwrap();
    articles.set("b", &article("Rye", "bread from rye flour")).unwrap();
    articles.set("c", &article("Butter", "milk and cream")).unwrap();
    let found = search(&articles, "bread salt");
    assert_eq!(ids(&found), ["a", "b"], "a holds both words and one in its heavier title");
    assert!(found.hits[0].score > found.hits[1].score);
    assert_eq!(found.hits[0].value, article("Sourdough bread", "flour, water and salt"));
    assert_eq!(found.corrected, None);
    assert!(search(&articles, "").hits.is_empty());
}

#[test]
fn a_word_is_found_as_written_and_by_its_stem_in_any_script() {
    let fixture = fixture();
    let notes = fixture.store.index::<String>("notes").open().unwrap();
    notes.set(1, &"Кошки спят на печи".to_owned()).unwrap();
    notes.set(2, &"東京タワーの夜景".to_owned()).unwrap();
    notes.set(3, &"Running in the CAFÉ".to_owned()).unwrap();
    let found = |text: &str| -> Vec<String> {
        checked(|| notes.search(text).run()).unwrap().hits.into_iter().map(|hit| hit.id).collect()
    };
    assert_eq!(found("кошка"), ["1"], "Russian by its stem");
    assert_eq!(found("кошкам"), ["1"]);
    assert_eq!(found("東京"), ["2"], "Japanese by its pairs of letters");
    assert_eq!(found("cafe running"), ["3"], "accents folded, case ignored");
    assert!(found("run").is_empty(), "English is not stemmed: search-plan measured a loss");
}

// contract: SRCH-04
#[test]
fn a_set_is_seen_by_the_next_search_and_a_deleted_document_never_answers() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("a", &article("Sourdough", "starter")).unwrap();
    assert_eq!(ids(&search(&articles, "sourdough")), ["a"]);
    articles.set("a", &article("Baguette", "crust")).unwrap();
    assert!(search(&articles, "sourdough").hits.is_empty(), "a set replaces the document whole");
    assert_eq!(ids(&search(&articles, "baguette")), ["a"]);
    maintain(&fixture.store).unwrap();
    assert_eq!(ids(&search(&articles, "crust")), ["a"]);
    assert!(articles.delete("a").unwrap());
    assert!(!articles.delete("a").unwrap(), "deleting an id that is not there does nothing");
    assert!(search(&articles, "baguette crust").hits.is_empty());
    maintain(&fixture.store).unwrap();
    assert!(search(&articles, "baguette crust").hits.is_empty());
}

#[test]
fn get_answers_the_value_set_or_none() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("a-17", &article("Хлеб на закваске", "…")).unwrap();
    assert_eq!(articles.get("a-17").unwrap(), Some(article("Хлеб на закваске", "…")));
    assert_eq!(articles.get("a-18").unwrap(), None);
    let other = fixture.articles::<Article>("other");
    assert_eq!(other.get("a-17").unwrap(), None, "each index keeps its own documents");
}

// contract: SRCH-05
#[test]
fn set_many_sets_every_document_in_one_commit_or_none() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    let (first, second) = (article("Rye bread", "flour"), article("Sourdough", "starter"));
    articles.set_many([("a-1", &first), ("a-2", &second), ("a-1", &article("Baguette", "crust"))]).unwrap();
    assert_eq!(articles.get("a-2").unwrap(), Some(second.clone()));
    assert_eq!(articles.get("a-1").unwrap(), Some(article("Baguette", "crust")), "a later place wins");
    assert!(search(&articles, "rye").hits.is_empty());
    let one_by_one = fixture.articles::<Article>("one-by-one");
    for (id, value) in [("a-1", &first), ("a-2", &second), ("a-1", &article("Baguette", "crust"))] {
        one_by_one.set(id, value).unwrap();
    }
    let hits = |index: &Index<Article>, text| -> Vec<(String, f64)> {
        search(index, text).hits.into_iter().map(|hit| (hit.id, hit.score)).collect()
    };
    for text in ["flour", "baguette crust", "sourdough starter bread"] {
        assert_eq!(hits(&articles, text), hits(&one_by_one, text), "{text}: counted as sets one by one count");
    }
    let notes = fixture.store.index::<serde_json::Value>("notes").field("title", 1.0).open().unwrap();
    let (good, bad) = (serde_json::json!({ "title": "kept" }), serde_json::json!({ "title": 7 }));
    let refused = notes.set_many([("n-1", &good), ("n-2", &bad)]).unwrap_err();
    let said = "index notes: document 1, id \"n-2\": field title holds a number, not text: invalid";
    assert_eq!(refused.to_string(), said);
    assert_eq!(notes.get("n-1").unwrap(), None, "none of the list is set");
    assert!(checked(|| notes.search("kept").run()).unwrap().hits.is_empty());
}

// contract: SRCH-05
#[test]
fn a_set_many_past_its_bound_is_a_limit_and_sets_nothing() {
    let fixture = fixture();
    let notes = fixture.store.index::<String>("notes").open().unwrap();
    let short = "word".to_owned();
    let many: Vec<(String, &String)> = (0..1001).map(|n| (format!("n-{n}"), &short)).collect();
    assert_eq!(notes.set_many(many).unwrap_err().kind(), ErrorKind::Limit);
    let large = "x".repeat(1_000_000);
    let heavy: Vec<(String, &String)> = (0..17).map(|n| (format!("n-{n}"), &large)).collect();
    assert_eq!(notes.set_many(heavy).unwrap_err().kind(), ErrorKind::Limit);
    assert_eq!(notes.get("n-0").unwrap(), None);
}

// contract: ERR-05
#[test]
fn a_call_past_a_bound_names_it_what_it_wanted_and_the_bound() {
    let fixture = fixture();
    let notes = fixture.store.index::<String>("notes").open().unwrap();
    let facts = |error: Error| {
        let facts = [error.fact("limit"), error.fact("wanted"), error.fact("bound")];
        (error.kind(), facts.map(|fact| fact.unwrap_or_default().to_owned()))
    };
    let short = "word".to_owned();
    let many: Vec<(String, &String)> = (0..1001).map(|n| (format!("n-{n}"), &short)).collect();
    let refused = notes.set_many(many).unwrap_err();
    assert_eq!(refused.to_string(), "index notes: a set_many of 1001 documents, past 1000: limit");
    assert_eq!(facts(refused), (ErrorKind::Limit, ["set_many documents".into(), "1001".into(), "1000".into()]));
    let large = "x".repeat(1_000_000);
    let heavy: Vec<(String, &String)> = (0..17).map(|n| (format!("n-{n}"), &large)).collect();
    let (kind, [limit, wanted, bound]) = facts(notes.set_many(heavy).unwrap_err());
    assert_eq!((kind, limit.as_str(), bound.as_str()), (ErrorKind::Limit, "set_many bytes", "16777216"));
    assert!(wanted.parse::<u64>().unwrap() > 16 << 20, "{wanted}");
    let hits = facts(notes.search("word").offset(1990).limit(10).run().unwrap_err());
    assert_eq!(hits, (ErrorKind::Limit, ["search hits".into(), "2000".into(), "1000".into()]));
}

#[test]
fn pages_of_a_search_join_into_its_whole_ranking() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    for n in 0..40 {
        articles.set(n, &article(&"bread ".repeat(n % 7 + 1), &format!("loaf {n}"))).unwrap();
    }
    let whole: Vec<String> =
        articles.search("bread loaf").limit(40).run().unwrap().hits.into_iter().map(|hit| hit.id).collect();
    let mut paged = Vec::new();
    for page in 0..4 {
        let found = articles.search("bread loaf").limit(10).offset(page * 10).run().unwrap();
        paged.extend(found.hits.into_iter().map(|hit| hit.id));
    }
    assert_eq!(whole.len(), 40);
    assert_eq!(paged, whole);
}

// contract: SRCH-09
#[test]
fn two_corrected_pairs_of_one_unspaced_run_read_as_one_text() {
    let fixture = fixture();
    let index = |name: &str| fixture.store.index::<String>(name).open().unwrap();
    let found = |notes: &Index<String>, text: &str| checked(|| notes.search(text).run()).unwrap();
    // A pair of Thai graphemes, marks and all, is long enough to be corrected.
    let notes = index("thai");
    notes.set("a", &"คิ้กิ".to_owned()).unwrap();
    notes.set("b", &"กิขิ้".to_owned()).unwrap();
    let thai = found(&notes, "คิ้กิ้ขิ้");
    assert_eq!(thai.corrected.as_deref(), Some("คิ้กิขิ้"), "both pairs read without the middle tone mark");
    assert_eq!(ids(&thai), ["a", "b"]);
    // Read as a character of three bytes, one of four leaves the text after it elsewhere.
    let (first, second, wide, narrow) =
        ("\u{e01}\u{e34}\u{e49}\u{e47}", "\u{e02}\u{e34}\u{e49}\u{e47}", "\u{20000}", "中");
    let notes = index("han");
    notes.set("c", &format!("{first}{narrow}")).unwrap();
    notes.set("d", &format!("{narrow}{second}")).unwrap();
    let han = found(&notes, &format!("{first}{wide}{second}"));
    assert_eq!(han.corrected, Some(format!("{first}{narrow}{second}")));
    assert_eq!(ids(&han), ["c", "d"]);
}

// contract: SRCH-09
#[test]
fn a_misspelt_word_is_read_as_the_nearest_and_corrected_says_the_text_read() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("a", &article("Replication", "hello world")).unwrap();
    articles.set("b", &article("Репликация", "журнал")).unwrap();
    let found = search(&articles, "Replicaiton, Hello!");
    assert_eq!(ids(&found), ["a"]);
    assert_eq!(found.corrected.as_deref(), Some("replication, hello!"));
    assert_eq!(search(&articles, "реплиакция").corrected.as_deref(), Some("репликация"));
    let short = search(&articles, "helo");
    assert!(short.hits.is_empty() && short.corrected.is_none(), "under five letters a word is read as written");
    let strict =
        fixture.store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).typo_tolerance(false);
    let strict = strict.open().unwrap();
    assert!(search(&strict, "replicaiton").hits.is_empty());
}

// contract: SRCH-09
#[test]
fn a_word_that_matches_is_never_changed() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("a", &article("hellp", "")).unwrap();
    articles.set("b", &article("hello", "")).unwrap();
    let found = search(&articles, "hellp");
    assert_eq!((ids(&found), found.corrected.as_deref()), (vec!["a"], None));
}

// contract: SRCH-11
#[test]
fn a_word_typed_halfway_finds_the_words_it_begins_below_one_typed_whole() {
    // the catalogue issue 39 searched, since only a Cyrillic word has a stem to meet a prefix
    let fixture = fixture();
    let courses = fixture.store.index::<String>("courses").open().unwrap();
    let names = [
        "Криптографические методы защиты информации",
        "Криптоанализ",
        "Криптография",
        "Основы криптографии",
        "Крипто и блокчейн",
        "Криптон",
    ];
    for (id, name) in (1..).zip(names) {
        courses.set(id, &name.to_owned()).unwrap();
    }
    let found = |text: &str| {
        let found = checked(|| courses.search(text).prefix().run()).unwrap();
        let ids: Vec<String> = found.hits.iter().map(|hit| hit.id.clone()).collect();
        (ids, found.corrected)
    };
    let typed = |text: &str| found(text).0;
    // the course named by the word itself first, then the shortest names by BM25, ties in the order set
    assert_eq!(typed("крипто"), ["5", "2", "3", "6", "4", "1"]);
    assert_eq!(ids(&checked(|| courses.search("крипто").run()).unwrap()), ["5"], "a whole word without prefix");
    assert_eq!(typed("крипто "), ["5"], "a word a space follows is whole");
    // `методы` is whole, so 1 is found by it and by the prefix, below 5's shorter name
    assert_eq!(typed("методы крипто"), ["5", "1", "2", "3", "6", "4"], "the last word alone is a prefix");
    // `информ` begins `информации` and is neither its word nor its stem
    assert_eq!(typed("информ крипто"), ["5", "2", "3", "6", "4", "1"], "a word before the last is never a prefix");
    // their stem finds 3 and 4, the prefix 1 too
    assert_eq!(typed("криптограф"), ["3", "4", "1"]);
    assert!(typed("к").is_empty(), "one letter is a whole word");
    // one edit from `криптон`, yet the start of three words: no typo
    assert_eq!(found("криптог"), (vec!["3".to_owned(), "4".to_owned(), "1".to_owned()], None));
    // a prefix that begins no word is corrected as a word is
    let (hits, corrected) = found("крипотграфия");
    assert_eq!((hits.first().map(String::as_str), corrected.as_deref()), (Some("3"), Some("криптография")));
}

// contract: SRCH-11
#[test]
fn a_prefix_reads_as_the_guide_shows_it() {
    let fixture = fixture();
    let courses = fixture.store.index::<String>("courses").open().unwrap();
    let names = [
        "Cryptographic methods of information security",
        "Cryptanalysis",
        "Cryptography",
        "Foundations of cryptography",
        "Cards",
        "Cardigan knitting",
    ];
    for (id, name) in (1..).zip(names) {
        courses.set(id, &name.to_owned()).unwrap();
    }
    let found = |text: &str, prefix: bool| {
        let call = courses.search(text);
        let found = checked(|| if prefix { call.prefix() } else { call }.run()).unwrap();
        let ids: Vec<String> = found.hits.iter().map(|hit| hit.id.clone()).collect();
        (ids, found.corrected)
    };
    let typed = |text: &str| found(text, true).0;
    assert_eq!(typed("crypt"), ["2", "3", "4", "1"]);
    assert!(found("crypt", false).0.is_empty());
    assert_eq!(typed("cryptograph"), ["3", "4", "1"]);
    for whole in ["crypt ", "crypt,", "c"] {
        assert!(typed(whole).is_empty(), "{whole:?} is a whole word");
    }
    assert_eq!(found("cardi", true), (vec!["6".to_owned()], None));
    assert_eq!(found("cardi", false), (vec!["5".to_owned()], Some("cards".to_owned())));
    let (hits, corrected) = found("cryptograhpy", true);
    assert_eq!((hits.first().map(String::as_str), corrected.as_deref()), (Some("3"), Some("cryptography")));
}

// contract: SRCH-11
#[test]
fn a_prefix_finds_every_document_holding_a_word_it_begins_waiting_and_packed() {
    let fixture = fixture();
    let index: Index<Article> =
        fixture.store.index("mix").field("title", 2.0).field("body", 1.0).typo_tolerance(false).open().unwrap();
    let mut random = Random::new(11);
    let mut docs: BTreeMap<String, Article> = BTreeMap::new();
    let begun = |docs: &BTreeMap<String, Article>, prefix: &str| -> BTreeSet<String> {
        let begins = |text: &String| {
            analyzer::words_of(&analyzer::normalize(text)).iter().any(|word| word.text.starts_with(prefix))
        };
        docs.iter().filter(|(_, value)| begins(&value.title) || begins(&value.body)).map(|(id, _)| id.clone()).collect()
    };
    let found = |prefix: &str| -> BTreeSet<String> {
        let found = checked(|| index.search(prefix).prefix().limit(1000).run()).unwrap();
        found.hits.into_iter().map(|hit| hit.id).collect()
    };
    for round in 0..3 {
        for _ in 0..400 {
            let id = format!("d{}", random.below(300));
            if random.below(5) == 0 {
                index.delete(&id).unwrap();
                docs.remove(&id);
            } else {
                let value = random_article(&mut random);
                index.set(&id, &value).unwrap();
                docs.insert(id, value);
            }
        }
        for prefix in ["rare39", "rare7", "кош", "соба", "те", "ba"] {
            let expected = begun(&docs, prefix);
            assert!(!expected.is_empty(), "round {round}: {prefix} begins a word");
            assert_eq!(found(prefix), expected, "round {round}: {prefix}");
        }
        maintain(&fixture.store).unwrap();
        for prefix in ["rare39", "кош", "ba"] {
            assert_eq!(found(prefix), begun(&docs, prefix), "round {round}, packed: {prefix}");
        }
    }
}

/// The ids of a search's hits and what it read, its scores checked to descend.
fn descending<T>(found: Found<T>) -> (Vec<String>, Option<String>) {
    let scores: Vec<f64> = found.hits.iter().map(|hit| hit.score).collect();
    assert!(scores.windows(2).all(|pair| pair[0] >= pair[1]), "scores rise down the page: {scores:?}");
    (found.hits.into_iter().map(|hit| hit.id).collect(), found.corrected)
}

// contract: SRCH-13
#[test]
fn every_word_begun_puts_first_the_documents_holding_a_word_for_each() {
    // issue 40's three courses: `лин` reaches `линий` by its stem as well
    let fixture = fixture();
    let courses = fixture.store.index::<String>("courses").open().unwrap();
    let names = ["Линейная алгебра", "Алгоритмизация и программирование", "Проектирование технологических линий"];
    for (id, name) in (1..).zip(names) {
        courses.set(id, &name.to_owned()).unwrap();
    }
    let every = |text: &str| descending(checked(|| courses.search(text).prefix_every().run()).unwrap()).0;
    assert_eq!(every("лин алг"), ["1", "3", "2"], "1 holds a word each began, then BM25");
    assert_eq!(every("алг лин"), ["1", "3", "2"], "`алг` begins `алгоритмизация` too");
    assert_eq!(every("лин алгебра"), ["1", "3"]);
    assert_eq!(every("линейная алг"), ["1", "2"]);
    assert_eq!(every("лин"), ["3", "1"], "one word: BM25 alone");
    let last = |text: &str| ids(&checked(|| courses.search(text).prefix().run()).unwrap()).join(" ");
    assert_eq!(last("лин алг"), "3 1 2", "the last word alone, as 0.4.1 read it");
    assert_eq!(last("алг лин"), "3 1");
    let (hits, corrected) = descending(checked(|| courses.search("линеная алг").prefix_every().run()).unwrap());
    assert_eq!((hits[0].as_str(), corrected.as_deref()), ("1", Some("линейная алг")), "a word that begins none");
}

// contract: SRCH-13
#[test]
fn every_word_begun_reads_as_the_guide_shows_it() {
    let fixture = fixture();
    let courses = fixture.store.index::<String>("courses").open().unwrap();
    let names = [
        "Cryptographic methods of information security",
        "Cryptanalysis",
        "Cryptography",
        "Foundations of cryptography",
        "Линейная алгебра",
        "Алгоритмизация и программирование",
        "Проектирование технологических линий",
    ];
    for (id, name) in (1..).zip(names) {
        courses.set(id, &name.to_owned()).unwrap();
    }
    assert_eq!(descending(checked(|| courses.search("лин алг").prefix_every().run()).unwrap()).0, ["5", "7", "6"]);
    assert_eq!(ids(&checked(|| courses.search("лин алг").prefix().run()).unwrap()), ["7", "5", "6"]);
}

// contract: SRCH-13
#[test]
fn every_word_begun_finds_the_course_its_reader_shortened_first() {
    let fixture = fixture();
    let courses = fixture.store.index::<String>("catalogue").open().unwrap();
    let names = [
        "Линейная алгебра",
        "Алгоритмизация и модульное программирование",
        "Инженерная графика",
        "Проектная графика и типографика",
        "Инженерное творчество",
        "Теория вероятностей",
        "Теория организации",
        "Начертательная геометрия",
        "Аналитическая геометрия",
        "Проектирование технологических линий",
    ];
    for (id, name) in (1..).zip(names) {
        courses.set(id, &name.to_owned()).unwrap();
    }
    let first = |text: &str| {
        let found = descending(checked(|| courses.search(text).prefix_every().run()).unwrap()).0;
        found.first().map(|id| names[id.parse::<usize>().unwrap() - 1]).unwrap_or_default()
    };
    // with the last word alone, issue 40's catalogue put the second of each first
    for (text, meant) in [
        ("лин алг", "Линейная алгебра"),
        ("инж граф", "Инженерная графика"),
        ("теор вер", "Теория вероятностей"),
        ("нач геом", "Начертательная геометрия"),
    ] {
        assert_eq!(first(text), meant, "{text}");
    }
}

// contract: SRCH-13
#[test]
fn every_word_begun_answers_the_documents_holding_one_for_each_first_waiting_and_packed() {
    let fixture = fixture();
    let builder = fixture.store.index("mix").field("title", 2.0).field("body", 1.0).filters(["category"]);
    let index: Index<Article> = builder.typo_tolerance(false).open().unwrap();
    let mut random = Random::new(40);
    let mut docs: BTreeMap<String, Article> = BTreeMap::new();
    // the documents holding a word each prefix begins, and those holding one for every prefix
    let begun = |docs: &BTreeMap<String, Article>, text: &str| -> (BTreeSet<String>, BTreeSet<String>) {
        let (mut any, mut every) = (BTreeSet::new(), BTreeSet::new());
        for (id, value) in docs {
            let words = analyzer::words(&format!("{} {}", value.title, value.body));
            let holds = |prefix: &str| words.iter().any(|word| word.text.starts_with(prefix));
            if text.split(' ').any(holds) {
                any.insert(id.clone());
            }
            if text.split(' ').all(holds) {
                every.insert(id.clone());
            }
        }
        (any, every)
    };
    let found = |text: &str, category: Option<&str>| {
        let call = index.search(text).prefix_every().limit(1000);
        let call = match category {
            Some(category) => call.filter(crate::search::eq("category", category)),
            None => call,
        };
        descending(checked(|| call.run()).unwrap()).0
    };
    for round in 0..3 {
        for _ in 0..400 {
            let id = format!("d{}", random.below(300));
            if random.below(5) == 0 {
                index.delete(&id).unwrap();
                docs.remove(&id);
            } else {
                let category = if random.below(3) == 0 { "shoes" } else { "boots" };
                let value = Article { category: Some(category.to_owned()), ..random_article(&mut random) };
                index.set(&id, &value).unwrap();
                docs.insert(id, value);
            }
        }
        for packed in [false, true] {
            if packed {
                maintain(&fixture.store).unwrap();
            }
            for text in ["rare39 ba", "кош соба", "те rare7 ba", "st ye", "cr сол"] {
                let (any, every) = begun(&docs, text);
                assert!(!every.is_empty(), "round {round}: {text} has documents holding a word for each");
                for category in [None, Some("shoes")] {
                    let kept = |ids: &BTreeSet<String>| -> BTreeSet<String> {
                        let passes = |id: &&String| category.is_none_or(|c| docs[*id].category.as_deref() == Some(c));
                        ids.iter().filter(passes).cloned().collect()
                    };
                    let (any, every) = (kept(&any), kept(&every));
                    let said = format!("round {round}, packed {packed}, {category:?}: {text}");
                    let hits = found(text, category);
                    assert_eq!(hits.iter().cloned().collect::<BTreeSet<_>>(), any, "{said}");
                    let first: BTreeSet<String> = hits[..every.len()].iter().cloned().collect();
                    assert_eq!(first, every, "{said}: those holding a word for each first");
                }
            }
        }
    }
}

#[test]
#[ignore = "a timing, run by hand"]
fn a_search_reading_every_word_as_a_prefix_takes() {
    let fixture = fixture();
    let index: Index<Article> = fixture.store.index("timed").field("title", 2.0).field("body", 1.0).open().unwrap();
    let mut random = Random::new(7);
    let documents = 5_000;
    for start in (0..documents).step_by(1000) {
        let articles: Vec<(String, Article)> =
            (start..start + 1000).map(|n| (format!("d{n}"), random_article(&mut random))).collect();
        index.set_many(articles.iter().map(|(id, value)| (id.as_str(), value))).unwrap();
    }
    maintain(&fixture.store).unwrap();
    let texts = ["bread rare3", "sour wat", "кош соба", "st ye ba", "хлеб мук"];
    let timed = |search: &dyn Fn(&str) -> Found<Article>| {
        let mut passes: Vec<std::time::Duration> = (0..7)
            .map(|_| {
                let started = std::time::Instant::now();
                for _ in 0..20 {
                    for text in texts {
                        std::hint::black_box(search(text));
                    }
                }
                started.elapsed() / (20 * texts.len() as u32)
            })
            .collect();
        passes.sort();
        passes[passes.len() / 2]
    };
    for turn in 0..2 {
        let plain = timed(&|text| index.search(text).run().unwrap());
        let last = timed(&|text| index.search(text).prefix().run().unwrap());
        let every = timed(&|text| index.search(text).prefix_every().run().unwrap());
        println!(
            "turn {turn}, {documents} documents, median a search: plain {plain:?}, prefix {last:?}, every {every:?}"
        );
    }
}

/// How long setting 100,000 passages of 50 words a thousand at a time takes,
/// their segments merged as background work merges them, then merged into
/// one, and where the time goes. Run by hand:
/// `cargo test -p tinystore --release --lib setting_passages -- --ignored --nocapture`.
#[test]
#[ignore = "a timing, run by hand"]
fn setting_passages_a_thousand_at_a_time_takes() {
    let fixture = fixture();
    let index = fixture.store.index::<String>("timing").typo_tolerance(false).open().unwrap();
    let mut random = Random::new(3);
    let zipf = Zipf::new(50_000);
    let (mut setting, mut merging) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
    for batch in 0..100 {
        let passages: Vec<String> = (0..1000).map(|_| zipf.text(&mut random, 50)).collect();
        let ids: Vec<String> = (0..1000).map(|n| format!("{batch}-{n}")).collect();
        let started = std::time::Instant::now();
        index.set_many(ids.iter().zip(&passages)).unwrap();
        setting += started.elapsed();
        let started = std::time::Instant::now();
        while !index.search.merge_step(&index.open, crate::search::merge::STEP_PIECES, false).unwrap().done {}
        merging += started.elapsed();
    }
    let started = std::time::Instant::now();
    maintain(&fixture.store).unwrap();
    let into_one = started.elapsed();
    let fields = [crate::search::settings::Field { path: String::new(), weight: 1.0, number: 0 }];
    let passages: Vec<serde_json::Value> = (0..100_000).map(|_| zipf.text(&mut random, 50).into()).collect();
    let started = std::time::Instant::now();
    for passage in &passages {
        std::hint::black_box(document::analyze(passage, &fields, &[]).unwrap());
    }
    eprintln!(
        "100,000 passages: sets {setting:?}, merges {merging:?}, into one {into_one:?}, their words alone {:?}",
        started.elapsed()
    );
}

/// How long a search by words takes over 200,000 passages of 50 words each,
/// the words of a vocabulary of 50,000 drawn by Zipf's law as a language's
/// are, asked by 400 questions of 3 to 8 words drawn the same way: the lists
/// in runs, then the same lists written again as a release before 0002
/// wrote them, in the same run, with what each layout's tables take. Run by
/// hand: `cargo test -p tinystore --release --lib a_search_by_words_over -- --ignored --nocapture`.
#[test]
#[ignore = "a timing, run by hand"]
fn a_search_by_words_over_two_hundred_thousand_passages_takes() {
    let fixture = fixture();
    let index = fixture.store.index::<String>("timing").typo_tolerance(false).open().unwrap();
    let mut random = Random::new(3);
    let zipf = Zipf::new(50_000);
    let started = std::time::Instant::now();
    for batch in 0..200 {
        let passages: Vec<String> = (0..1000).map(|_| zipf.text(&mut random, 50)).collect();
        let ids: Vec<String> = (0..1000).map(|n| format!("{batch}-{n}")).collect();
        index.set_many(ids.iter().zip(&passages)).unwrap();
    }
    let set = started.elapsed();
    maintain(&fixture.store).unwrap();
    eprintln!("built: sets {set:?}, packing {:?}", started.elapsed() - set);
    let questions: Vec<String> = (0..400)
        .map(|_| {
            let count = 3 + random.below(6) as usize;
            zipf.text(&mut random, count)
        })
        .collect();
    let timed = |layout: &str| {
        for question in &questions {
            index.search(question).run().unwrap();
        }
        for pass in 0..2 {
            let mut took: Vec<f64> = questions
                .iter()
                .map(|question| {
                    let started = std::time::Instant::now();
                    std::hint::black_box(index.search(question).run().unwrap());
                    started.elapsed().as_secs_f64() * 1000.0
                })
                .collect();
            took.sort_by(f64::total_cmp);
            let at = |share: f64| took[((took.len() as f64 * share) as usize).min(took.len() - 1)];
            eprintln!("{layout}, pass {pass}: p50 {:.2} ms, p90 {:.2}, p99 {:.2}", at(0.5), at(0.9), at(0.99));
        }
    };
    let space = |layout: &str| eprintln!("{layout}: {}", tables(fixture.dir.path()));
    space("a segment");
    timed("a segment");
    crate::search::execute::SEEDED.set(false);
    timed("a segment, no seeds");
    crate::search::execute::SEEDED.set(true);
    timed("a segment");
    crate::search::legacy::written::rewrite(fixture.dir.path(), "timing");
    space("rows of blocks");
    timed("rows of blocks");
    maintain(&fixture.store).unwrap();
    space("a segment again");
    timed("a segment again");
}

/// What the tables that hold postings take, in bytes a posting: their
/// payloads, and their pages in the file.
fn tables(dir: &Path) -> String {
    let connection = rusqlite::Connection::open(dir.join("search.db")).unwrap();
    let postings: f64 = connection
        .query_row("select sum(documents) from _tinystore_search_keys where part < 1073741824", [], |row| row.get(0))
        .unwrap();
    let payload = |sql: &str| -> f64 {
        connection.query_row(sql, [], |row| row.get::<_, Option<f64>>(0)).unwrap().unwrap_or(0.0)
    };
    let pages = |table: &str| -> f64 {
        let sql = "select sum(pgsize) from dbstat where name = ?1";
        connection.query_row(sql, [table], |row| row.get::<_, Option<f64>>(0)).unwrap().unwrap_or(0.0)
    };
    let shown = [
        ("runs", payload("select sum(length(blocks)) from _tinystore_search_runs"), pages("_tinystore_search_runs")),
        (
            "blocks",
            payload("select sum(length(payload)) from _tinystore_search_blocks"),
            pages("_tinystore_search_blocks"),
        ),
        (
            "lists",
            payload(
                "select sum(coalesce(length(directory), 0) + coalesce(length(inline), 0)) from _tinystore_search_lists",
            ),
            pages("_tinystore_search_lists"),
        ),
        (
            "pieces",
            payload(
                "select sum(coalesce(length(postings), 0) + coalesce(length(directory), 0) + coalesce(length(best), 0))
                from _tinystore_search_pieces",
            ),
            pages("_tinystore_search_pieces"),
        ),
    ];
    let mut said = format!("{postings} postings;");
    for (name, payload, pages) in shown {
        said += &format!(" {name} {:.3} B payload, {:.3} B pages;", payload / postings, pages / postings);
    }
    said
}

/// Words drawn by Zipf's law: the word of rank r about 1/r as often as the first.
struct Zipf {
    cumulative: Vec<f64>,
}

impl Zipf {
    fn new(words: usize) -> Zipf {
        let mut total = 0.0;
        let cumulative = (1..=words)
            .map(|rank| {
                total += 1.0 / rank as f64;
                total
            })
            .collect();
        Zipf { cumulative }
    }

    fn text(&self, random: &mut Random, words: usize) -> String {
        let total = self.cumulative[self.cumulative.len() - 1];
        let picked: Vec<String> = (0..words)
            .map(|_| {
                let at = random.below(1 << 53) as f64 / (1_u64 << 53) as f64 * total;
                Zipf::word(self.cumulative.partition_point(|sum| *sum < at))
            })
            .collect();
        picked.join(" ")
    }

    /// The word of a rank: syllables of a consonant and a vowel, two at least.
    fn word(rank: usize) -> String {
        const CONSONANTS: &[u8] = b"bdfgklmnprstvz";
        const VOWELS: &[u8] = b"aeiou";
        let syllables = CONSONANTS.len() * VOWELS.len();
        let mut rest = rank + syllables;
        let mut word = String::new();
        while rest > 0 {
            let syllable = rest % syllables;
            word.push(char::from(CONSONANTS[syllable / VOWELS.len()]));
            word.push(char::from(VOWELS[syllable % VOWELS.len()]));
            rest /= syllables;
        }
        word
    }
}

#[test]
fn a_word_new_since_the_dictionary_was_built_is_read_once_maintenance_builds_it_again() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("a", &article("replication", "")).unwrap();
    assert_eq!(search(&articles, "replicaiton").corrected.as_deref(), Some("replication"));
    articles.set("b", &article("sourdough", "")).unwrap();
    assert!(search(&articles, "sourduogh").hits.is_empty(), "the dictionary kept is behind the words");
    maintain(&fixture.store).unwrap();
    assert_eq!(ids(&search(&articles, "sourduogh")), ["b"]);
    articles.delete("a").unwrap();
    let gone = search(&articles, "replicaiton");
    assert!(gone.hits.is_empty() && gone.corrected.is_none(), "a word gone since is never read");
}

// contract: STORE-11
// contract: SRCH-01
#[test]
fn lists_and_a_head_a_release_wrote_answer_as_before_until_maintenance_writes_them_anew() {
    let fixture = fixture();
    let released = fixture.articles::<Article>("released");
    let fresh = fixture.articles::<Article>("fresh");
    let mut random = Random::new(11);
    let write = |random: &mut Random, count: u32, deletes: u32| {
        for _ in 0..count {
            let (id, value) = (format!("d{}", random.below(4000)), random_article(random));
            released.set(&id, &value).unwrap();
            fresh.set(&id, &value).unwrap();
        }
        for _ in 0..deletes {
            let id = format!("d{}", random.below(4000));
            assert_eq!(released.delete(&id).unwrap(), fresh.delete(&id).unwrap());
        }
        maintain(&fixture.store).unwrap();
    };
    let texts: Vec<String> = (0..40).map(|_| words(&mut random, 4)).collect();
    let answers = |index: &Index<Article>| -> Vec<Vec<(String, f64)>> {
        let found = |text: &String| search(index, text).hits.into_iter().map(|hit| (hit.id, hit.score)).collect();
        texts.iter().map(found).collect()
    };
    write(&mut random, 3000, 0);
    for _ in 0..60 {
        let (id, value) = (format!("d{}", random.below(4000)), random_article(&mut random));
        released.set(&id, &value).unwrap();
        fresh.set(&id, &value).unwrap();
    }
    crate::search::legacy::written::rewrite(fixture.dir.path(), "released");
    let (blocks, head) = crate::search::legacy::written::rows(fixture.dir.path());
    assert!(blocks > 0 && head > 0, "the released index's lists are rows of blocks, its head a row a posting");
    assert_eq!(answers(&released), answers(&fresh), "read as a release wrote them");
    write(&mut random, 400, 200);
    assert_eq!(crate::search::legacy::written::rows(fixture.dir.path()), (0, 0), "maintenance wrote them anew");
    assert_eq!(answers(&released), answers(&fresh), "after packing and a purge");
}

/// Every row that holds a posting, as one string.
fn postings_in(dir: &Path) -> String {
    let connection = rusqlite::Connection::open(dir.join("search.db")).unwrap();
    let mut rows = String::new();
    for sql in [
        "select key, first, payload from _tinystore_search_blocks order by key, first",
        "select id, blocks from _tinystore_search_runs order by id",
        "select * from _tinystore_search_pieces order by segment, key",
        "select * from _tinystore_search_segments order by id",
        "select * from _tinystore_search_lists order by key",
    ] {
        let mut select = connection.prepare(sql).unwrap();
        let count = select.column_count();
        let mut found = select.query([]).unwrap();
        while let Some(row) = found.next().unwrap() {
            for at in 0..count {
                rows.push_str(&format!("{:?} ", row.get_ref(at).unwrap()));
            }
            rows.push('\n');
        }
    }
    rows
}

#[test]
fn a_changed_weight_rebuilds_nothing_and_the_next_search_reads_it() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("title", &article("bread", "salt")).unwrap();
    articles.set("body", &article("salt", "bread")).unwrap();
    for n in 0..30 {
        articles.set(format!("filler-{n}"), &article("water", &format!("salt {n}"))).unwrap();
    }
    maintain(&fixture.store).unwrap();
    assert_eq!(ids(&search(&articles, "bread"))[0], "title");
    let before = postings_in(fixture.dir.path());
    let reweighed = fixture.store.index::<Article>("articles").field("title", 1.0).field("body", 9.0).open().unwrap();
    assert_eq!(postings_in(fixture.dir.path()), before, "no block or list written again");
    assert_eq!(ids(&search(&reweighed, "bread"))[0], "body");
    assert_eq!(ids(&search(&articles, "bread"))[0], "body", "every handle of the index reads it");
}

// contract: SRCH-06
#[test]
fn a_field_removed_leaves_searches_at_once_and_one_added_is_read_beside_the_index_until_it_switches_in() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("a", &article("bread", "salt")).unwrap();
    let titles = fixture.store.index::<Article>("articles").field("title", 2.0).open().unwrap();
    assert!(search(&titles, "salt").hits.is_empty());
    assert_eq!(ids(&search(&titles, "bread")), ["a"]);
    let added = fixture.store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).open().unwrap();
    assert_eq!(added.status().unwrap(), crate::search::Status::Rebuilding { done: 0.0, error: None });
    assert!(search(&added, "salt").hits.is_empty(), "the index answers as before until then");
    maintain(&fixture.store).unwrap();
    added.ready().unwrap();
    assert_eq!(added.status().unwrap(), crate::search::Status::Ready { error: None });
    assert_eq!(ids(&search(&added, "salt")), ["a"]);
    assert_eq!(ids(&search(&titles, "salt")), ["a"], "every handle of the index reads it");
    let empty = fixture.store.index::<Article>("empty").field("title", 1.0).open().unwrap();
    drop(empty);
    let empty = fixture.store.index::<Article>("empty").field("title", 1.0).field("body", 1.0).open().unwrap();
    assert_eq!(
        empty.status().unwrap(),
        crate::search::Status::Ready { error: None },
        "an empty index takes a field at once"
    );
}

// contract: SRCH-16
#[test]
fn a_maintenance_pass_that_keeps_failing_is_told_by_the_status_of_its_index_until_one_passes() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    let other = fixture.articles::<Article>("other");
    for index in [&articles, &other] {
        index.set("a", &article("bread", "salt")).unwrap();
        index.set("b", &article("rye", "flour")).unwrap();
    }
    maintain(&fixture.store).unwrap();
    let id = articles.open.id();
    // as a full disk would: a purge of articles' documents gone cannot forget them
    let beside = rusqlite::Connection::open(fixture.dir.path().join("search.db")).unwrap();
    let full = format!(
        "create trigger full before delete on _tinystore_search_gone when old.index_id = {id} \
         begin select raise(abort, 'disk full'); end"
    );
    beside.execute_batch(&full).unwrap();
    assert!(articles.delete("a").unwrap() && other.delete("a").unwrap());
    let failing = |index: &Index<Article>| match index.status().unwrap() {
        crate::search::Status::Ready { error: Some(error) } => error,
        status => panic!("{status:?}"),
    };
    for _ in 0..2 {
        let error = maintain(&fixture.store).unwrap_err();
        assert!(error.to_string().starts_with("index articles: "), "{error}");
        assert!(failing(&articles).contains("disk full"), "{}", failing(&articles));
    }
    assert_eq!(other.status().unwrap(), crate::search::Status::Ready { error: None }, "the other passed");
    let listed = crate::search::list(&fixture.store).unwrap();
    let status = listed.iter().find(|index| index.name == "articles").map(|index| index.status.clone());
    assert_eq!(status, Some(articles.status().unwrap()), "a listing says it too");
    articles.ready().unwrap();
    assert!(search(&articles, "bread").hits.is_empty(), "searches answer meanwhile");
    beside.execute_batch("drop trigger full").unwrap();
    maintain(&fixture.store).unwrap();
    assert_eq!(articles.status().unwrap(), crate::search::Status::Ready { error: None });
}

// contract: SRCH-10
#[test]
fn an_index_answers_after_a_restart_as_it_did_before() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    for n in 0..50 {
        articles.set(n, &article(&format!("loaf {n}"), "bread and salt")).unwrap();
    }
    maintain(&fixture.store).unwrap();
    articles.set("late", &article("loaf", "in the head")).unwrap();
    let before = search(&articles, "loaf bread");
    drop(articles);
    let Fixture { dir, store } = fixture;
    store.close().unwrap();
    let store = open(dir.path());
    let articles = store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).open().unwrap();
    assert_eq!(checked(|| articles.search("loaf bread").run()).unwrap(), before);
}

// contract: ERR-02
#[test]
fn errors_name_the_index_the_id_and_what_failed() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    let failure = |error: crate::Error| (error.kind(), error.to_string());
    let bad = fixture.store.index::<Article>("Articles").open().unwrap_err();
    assert_eq!(failure(bad).0, ErrorKind::Invalid);
    let heavy = fixture.store.index::<Article>("weights").field("title", 0.0).open().unwrap_err();
    assert_eq!(failure(heavy).0, ErrorKind::Invalid);
    let empty = articles.set("", &article("a", "b")).unwrap_err();
    assert_eq!(failure(empty), (ErrorKind::Invalid, "index articles: id \"\": an empty id: invalid".to_owned()));
    let large = articles.set("big", &article("big", &"x".repeat(1 << 20))).unwrap_err();
    assert_eq!(failure(large).0, ErrorKind::Limit);
    let years = fixture.store.index::<serde_json::Value>("years").field("year", 1.0).open().unwrap();
    let year = years.set("a-17", &serde_json::json!({ "year": 2024 })).unwrap_err();
    let said = "index years: id \"a-17\": field year holds a number, not text: invalid";
    assert_eq!(failure(year), (ErrorKind::Invalid, said.to_owned()));
    assert_eq!(failure(articles.search(&"word ".repeat(300)).run().unwrap_err()).0, ErrorKind::Limit);
    assert_eq!(failure(articles.search("bread").limit(0).run().unwrap_err()).0, ErrorKind::Invalid);
    assert_eq!(failure(articles.search("bread").offset(995).limit(10).run().unwrap_err()).0, ErrorKind::Limit);
}

// contract: ERR-04
#[test]
fn a_block_its_directory_places_past_its_run_fails_corrupt_in_a_merge_a_purge_and_a_search() {
    let corrupt = |error: crate::Error| {
        let said = error.to_string();
        assert_eq!(error.kind(), ErrorKind::Corrupt, "{said}");
        assert!(said.contains("key ") && said.contains(": run "), "the key and the run named: {said}");
    };
    let searched = fixture();
    let articles = misplaced(&searched);
    let filtered = articles.search("flour").filter(crate::search::eq("category", "bread"));
    corrupt(filtered.run().unwrap_err());
    corrupt(articles.search("flour").run().unwrap_err());
    let purged = fixture();
    let articles = misplaced(&purged);
    assert!(articles.delete(0).unwrap());
    corrupt(maintain(&purged.store).unwrap_err());
    let merged = fixture();
    let articles = misplaced(&merged);
    articles.set("late", &article("loaf", "flour")).unwrap();
    corrupt(maintain(&merged.store).unwrap_err());
}

/// The index `articles` of forty documents of the category bread in one
/// folded segment, every block of its pieces in runs then placed past its
/// run's end, as a bit flipped in search.db would place it.
fn misplaced(fixture: &Fixture) -> Index<Article> {
    let builder = fixture.store.index("articles").field("title", 2.0).field("body", 1.0).filters(["category"]);
    let articles: Index<Article> = builder.open().unwrap();
    for n in 0..40 {
        let value = Article { category: Some("bread".to_owned()), ..article(&format!("loaf {n}"), "flour") };
        articles.set(n, &value).unwrap();
    }
    maintain(&fixture.store).unwrap();
    let connection = rusqlite::Connection::open(fixture.dir.path().join("search.db")).unwrap();
    let pieces: Vec<(i64, i64, Vec<u8>)> = connection
        .prepare("select segment, key, directory from _tinystore_search_pieces where directory is not null")
        .unwrap()
        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
        .unwrap()
        .collect::<rusqlite::Result<_>>()
        .unwrap();
    assert!(!pieces.is_empty(), "the words and the category of forty documents are pieces in runs");
    for (segment, key, bytes) in pieces {
        let mut directory = crate::search::packed::Directory::decode(&bytes).unwrap();
        directory.blocks.iter_mut().for_each(|block| block.at = u16::MAX);
        let write = "update _tinystore_search_pieces set directory = ?3 where segment = ?1 and key = ?2";
        connection.execute(write, (segment, key, directory.encode())).unwrap();
    }
    // as a file damaged beside the store: what the store keeps of its pieces is behind
    connection.execute("update _tinystore_search_indexes set lists_version = lists_version + 1", []).unwrap();
    articles
}

const WORDS: &[&str] = &[
    "bread",
    "sourdough",
    "flour",
    "water",
    "salt",
    "oven",
    "crust",
    "yeast",
    "starter",
    "dough",
    "rye",
    "wheat",
    "honey",
    "seed",
    "loaf",
    "bake",
    "baker",
    "knead",
    "crumb",
    "steam",
    "хлеб",
    "закваска",
    "мука",
    "вода",
    "соль",
    "печь",
    "корка",
    "тесто",
    "кошки",
    "кошка",
    "собаки",
    "собака",
    "東京",
    "世界和平",
];

/// Up to `most` words: a common one of [`WORDS`] mostly, and one in four of
/// hundreds of rare ones, whose short lists bound their blocks high.
fn words(random: &mut Random, most: u64) -> String {
    let count = random.below(most + 1);
    let word = |random: &mut Random| match random.below(4) {
        0 => format!("rare{}", random.skewed(400)),
        _ => WORDS[random.skewed(WORDS.len() as u64) as usize].to_owned(),
    };
    let picked: Vec<String> = (0..count).map(|_| word(random)).collect();
    picked.join(" ")
}

fn random_article(random: &mut Random) -> Article {
    Article { title: words(random, 5), body: words(random, 60), ..Article::default() }
}

/// The documents an index should hold, each with the number its set gave
/// it and its words as the index's fields read them.
#[derive(Default)]
struct Model {
    docs: BTreeMap<String, Doc>,
    next: u32,
    /// What begins every id the model's writer sets.
    prefix: String,
}

/// A document of the model: its number, its value, its words and its vector.
struct Doc {
    number: u32,
    value: Article,
    terms: HashMap<(Part, String), u32>,
    analyzed: Analyzed,
    vector: Option<Vec<f32>>,
}

impl Model {
    /// The same documents as `settings` read them.
    fn read_by(&self, settings: &Settings) -> Model {
        let mut model = Model { next: self.next, prefix: self.prefix.clone(), ..Model::default() };
        for (id, doc) in &self.docs {
            let analyzed =
                document::analyze(&serde_json::to_value(&doc.value).unwrap(), &settings.fields, &settings.filters)
                    .unwrap();
            let terms = analyzed.terms.iter().map(|(part, term, tf)| ((*part, term.clone()), *tf)).collect();
            let value = doc.value.clone();
            model
                .docs
                .insert(id.clone(), Doc { number: doc.number, value, terms, analyzed, vector: doc.vector.clone() });
        }
        model
    }

    fn set(&mut self, settings: &Settings, id: String, value: Article) {
        self.set_with(settings, id, value, None);
    }

    fn set_with(&mut self, settings: &Settings, id: String, value: Article, vector: Option<Vec<f32>>) {
        self.next += 1;
        let analyzed =
            document::analyze(&serde_json::to_value(&value).unwrap(), &settings.fields, &settings.filters).unwrap();
        let terms = analyzed.terms.iter().map(|(part, term, tf)| ((*part, term.clone()), *tf)).collect();
        self.docs.insert(id, Doc { number: self.next, value, terms, analyzed, vector });
    }

    /// The best `k` by scoring every document the model holds that the
    /// search keeps, as the engine's hits say them; every document counts in
    /// the scores.
    fn best(&self, settings: &Settings, ask: &Ask<'_>, k: usize) -> Vec<(String, f64)> {
        let documents = self.docs.len() as u64;
        let mut holding: HashMap<&(Part, String), u64> = HashMap::new();
        let mut tokens: HashMap<Part, u64> = HashMap::new();
        for doc in self.docs.values() {
            doc.terms.keys().for_each(|key| *holding.entry(key).or_default() += 1);
            doc.analyzed.lengths.iter().for_each(|(part, len)| *tokens.entry(*part).or_default() += u64::from(*len));
        }
        let query = forms(&analyzer::words(ask.text).into_iter().take(32).collect::<Vec<_>>(), settings);
        let mut scored: Vec<(u64, u32, &String)> = Vec::new();
        for (id, doc) in self.docs.iter().filter(|(_, doc)| (ask.keep)(&doc.value)) {
            let mut total: Option<u64> = None;
            for key in &query {
                let Some(tf) = doc.terms.get(key) else { continue };
                let part = key.0;
                let weight = settings.weight(part.field()).unwrap();
                let scale = part.weight(weight) * idf(documents, holding[key]);
                let average = average(tokens.get(&part).copied().unwrap_or(0), documents);
                let added = points(scale, *tf, doc.analyzed.length(part), average);
                total = Some(total.unwrap_or(0).saturating_add(added));
            }
            if let Some(total) = total {
                scored.push((total, doc.number, id));
            }
        }
        scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
        scored.into_iter().take(k).map(|(total, _, id)| (id.clone(), score(total))).collect()
    }

    /// The cosine of a document's vector with `question`, none when it has none.
    fn cosine(&self, id: &str, question: &[f32]) -> Option<f64> {
        let length = |vector: &[f32]| vector.iter().map(|x| f64::from(*x) * f64::from(*x)).sum::<f64>().sqrt();
        let vector = self.docs[id].vector.as_ref()?;
        let dot: f64 = question.iter().zip(vector).map(|(q, v)| f64::from(*q) * f64::from(*v)).sum();
        Some(dot / (length(question) * length(vector)))
    }

    /// The best `k` by scoring every vector the model holds that the
    /// search keeps.
    fn nearest(&self, ask: &Ask<'_>, k: usize) -> Vec<(String, f64)> {
        let kept = self.docs.iter().filter(|(_, doc)| (ask.keep)(&doc.value));
        let scored = kept.filter_map(|(id, _)| Some((id.clone(), self.cosine(id, ask.question)?)));
        self.ordered(scored.collect(), k)
    }

    /// Hits by their scores, the document set first of equal ones.
    fn ordered(&self, mut hits: Vec<(String, f64)>, k: usize) -> Vec<(String, f64)> {
        let number = |id: &str| self.docs[id].number;
        hits.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap().then(number(&a.0).cmp(&number(&b.0))));
        hits.truncate(k);
        hits
    }

    /// The best `k` of a search by `text` and `question` at once, from the
    /// best hundred of each half, or `k` if more.
    fn both(&self, settings: &Settings, ask: &Ask<'_>, how: How, k: usize) -> Vec<(String, f64)> {
        let (text, question) = (ask.text, ask.question);
        let alone = analyzer::words(text).is_empty() && !matches!(how, How::Rerank);
        if alone || matches!(how, How::Sum(1.0)) {
            return self.nearest(ask, k);
        }
        if matches!(how, How::Sum(0.0)) {
            return self.best(settings, ask, k);
        }
        let words = self.best(settings, ask, k.max(100));
        let How::Sum(weight) = how else {
            let (with, without): (Vec<_>, Vec<_>) =
                words.into_iter().partition(|(id, _)| self.docs[id].vector.is_some());
            let cosines = with.into_iter().map(|(id, _)| (id.clone(), self.cosine(&id, question).unwrap())).collect();
            let mut reranked = self.ordered(cosines, usize::MAX);
            reranked.extend(without.into_iter().map(|(id, _)| (id, -1.0)));
            reranked.truncate(k);
            return reranked;
        };
        let (words, vectors) = (scaled(&words), scaled(&self.nearest(ask, k.max(100))));
        let ids: BTreeSet<&String> = words.keys().chain(vectors.keys()).collect();
        let half = |half: &HashMap<String, f64>, id: &String| half.get(id).copied().unwrap_or(0.0);
        let sums =
            ids.into_iter().map(|id| (id.clone(), (1.0 - weight) * half(&words, id) + weight * half(&vectors, id)));
        self.ordered(sums.collect(), k)
    }
}

/// What a check asks the model: a search's text and vector, and which
/// documents its filter keeps.
struct Ask<'a> {
    text: &'a str,
    question: &'a [f32],
    keep: &'a dyn Fn(&Article) -> bool,
}

/// How a search by both combines its halves.
#[derive(Clone, Copy, Debug)]
enum How {
    Sum(f64),
    Rerank,
}

/// A half's scores from 0, its lowest, to 1, its highest; 1 each when all are equal.
fn scaled(half: &[(String, f64)]) -> HashMap<String, f64> {
    let lowest = half.iter().map(|(_, score)| *score).fold(f64::INFINITY, f64::min);
    let highest = half.iter().map(|(_, score)| *score).fold(f64::NEG_INFINITY, f64::max);
    let scale = |score: f64| if highest > lowest { (score - lowest) / (highest - lowest) } else { 1.0 };
    half.iter().map(|(id, score)| (id.clone(), scale(*score))).collect()
}

/// Checks a search against the model, by every document it holds.
fn agrees(index: &Index<Article>, model: &Model, random: &mut Random, seed: u64) {
    let settings = Settings::clone(&index.open.settings());
    let text = words(random, 4);
    let (offset, limit) = (random.below(15) as usize, 1 + random.below(25) as usize);
    let found = checked(|| index.search(&text).offset(offset).limit(limit).run()).unwrap();
    let mut expected = model.best(&settings, &Ask { text: &text, question: &[], keep: &|_| true }, offset + limit);
    expected.drain(..offset.min(expected.len()));
    let got: Vec<(String, f64)> = found.hits.iter().map(|hit| (hit.id.clone(), hit.score)).collect();
    assert_eq!(got, expected, "seed {seed}: {text:?}");
    for hit in &found.hits {
        assert_eq!(hit.value, model.docs[&hit.id].value, "seed {seed}: a hit's value is the one set last");
    }
}

// contract: SRCH-01
#[test]
fn a_search_answers_what_scoring_every_document_answers_under_sets_deletes_packing_and_purging() {
    for seed in 0..4 {
        let fixture = fixture();
        let index: Index<Article> =
            fixture.store.index("mix").field("title", 2.0).field("body", 1.0).typo_tolerance(false).open().unwrap();
        let mut random = Random::new(seed);
        let mut model = Model::default();
        let settings = Settings::clone(&index.open.settings());
        for _ in 0..2500 {
            match random.below(100) {
                0..70 => {
                    let (id, value) = (format!("d{}", random.below(500)), random_article(&mut random));
                    index.set(&id, &value).unwrap();
                    model.set(&settings, id, value);
                }
                70..82 => {
                    let id = format!("d{}", random.below(500));
                    assert_eq!(index.delete(&id).unwrap(), model.docs.remove(&id).is_some());
                }
                82..84 => drop(maintain(&fixture.store).unwrap()),
                84..86 => {
                    let ids: Vec<String> =
                        (0..1 + random.below(12)).map(|_| format!("d{}", random.below(500))).collect();
                    let values: Vec<Article> = ids.iter().map(|_| random_article(&mut random)).collect();
                    index.set_many(ids.iter().zip(&values)).unwrap();
                    ids.into_iter().zip(values).for_each(|(id, value)| model.set(&settings, id, value));
                }
                86..88 => drop(index.search.merge_step(&index.open, 1 + random.below(3000) as usize, true).unwrap()),
                88..89 => index.search.purge_in_steps(&index.open, 1 + random.below(40) as usize, || {}).unwrap(),
                _ => agrees(&index, &model, &mut random, seed),
            }
        }
        for _ in 0..20 {
            agrees(&index, &model, &mut random, seed);
        }
    }
}

// contract: DUR-09
#[test]
fn merging_and_purging_change_no_answer() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    let mut random = Random::new(7);
    for n in 0..600 {
        // the first 300 merged, so that the last 300 leave documents gone in them
        if n == 300 {
            maintain(&fixture.store).unwrap();
        }
        articles.set(n % 300, &random_article(&mut random)).unwrap();
    }
    let texts: Vec<String> = (0..30).map(|_| words(&mut random, 4)).collect();
    let answers = |articles: &Index<Article>| -> Vec<Found<Article>> {
        texts.iter().map(|text| checked(|| articles.search(text).limit(20).run()).unwrap()).collect()
    };
    let before = answers(&articles);
    loop {
        let step = articles.search.merge_step(&articles.open, 700, true).unwrap();
        assert_eq!(answers(&articles), before, "a step of merging");
        if step.done {
            break;
        }
    }
    articles
        .search
        .purge_in_steps(&articles.open, 25, || assert_eq!(answers(&articles), before, "a step of purging"))
        .unwrap();
}

#[test]
fn searches_and_writes_from_many_threads_answer_as_one_at_a_time_would() {
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    let fixture = fixture();
    let index: Index<Article> =
        fixture.store.index("threads").field("title", 2.0).field("body", 1.0).typo_tolerance(false).open().unwrap();
    let (done, searches) = (AtomicBool::new(false), AtomicUsize::new(0));
    let models: Vec<Model> = std::thread::scope(|scope| {
        for reader in 0..3 {
            let (index, done, searches) = (&index, &done, &searches);
            scope.spawn(move || {
                let mut random = Random::new(100 + reader);
                while !done.load(Ordering::Acquire) {
                    checked(|| index.search(&words(&mut random, 3)).limit(15).run()).unwrap();
                    searches.fetch_add(1, Ordering::Relaxed);
                }
            });
        }
        let maintaining = scope.spawn(|| {
            while !done.load(Ordering::Acquire) {
                maintain(&fixture.store).unwrap();
            }
        });
        let writers: Vec<_> = (0..4)
            .map(|writer| {
                let index = &index;
                scope.spawn(move || {
                    let mut random = Random::new(writer);
                    let mut model = Model { prefix: format!("w{writer}-"), ..Model::default() };
                    for _ in 0..400 {
                        let id = format!("{}{}", model.prefix, random.below(60));
                        if random.below(5) == 0 {
                            index.delete(&id).unwrap();
                            model.docs.remove(&id);
                        } else {
                            let value = random_article(&mut random);
                            index.set(&id, &value).unwrap();
                            model.set(&index.open.settings(), id, value);
                        }
                    }
                    model
                })
            })
            .collect();
        let models = writers.into_iter().map(|writer| writer.join().unwrap()).collect();
        done.store(true, Ordering::Release);
        maintaining.join().unwrap();
        models
    });
    assert!(searches.load(Ordering::Relaxed) > 0);
    for model in models {
        for n in 0..60 {
            let id = format!("{}{n}", model.prefix);
            assert_eq!(index.get(&id).unwrap(), model.docs.get(&id).map(|doc| doc.value.clone()), "{id}");
        }
        for (id, Doc { value, .. }) in &model.docs {
            let Some(word) = value.title.split(' ').chain(value.body.split(' ')).find(|word| !word.is_empty()) else {
                continue;
            };
            let found = checked(|| index.search(word).limit(1000).run()).unwrap();
            let hit = found.hits.iter().find(|hit| &hit.id == id);
            assert_eq!(hit.map(|hit| &hit.value), Some(value), "{id} is found by its words as last set");
        }
    }
}

/// The files of search.db as a crash would leave them now.
fn crash_image(dir: &Path) -> tempfile::TempDir {
    let image = tempfile::tempdir().unwrap();
    for name in ["search.db", "search.db-wal"] {
        if dir.join(name).exists() {
            std::fs::copy(dir.join(name), image.path().join(name)).unwrap();
        }
    }
    image
}

// contract: DUR-09
#[test]
fn a_crash_between_steps_of_merging_or_purging_leaves_the_last_commit() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    let mut random = Random::new(11);
    for n in 0..300 {
        // the first 200 merged, so that the last 100 leave documents gone in them
        if n == 200 {
            maintain(&fixture.store).unwrap();
        }
        articles.set(n % 200, &random_article(&mut random)).unwrap();
    }
    let texts: Vec<String> = (0..10).map(|_| words(&mut random, 3)).collect();
    let answers = |articles: &Index<Article>| -> Vec<Found<Article>> {
        texts.iter().map(|text| checked(|| articles.search(text).run()).unwrap()).collect()
    };
    let before = answers(&articles);
    let mut images = vec![crash_image(fixture.dir.path())];
    while !articles.search.merge_step(&articles.open, 100, true).unwrap().done {
        images.push(crash_image(fixture.dir.path()));
    }
    articles.search.purge_in_steps(&articles.open, 30, || images.push(crash_image(fixture.dir.path()))).unwrap();
    assert!(images.len() > 4, "merging and purging took several steps");
    for image in images {
        let store = open(image.path());
        let reopened = store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).open().unwrap();
        assert_eq!(answers(&reopened), before);
        maintain(&store).unwrap();
        assert_eq!(answers(&reopened), before, "and once its merging and purging go on");
    }
}

/// search.db's bytes once its WAL is copied into it.
fn checkpointed(dir: &Path) -> u64 {
    let connection = rusqlite::Connection::open(dir.join("search.db")).unwrap();
    connection.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(())).unwrap();
    sizes(dir).0
}

fn sizes(dir: &Path) -> (u64, u64) {
    let size = |name: &str| std::fs::metadata(dir.join(name)).map_or(0, |metadata| metadata.len());
    (size("search.db"), size("search.db-wal"))
}

#[test]
fn through_a_long_mix_the_file_stays_near_a_fresh_build_of_the_same_documents() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    let mut random = Random::new(13);
    let mut model = Model::default();
    let settings = Settings::clone(&articles.open.settings());
    for round in 0..8000 {
        let id = format!("d{}", random.below(400));
        if random.below(6) == 0 {
            articles.delete(&id).unwrap();
            model.docs.remove(&id);
        } else {
            let value = random_article(&mut random);
            articles.set(&id, &value).unwrap();
            model.set(&settings, id, value);
        }
        if round % 1000 == 999 {
            maintain(&fixture.store).unwrap();
        }
    }
    maintain(&fixture.store).unwrap();
    let fresh = crate::search::fixture::fixture();
    let rebuilt = fresh.articles::<Article>("articles");
    for (id, doc) in &model.docs {
        rebuilt.set(id, &doc.value).unwrap();
    }
    maintain(&fresh.store).unwrap();
    let ((_, mixed_log), (_, _)) = (sizes(fixture.dir.path()), sizes(fresh.dir.path()));
    // search.db checkpoints after 16,000 frames: its pages are measured in the file
    let (mixed, built) = (checkpointed(fixture.dir.path()), checkpointed(fresh.dir.path()));
    // what the last merges and rebuilds freed stays free a while, and upkeep
    // gives it back then, as it does a dropped index's pages
    let used = mixed - pages(fixture.dir.path()).1.unsigned_abs() * 4096;
    eprintln!("{mixed} bytes after the mix, {used} of them used, {built} built afresh, a log of {mixed_log}");
    assert!(used <= built * 3 / 2, "{used} bytes used after the mix, {built} built afresh");
    assert!(mixed_log <= 8 << 20, "the write-ahead log holds {mixed_log} bytes");
}

/// The dimensions of the vectors the tests give.
const DIMENSIONS: usize = 6;

/// A vector of whole numbers and of fractions, which gives equal cosines as
/// often as nearly equal ones.
fn embedding(random: &mut Random) -> Vec<f32> {
    let mut values: Vec<f32> = (0..DIMENSIONS)
        .map(|_| match random.below(3) {
            0 => random.below(5) as f32 - 2.0,
            _ => (random.below(2001) as f32 - 1000.0) / 997.0,
        })
        .collect();
    if values.iter().all(|value| *value == 0.0) {
        values[0] = 1.0;
    }
    values
}

fn products(fixture: &Fixture) -> Index<Article> {
    let builder = fixture.store.index("products").field("title", 2.0).field("body", 1.0);
    builder.typo_tolerance(false).vectors(DIMENSIONS).open().unwrap()
}

#[test]
fn a_search_by_a_vector_answers_the_nearest_by_their_cosine() {
    let fixture = fixture();
    let shoes = fixture.store.index::<Article>("shoes").field("title", 1.0).vectors(3).open().unwrap();
    shoes.id("a").vector(&[1.0, 0.0, 0.0]).set(&article("red shoes", "")).unwrap();
    shoes.id("b").vector(&[0.0, 1.0, 0.0]).set(&article("blue shoes", "")).unwrap();
    shoes.id("c").vector(&[2.0, 0.5, 0.0]).set(&article("red hat", "")).unwrap();
    shoes.id("d").without_vector().set(&article("red", "")).unwrap();
    let nearest = checked(|| shoes.search_vector(&[1.0, 0.0, 0.0]).run()).unwrap();
    assert_eq!(ids(&nearest), ["a", "c", "b"], "a document without a vector is found by its words alone");
    assert_eq!(nearest.hits.iter().map(|hit| hit.score).collect::<Vec<_>>(), [1.0, 2.0 / 4.25f64.sqrt(), 0.0]);
    let reranked = checked(|| shoes.search("red").vector(&[0.0, 1.0, 0.0]).rerank().run()).unwrap();
    assert_eq!(ids(&reranked), ["c", "a", "d"], "the words' hits by their vectors, none without last");
    assert_eq!(reranked.hits[2].score, -1.0);
    let words = checked(|| shoes.search("red").vector(&[0.0, 1.0, 0.0]).vector_weight(0.0).run()).unwrap();
    let scores = |found: &Found<Article>| found.hits.iter().map(|hit| (hit.id.clone(), hit.score)).collect::<Vec<_>>();
    assert_eq!(scores(&words), scores(&search(&shoes, "red")), "a weight of 0 is the search by the words alone");
    let similarities: BTreeMap<_, _> = words.hits.iter().map(|hit| (hit.id.as_str(), hit.similarity)).collect();
    let expected = BTreeMap::from([("a", Some(0.0)), ("c", Some(0.5 / 4.25f64.sqrt())), ("d", None)]);
    assert_eq!(similarities, expected, "its hits' cosines read all the same");
    let vector = checked(|| shoes.search("red").vector(&[1.0, 0.0, 0.0]).vector_weight(1.0).run()).unwrap();
    assert_eq!(vector, nearest, "and of 1, by the vector alone");
    let (first, second, third) = (article("a", ""), article("b", ""), article("c", ""));
    let (va, vb) = (vec![1.0, 2.0, 3.0], vec![3.0, 2.0, 1.0]);
    shoes.set_many([("e", &first, &va), ("f", &second, &vb)]).unwrap();
    shoes.set_many([("g", &third, Some(&va[..])), ("h", &third, None)]).unwrap();
    let listed = checked(|| shoes.search_vector(&[3.0, 2.0, 1.0]).limit(20).run()).unwrap();
    assert_eq!(ids(&listed), ["f", "c", "a", "e", "g", "b"], "of equal cosines, e set first; h has no vector");
}

// contract: SRCH-15
#[test]
fn a_hit_keeps_each_half_of_its_score_and_a_floor_keeps_a_far_vector_out_of_the_sum() {
    let fixture = fixture();
    let notes = fixture.store.index::<Article>("notes").field("title", 1.0).vectors(3).open().unwrap();
    notes.id("dota").vector(&[1.0, 0.0, 0.0]).set(&article("dota is dead", "")).unwrap();
    notes.id("rain").vector(&[0.0, 1.0, 0.0]).set(&article("loves the rain", "")).unwrap();
    notes.id("patch").vector(&[0.0, 0.0, 1.0]).set(&article("the new dota patch", "")).unwrap();
    // −1/√3, in thousandths
    let (far, cosine) = ([-1.0, -1.0, -1.0], -577);
    let halves = |found: &Found<Article>| -> Vec<(String, f64, bool, Option<i64>)> {
        let thousandths = |cosine: f64| (cosine * 1000.0).round() as i64;
        let half =
            |hit: &Hit<Article>| (hit.id.clone(), hit.score, hit.text_score.is_some(), hit.similarity.map(thousandths));
        found.hits.iter().map(half).collect()
    };
    let words = search(&notes, "dota");
    assert_eq!(words.hits[0].text_score, Some(words.hits[0].score), "a search by words alone scores by them");
    assert_eq!(words.hits[0].similarity, None);

    let summed = checked(|| notes.search("dota").vector(&far).run()).unwrap();
    let near_nothing = [
        ("dota".to_owned(), 1.0, true, Some(cosine)),
        ("rain".to_owned(), 0.5, false, Some(cosine)),
        ("patch".to_owned(), 0.5, true, Some(cosine)),
    ];
    assert_eq!(halves(&summed), near_nothing, "the vector's least near still weighs in the sum");
    let floored = checked(|| notes.search("dota").vector(&far).min_similarity(0.58).run()).unwrap();
    let kept = [("dota".to_owned(), 0.5, true, Some(cosine)), ("patch".to_owned(), 0.0, true, Some(cosine))];
    assert_eq!(halves(&floored), kept, "under the floor the vector finds nothing, and rain no word finds");
    let nearest = checked(|| notes.search_vector(&[1.0, 0.0, 0.0]).min_similarity(0.5).run()).unwrap();
    assert_eq!(halves(&nearest), [("dota".to_owned(), 1.0, false, Some(1000))], "a vector alone leaves the rest out");

    let reranked = checked(|| notes.search("dota").vector(&far).rerank().run()).unwrap();
    assert!(reranked.hits.iter().all(|hit| hit.text_score.is_some() && hit.similarity == Some(hit.score)));
    let refused = [
        notes.search("dota").vector(&far).rerank().min_similarity(0.5).run().unwrap_err(),
        notes.search("dota").min_similarity(0.5).run().unwrap_err(),
        notes.search_vector(&far).min_similarity(1.5).run().unwrap_err(),
    ];
    for error in refused {
        assert_eq!(error.kind(), ErrorKind::Invalid, "{error}");
    }
}

#[test]
fn an_index_with_vectors_asks_each_set_for_one_and_refuses_a_vector_it_cannot_compare() {
    let fixture = fixture();
    let products = products(&fixture);
    let kind = |result: crate::Result<()>| result.unwrap_err().kind();
    let said = products.set("p", &article("shoes", "")).unwrap_err().to_string();
    assert!(said.starts_with("index products: id \"p\": the index keeps vectors"), "{said}");
    assert_eq!(kind(products.id("p").vector(&[1.0; 5]).set(&article("shoes", ""))), ErrorKind::Invalid);
    assert_eq!(kind(products.id("p").vector(&[f32::NAN; DIMENSIONS]).set(&article("", ""))), ErrorKind::Invalid);
    assert_eq!(kind(products.id("p").vector(&[0.0; DIMENSIONS]).set(&article("", ""))), ErrorKind::Invalid);
    let many = products.set_many([("p", &article("shoes", ""))]).unwrap_err().to_string();
    assert!(many.starts_with("index products: document 0, id \"p\": the index keeps vectors"), "{many}");
    assert_eq!(products.get("p").unwrap(), None);
    let words = fixture.articles::<Article>("articles");
    assert_eq!(kind(words.id("a").vector(&[1.0]).set(&article("", ""))), ErrorKind::Invalid);
    words.id("a").without_vector().set(&article("bread", "")).unwrap();
    let search = |call: SearchCall<'_, Article>| call.run().map(drop).unwrap_err().kind();
    let q = [1.0; DIMENSIONS];
    assert_eq!(search(words.search("bread").vector(&q)), ErrorKind::Invalid);
    assert_eq!(search(products.search("bread").vector(&[1.0; 5])), ErrorKind::Invalid);
    assert_eq!(search(products.search("bread").vector(&[0.0; DIMENSIONS])), ErrorKind::Invalid);
    assert_eq!(search(products.search("bread").vector(&q).vector_weight(1.5)), ErrorKind::Invalid);
    assert_eq!(search(products.search("bread").vector(&q).vector_weight(0.5).rerank()), ErrorKind::Invalid);
    assert_eq!(search(products.search("bread").vector_weight(0.5)), ErrorKind::Invalid);
    assert_eq!(search(products.search("bread").rerank()), ErrorKind::Invalid);
    assert_eq!(search(products.search("").vector(&q).rerank()), ErrorKind::Invalid);
}

#[test]
fn vectors_added_leave_the_documents_held_without_and_other_dimensions_are_refused() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    articles.set("old", &article("bread", "")).unwrap();
    let opened = |dimensions: Option<usize>| {
        let builder = fixture.store.index::<Article>("articles").field("title", 2.0).field("body", 1.0);
        match dimensions {
            Some(dimensions) => builder.vectors(dimensions).open(),
            None => builder.open(),
        }
    };
    let with = opened(Some(2)).unwrap();
    with.id("new").vector(&[1.0, 0.0]).set(&article("bread", "")).unwrap();
    assert_eq!(ids(&checked(|| with.search("").vector(&[1.0, 1.0]).run()).unwrap()), ["new"]);
    assert_eq!(ids(&search(&with, "bread")), ["old", "new"]);
    assert_eq!(opened(Some(3)).unwrap_err().kind(), ErrorKind::Invalid);
    assert_eq!(opened(None).unwrap_err().kind(), ErrorKind::Invalid, "nor would an open without them drop them");
}

#[test]
fn a_changed_vector_weight_rebuilds_nothing_and_the_next_search_reads_it() {
    let fixture = fixture();
    let products = products(&fixture);
    let mut random = Random::new(3);
    for n in 0..40 {
        products.id(n).vector(&embedding(&mut random)).set(&random_article(&mut random)).unwrap();
    }
    maintain(&fixture.store).unwrap();
    let (text, q) = (words(&mut random, 3) + " bread", embedding(&mut random));
    let weighed = checked(|| products.search(&text).vector(&q).vector_weight(0.8).run()).unwrap();
    let before = postings_in(fixture.dir.path());
    let builder = fixture.store.index::<Article>("products").field("title", 2.0).field("body", 1.0);
    let reopened = builder.typo_tolerance(false).vectors(DIMENSIONS).vector_weight(0.8).open().unwrap();
    assert_eq!(postings_in(fixture.dir.path()), before, "no block or list written again");
    assert_eq!(checked(|| reopened.search(&text).vector(&q).run()).unwrap(), weighed);
    assert_eq!(checked(|| products.search(&text).vector(&q).run()).unwrap(), weighed, "every handle reads it");
}

/// Checks a search by a vector, or by words and a vector, against the model.
fn agrees_by_vector(index: &Index<Article>, model: &Model, random: &mut Random, seed: u64) {
    let settings = Settings::clone(&index.open.settings());
    let (offset, limit) = (random.below(15) as usize, 1 + random.below(25) as usize);
    let (text, q) = (if random.below(4) == 0 { String::new() } else { words(random, 4) }, embedding(random));
    let call = index.search(&text).vector(&q).offset(offset).limit(limit);
    let (call, how) = match random.below(4) {
        0 if !text.trim().is_empty() => (call.rerank(), How::Rerank),
        1 => {
            let weight = [0.0, 0.3, 1.0][random.below(3) as usize];
            (call.vector_weight(weight), How::Sum(weight))
        }
        _ => (call, How::Sum(0.5)),
    };
    let found = checked(|| call.run()).unwrap();
    let ask = Ask { text: &text, question: &q, keep: &|_| true };
    let mut expected = model.both(&settings, &ask, how, offset + limit);
    expected.drain(..offset.min(expected.len()));
    let got: Vec<(String, f64)> = found.hits.iter().map(|hit| (hit.id.clone(), hit.score)).collect();
    assert_eq!(got, expected, "seed {seed}: {text:?} {how:?}");
}

/// Sets a document of the model's with its vector, or without one.
fn set_with(index: &Index<Article>, id: &str, value: &Article, vector: Option<&[f32]>) {
    let call = index.id(id);
    let call = match vector {
        Some(vector) => call.vector(vector),
        None => call.without_vector(),
    };
    call.set(value).unwrap();
}

// contract: SRCH-02
#[test]
fn searches_by_a_vector_and_by_both_answer_what_scoring_every_document_answers() {
    for seed in 0..4 {
        let fixture = fixture();
        let index = products(&fixture);
        let mut random = Random::new(seed);
        let mut model = Model::default();
        let settings = Settings::clone(&index.open.settings());
        for _ in 0..1500 {
            match random.below(100) {
                0..60 => {
                    let (id, value) = (format!("d{}", random.below(300)), random_article(&mut random));
                    let vector = (random.below(10) != 0).then(|| embedding(&mut random));
                    set_with(&index, &id, &value, vector.as_deref());
                    model.set_with(&settings, id, value, vector);
                }
                60..72 => {
                    let id = format!("d{}", random.below(300));
                    assert_eq!(index.delete(&id).unwrap(), model.docs.remove(&id).is_some());
                }
                72..74 => drop(maintain(&fixture.store).unwrap()),
                74..76 => {
                    let ids: Vec<String> =
                        (0..1 + random.below(8)).map(|_| format!("d{}", random.below(300))).collect();
                    let values: Vec<(Article, Vec<f32>)> =
                        ids.iter().map(|_| (random_article(&mut random), embedding(&mut random))).collect();
                    index.set_many(ids.iter().zip(&values).map(|(id, (value, vector))| (id, value, vector))).unwrap();
                    for (id, (value, vector)) in ids.into_iter().zip(values) {
                        model.set_with(&settings, id, value, Some(vector));
                    }
                }
                76..78 => drop(index.search.merge_step(&index.open, 1 + random.below(3000) as usize, true).unwrap()),
                78..79 => index.search.purge_in_steps(&index.open, 1 + random.below(40) as usize, || {}).unwrap(),
                79..85 => agrees(&index, &model, &mut random, seed),
                _ => agrees_by_vector(&index, &model, &mut random, seed),
            }
        }
        let Fixture { dir, store } = fixture;
        drop(index);
        store.close().unwrap();
        let reopened = Fixture { store: open(dir.path()), dir };
        let index = products(&reopened);
        for _ in 0..20 {
            agrees_by_vector(&index, &model, &mut random, seed);
        }
    }
}

/// How long an exact search by a vector takes over 100,000 vectors of 1,024
/// dimensions, each number a sum of three uniform ones. Run by hand:
/// `cargo test -p tinystore --release --lib a_search_by_a_vector_over -- --ignored --nocapture`.
#[test]
#[ignore = "a timing, run by hand"]
fn a_search_by_a_vector_over_a_hundred_thousand_takes() {
    let fixture = fixture();
    let index = fixture.store.index::<String>("timing").vectors(1024).open().unwrap();
    let mut random = Random::new(1);
    let mut normal = |_| (0..3).map(|_| random.below(2001) as f32 / 1000.0 - 1.0).sum::<f32>();
    let empty = String::new();
    for batch in 0..100 {
        let vectors: Vec<Vec<f32>> = (0..1000).map(|_| (0..1024).map(&mut normal).collect()).collect();
        let ids: Vec<String> = (0..1000).map(|n| format!("{batch}-{n}")).collect();
        index.set_many(ids.iter().zip(&vectors).map(|(id, vector)| (id, &empty, vector))).unwrap();
    }
    let questions: Vec<Vec<f32>> = (0..21).map(|_| (0..1024).map(&mut normal).collect()).collect();
    index.search("").vector(&questions[0]).run().unwrap();
    let mut took: Vec<f64> = questions[1..]
        .iter()
        .map(|question| {
            let started = std::time::Instant::now();
            index.search("").vector(question).run().unwrap();
            started.elapsed().as_secs_f64() * 1000.0
        })
        .collect();
    took.sort_by(f64::total_cmp);
    eprintln!("a search by a vector over 100,000: {:.1} ms at the median, {:.1} at most", took[10], took[19]);
}

/// A condition as the tests ask it, which the engine is given and the model
/// passes documents by itself.
#[derive(Clone, Debug)]
enum Test {
    Eq(&'static str, serde_json::Value),
    In(&'static str, Vec<serde_json::Value>),
    /// From the first, inclusive, to the second, exclusive.
    Range(&'static str, Option<i64>, Option<i64>),
    Or(Vec<Test>),
    And(Vec<Test>),
}

const CATEGORIES: &[&str] = &["shoes", "boots", "hats", "bags", "socks", "coats"];

/// An article with a category mostly, a price mostly, and tags of which
/// some few documents hold each, so that a filter by one passes few.
fn random_product(random: &mut Random) -> Article {
    let category = (random.below(6) != 0).then(|| CATEGORIES[random.below(6) as usize].to_owned());
    let price = (random.below(8) != 0).then(|| random.below(2000) as i64 - 300);
    let tags = (0..random.below(4)).map(|_| format!("tag{}", random.skewed(60))).collect();
    Article { category, price, tags, ..random_article(random) }
}

/// The values a document holds at a filter's path.
fn values_of(article: &Article, path: &str) -> Vec<serde_json::Value> {
    match path {
        "category" => article.category.iter().map(|category| serde_json::json!(category)).collect(),
        "price" => article.price.iter().map(|price| serde_json::json!(price)).collect(),
        _ => article.tags.iter().map(|tag| serde_json::json!(tag)).collect(),
    }
}

impl Test {
    fn passes(&self, article: &Article) -> bool {
        match self {
            Test::Eq(path, serde_json::Value::Null) => values_of(article, path).is_empty(),
            Test::Eq(path, value) => values_of(article, path).contains(value),
            Test::In(path, values) => values.iter().any(|value| Test::Eq(path, value.clone()).passes(article)),
            Test::Range(path, low, high) => values_of(article, path)
                .iter()
                .filter_map(serde_json::Value::as_i64)
                .any(|number| low.is_none_or(|low| number >= low) && high.is_none_or(|high| number < high)),
            Test::Or(parts) => parts.iter().any(|part| part.passes(article)),
            Test::And(parts) => parts.iter().all(|part| part.passes(article)),
        }
    }

    fn condition(&self) -> crate::search::Condition {
        use crate::search::{and, eq, is_in, or, range};
        match self {
            Test::Eq(path, serde_json::Value::Null) => crate::search::missing(path),
            Test::Eq(path, value) => eq(path, value),
            Test::In(path, values) => is_in(path, values),
            Test::Range(path, Some(low), Some(high)) => range(path, *low..*high),
            Test::Range(path, Some(low), None) => range(path, *low..),
            Test::Range(path, None, Some(high)) => range(path, ..*high),
            Test::Range(path, None, None) => range::<i64>(path, ..),
            Test::Or(parts) => or(parts.iter().map(Test::condition)),
            Test::And(parts) => and(parts.iter().map(Test::condition)),
        }
    }

    fn random(random: &mut Random, depth: u32) -> Test {
        let tag = |random: &mut Random| serde_json::json!(format!("tag{}", random.skewed(60)));
        let price = |random: &mut Random| (random.below(5) != 0).then(|| random.below(2200) as i64 - 400);
        match random.below(if depth == 0 { 6 } else { 4 }) {
            0 => {
                let category = CATEGORIES[random.below(6) as usize];
                Test::Eq("category", if random.below(8) == 0 { serde_json::Value::Null } else { category.into() })
            }
            1 => Test::In("tags", (0..random.below(4)).map(|_| tag(random)).collect()),
            2 => Test::Eq("tags", tag(random)),
            3 => Test::Range("price", price(random), price(random)),
            4 => Test::Or((0..2).map(|_| Test::random(random, depth + 1)).collect()),
            _ => Test::And((0..2).map(|_| Test::random(random, depth + 1)).collect()),
        }
    }
}

fn shop(fixture: &Fixture) -> Index<Article> {
    let builder = fixture.store.index("shop").field("title", 2.0).field("body", 1.0);
    let builder = builder.filters(["category", "price", "tags"]).vectors(DIMENSIONS);
    builder.typo_tolerance(false).open().unwrap()
}

/// Checks a filtered search, by words, by a vector or by both, against the
/// model, which passes each document by the conditions itself.
fn agrees_filtered(index: &Index<Article>, model: &Model, random: &mut Random, seed: u64) {
    let settings = Settings::clone(&index.open.settings());
    let tests: Vec<Test> = (0..1 + random.below(2)).map(|_| Test::random(random, 0)).collect();
    let keep = |article: &Article| tests.iter().all(|test| test.passes(article));
    let (offset, limit) = (random.below(10) as usize, 1 + random.below(20) as usize);
    let (text, q) = (words(random, 4), embedding(random));
    let ask = Ask { text: &text, question: &q, keep: &keep };
    let (call, mut expected) = match random.below(4) {
        0 => (index.search(&text), model.best(&settings, &ask, offset + limit)),
        1 => (index.search_vector(&q), model.nearest(&ask, offset + limit)),
        2 if !text.trim().is_empty() => {
            (index.search(&text).vector(&q).rerank(), model.both(&settings, &ask, How::Rerank, offset + limit))
        }
        _ => (index.search(&text).vector(&q), model.both(&settings, &ask, How::Sum(0.5), offset + limit)),
    };
    let call = tests.iter().fold(call.offset(offset).limit(limit), |call, test| call.filter(test.condition()));
    let found = checked(|| call.run()).unwrap();
    expected.drain(..offset.min(expected.len()));
    let got: Vec<(String, f64)> = found.hits.iter().map(|hit| (hit.id.clone(), hit.score)).collect();
    assert_eq!(got, expected, "seed {seed}: {text:?} {tests:?}");
}

// contract: SRCH-03
#[test]
fn a_filtered_search_answers_what_scoring_every_document_it_passes_answers() {
    for seed in 0..4 {
        let fixture = fixture();
        let index = shop(&fixture);
        let mut random = Random::new(seed);
        let mut model = Model::default();
        let settings = Settings::clone(&index.open.settings());
        for _ in 0..1500 {
            match random.below(100) {
                0..60 => {
                    let (id, value) = (format!("d{}", random.below(400)), random_product(&mut random));
                    let vector = (random.below(10) != 0).then(|| embedding(&mut random));
                    set_with(&index, &id, &value, vector.as_deref());
                    model.set_with(&settings, id, value, vector);
                }
                60..70 => {
                    let id = format!("d{}", random.below(400));
                    assert_eq!(index.delete(&id).unwrap(), model.docs.remove(&id).is_some());
                }
                70..72 => drop(maintain(&fixture.store).unwrap()),
                72..74 => drop(index.search.merge_step(&index.open, 1 + random.below(3000) as usize, true).unwrap()),
                74..75 => index.search.purge_in_steps(&index.open, 1 + random.below(40) as usize, || {}).unwrap(),
                _ => agrees_filtered(&index, &model, &mut random, seed),
            }
        }
    }
}

#[test]
fn a_filter_keeps_a_search_to_its_documents_and_names_what_it_cannot_read() {
    use crate::search::{and, eq, is_in, or, range};
    let fixture = fixture();
    let shop = shop(&fixture);
    let item = |category: Option<&str>, price: Option<i64>, tags: &[&str]| Article {
        category: category.map(str::to_owned),
        price,
        tags: tags.iter().map(|tag| (*tag).to_owned()).collect(),
        ..article("red shoes", "")
    };
    shop.id("a").without_vector().set(&item(Some("shoes"), Some(50), &["sale"])).unwrap();
    shop.id("b").without_vector().set(&item(Some("boots"), Some(150), &["sale", "new"])).unwrap();
    shop.id("c").without_vector().set(&item(None, Some(-5), &[])).unwrap();
    let found = |condition| ids(&checked(|| shop.search("red").filter(condition).limit(20).run()).unwrap()).join(",");
    assert_eq!(found(eq("category", "shoes")), "a");
    assert_eq!(found(is_in("category", &["shoes", "boots"])), "a,b");
    assert_eq!(found(crate::search::missing("category")), "c", "missing passes a document with no value");
    assert_eq!(found(eq("tags", "new")), "b", "a list passes on any of its values");
    assert_eq!(found(is_in("tags", &["new", "sale"])), "a,b", "a document holding two of the values is found once");
    assert_eq!(found(range("price", 0..150)), "a");
    assert_eq!(found(range("price", ..=150)), "a,b,c");
    assert_eq!(found(or([eq("category", "boots"), range("price", ..0)])), "b,c");
    assert_eq!(found(and([eq("tags", "sale"), range("price", 100..)])), "b");
    assert_eq!(found(eq("category", "hats")), "", "a value no document holds passes none");
    assert_eq!(found(eq("price", "50")), "", "the text 50 is not the number 50");
    let kind = |condition| shop.search("red").filter(condition).run().map(drop).unwrap_err().kind();
    assert_eq!(kind(eq("color", "red")), ErrorKind::Invalid, "a field the index was not opened with");
    let said = shop.search("red").filter(eq("prise", &5)).run().map(drop).unwrap_err().to_string();
    assert!(said.ends_with("did you mean price?: invalid"), "{said}");
    assert_eq!(kind(eq("price", &serde_json::json!({ "a": 1 }))), ErrorKind::Invalid, "an object is no value");
    assert_eq!(kind(or((0..9).map(|n| eq("price", &n)))), ErrorKind::Limit);
    let said = |condition| shop.search("red").filter(condition).run().map(drop).unwrap_err().to_string();
    let values: Vec<i64> = (0..101).collect();
    assert!(said(is_in("price", &values)).ends_with("a filter of 101 values, past 100: limit"));
    assert!(said(or((0..9).map(|n| eq("price", &n)))).ends_with("a filter of 9 conditions, past 8: limit"));
    let many: Vec<i64> = (0..100).collect();
    assert_eq!(found(is_in("price", &many)), "a", "a list of 100 values joins each value's documents once");
    let refused = shop.id("d").without_vector().set(&Article { tags: vec!["x".repeat(300)], ..article("", "") });
    assert_eq!(refused.unwrap_err().kind(), ErrorKind::Limit);
}

/// Where a filter's own documents are best scored alone: 100,000 articles
/// with vectors of 256 dimensions, each tagged `1/m` one time in `m`, a
/// search by three common words and one by a vector timed on each path.
/// Run by hand:
/// `cargo test -p tinystore --release --lib where_a_filter_is_scored_alone -- --ignored --nocapture`.
#[test]
#[ignore = "a timing, run by hand"]
fn where_a_filter_is_scored_alone_takes() {
    use crate::search::read::NARROW;
    let fixture = fixture();
    let builder = fixture.store.index::<Article>("timing").field("title", 2.0).field("body", 1.0);
    let index = builder.filters(["tags"]).vectors(256).typo_tolerance(false).open().unwrap();
    let shares = [2, 8, 32, 128, 512, 2048, 8192];
    let mut random = Random::new(1);
    let normal = |random: &mut Random| (0..3).map(|_| random.below(2001) as f32 / 1000.0 - 1.0).sum::<f32>();
    for batch in 0..100 {
        let mut documents = Vec::new();
        for n in 0..1000 {
            let tags = shares.iter().filter(|m| random.below(**m) == 0).map(|m| format!("1/{m}")).collect();
            let vector: Vec<f32> = (0..256).map(|_| normal(&mut random)).collect();
            documents.push((format!("{batch}-{n}"), Article { tags, ..random_article(&mut random) }, vector));
        }
        index.set_many(documents.iter().map(|(id, value, vector)| (id, value, vector))).unwrap();
    }
    maintain(&fixture.store).unwrap();
    let texts: Vec<String> = (0..20).map(|_| words(&mut random, 3) + " bread").collect();
    let questions: Vec<Vec<f32>> = (0..10).map(|_| (0..256).map(|_| normal(&mut random)).collect()).collect();
    let median = |mut took: Vec<f64>| {
        took.sort_by(f64::total_cmp);
        took[took.len() / 2]
    };
    let time = |run: &dyn Fn() -> crate::Result<()>| {
        let started = std::time::Instant::now();
        run().unwrap();
        started.elapsed().as_secs_f64() * 1000.0
    };
    eprintln!("share   words alone  words crossed  vector alone  vector crossed   (ms, median)");
    for share in shares {
        let tag = format!("1/{share}");
        let mut row = Vec::new();
        for narrow in [true, false] {
            NARROW.set(Some(narrow));
            let filter = || crate::search::eq("tags", &tag);
            let took = texts.iter().map(|text| time(&|| index.search(text).filter(filter()).run().map(drop)));
            row.push(median(took.collect()));
            let took = questions.iter().map(|q| time(&|| index.search_vector(q).filter(filter()).run().map(drop)));
            row.push(median(took.collect()));
        }
        NARROW.set(None);
        eprintln!("1/{share:<6} {:>10.2} {:>14.2} {:>13.2} {:>15.2}", row[0], row[2], row[1], row[3]);
    }
}

/// Sets or deletes a random document of the mix, in the index and the model.
fn mixed(index: &Index<Article>, model: &mut Model, random: &mut Random) {
    let id = format!("d{}", random.below(300));
    if random.below(5) == 0 {
        assert_eq!(index.delete(&id).unwrap(), model.docs.remove(&id).is_some());
    } else {
        let value = random_article(random);
        index.set(&id, &value).unwrap();
        model.set(&index.open.settings(), id, value);
    }
}

// contract: SRCH-06
#[test]
fn writes_while_an_index_is_read_again_reach_its_new_rows_and_it_answers_by_them_once_switched() {
    for seed in 0..3 {
        let fixture = fixture();
        fn titles(store: &crate::Store) -> IndexBuilder<'_, Article> {
            store.index::<Article>("mix").field("title", 2.0).typo_tolerance(false)
        }
        let index = titles(&fixture.store).open().unwrap();
        let (mut random, mut model) = (Random::new(seed), Model::default());
        for _ in 0..300 {
            mixed(&index, &mut model, &mut random);
        }
        maintain(&fixture.store).unwrap();
        let both = titles(&fixture.store).field("body", 1.0).open().unwrap();
        for _ in 0..400 {
            match random.below(10) {
                0 => drop(both.search.copy_step(&both.open).unwrap()),
                1 => agrees(&both, &model, &mut random, seed),
                _ => mixed(&both, &mut model, &mut random),
            }
        }
        assert!(matches!(both.status().unwrap(), crate::search::Status::Rebuilding { .. }));
        maintain(&fixture.store).unwrap();
        assert_eq!(both.status().unwrap(), crate::search::Status::Ready { error: None });
        let model = model.read_by(&both.open.settings());
        for _ in 0..40 {
            agrees(&both, &model, &mut random, seed);
        }
        for (id, doc) in &model.docs {
            assert_eq!(both.get(id).unwrap().as_ref(), Some(&doc.value), "seed {seed}: {id}");
        }
    }
}

#[test]
fn an_index_rebuilt_by_hand_refuses_a_change_that_needs_it_until_reindex_asks() {
    use crate::search::Rebuild;
    let fixture = fixture();
    fn manual(store: &crate::Store) -> IndexBuilder<'_, Article> {
        store.index::<Article>("articles").field("title", 2.0).rebuild(Rebuild::Manual)
    }
    let articles = manual(&fixture.store).open().unwrap();
    articles.set("a", &article("bread", "salt")).unwrap();
    let refused = manual(&fixture.store).field("body", 1.0).open().unwrap_err();
    assert_eq!(refused.kind(), ErrorKind::Invalid);
    assert!(refused.to_string().contains("body added"), "{refused}");
    let reindexed = manual(&fixture.store).field("body", 1.0).reindex().unwrap();
    maintain(&fixture.store).unwrap();
    reindexed.ready().unwrap();
    assert_eq!(ids(&search(&reindexed, "salt")), ["a"]);
}

#[test]
fn a_rebuild_that_cannot_read_a_document_fails_and_the_index_answers_as_before() {
    let fixture = fixture();
    let notes = fixture.store.index::<serde_json::Value>("notes").field("title", 1.0).open().unwrap();
    notes.set("n", &serde_json::json!({ "title": "bread", "year": 2024 })).unwrap();
    let years =
        fixture.store.index::<serde_json::Value>("notes").field("title", 1.0).field("year", 1.0).open().unwrap();
    maintain(&fixture.store).unwrap();
    let crate::search::Status::Failed { error } = years.status().unwrap() else { panic!("{:?}", years.status()) };
    assert!(error.contains("field year holds a number"), "{error}");
    assert_eq!(years.ready().unwrap_err().kind(), ErrorKind::Invalid);
    assert_eq!(checked(|| years.search("bread").run()).unwrap().hits.len(), 1, "the index answers as before");
    years.set("m", &serde_json::json!({ "title": "salt" })).unwrap();
    let back = fixture.store.index::<serde_json::Value>("notes").field("title", 1.0).open().unwrap();
    assert_eq!(back.status().unwrap(), crate::search::Status::Failed { error }, "until another change asks");
    let again = fixture.store.index::<serde_json::Value>("notes").field("title", 1.0).reindex().unwrap();
    maintain(&fixture.store).unwrap();
    again.ready().unwrap();
}

#[test]
fn ready_on_a_store_without_background_work_runs_maintenance_itself() {
    let fixture = fixture();
    let titles = fixture.store.index::<Article>("articles").field("title", 2.0).open().unwrap();
    titles.set("a", &article("bread", "salt")).unwrap();
    let bodies = fixture.store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).open().unwrap();
    bodies.ready().unwrap();
    assert_eq!(ids(&search(&bodies, "salt")), ["a"]);
}

/// How many numbers an index has given.
fn numbers_given<T>(index: &Index<T>) -> i64 {
    let id = index.open.id();
    index
        .search
        .file_read(|connection| {
            connection
                .query_row("select next_doc - 1 from _tinystore_search_indexes where id = ?1", [id], |row| row.get(0))
                .map_err(|error| crate::sqlite::sql_error("read numbers", error))
        })
        .unwrap()
}

#[test]
fn an_index_whose_numbers_pass_twice_its_documents_is_numbered_again_and_answers_alike() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    let mut random = Random::new(21);
    for n in 0..600 {
        articles.set(n % 40, &random_article(&mut random)).unwrap();
    }
    let texts: Vec<String> = (0..20).map(|_| words(&mut random, 3)).collect();
    let answers = |articles: &Index<Article>| -> Vec<Found<Article>> {
        texts.iter().map(|text| checked(|| articles.search(text).limit(20).run()).unwrap()).collect()
    };
    let before = answers(&articles);
    assert_eq!(numbers_given(&articles), 600);
    maintain(&fixture.store).unwrap();
    maintain(&fixture.store).unwrap();
    assert_eq!(numbers_given(&articles), 40, "numbered again from 1");
    assert_eq!(answers(&articles), before);
}

// contract: SRCH-06
#[test]
fn an_index_reopened_in_the_middle_of_a_rebuild_goes_on_from_where_it_stood() {
    let fixture = fixture();
    let articles = fixture.store.index::<Article>("articles").field("title", 2.0).open().unwrap();
    let mut random = Random::new(22);
    for n in 0..900 {
        articles.set(n, &random_article(&mut random)).unwrap();
    }
    let both = fixture.store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).open().unwrap();
    both.search.copy_step(&both.open).unwrap();
    let mut images = vec![crash_image(fixture.dir.path())];
    while both.search.copy_step(&both.open).unwrap() {
        images.push(crash_image(fixture.dir.path()));
    }
    let crate::search::Status::Rebuilding { done, .. } = both.status().unwrap() else { panic!() };
    assert!(done > 0.5, "{done}");
    let text = words(&mut random, 3) + " bread";
    maintain(&fixture.store).unwrap();
    let answer = checked(|| both.search(&text).run()).unwrap();
    for image in images {
        let store = open(image.path());
        let reopened = store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).open().unwrap();
        assert!(matches!(reopened.status().unwrap(), crate::search::Status::Rebuilding { .. }));
        maintain(&store).unwrap();
        reopened.ready().unwrap();
        assert_eq!(checked(|| reopened.search(&text).run()).unwrap(), answer);
    }
}

/// Pages search.db holds, and of them those free.
fn pages(dir: &Path) -> (i64, i64) {
    let connection = rusqlite::Connection::open(dir.join("search.db")).unwrap();
    let count = |pragma: &str| connection.query_row(pragma, [], |row| row.get::<_, i64>(0)).unwrap();
    (count("pragma page_count"), count("pragma freelist_count"))
}

#[test]
fn a_dropped_index_gives_its_pages_back_to_the_disk_once_they_stayed_free() {
    use crate::Clock;
    let dir = tempfile::tempdir().unwrap();
    let clock = Arc::new(crate::TestClock::new(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000)));
    let options = crate::Options { clock: Some(clock.clone()), background: false, ..crate::Options::default() };
    let store = crate::Store::open(dir.path(), options).unwrap();
    let old = store.index::<Article>("catalog-v2").field("title", 2.0).field("body", 1.0).open().unwrap();
    let mut random = Random::new(29);
    for start in (0..3000).step_by(500) {
        let articles: Vec<(String, Article)> =
            (start..start + 500).map(|n| (format!("d{n}"), random_article(&mut random))).collect();
        old.set_many(articles.iter().map(|(id, value)| (id.as_str(), value))).unwrap();
    }
    maintain(&store).unwrap();
    let (held, _) = pages(dir.path());
    assert!(store.drop_index("catalog-v2").unwrap());
    maintain(&store).unwrap();
    let (dropped, free) = pages(dir.path());
    assert!(dropped == held && free * 2 > held, "the drop frees its pages and the file keeps them a while");
    clock.set(clock.now() + std::time::Duration::from_mins(11)).unwrap();
    for _ in 0..100 {
        maintain(&store).unwrap();
        if pages(dir.path()).1 == 0 {
            break;
        }
        clock.set(clock.now() + std::time::Duration::from_secs(10)).unwrap();
    }
    let (given, free) = pages(dir.path());
    assert!(given * 2 < held && free == 0, "{held} pages before, {given} after, {free} free");
    drop(store);
}

#[test]
fn a_dropped_index_refuses_its_handles_and_leaves_no_row() {
    let fixture = fixture();
    let articles = fixture.articles::<Article>("articles");
    let kept = fixture.articles::<Article>("kept");
    let mut random = Random::new(23);
    for n in 0..200 {
        articles.set(n, &random_article(&mut random)).unwrap();
        kept.set(n, &random_article(&mut random)).unwrap();
    }
    maintain(&fixture.store).unwrap();
    assert!(fixture.store.drop_index("articles").unwrap());
    assert!(!fixture.store.drop_index("articles").unwrap(), "dropping again finds none");
    assert_eq!(articles.set("x", &article("a", "b")).unwrap_err().kind(), ErrorKind::Invalid);
    assert_eq!(articles.search("bread").run().unwrap_err().kind(), ErrorKind::Invalid);
    maintain(&fixture.store).unwrap();
    let listed = crate::search::list(&fixture.store).unwrap();
    assert_eq!(listed.iter().map(|index| index.name.as_str()).collect::<Vec<_>>(), ["kept"]);
    assert_eq!(listed[0].documents, 200);
    assert!(listed[0].opened.is_some());
    let rows: i64 = kept
        .search
        .file_read(|connection| {
            connection
                .query_row(
                    "select count(*) from _tinystore_search_docs where index_id != ?1",
                    [kept.open.id()],
                    |row| row.get(0),
                )
                .map_err(|error| crate::sqlite::sql_error("count", error))
        })
        .unwrap();
    assert_eq!(rows, 0, "every row of the dropped index is gone");
    let again = fixture.articles::<Article>("articles");
    assert!(search(&again, "bread").hits.is_empty(), "the name opens a new index");
}

/// Waits up to five seconds for `holds`, and says whether it held.
fn holds_soon(holds: impl Fn() -> bool) -> bool {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while !holds() {
        if std::time::Instant::now() > deadline {
            return false;
        }
        std::thread::sleep(std::time::Duration::from_millis(1));
    }
    true
}

/// Holds every reader of `file` until the barrier given back is waited on.
fn every_reader_held(file: &Arc<crate::sqlite::File>) -> (Arc<Barrier>, Vec<JoinHandle<crate::Result<()>>>) {
    let readers = file.readers_at_most();
    let (hold, release) = (Arc::new(Barrier::new(readers + 1)), Arc::new(Barrier::new(readers + 1)));
    let holders = (0..readers)
        .map(|_| {
            let (file, hold, release) = (Arc::clone(file), Arc::clone(&hold), Arc::clone(&release));
            std::thread::spawn(move || {
                file.read(|_| {
                    hold.wait();
                    release.wait();
                    Ok(())
                })
            })
        })
        .collect();
    hold.wait();
    (release, holders)
}

#[test]
fn a_drop_leaves_working_the_index_an_open_made_after_the_drop_committed() {
    let fixture = fixture();
    fixture.articles::<Article>("articles").set("a", &article("Rye", "flour")).unwrap();
    fixture.store.close().unwrap();
    // Opened again, the store finds the index in its file and has it open nowhere.
    let store = open(fixture.dir.path());
    let engine = Arc::clone(&store.index::<Article>("other").field("title", 1.0).open().unwrap().search);
    let writer = engine.file.hold_writer();
    let before = Arc::strong_count(&engine);
    let dropping = {
        let store = store.clone();
        std::thread::spawn(move || store.drop_index("articles"))
    };
    // Holding the engine, the drop finds no index open here, then waits for the writer.
    assert!(holds_soon(|| Arc::strong_count(&engine) > before), "the drop began");
    std::thread::sleep(std::time::Duration::from_millis(200));
    // With every reader held, an open waits for one while it holds the indexes open here.
    let (release, holders) = every_reader_held(&engine.file);
    let opening = {
        let store = store.clone();
        std::thread::spawn(move || store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).open())
    };
    assert!(holds_soon(|| engine.file.readers_waiting() == 1), "the open waits for a reader");
    // The drop commits, then waits for those indexes; the open then reads
    // that no index has the name, and makes a new one.
    drop(writer);
    let beside = rusqlite::Connection::open(fixture.dir.path().join("search.db")).unwrap();
    beside.busy_timeout(std::time::Duration::from_secs(5)).unwrap();
    let named = "select count(*) from _tinystore_search_indexes where name = 'articles'";
    let committed_first = holds_soon(|| beside.query_row(named, [], |row| row.get::<_, i64>(0)).unwrap() == 0);
    drop(beside);
    release.wait();
    holders.into_iter().for_each(|holder| holder.join().unwrap().unwrap());
    let reopened = opening.join().unwrap().unwrap();
    assert!(dropping.join().unwrap().unwrap(), "the drop found the index");
    let works = reopened.set("b", &article("Spelt", "flour")).is_ok();
    let listed = crate::search::list(&store).unwrap().iter().any(|index| index.name == "articles");
    assert_eq!(works, listed, "a handle works while its index is in the file, and only then");
    // A machine too slow to begin the drop first leaves only that to check.
    if committed_first {
        assert!(works, "the open came after the drop's commit: its index is a new one");
        assert_eq!(ids(&search(&reopened, "flour")), ["b"], "and holds nothing of the dropped one's");
    }
}

// contract: SRCH-18
#[test]
fn a_total_counts_every_document_a_search_finds_under_its_filter_whatever_its_page() {
    let fixture = fixture();
    let notes = fixture.store.index::<Article>("notes").field("title", 1.0).filters(["category"]).open().unwrap();
    let note = |n: usize| Article {
        category: Some(if n.is_multiple_of(2) { "even" } else { "odd" }.to_owned()),
        ..article(&format!("bread {} {n}", if n.is_multiple_of(3) { "rye" } else { "wheat" }), "")
    };
    for (round, first) in [0, 1000, 2000].into_iter().enumerate() {
        let notes_of: Vec<(String, Article)> = (first..first + 1000).map(|n| (format!("n{n}"), note(n))).collect();
        notes.set_many(notes_of.iter().map(|(id, note)| (id.as_str(), note))).unwrap();
        if round == 1 {
            maintain(&fixture.store).unwrap();
        }
    }
    for n in [0, 3, 4, 2999] {
        notes.delete(format!("n{n}")).unwrap();
    }
    let gone = |n: usize| [0, 3, 4, 2999].contains(&n);
    let every = |keep: &dyn Fn(usize) -> bool| (0..3000).filter(|n| !gone(*n) && keep(*n)).count() as u64;
    let total = |call: SearchCall<'_, Article>| call.total().run().unwrap().total.unwrap();
    let exactly = |count| Total { count, at_least: false };
    assert_eq!(total(notes.search("bread").limit(1)), exactly(2996), "whatever the page");
    assert_eq!(total(notes.search("rye").offset(990).limit(10)), exactly(every(&|n| n.is_multiple_of(3))));
    assert_eq!(total(notes.search("rye wheat")), exactly(2996), "a document holding both is counted once");
    let even = || crate::search::eq("category", "even");
    assert_eq!(total(notes.search("rye").filter(even())), exactly(every(&|n| n.is_multiple_of(6))), "under its filter");
    assert_eq!(total(notes.search("wheet")), exactly(every(&|n| !n.is_multiple_of(3))), "as its corrected word finds");
    assert_eq!(total(notes.search("whe").prefix()), exactly(every(&|n| !n.is_multiple_of(3))), "as its prefix finds");
    assert_eq!(total(notes.search("rye 1500").prefix_every()), exactly(every(&|n| n.is_multiple_of(3) || n == 1500)));
    assert_eq!(total(notes.search("nothing")), exactly(0));
    let page = notes.search("rye").filter(even()).limit(1000).total().run().unwrap();
    assert_eq!(page.total.unwrap().count, page.hits.len() as u64, "what a page of every hit holds");
    assert_eq!(notes.search("rye").run().unwrap().total, None, "none unless asked");
    let vectors = fixture.store.index::<Article>("vectors").field("title", 1.0).vectors(2).open().unwrap();
    let refused = vectors.search_vector(&[1.0, 0.0]).total().run().unwrap_err();
    assert_eq!(refused.kind(), ErrorKind::Invalid, "a vector finds every document that has one");
}

// contract: SRCH-18
#[test]
fn a_total_past_ten_thousand_says_at_least_ten_thousand_and_one_of_ten_thousand_is_exact() {
    let fixture = fixture();
    let notes = fixture.store.index::<String>("notes").open().unwrap();
    let bread = "bread".to_owned();
    for first in (0..10_000).step_by(1000) {
        notes.set_many((first..first + 1000).map(|n| (format!("n{n}"), &bread))).unwrap();
    }
    let total = || notes.search("bread").total().run().unwrap().total.unwrap();
    assert_eq!(total(), Total { count: 10_000, at_least: false });
    notes.set("n10000", &bread).unwrap();
    assert_eq!(total(), Total { count: 10_000, at_least: true }, "never an estimate");
}