sightingdb 0.5.7

A database designed for Sightings, a technique to count items
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
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};

use chrono::{DateTime, Utc};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};

use crate::attribute::{Attribute, AttributeView};
use crate::db_log::log_attribute;
use crate::tier::{Tier, TierPolicy};

/// Namespace holding every value ever written, used to derive consensus.
pub const ALL_NAMESPACE: &str = "_all";
/// Prefix under which reads are recorded ("shadow sightings").
pub const SHADOW_PREFIX: &str = "_shadow/";
/// Prefix holding the server's own configuration, including API keys.
pub const CONFIG_PREFIX: &str = "_config/";
/// Namespace under which API keys live.
pub const APIKEYS_NAMESPACE: &str = "_config/acl/apikeys/";
/// API key seeded on a fresh database, unless `-k` supplies one.
pub const DEFAULT_APIKEY: &str = "changeme";
/// Bumped whenever the on-disk snapshot layout changes incompatibly.
pub const SNAPSHOT_VERSION: u32 = 1;

/// A lookup that did not resolve, rendered as-is into the JSON body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NotFound {
    pub error: &'static str,
    pub namespace: String,
    pub value: String,
}

impl NotFound {
    pub fn namespace(namespace: &str, value: &str) -> Self {
        Self {
            error: "Path not found",
            namespace: namespace.to_string(),
            value: value.to_string(),
        }
    }

    pub fn value(namespace: &str, value: &str) -> Self {
        Self {
            error: "Value not found",
            namespace: namespace.to_string(),
            value: value.to_string(),
        }
    }
}

/// Retention rules applied to every write. Both default to "keep everything",
/// so an existing deployment does not start discarding data on upgrade.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DatabasePolicy {
    /// Hourly statistics buckets kept per attribute; 0 keeps all of them.
    pub stats_retention: usize,
    /// TTL applied to shadow sightings; 0 means they never expire.
    pub shadow_ttl: u64,
}

/// How a single write should behave.
#[derive(Debug, Clone, Copy, Default)]
pub struct WriteOpts {
    /// Count this value towards consensus in [`ALL_NAMESPACE`].
    pub consensus: bool,
    /// Set the attribute's TTL. `None` leaves whatever it already had.
    pub ttl: Option<u64>,
}

/// One namespace as the management interface sees it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NamespaceEntry {
    pub namespace: String,
    /// The top-level namespace, which is what a tier applies to.
    pub shard: String,
    pub tier: String,
    pub resident: bool,
}

/// One step down the namespace tree, as the management interface browses it.
///
/// A path can be both at once: `myorg` may hold values of its own and still
/// have `myorg/feeds` underneath it, the way a directory holds files as well as
/// subdirectories.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TreeEntry {
    /// The path segment, which is what a row is labelled with.
    pub name: String,
    /// The whole path, which is what the row links to.
    pub path: String,
    /// Whether the path is a namespace in its own right, and so may hold values.
    pub namespace: bool,
    /// Namespaces below this one, so a folder can say how much is inside it.
    pub descendants: usize,
    /// The top-level namespace, which is what a tier applies to.
    pub shard: String,
    pub tier: String,
    pub resident: bool,
}

/// One namespace a value has been seen in, for the relationship view.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Sighting {
    pub namespace: String,
    /// The top-level namespace, which is what colours a cluster.
    pub shard: String,
    pub count: u64,
    pub first_seen: i64,
    pub last_seen: i64,
}

/// Everywhere one value was found, and what the search cost.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Default)]
pub struct Sightings {
    pub items: Vec<Sighting>,
    /// True when the search stopped at the limit, so there may be more.
    pub truncated: bool,
    /// True when finding them all meant reading shards back from disk.
    pub paged_in: bool,
}

/// A slice of a listing, with the total so a caller can page through it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Page<T> {
    pub items: Vec<T>,
    /// Matches before paging, not the number returned.
    pub total: usize,
    pub offset: usize,
}

/// What an eviction pass did.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct EvictReport {
    pub evicted: usize,
    /// Still in use by a request, so left for the next sweep.
    pub busy: usize,
    /// Could not be written out, so deliberately kept in memory.
    pub failed: usize,
}

impl EvictReport {
    pub fn is_empty(&self) -> bool {
        self.evicted == 0 && self.busy == 0 && self.failed == 0
    }
}

/// What a sweep reclaimed.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SweepReport {
    pub values_removed: usize,
    pub namespaces_removed: usize,
}

impl SweepReport {
    pub fn is_empty(&self) -> bool {
        self.values_removed == 0 && self.namespaces_removed == 0
    }
}

/// One namespace's values.
///
/// Values are behind their own mutex so that concurrent writes to *different*
/// values in the same namespace do not contend: the map lock is only taken for
/// writing when a value is seen for the first time.
#[derive(Default)]
struct Namespace {
    values: RwLock<HashMap<String, Mutex<Attribute>>>,
    /// Set once any attribute here is given a TTL, so that sweeps can skip
    /// namespaces that can never expire — which is all of them by default.
    has_ttl: AtomicBool,
}

impl Namespace {
    fn from_values(values: HashMap<String, Attribute>) -> Self {
        let has_ttl = values.values().any(|attr| attr.ttl > 0);
        Self {
            values: RwLock::new(
                values
                    .into_iter()
                    .map(|(value, attr)| (value, Mutex::new(attr)))
                    .collect(),
            ),
            has_ttl: AtomicBool::new(has_ttl),
        }
    }

    /// Record a sighting, reporting the new count, whether this was the first
    /// time the value appeared here, and a snapshot for the write log.
    fn record(
        &self,
        value: &str,
        when: DateTime<Utc>,
        ttl: Option<u64>,
        retention: usize,
        tags: &str,
    ) -> (u64, bool, AttributeView) {
        if ttl.is_some_and(|ttl| ttl > 0) {
            self.has_ttl.store(true, Ordering::Relaxed);
        }

        // Fast path: the value already exists, so a read lock is enough and
        // other values in this namespace stay writable.
        {
            let values = self.values.read().unwrap_or_else(PoisonError::into_inner);
            if let Some(cell) = values.get(value) {
                let mut attr = cell.lock().unwrap_or_else(PoisonError::into_inner);
                if let Some(ttl) = ttl {
                    attr.set_ttl(ttl);
                }
                if !tags.is_empty() {
                    attr.add_tags(tags);
                }
                attr.increment(when, retention);
                return (attr.count(), false, attr.view(0, false));
            }
        }

        // Slow path: first sighting of this value here. Deciding "is this new?"
        // under the write lock is what keeps consensus from being double
        // counted when two writers race.
        let mut values = self.values.write().unwrap_or_else(PoisonError::into_inner);
        let is_new = !values.contains_key(value);
        let cell = values
            .entry(value.to_string())
            .or_insert_with(|| Mutex::new(Attribute::new(value)));
        // We hold the map's write lock, so the mutex needs no locking here.
        let attr = cell.get_mut().unwrap_or_else(PoisonError::into_inner);
        if let Some(ttl) = ttl {
            attr.set_ttl(ttl);
        }
        if !tags.is_empty() {
            attr.add_tags(tags);
        }
        attr.increment(when, retention);
        (attr.count(), is_new, attr.view(0, false))
    }

    /// An expired attribute is invisible to readers even before the sweeper
    /// gets round to reclaiming it.
    fn view(
        &self,
        value: &str,
        consensus: u64,
        with_stats: bool,
        now: DateTime<Utc>,
    ) -> Option<AttributeView> {
        let values = self.values.read().unwrap_or_else(PoisonError::into_inner);
        let cell = values.get(value)?;
        let attr = cell.lock().unwrap_or_else(PoisonError::into_inner);
        (!attr.is_expired(now)).then(|| attr.view(consensus, with_stats))
    }

    fn count(&self, value: &str, now: DateTime<Utc>) -> u64 {
        let values = self.values.read().unwrap_or_else(PoisonError::into_inner);
        values.get(value).map_or(0, |cell| {
            let attr = cell.lock().unwrap_or_else(PoisonError::into_inner);
            if attr.is_expired(now) {
                0
            } else {
                attr.count()
            }
        })
    }

    /// Every live value here, with a placeholder consensus the caller fills in
    /// afterwards — see the lock-ordering note on [`Database`].
    fn all_views(&self, with_stats: bool, now: DateTime<Utc>) -> Vec<AttributeView> {
        let values = self.values.read().unwrap_or_else(PoisonError::into_inner);
        values
            .values()
            .filter_map(|cell| {
                let attr = cell.lock().unwrap_or_else(PoisonError::into_inner);
                (!attr.is_expired(now)).then(|| attr.view(0, with_stats))
            })
            .collect()
    }

    /// Drop expired attributes, returning the values that went.
    fn remove_expired(&self, now: DateTime<Utc>) -> Vec<String> {
        // Nothing here has ever had a TTL, so nothing here can expire.
        if !self.has_ttl.load(Ordering::Relaxed) {
            return Vec::new();
        }

        // Check under a read lock first: sweeps usually find nothing, and
        // taking the write lock would block every reader of this namespace.
        {
            let values = self.values.read().unwrap_or_else(PoisonError::into_inner);
            let any_expired = values.values().any(|cell| {
                cell.lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .is_expired(now)
            });
            if !any_expired {
                return Vec::new();
            }
        }

        let mut values = self.values.write().unwrap_or_else(PoisonError::into_inner);
        let mut removed = Vec::new();
        values.retain(|value, cell| {
            let expired = cell
                .get_mut()
                .unwrap_or_else(PoisonError::into_inner)
                .is_expired(now);
            if expired {
                removed.push(value.clone());
            }
            !expired
        });
        removed
    }

    /// Replace one value's tag set, reporting whether the value was there.
    fn retag(&self, value: &str, tags: &str, now: DateTime<Utc>) -> bool {
        let values = self.values.read().unwrap_or_else(PoisonError::into_inner);
        let Some(cell) = values.get(value) else {
            return false;
        };
        let mut attr = cell.lock().unwrap_or_else(PoisonError::into_inner);
        if attr.is_expired(now) {
            return false;
        }
        attr.set_tags(tags);
        true
    }

    /// Give back one consensus count, dropping the entry when it reaches zero.
    /// Done under the write lock so a concurrent write cannot resurrect a value
    /// between the decrement and the removal.
    fn release(&self, value: &str) {
        let mut values = self.values.write().unwrap_or_else(PoisonError::into_inner);
        let Some(cell) = values.get_mut(value) else {
            return;
        };
        let remaining = cell
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner)
            .decrement();
        if remaining == 0 {
            values.remove(value);
        }
    }

    /// The values stored here, live or not, for consensus bookkeeping on delete.
    fn value_names(&self) -> Vec<String> {
        self.values
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .keys()
            .cloned()
            .collect()
    }

    fn is_empty(&self) -> bool {
        self.values
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .is_empty()
    }
}

/// In-memory store: namespace -> value -> attribute.
///
/// Every method takes `&self`; there is no global lock. Namespaces are handed
/// out as `Arc`s so the outer map's lock is released before any value is
/// touched.
///
/// **Lock ordering:** outer map, then a namespace's value map, then a single
/// attribute — and never two namespaces at once. Anything needing a second
/// namespace (consensus lives in `_all`) must finish with the first one before
/// reaching for it, or two writers can deadlock.
/// What is known about a shard, whether or not its data is in memory.
#[derive(Debug, Default, Clone)]
struct ShardMeta {
    /// Namespace names belonging to this shard. Kept even while evicted, so
    /// the management interface can list namespaces without paging data in.
    namespaces: HashSet<String>,
    resident: bool,
    /// Unix seconds of the last read or write.
    last_access: i64,
}

/// Where shards are read from and written to when they are paged in and out.
#[derive(Debug, Clone)]
pub struct Store {
    pub dbdir: PathBuf,
    pub level: i32,
}

#[derive(Default)]
pub struct Database {
    namespaces: RwLock<HashMap<String, Arc<Namespace>>>,
    policy: DatabasePolicy,
    /// Shards written to since the last save, so a snapshot costs what changed
    /// rather than what exists.
    dirty: Mutex<HashSet<String>>,
    /// Catalogue of shards, resident or not.
    shards: RwLock<HashMap<String, ShardMeta>>,
    /// Set once persistence is configured; without it nothing is ever evicted,
    /// because there would be nowhere to put it.
    store: RwLock<Option<Store>>,
    tiers: RwLock<TierPolicy>,
}

impl Database {
    /// A database with the default (keep-everything) policy. Production code
    /// always has a policy to hand and calls [`Database::with_policy`].
    #[cfg(test)]
    pub fn new() -> Database {
        Database::with_policy(DatabasePolicy::default())
    }

    pub fn with_policy(policy: DatabasePolicy) -> Database {
        Database {
            namespaces: RwLock::new(HashMap::new()),
            policy,
            dirty: Mutex::new(HashSet::new()),
            shards: RwLock::new(HashMap::new()),
            store: RwLock::new(None),
            tiers: RwLock::new(TierPolicy::default()),
        }
    }

    /// Rebuild a database from a snapshot. No API key is seeded here: the
    /// snapshot carries whatever keys were registered when it was written.
    pub fn from_snapshot(data: SnapshotData, policy: DatabasePolicy) -> Database {
        let namespaces: HashMap<String, Arc<Namespace>> = data
            .namespaces
            .into_iter()
            .map(|(name, values)| (name, Arc::new(Namespace::from_values(values))))
            .collect();

        let mut shards: HashMap<String, ShardMeta> = HashMap::new();
        let seen = now_secs();
        for name in namespaces.keys() {
            let meta = shards
                .entry(crate::persistence::shard_of(name).to_string())
                .or_default();
            meta.namespaces.insert(name.clone());
            meta.resident = true;
            meta.last_access = seen;
        }

        Database {
            namespaces: RwLock::new(namespaces),
            policy,
            dirty: Mutex::new(HashSet::new()),
            shards: RwLock::new(shards),
            store: RwLock::new(None),
            tiers: RwLock::new(TierPolicy::default()),
        }
    }

    /// API keys found in a snapshot written by an older build, which stored
    /// them as `_config/acl/apikeys/<key>` namespaces.
    ///
    /// Permissions now come from the configuration instead; this exists only so
    /// that upgrading does not lock an existing deployment out of its own data.
    pub fn legacy_apikeys(&self) -> Vec<String> {
        self.namespaces
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .keys()
            .filter_map(|name| name.strip_prefix(APIKEYS_NAMESPACE))
            .filter(|key| !key.is_empty())
            .map(String::from)
            .collect()
    }

    /// Record one sighting of `value` in `path` at `when`, returning the new count.
    ///
    /// When `opts.consensus` is set, the value is also counted in
    /// [`ALL_NAMESPACE`] — but only the *first* time it appears in this
    /// namespace, since consensus means "how many namespaces have seen this
    /// value", not "how many times was it written".
    pub fn write(&self, path: &str, value: &str, when: DateTime<Utc>, opts: WriteOpts) -> u64 {
        self.write_tagged(path, value, when, opts, "")
    }

    /// A sighting that also carries what is known about the value.
    ///
    /// Tags are merged into whatever the value already had, in the same lock as
    /// the sighting itself: an importer contributing `stix-type:ipv4-addr` and
    /// a writer contributing `tlp:amber` both end up on the value, and neither
    /// write can be lost to the other. See [`crate::attribute::split_tags`] for
    /// the format.
    pub fn write_tagged(
        &self,
        path: &str,
        value: &str,
        when: DateTime<Utc>,
        opts: WriteOpts,
        tags: &str,
    ) -> u64 {
        // Shadow sightings get their retention from policy rather than from the
        // caller, which is what bounds `_shadow/*` growth.
        let ttl = match opts.ttl {
            Some(ttl) => Some(ttl),
            None if path.starts_with(SHADOW_PREFIX) && self.policy.shadow_ttl > 0 => {
                Some(self.policy.shadow_ttl)
            }
            None => None,
        };

        let namespace = self.namespace_or_create(path);
        let (count, is_new, mut view) =
            namespace.record(value, when, ttl, self.policy.stats_retention, tags);

        // The namespace's locks are released by now, so reaching into `_all`
        // here respects the ordering rule above.
        if opts.consensus && is_new {
            self.write(ALL_NAMESPACE, value, when, WriteOpts::default());
        }

        view.consensus = self.count(ALL_NAMESPACE, value);
        log_attribute(path, &view);
        self.mark_dirty(path);

        count
    }

    /// Replace a value's tags outright, which is how a wrong one comes off.
    ///
    /// This is not a sighting: nothing is counted, and `first_seen` and
    /// `last_seen` do not move. Returns false if the value is not there.
    pub fn set_tags(&self, path: &str, value: &str, tags: &str) -> bool {
        let Some(namespace) = self.namespace(path) else {
            return false;
        };
        let changed = namespace.retag(value, tags, Utc::now());
        if changed {
            self.mark_dirty(path);
        }
        changed
    }

    pub fn view(
        &self,
        path: &str,
        value: &str,
        consensus: u64,
        with_stats: bool,
    ) -> Option<AttributeView> {
        self.namespace(path)?
            .view(value, consensus, with_stats, Utc::now())
    }

    pub fn count(&self, path: &str, value: &str) -> u64 {
        let now = Utc::now();
        self.namespace(path)
            .map_or(0, |namespace| namespace.count(value, now))
    }

    /// Whether a namespace exists at all, resident or evicted.
    pub fn namespace_exists(&self, namespace: &str) -> bool {
        if self
            .namespaces
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .contains_key(namespace)
        {
            return true;
        }
        self.shards
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .get(crate::persistence::shard_of(namespace))
            .is_some_and(|meta| meta.namespaces.contains(namespace))
    }

    /// Every live attribute stored in `namespace`, or `None` if it does not exist.
    ///
    /// Consensus is filled in only after the namespace's lock has been dropped,
    /// so that this never holds two namespaces at once.
    pub fn namespace_views(&self, namespace: &str) -> Option<Vec<AttributeView>> {
        let mut views = self.namespace(namespace)?.all_views(false, Utc::now());
        for view in &mut views {
            view.consensus = self.count(ALL_NAMESPACE, &view.value);
        }
        Some(views)
    }

    /// Drop a namespace, giving back the consensus its values were holding.
    pub fn delete(&self, name: &str) -> bool {
        let Some(namespace) = self.namespace(name) else {
            return false;
        };
        let values = namespace.value_names();
        drop(namespace);

        let removed = self
            .namespaces
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(name)
            .is_some();

        if removed {
            self.mark_dirty(name);
            if let Some(meta) = self
                .shards
                .write()
                .unwrap_or_else(PoisonError::into_inner)
                .get_mut(crate::persistence::shard_of(name))
            {
                meta.namespaces.remove(name);
            }
        }
        if removed && counts_towards_consensus(name) {
            for value in values {
                self.release_consensus(&value);
            }
        }
        removed
    }

    /// Reclaim expired attributes and the namespaces left empty by them.
    pub fn sweep(&self, now: DateTime<Utc>) -> SweepReport {
        let entries: Vec<(String, Arc<Namespace>)> = {
            let map = self
                .namespaces
                .read()
                .unwrap_or_else(PoisonError::into_inner);
            map.iter()
                .map(|(name, namespace)| (name.clone(), Arc::clone(namespace)))
                .collect()
        };

        let mut report = SweepReport::default();
        // Namespaces this pass emptied, which are the only ones it may reclaim.
        let mut emptied: Vec<String> = Vec::new();
        for (name, namespace) in &entries {
            // API keys have no TTL and must never be swept out from under the ACL.
            if name.starts_with(CONFIG_PREFIX) {
                continue;
            }

            let expired = namespace.remove_expired(now);
            if !expired.is_empty() {
                self.mark_dirty(name);
                if namespace.is_empty() {
                    emptied.push(name.clone());
                }
            }
            report.values_removed += expired.len();

            if counts_towards_consensus(name) {
                for value in expired {
                    self.release_consensus(&value);
                }
            }
        }

        // Our own handles must go before pruning, or `strong_count` below would
        // see them and conclude every namespace is still in use.
        drop(entries);
        report.namespaces_removed = self.prune_empty(&emptied);
        report
    }

    /// Note that a shard is dirty, so the next save rewrites it.
    pub fn mark_dirty(&self, namespace: &str) {
        self.mark_shard_dirty(crate::persistence::shard_of(namespace));
    }

    pub fn mark_shard_dirty(&self, shard: &str) {
        self.dirty
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(shard.to_string());
    }

    /// Take the dirty set, leaving it empty. A failed save puts its shard back.
    pub fn take_dirty(&self) -> HashSet<String> {
        std::mem::take(&mut *self.dirty.lock().unwrap_or_else(PoisonError::into_inner))
    }

    /// Every shard that currently holds a namespace.
    pub fn shards(&self) -> HashSet<String> {
        self.namespaces
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .keys()
            .map(|name| crate::persistence::shard_of(name).to_string())
            .collect()
    }

    /// A borrowed, streaming view of one shard.
    pub fn shard_snapshot<'a>(&'a self, shard: &'a str) -> ShardSnapshot<'a> {
        ShardSnapshot(self, shard)
    }

    /// A borrowed, streaming view of the whole database. Shards are what gets
    /// written now; this remains for tests and for comparing against the
    /// single-file format.
    #[cfg(test)]
    pub fn snapshot(&self) -> Snapshot<'_> {
        Snapshot(self)
    }

    pub fn namespace_count(&self) -> usize {
        self.shards
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .values()
            .map(|meta| meta.namespaces.len())
            .sum()
    }

    /// Namespace names matching `filter`, sorted, one page at a time.
    ///
    /// `_config` (server state) and `_all` (the consensus tally) are left out:
    /// they are bookkeeping, not data anyone browses. `_shadow/*` is kept,
    /// since what was searched for is genuinely interesting.
    /// `allowed` decides which namespaces the caller may even know about, so a
    /// key scoped to one subtree does not learn the names of the others.
    pub fn namespace_page(
        &self,
        filter: &str,
        offset: usize,
        limit: usize,
        allowed: impl Fn(&str) -> bool,
    ) -> Page<NamespaceEntry> {
        let filter = filter.to_ascii_lowercase();

        // The catalogue, not the resident map: an evicted namespace still
        // exists and must still be listed.
        let shards = self.shards.read().unwrap_or_else(PoisonError::into_inner);
        let mut names: Vec<&String> = shards
            .values()
            .flat_map(|meta| meta.namespaces.iter())
            .filter(|name| !name.starts_with(CONFIG_PREFIX) && *name != ALL_NAMESPACE)
            .filter(|name| filter.is_empty() || name.to_ascii_lowercase().contains(&filter))
            .filter(|name| allowed(name))
            .collect();
        names.sort_unstable();
        names.dedup();

        let total = names.len();
        let tiers = self.tiers.read().unwrap_or_else(PoisonError::into_inner);
        let items = names
            .into_iter()
            .skip(offset)
            .take(limit)
            .map(|name| {
                let shard = crate::persistence::shard_of(name);
                NamespaceEntry {
                    namespace: name.clone(),
                    shard: shard.to_string(),
                    tier: tiers.tier_of(shard).as_str().to_string(),
                    resident: shards.get(shard).is_some_and(|meta| meta.resident),
                }
            })
            .collect();

        Page {
            items,
            total,
            offset,
        }
    }

    /// Declare a namespace before anything has been written to it, so the
    /// management interface can make one the way a file browser makes a folder.
    ///
    /// Returns false if it already exists. Nothing else is needed to make it
    /// last: an empty namespace is written to its shard like any other, and
    /// sweeps only reclaim namespaces they emptied themselves.
    pub fn create_namespace(&self, name: &str) -> bool {
        if self.namespace_exists(name) {
            return false;
        }
        // Held only long enough to register it; the handle must not outlive
        // this call or a sweep would take it for a namespace in use.
        drop(self.namespace_or_create(name));
        self.mark_dirty(name);
        true
    }

    /// One level of the namespace tree: what sits directly under `prefix`.
    ///
    /// Namespaces are flat paths in the database — `feeds/misp/ips` is a name,
    /// not a nesting — so the tree is derived here by grouping on the segment
    /// that follows the prefix. The same exclusions as [`Database::namespace_page`]
    /// apply, and `allowed` decides which names the caller may know about, so a
    /// folder whose whole contents are out of reach is not even listed.
    pub fn namespace_children(
        &self,
        prefix: &str,
        filter: &str,
        offset: usize,
        limit: usize,
        allowed: impl Fn(&str) -> bool,
    ) -> Page<TreeEntry> {
        let prefix = prefix.trim_matches('/');
        let filter = filter.to_ascii_lowercase();

        // (is a namespace itself, namespaces below it)
        let mut children: HashMap<&str, (bool, usize)> = HashMap::new();
        let shards = self.shards.read().unwrap_or_else(PoisonError::into_inner);
        for name in shards
            .values()
            .flat_map(|meta| meta.namespaces.iter())
            .filter(|name| !name.starts_with(CONFIG_PREFIX) && *name != ALL_NAMESPACE)
            .filter(|name| allowed(name))
        {
            let rest = if prefix.is_empty() {
                name.as_str()
            } else if let Some(rest) = name.strip_prefix(prefix).and_then(|r| r.strip_prefix('/')) {
                rest
            } else {
                // Either unrelated, or the prefix itself: neither is a child.
                continue;
            };
            let segment = rest.split('/').next().unwrap_or("");
            if segment.is_empty() {
                continue;
            }

            let entry = children.entry(segment).or_insert((false, 0));
            if segment.len() == rest.len() {
                entry.0 = true;
            } else {
                entry.1 += 1;
            }
        }

        let mut names: Vec<&str> = children
            .keys()
            .copied()
            .filter(|name| filter.is_empty() || name.to_ascii_lowercase().contains(&filter))
            .collect();
        names.sort_unstable();

        let total = names.len();
        let tiers = self.tiers.read().unwrap_or_else(PoisonError::into_inner);
        let items = names
            .into_iter()
            .skip(offset)
            .take(limit)
            .map(|name| {
                let path = if prefix.is_empty() {
                    name.to_string()
                } else {
                    format!("{prefix}/{name}")
                };
                let (namespace, descendants) = children[name];
                let shard = crate::persistence::shard_of(&path);
                TreeEntry {
                    name: name.to_string(),
                    namespace,
                    descendants,
                    shard: shard.to_string(),
                    tier: tiers.tier_of(shard).as_str().to_string(),
                    resident: shards.get(shard).is_some_and(|meta| meta.resident),
                    path,
                }
            })
            .collect();

        Page {
            items,
            total,
            offset,
        }
    }

    /// Every namespace holding `value`, so the interface can draw what a value
    /// relates to rather than only where you happened to click.
    ///
    /// The cost is one lookup per namespace, so the search is arranged to do as
    /// little of it as possible. `_all` already knows how many namespaces hold
    /// the value, which gives a target to stop at; namespaces already in memory
    /// are searched first, and evicted shards are read back only if the target
    /// has not been reached by then. A value in two namespaces out of a hundred
    /// thousand therefore normally touches the disk not at all.
    ///
    /// `allowed` decides which namespaces the caller may know about, exactly as
    /// when browsing. A hidden namespace is still counted towards the target,
    /// or a scoped key would drive the search to read the whole database.
    ///
    /// `_shadow/*` is left out. It records what was *searched* for rather than
    /// what was seen, does not count towards consensus, and including it would
    /// make the result depend on where the search happened to stop.
    pub fn sightings_of(
        &self,
        value: &str,
        limit: usize,
        allowed: impl Fn(&str) -> bool,
    ) -> Sightings {
        let target = self.count(ALL_NAMESPACE, value);

        // Resident first, so the common case never goes near the disk.
        let (resident, evicted): (Vec<String>, Vec<String>) = {
            let shards = self.shards.read().unwrap_or_else(PoisonError::into_inner);
            let mut resident = Vec::new();
            let mut evicted = Vec::new();
            for meta in shards.values() {
                for name in &meta.namespaces {
                    if !counts_towards_consensus(name) {
                        continue;
                    }
                    if meta.resident {
                        resident.push(name.clone());
                    } else {
                        evicted.push(name.clone());
                    }
                }
            }
            (resident, evicted)
        };

        let mut found = Sightings::default();
        // Namespaces holding the value, visible to this caller or not, counted
        // against `target`.
        let mut seen = 0u64;

        'search: for (names, from_disk) in [(resident, false), (evicted, true)] {
            for name in names {
                // Everything is accounted for; the rest cannot hold the value.
                if target > 0 && seen >= target {
                    break 'search;
                }
                let Some(view) = self.view(&name, value, 0, false) else {
                    continue;
                };
                if from_disk {
                    found.paged_in = true;
                }
                seen += 1;
                if !allowed(&name) {
                    continue;
                }
                if found.items.len() >= limit {
                    found.truncated = true;
                    break 'search;
                }
                found.items.push(Sighting {
                    shard: crate::persistence::shard_of(&name).to_string(),
                    namespace: name,
                    count: view.count,
                    first_seen: view.first_seen,
                    last_seen: view.last_seen,
                });
            }
        }

        found.items.sort_by(|a, b| a.namespace.cmp(&b.namespace));
        found
    }

    /// Change a shard's tier, taking effect at once.
    ///
    /// Promoting to `hot` does not load anything: the shard is paged in when
    /// it is next used, as it would have been anyway.
    pub fn set_tier(&self, shard: &str, tier: Tier) {
        self.tiers
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .shards
            .insert(shard.to_string(), tier);
    }

    /// The current policy, for writing back to disk.
    pub fn tier_policy(&self) -> TierPolicy {
        self.tiers
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Values inside one namespace, sorted, one page at a time.
    ///
    /// Only the page's attributes are cloned. The sort is still O(n log n) over
    /// the namespace, which is the price of stable paging over a hash map — a
    /// namespace with millions of values will feel it.
    pub fn value_page(
        &self,
        namespace: &str,
        filter: &str,
        offset: usize,
        limit: usize,
        with_stats: bool,
    ) -> Option<Page<AttributeView>> {
        let now = Utc::now();
        let filter = filter.to_ascii_lowercase();
        let ns = self.namespace(namespace)?;
        let values = ns.values.read().unwrap_or_else(PoisonError::into_inner);

        let mut matching: Vec<&String> = values
            .iter()
            .filter(|(value, _)| filter.is_empty() || value.to_ascii_lowercase().contains(&filter))
            .filter(|(_, cell)| {
                !cell
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .is_expired(now)
            })
            .map(|(value, _)| value)
            .collect();
        matching.sort_unstable();

        let total = matching.len();
        let items: Vec<AttributeView> = matching
            .into_iter()
            .skip(offset)
            .take(limit)
            .filter_map(|value| {
                let attr = values
                    .get(value)?
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner);
                Some(attr.view(0, with_stats))
            })
            .collect();
        drop(values);

        // Consensus comes from `_all`, so fill it in once this namespace is
        // released — see the lock-ordering note above.
        let items = items
            .into_iter()
            .map(|mut view| {
                view.consensus = self.count(ALL_NAMESPACE, &view.value);
                view
            })
            .collect();

        Some(Page {
            items,
            total,
            offset,
        })
    }

    /// Tell the database where shards live, which is what makes eviction
    /// possible: without somewhere to put a shard, it can never leave memory.
    pub fn attach_store(&self, store: Store, tiers: TierPolicy) {
        *self.store.write().unwrap_or_else(PoisonError::into_inner) = Some(store);
        *self.tiers.write().unwrap_or_else(PoisonError::into_inner) = tiers;
    }

    #[cfg(test)]
    pub fn is_shard_resident(&self, shard: &str) -> bool {
        self.shards
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .get(shard)
            .is_some_and(|meta| meta.resident)
    }

    /// How many shards are in memory, out of how many exist.
    pub fn residency(&self) -> (usize, usize) {
        let shards = self.shards.read().unwrap_or_else(PoisonError::into_inner);
        (shards.values().filter(|m| m.resident).count(), shards.len())
    }

    /// Read a shard back into memory.
    ///
    /// Two requests can race here; the second finds the shard already resident
    /// and does nothing rather than loading it twice.
    fn page_in(&self, shard: &str) -> anyhow::Result<()> {
        let store = self
            .store
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        let Some(store) = store else {
            return Ok(());
        };

        // Held across the load so a second caller waits rather than duplicating
        // the work, and so nothing observes a half-populated shard.
        let mut namespaces = self
            .namespaces
            .write()
            .unwrap_or_else(PoisonError::into_inner);
        {
            let shards = self.shards.read().unwrap_or_else(PoisonError::into_inner);
            if shards.get(shard).is_some_and(|meta| meta.resident) {
                return Ok(());
            }
        }

        let data = crate::persistence::read_shard_file(&store.dbdir, shard)?;
        let mut names = HashSet::new();
        for (name, values) in data {
            names.insert(name.clone());
            namespaces.insert(name, Arc::new(Namespace::from_values(values)));
        }
        drop(namespaces);

        let mut shards = self.shards.write().unwrap_or_else(PoisonError::into_inner);
        let meta = shards.entry(shard.to_string()).or_default();
        meta.namespaces.extend(names);
        meta.resident = true;
        meta.last_access = now_secs();

        log::debug!("Paged in shard '{shard}'");
        Ok(())
    }

    /// Write out and drop shards that have been idle longer than their tier
    /// allows.
    ///
    /// A dirty shard is always saved first: dropping it otherwise would lose
    /// everything written since the last snapshot.
    pub fn evict_idle(&self, now: i64) -> EvictReport {
        let store = self
            .store
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        let Some(store) = store else {
            return EvictReport::default();
        };
        let tiers = self
            .tiers
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();

        let candidates: Vec<String> = {
            let shards = self.shards.read().unwrap_or_else(PoisonError::into_inner);
            shards
                .iter()
                .filter(|(_, meta)| meta.resident)
                .filter(|(shard, meta)| match tiers.idle_allowance(shard) {
                    None => false,
                    Some(allowance) => {
                        now.saturating_sub(meta.last_access) >= allowance.as_secs() as i64
                    }
                })
                .map(|(shard, _)| shard.clone())
                .collect()
        };

        let mut report = EvictReport::default();
        for shard in candidates {
            if self
                .dirty
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .contains(&shard)
                && let Err(e) =
                    crate::persistence::save_shard(self, &store.dbdir, &shard, store.level)
            {
                // Keep it in memory rather than lose it.
                log::error!("Not evicting '{shard}': could not save it: {e:#}");
                report.failed += 1;
                continue;
            }
            self.dirty
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .remove(&shard);

            if self.drop_shard(&shard) {
                report.evicted += 1;
            } else {
                report.busy += 1;
            }
        }

        report
    }

    /// Remove a shard's namespaces from memory. Returns false if anything is
    /// still holding one, in which case it stays for the next sweep.
    fn drop_shard(&self, shard: &str) -> bool {
        let mut namespaces = self
            .namespaces
            .write()
            .unwrap_or_else(PoisonError::into_inner);

        let mine: Vec<String> = namespaces
            .keys()
            .filter(|name| crate::persistence::shard_of(name) == shard)
            .cloned()
            .collect();

        // A writer that already took an `Arc` would otherwise record its
        // sighting into an orphan and lose it.
        if mine.iter().any(|name| {
            namespaces
                .get(name)
                .is_some_and(|ns| Arc::strong_count(ns) > 1)
        }) {
            return false;
        }
        for name in &mine {
            namespaces.remove(name);
        }
        drop(namespaces);

        if let Some(meta) = self
            .shards
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .get_mut(shard)
        {
            meta.resident = false;
        }
        log::debug!("Evicted shard '{shard}'");
        true
    }

    fn release_consensus(&self, value: &str) {
        if let Some(all) = self.namespace(ALL_NAMESPACE) {
            all.release(value);
        }
    }

    /// Reclaim the namespaces a sweep has just emptied.
    ///
    /// Only those are candidates. An empty namespace is not litter by itself:
    /// one created through the management interface exists before anything is
    /// written to it, the way a new directory does, and must survive until it
    /// is deleted.
    fn prune_empty(&self, emptied: &[String]) -> usize {
        if emptied.is_empty() {
            return 0;
        }

        let mut removed: Vec<&str> = Vec::new();
        {
            let mut map = self
                .namespaces
                .write()
                .unwrap_or_else(PoisonError::into_inner);
            for name in emptied {
                if name.starts_with(CONFIG_PREFIX) {
                    continue;
                }
                // Only drop a namespace nobody else is holding: a writer that
                // already took an `Arc` would otherwise record its sighting into
                // an orphaned namespace and lose it. A write between the sweep
                // and here leaves it non-empty again, so check that too.
                let gone = map.get(name).is_some_and(|namespace| {
                    Arc::strong_count(namespace) == 1 && namespace.is_empty()
                });
                if gone {
                    map.remove(name);
                    removed.push(name);
                }
            }
        }

        if !removed.is_empty() {
            let mut shards = self.shards.write().unwrap_or_else(PoisonError::into_inner);
            for name in &removed {
                if let Some(meta) = shards.get_mut(crate::persistence::shard_of(name)) {
                    meta.namespaces.remove(*name);
                }
            }
        }
        removed.len()
    }

    /// Fetch a namespace, paging its shard in from disk if it has been evicted.
    fn namespace(&self, name: &str) -> Option<Arc<Namespace>> {
        let shard = crate::persistence::shard_of(name);
        self.touch(shard);

        if let Some(namespace) = self.resident(name) {
            return Some(namespace);
        }
        // Only worth going to disk if the catalogue says this shard holds it.
        if !self.catalogued(shard, name) {
            return None;
        }
        if let Err(e) = self.page_in(shard) {
            log::error!("Could not load shard '{shard}': {e:#}");
            return None;
        }
        self.resident(name)
    }

    fn resident(&self, name: &str) -> Option<Arc<Namespace>> {
        self.namespaces
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .get(name)
            .cloned()
    }

    fn catalogued(&self, shard: &str, name: &str) -> bool {
        self.shards
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .get(shard)
            .is_some_and(|meta| !meta.resident && meta.namespaces.contains(name))
    }

    fn namespace_or_create(&self, name: &str) -> Arc<Namespace> {
        if let Some(namespace) = self.namespace(name) {
            return namespace;
        }

        // The shard may exist on disk with other namespaces in it. Registering
        // a namespace marks its shard resident, so the rest of the shard has to
        // be back in memory first: otherwise everything else in it would read
        // as missing, and the next snapshot would write the shard out without
        // it. Only a namespace that is genuinely new gets here — an existing
        // one was paged in by `namespace` above.
        let shard = crate::persistence::shard_of(name);
        let evicted = self
            .shards
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .get(shard)
            .is_some_and(|meta| !meta.resident);
        if evicted && let Err(e) = self.page_in(shard) {
            // Nothing here can recover it; refusing to create the namespace
            // would only lose the write as well.
            log::error!("Could not load shard '{shard}' before extending it: {e:#}");
        }

        let namespace = self
            .namespaces
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .entry(name.to_string())
            .or_default()
            .clone();
        self.record(name);
        namespace
    }

    /// Note a namespace in the catalogue and mark its shard resident.
    fn record(&self, name: &str) {
        let shard = crate::persistence::shard_of(name);
        let mut shards = self.shards.write().unwrap_or_else(PoisonError::into_inner);
        let meta = shards.entry(shard.to_string()).or_default();
        meta.namespaces.insert(name.to_string());
        meta.resident = true;
        meta.last_access = now_secs();
    }

    fn touch(&self, shard: &str) {
        if let Some(meta) = self
            .shards
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .get_mut(shard)
        {
            meta.last_access = now_secs();
        }
    }
}

/// Namespaces whose values were counted towards consensus when written, and so
/// must give that count back when they go away.
fn now_secs() -> i64 {
    Utc::now().timestamp()
}

fn counts_towards_consensus(name: &str) -> bool {
    name != ALL_NAMESPACE && !name.starts_with(SHADOW_PREFIX) && !name.starts_with(CONFIG_PREFIX)
}

// ---------------------------------------------------------------------------
// Snapshots
// ---------------------------------------------------------------------------

/// Owned form of a snapshot, used when loading from disk.
#[derive(Debug, Deserialize)]
pub struct SnapshotData {
    pub version: u32,
    pub namespaces: HashMap<String, HashMap<String, Attribute>>,
}

/// Owned form of one shard, which has the same shape as a whole snapshot.
pub type ShardData = SnapshotData;

#[cfg(test)]
pub struct Snapshot<'a>(&'a Database);

/// One shard, serialized in the same shape as a full snapshot so that either
/// can be read by the same code.
pub struct ShardSnapshot<'a>(&'a Database, &'a str);

impl Serialize for ShardSnapshot<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut out = serializer.serialize_struct("Snapshot", 2)?;
        out.serialize_field("version", &SNAPSHOT_VERSION)?;
        out.serialize_field("namespaces", &NamespacesRef(self.0, Some(self.1)))?;
        out.end()
    }
}

#[cfg(test)]
impl Serialize for Snapshot<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut out = serializer.serialize_struct("Snapshot", 2)?;
        out.serialize_field("version", &SNAPSHOT_VERSION)?;
        out.serialize_field("namespaces", &NamespacesRef(self.0, None))?;
        out.end()
    }
}

/// All namespaces, or only those in one shard.
struct NamespacesRef<'a>(&'a Database, Option<&'a str>);

impl Serialize for NamespacesRef<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;

        // Only the names are copied up front; each namespace is locked, written
        // and released in turn.
        let entries: Vec<(String, Arc<Namespace>)> = {
            let map = self
                .0
                .namespaces
                .read()
                .unwrap_or_else(PoisonError::into_inner);
            map.iter()
                .filter(|(name, _)| {
                    self.1
                        .is_none_or(|shard| crate::persistence::shard_of(name) == shard)
                })
                .map(|(name, namespace)| (name.clone(), Arc::clone(namespace)))
                .collect()
        };

        let mut out = serializer.serialize_map(Some(entries.len()))?;
        for (name, namespace) in &entries {
            out.serialize_entry(name, &NamespaceRef(namespace))?;
        }
        out.end()
    }
}

struct NamespaceRef<'a>(&'a Namespace);

impl Serialize for NamespaceRef<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;

        let values = self.0.values.read().unwrap_or_else(PoisonError::into_inner);

        let mut out = serializer.serialize_map(Some(values.len()))?;
        for (value, cell) in values.iter() {
            let attr = cell.lock().unwrap_or_else(PoisonError::into_inner);
            out.serialize_entry(value, &*attr)?;
        }
        out.end()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).expect("timestamp in range")
    }

    /// Listings carry the shard and tier now; most tests only care about names.
    fn names(page: &Page<NamespaceEntry>) -> Vec<&str> {
        page.items.iter().map(|e| e.namespace.as_str()).collect()
    }

    fn consensus() -> WriteOpts {
        WriteOpts {
            consensus: true,
            ttl: None,
        }
    }

    fn with_ttl(ttl: u64) -> WriteOpts {
        WriteOpts {
            consensus: true,
            ttl: Some(ttl),
        }
    }

    #[test]
    fn write_returns_the_running_count() {
        let db = Database::default();

        assert_eq!(db.write("ns", "1.2.3.4", at(100), consensus()), 1);
        assert_eq!(db.write("ns", "1.2.3.4", at(200), consensus()), 2);
        assert_eq!(db.count("ns", "1.2.3.4"), 2);
    }

    #[test]
    fn consensus_counts_namespaces_not_writes() {
        let db = Database::default();

        db.write("my/namespace", "127.0.0.1", at(100), consensus());
        db.write("another/namespace", "127.0.0.1", at(200), consensus());
        db.write("another/namespace", "127.0.0.1", at(300), consensus());

        assert_eq!(db.count(ALL_NAMESPACE, "127.0.0.1"), 2);
    }

    #[test]
    fn a_new_value_in_an_existing_namespace_still_counts_for_consensus() {
        let db = Database::default();

        db.write("ns", "a", at(100), consensus());
        db.write("ns", "b", at(100), consensus());

        assert_eq!(db.count(ALL_NAMESPACE, "b"), 1);
    }

    #[test]
    fn writes_without_consensus_leave_all_alone() {
        let db = Database::default();

        db.write("ns", "a", at(100), WriteOpts::default());

        assert_eq!(db.count(ALL_NAMESPACE, "a"), 0);
    }

    #[test]
    fn missing_lookups_are_zero_and_none() {
        let db = Database::default();

        assert_eq!(db.count("nope", "nope"), 0);
        assert!(db.view("nope", "nope", 0, false).is_none());
        assert!(!db.namespace_exists("nope"));
        assert!(db.namespace_views("nope").is_none());
    }

    /// Older builds kept API keys as namespaces. We no longer write them, but
    /// we must still recognise them in a restored snapshot.
    #[test]
    fn legacy_apikeys_are_recovered_from_old_snapshots() {
        let db = Database::default();
        assert!(db.legacy_apikeys().is_empty());

        db.write(
            &format!("{APIKEYS_NAMESPACE}{DEFAULT_APIKEY}"),
            "",
            at(100),
            WriteOpts::default(),
        );
        db.write(
            &format!("{APIKEYS_NAMESPACE}secret"),
            "",
            at(100),
            WriteOpts::default(),
        );

        let mut keys = db.legacy_apikeys();
        keys.sort();
        assert_eq!(keys, [DEFAULT_APIKEY, "secret"]);
    }

    #[test]
    fn a_fresh_database_stores_no_keys() {
        let db = Database::new();
        assert!(db.legacy_apikeys().is_empty());
    }

    // -- delete ------------------------------------------------------------

    #[test]
    fn delete_removes_the_namespace_once() {
        let db = Database::default();
        db.write("ns", "a", at(100), consensus());

        assert!(db.delete("ns"));
        assert!(!db.delete("ns"));
        assert!(!db.namespace_exists("ns"));
    }

    #[test]
    fn delete_gives_back_the_consensus_it_was_holding() {
        let db = Database::default();
        db.write("a/ns", "v", at(100), consensus());
        db.write("b/ns", "v", at(100), consensus());
        assert_eq!(db.count(ALL_NAMESPACE, "v"), 2);

        db.delete("a/ns");
        assert_eq!(db.count(ALL_NAMESPACE, "v"), 1);

        // The last holder going away retires the `_all` entry entirely.
        db.delete("b/ns");
        assert_eq!(db.count(ALL_NAMESPACE, "v"), 0);
    }

    // -- TTL ---------------------------------------------------------------

    #[test]
    fn an_expired_attribute_is_invisible_before_it_is_swept() {
        let db = Database::default();
        // Written in 1970 with a one minute TTL, so it is long expired by now.
        db.write("ns", "v", at(1000), with_ttl(60));

        assert!(db.view("ns", "v", 0, false).is_none());
        assert_eq!(db.count("ns", "v"), 0);
        assert_eq!(db.namespace_views("ns").unwrap().len(), 0);
    }

    #[test]
    fn a_live_attribute_reports_its_ttl() {
        let db = Database::default();
        db.write("ns", "v", Utc::now(), with_ttl(3600));

        let view = db.view("ns", "v", 0, false).unwrap();
        assert_eq!(view.ttl, 3600);
    }

    #[test]
    fn writing_again_without_a_ttl_keeps_the_existing_one() {
        let db = Database::default();
        db.write("ns", "v", Utc::now(), with_ttl(3600));
        db.write("ns", "v", Utc::now(), consensus());

        assert_eq!(db.view("ns", "v", 0, false).unwrap().ttl, 3600);
    }

    #[test]
    fn sweeping_reclaims_expired_values_and_their_consensus() {
        let db = Database::default();
        db.write("a/ns", "v", at(1000), with_ttl(60));
        db.write("b/ns", "v", at(1000), consensus());
        assert_eq!(db.count(ALL_NAMESPACE, "v"), 2);

        let report = db.sweep(Utc::now());

        assert_eq!(report.values_removed, 1);
        assert_eq!(report.namespaces_removed, 1); // a/ns is now empty
        assert!(!db.namespace_exists("a/ns"));
        assert!(db.namespace_exists("b/ns"));
        // b/ns still holds the value, so consensus drops to one rather than zero.
        assert_eq!(db.count(ALL_NAMESPACE, "v"), 1);
    }

    /// A namespace made in advance holds nothing, and holding nothing is not a
    /// reason to reclaim it: it is a folder someone created, not litter.
    #[test]
    fn a_created_namespace_is_empty_and_survives_a_sweep() {
        let db = Database::default();

        assert!(db.create_namespace("feeds/domains"));
        // Already there, so making it again changes nothing.
        assert!(!db.create_namespace("feeds/domains"));

        assert!(db.namespace_exists("feeds/domains"));
        assert_eq!(
            db.value_page("feeds/domains", "", 0, 10, false)
                .unwrap()
                .total,
            0
        );

        assert_eq!(db.sweep(Utc::now()), SweepReport::default());
        assert!(db.namespace_exists("feeds/domains"));
    }

    /// Namespaces are flat paths; the tree is grouped out of them by segment.
    #[test]
    fn the_tree_groups_namespaces_by_segment() {
        let db = Database::default();
        for namespace in ["feeds", "feeds/misp/ips", "feeds/misp/domains", "other/x"] {
            db.write(namespace, "v", at(100), WriteOpts::default());
        }

        let root = db.namespace_children("", "", 0, 10, |_| true);
        assert_eq!(root.total, 2);
        // `feeds` holds values of its own *and* has namespaces under it.
        assert_eq!(root.items[0].name, "feeds");
        assert_eq!(root.items[0].path, "feeds");
        assert!(root.items[0].namespace);
        assert_eq!(root.items[0].descendants, 2);
        assert_eq!(root.items[1].name, "other");
        assert!(!root.items[1].namespace);

        // A level in, `misp` is a folder holding two namespaces.
        let feeds = db.namespace_children("feeds", "", 0, 10, |_| true);
        assert_eq!(feeds.total, 1);
        assert_eq!(feeds.items[0].path, "feeds/misp");
        assert!(!feeds.items[0].namespace);
        assert_eq!(feeds.items[0].descendants, 2);

        let misp = db.namespace_children("feeds/misp", "", 0, 10, |_| true);
        assert_eq!(
            misp.items
                .iter()
                .map(|e| e.name.as_str())
                .collect::<Vec<_>>(),
            ["domains", "ips"]
        );
        // A leaf has nothing under it.
        assert_eq!(
            db.namespace_children("other/x", "", 0, 10, |_| true).total,
            0
        );
    }

    #[test]
    fn the_tree_filters_pages_and_respects_permission() {
        let db = Database::default();
        for namespace in ["a/one", "a/two", "b/three"] {
            db.write(namespace, "v", at(100), consensus());
        }

        // Bookkeeping namespaces are left out, as they are of the flat listing.
        assert!(db.namespace_exists(ALL_NAMESPACE));
        let root = db.namespace_children("", "", 0, 10, |_| true);
        assert_eq!(
            root.items
                .iter()
                .map(|e| e.name.as_str())
                .collect::<Vec<_>>(),
            ["a", "b"]
        );

        let page = db.namespace_children("a", "", 1, 1, |_| true);
        assert_eq!(page.total, 2);
        assert_eq!(page.items[0].name, "two");

        let filtered = db.namespace_children("a", "ON", 0, 10, |_| true);
        assert_eq!(filtered.items.len(), 1);
        assert_eq!(filtered.items[0].name, "one");

        // A folder whose whole contents are out of reach is not listed at all.
        let scoped = db.namespace_children("", "", 0, 10, |name| name.starts_with("a"));
        assert_eq!(scoped.total, 1);
        assert_eq!(scoped.items[0].name, "a");
    }

    #[test]
    fn a_value_reports_every_namespace_holding_it() {
        let db = Database::default();
        for namespace in ["feeds/misp/ips", "feeds/otx/ips", "internal/allowlist"] {
            db.write(namespace, "1.2.3.4", at(100), consensus());
        }
        db.write("feeds/misp/ips", "1.2.3.4", at(200), consensus());
        db.write("feeds/misp/ips", "9.9.9.9", at(100), consensus());

        let found = db.sightings_of("1.2.3.4", 100, |_| true);
        assert_eq!(
            found
                .items
                .iter()
                .map(|s| s.namespace.as_str())
                .collect::<Vec<_>>(),
            ["feeds/misp/ips", "feeds/otx/ips", "internal/allowlist"]
        );
        // The count is per namespace, which is what sizes a node.
        assert_eq!(found.items[0].count, 2);
        assert_eq!(found.items[0].shard, "feeds");
        assert_eq!(found.items[1].count, 1);
        assert!(!found.truncated);
        assert!(!found.paged_in);

        // A value nobody has seen relates to nothing.
        assert!(db.sightings_of("nope", 100, |_| true).items.is_empty());
    }

    /// The same rule as browsing: a scoped key is told about its own subtree
    /// and nothing else.
    #[test]
    fn sightings_leave_out_namespaces_the_caller_cannot_read() {
        let db = Database::default();
        for namespace in ["feeds/ips", "private/ips"] {
            db.write(namespace, "1.2.3.4", at(100), consensus());
        }

        let found = db.sightings_of("1.2.3.4", 100, |name| name.starts_with("feeds"));
        assert_eq!(found.items.len(), 1);
        assert_eq!(found.items[0].namespace, "feeds/ips");
    }

    #[test]
    fn a_value_in_too_many_namespaces_is_cut_off() {
        let db = Database::default();
        for i in 0..5 {
            db.write(&format!("feeds/{i}"), "1.2.3.4", at(100), consensus());
        }

        let found = db.sightings_of("1.2.3.4", 2, |_| true);
        assert_eq!(found.items.len(), 2);
        assert!(found.truncated);
    }

    #[test]
    fn sweeping_leaves_live_data_alone() {
        let db = Database::default();
        db.write("ns", "forever", at(1000), consensus());
        db.write("ns", "later", Utc::now(), with_ttl(3600));

        assert_eq!(db.sweep(Utc::now()), SweepReport::default());
        assert_eq!(db.namespace_views("ns").unwrap().len(), 2);
    }

    /// A legacy key namespace has no TTL, but the sweeper skips the whole
    /// `_config` tree anyway rather than relying on that.
    #[test]
    fn sweeping_never_touches_api_keys() {
        let db = Database::default();
        let namespace = format!("{APIKEYS_NAMESPACE}{DEFAULT_APIKEY}");
        db.write(&namespace, "", at(100), WriteOpts::default());

        db.sweep(Utc::now());

        assert!(db.namespace_exists(&namespace));
        assert_eq!(db.legacy_apikeys(), [DEFAULT_APIKEY]);
    }

    #[test]
    fn shadow_sightings_inherit_the_policy_ttl() {
        let db = Database::with_policy(DatabasePolicy {
            stats_retention: 0,
            shadow_ttl: 60,
        });
        db.write("_shadow/ns", "v", at(1000), WriteOpts::default());

        // Expired by policy, without the caller asking for a TTL.
        assert_eq!(db.count("_shadow/ns", "v"), 0);
        assert_eq!(db.sweep(Utc::now()).values_removed, 1);
    }

    #[test]
    fn the_policy_ttl_does_not_leak_into_ordinary_namespaces() {
        let db = Database::with_policy(DatabasePolicy {
            stats_retention: 0,
            shadow_ttl: 60,
        });
        db.write("ns", "v", at(1000), consensus());

        assert_eq!(db.count("ns", "v"), 1);
    }

    #[test]
    fn stats_retention_is_applied_on_write() {
        let db = Database::with_policy(DatabasePolicy {
            stats_retention: 2,
            shadow_ttl: 0,
        });
        for hour in 0..5 {
            db.write("ns", "v", at(hour * 3600), consensus());
        }

        let view = db.view("ns", "v", 0, true).unwrap();
        assert_eq!(view.stats.unwrap().len(), 2);
        assert_eq!(view.count, 5);
    }

    // -- snapshots ---------------------------------------------------------

    #[test]
    fn a_snapshot_round_trips() {
        let db = Database::new();
        db.write("my/ns", "1.2.3.4", at(1_600_000_000), consensus());
        db.write("my/ns", "1.2.3.4", at(1_600_003_600), consensus());
        db.write("other/ns", "1.2.3.4", at(1_600_000_000), with_ttl(99));

        let json = serde_json::to_string(&db.snapshot()).unwrap();
        let data: SnapshotData = serde_json::from_str(&json).unwrap();
        assert_eq!(data.version, SNAPSHOT_VERSION);

        let restored = Database::from_snapshot(data, DatabasePolicy::default());

        assert_eq!(restored.count("my/ns", "1.2.3.4"), 2);
        assert_eq!(restored.count(ALL_NAMESPACE, "1.2.3.4"), 2);

        let view = restored.view("my/ns", "1.2.3.4", 0, true).unwrap();
        assert_eq!(view.first_seen, 1_600_000_000);
        assert_eq!(view.last_seen, 1_600_003_600);
        assert_eq!(view.stats.unwrap().len(), 2);
    }

    #[test]
    fn a_restored_database_still_knows_about_ttls() {
        let db = Database::new();
        db.write("ns", "v", at(1000), with_ttl(60));

        let json = serde_json::to_string(&db.snapshot()).unwrap();
        let restored = Database::from_snapshot(
            serde_json::from_str(&json).unwrap(),
            DatabasePolicy::default(),
        );

        // `has_ttl` must survive the round trip, or the sweeper would skip this.
        assert_eq!(restored.sweep(Utc::now()).values_removed, 1);
    }

    #[test]
    fn an_empty_database_snapshots_cleanly() {
        let db = Database::default();
        let json = serde_json::to_string(&db.snapshot()).unwrap();

        assert_eq!(json, r#"{"version":1,"namespaces":{}}"#);
    }

    // -- paging ------------------------------------------------------------

    #[test]
    fn namespaces_page_in_sorted_order() {
        let db = Database::default();
        for name in ["c/ns", "a/ns", "b/ns"] {
            db.write(name, "v", at(100), consensus());
        }

        let first = db.namespace_page("", 0, 2, |_| true);
        assert_eq!(names(&first), ["a/ns", "b/ns"]);
        // `total` counts matches, not the page, so a UI knows how far it can go.
        assert_eq!(first.total, 3);
        assert_eq!(first.offset, 0);

        let second = db.namespace_page("", 2, 2, |_| true);
        assert_eq!(names(&second), ["c/ns"]);
    }

    #[test]
    fn namespaces_can_be_filtered() {
        let db = Database::default();
        db.write("feeds/misp", "v", at(100), consensus());
        db.write("feeds/otx", "v", at(100), consensus());
        db.write("internal/notes", "v", at(100), consensus());

        let page = db.namespace_page("feeds", 0, 10, |_| true);
        assert_eq!(names(&page), ["feeds/misp", "feeds/otx"]);
        assert_eq!(page.total, 2);
    }

    /// The admin interface browses data, so server state must not show up in it.
    #[test]
    fn the_config_tree_is_not_listed() {
        let db = Database::default();
        db.write(
            "_config/acl/apikeys/changeme",
            "",
            at(100),
            WriteOpts::default(),
        );
        db.write("ns", "v", at(100), consensus());

        let page = db.namespace_page("", 0, 100, |_| true);
        assert!(!names(&page).iter().any(|n| n.starts_with("_config")));
        // `_all` is a consensus tally, not something to browse.
        assert!(!names(&page).contains(&ALL_NAMESPACE));
        assert_eq!(names(&page), ["ns"]);
    }

    #[test]
    fn values_page_in_sorted_order_with_a_total() {
        let db = Database::default();
        for value in ["ccc", "aaa", "bbb", "ddd"] {
            db.write("ns", value, at(100), consensus());
        }

        let page = db.value_page("ns", "", 1, 2, false).unwrap();
        let values: Vec<&str> = page.items.iter().map(|v| v.value.as_str()).collect();
        assert_eq!(values, ["bbb", "ccc"]);
        assert_eq!(page.total, 4);
        assert_eq!(page.offset, 1);
    }

    #[test]
    fn values_can_be_filtered_and_carry_consensus() {
        let db = Database::default();
        db.write("a/ns", "1.2.3.4", at(100), consensus());
        db.write("b/ns", "1.2.3.4", at(100), consensus());
        db.write("a/ns", "9.9.9.9", at(100), consensus());

        let page = db.value_page("a/ns", "1.2", 0, 10, false).unwrap();
        assert_eq!(page.total, 1);
        assert_eq!(page.items[0].value, "1.2.3.4");
        assert_eq!(page.items[0].consensus, 2);
    }

    #[test]
    fn stats_are_included_only_when_asked_for() {
        let db = Database::default();
        db.write("ns", "v", at(3600), consensus());

        assert!(
            db.value_page("ns", "", 0, 10, false).unwrap().items[0]
                .stats
                .is_none()
        );
        let with = db.value_page("ns", "", 0, 10, true).unwrap();
        assert_eq!(with.items[0].stats.as_ref().unwrap().get(&3600), Some(&1));
    }

    #[test]
    fn expired_values_do_not_appear_in_a_page() {
        let db = Database::default();
        db.write("ns", "live", Utc::now(), consensus());
        db.write("ns", "dead", at(1000), with_ttl(60));

        let page = db.value_page("ns", "", 0, 10, false).unwrap();
        assert_eq!(page.total, 1);
        assert_eq!(page.items[0].value, "live");
    }

    #[test]
    fn paging_a_missing_namespace_is_none() {
        assert!(
            Database::default()
                .value_page("nope", "", 0, 10, false)
                .is_none()
        );
    }

    #[test]
    fn an_offset_past_the_end_is_an_empty_page_not_an_error() {
        let db = Database::default();
        db.write("ns", "v", at(100), consensus());

        let page = db.value_page("ns", "", 500, 10, false).unwrap();
        assert!(page.items.is_empty());
        assert_eq!(page.total, 1);
    }

    /// A key that cannot read a namespace should not learn it exists.
    #[test]
    fn the_listing_hides_namespaces_the_caller_cannot_read() {
        let db = Database::default();
        db.write("feeds/misp", "v", at(100), consensus());
        db.write("secrets/hr", "v", at(100), consensus());

        let page = db.namespace_page("", 0, 100, |name| name.starts_with("feeds"));

        assert_eq!(names(&page), ["feeds/misp"]);
        // The total must reflect what was allowed, or paging would show gaps.
        assert_eq!(page.total, 1);
    }

    // -- tiering -----------------------------------------------------------

    struct Scratch(std::path::PathBuf);
    impl Scratch {
        fn new(tag: &str) -> Self {
            let path = std::env::temp_dir().join(format!("sightingdb-tier-{tag}"));
            let _ = std::fs::remove_dir_all(&path);
            std::fs::create_dir_all(&path).unwrap();
            Scratch(path)
        }
    }
    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn tiered(dir: &std::path::Path, tier: crate::tier::Tier) -> Database {
        let db = Database::default();
        db.attach_store(
            Store {
                dbdir: dir.to_path_buf(),
                level: 1,
            },
            TierPolicy {
                default_tier: tier,
                shards: HashMap::new(),
                warm_idle: std::time::Duration::from_secs(3600),
            },
        );
        db
    }

    /// The one that must never fail: everything written since the last save
    /// has to reach disk before the shard leaves memory.
    #[test]
    fn eviction_writes_out_before_dropping() {
        let dir = Scratch::new("nodataloss");
        let db = tiered(&dir.0, crate::tier::Tier::Cold);
        db.write("myorg/ns", "1.2.3.4", at(1000), consensus());

        let report = db.evict_idle(now_secs());
        assert_eq!(report.evicted, 1, "{report:?}");
        assert!(!db.is_shard_resident("myorg"));

        // Still readable: the read pages the shard back in.
        assert_eq!(db.count("myorg/ns", "1.2.3.4"), 1);
        assert!(db.is_shard_resident("myorg"));
    }

    #[test]
    fn an_evicted_namespace_is_still_listed_and_still_exists() {
        let dir = Scratch::new("listing");
        let db = tiered(&dir.0, crate::tier::Tier::Cold);
        db.write("myorg/ns", "v", at(1000), consensus());
        db.evict_idle(now_secs());

        // The management interface must not lose sight of it.
        let page = db.namespace_page("", 0, 10, |_| true);
        assert!(names(&page).contains(&"myorg/ns"), "{page:?}");
        assert!(db.namespace_exists("myorg/ns"));
        assert_eq!(db.namespace_count(), 2); // myorg/ns and _all
    }

    #[test]
    fn writing_to_an_evicted_namespace_pages_it_back_in() {
        let dir = Scratch::new("writeback");
        let db = tiered(&dir.0, crate::tier::Tier::Cold);
        db.write("myorg/ns", "v", at(1000), consensus());
        db.evict_idle(now_secs());

        db.write("myorg/ns", "v", at(2000), consensus());

        assert_eq!(
            db.count("myorg/ns", "v"),
            2,
            "the earlier sighting was lost"
        );
    }

    /// A new namespace in an evicted shard must not make the shard look
    /// resident while the rest of it is still on disk: everything else in it
    /// would read as missing, and the next snapshot would write the shard back
    /// without it.
    #[test]
    fn creating_a_namespace_in_an_evicted_shard_brings_the_shard_back() {
        let dir = Scratch::new("createevicted");
        let db = tiered(&dir.0, crate::tier::Tier::Cold);
        db.write("myorg/ns", "v", at(1000), consensus());
        db.evict_idle(now_secs());
        assert!(!db.is_shard_resident("myorg"));

        assert!(db.create_namespace("myorg/second"));

        assert_eq!(
            db.count("myorg/ns", "v"),
            1,
            "the evicted namespace was lost"
        );
        assert!(db.namespace_exists("myorg/second"));
    }

    /// The same hazard reached through an ordinary write rather than through
    /// the management interface.
    #[test]
    fn writing_a_new_namespace_into_an_evicted_shard_keeps_the_rest_of_it() {
        let dir = Scratch::new("writeevicted");
        let db = tiered(&dir.0, crate::tier::Tier::Cold);
        db.write("myorg/ns", "v", at(1000), consensus());
        db.evict_idle(now_secs());

        db.write("myorg/second", "v", at(2000), consensus());

        assert_eq!(
            db.count("myorg/ns", "v"),
            1,
            "the evicted namespace was lost"
        );
        assert_eq!(db.count("myorg/second", "v"), 1);
    }

    #[test]
    fn a_hot_shard_is_never_evicted() {
        let dir = Scratch::new("hot");
        let db = tiered(&dir.0, crate::tier::Tier::Hot);
        db.write("myorg/ns", "v", at(1000), consensus());

        assert_eq!(db.evict_idle(now_secs() + 100_000).evicted, 0);
        assert!(db.is_shard_resident("myorg"));
    }

    #[test]
    fn a_warm_shard_survives_until_its_window_passes() {
        let dir = Scratch::new("warm");
        let db = tiered(&dir.0, crate::tier::Tier::Warm);
        db.write("myorg/ns", "v", at(1000), consensus());

        // Inside the hour.
        assert_eq!(db.evict_idle(now_secs() + 60).evicted, 0);
        assert!(db.is_shard_resident("myorg"));

        // Past it.
        assert_eq!(db.evict_idle(now_secs() + 3601).evicted, 1);
        assert!(!db.is_shard_resident("myorg"));
    }

    /// "If the namespace is used, we keep the access for one hour again."
    #[test]
    fn using_a_warm_shard_restarts_its_hour() {
        let dir = Scratch::new("touch");
        let db = tiered(&dir.0, crate::tier::Tier::Warm);
        db.write("myorg/ns", "v", at(1000), consensus());

        // A read counts as use, so the window starts again from now.
        assert_eq!(db.count("myorg/ns", "v"), 1);
        assert_eq!(db.evict_idle(now_secs() + 3599).evicted, 0);
        assert!(db.is_shard_resident("myorg"));
    }

    /// Consensus is consulted on every write, so paying a load for it would
    /// undo the point of tiering.
    #[test]
    fn the_internal_shard_stays_resident_even_when_everything_is_cold() {
        let dir = Scratch::new("internal");
        let db = tiered(&dir.0, crate::tier::Tier::Cold);
        db.write("myorg/ns", "v", at(1000), consensus());

        db.evict_idle(now_secs() + 100_000);

        assert!(db.is_shard_resident(crate::persistence::INTERNAL_SHARD));
        assert_eq!(db.count(ALL_NAMESPACE, "v"), 1);
    }

    /// A request holding an `Arc` would otherwise write into an orphan.
    #[test]
    fn a_shard_in_use_is_left_for_the_next_sweep() {
        let dir = Scratch::new("busy");
        let db = tiered(&dir.0, crate::tier::Tier::Cold);
        db.write("myorg/ns", "v", at(1000), consensus());

        let held = db.namespace("myorg/ns").unwrap();
        let report = db.evict_idle(now_secs());
        assert_eq!(report.evicted, 0);
        assert_eq!(report.busy, 1);

        drop(held);
        assert_eq!(db.evict_idle(now_secs()).evicted, 1);
    }

    #[test]
    fn nothing_is_evicted_without_somewhere_to_put_it() {
        let db = Database::default();
        db.write("myorg/ns", "v", at(1000), consensus());

        // No store attached, so eviction would be data loss.
        assert_eq!(db.evict_idle(now_secs() + 100_000), EvictReport::default());
        assert_eq!(db.count("myorg/ns", "v"), 1);
    }

    #[test]
    fn residency_is_reported() {
        let dir = Scratch::new("residency");
        let db = tiered(&dir.0, crate::tier::Tier::Cold);
        db.write("myorg/ns", "v", at(1000), consensus());
        db.write("acme/ns", "v", at(1000), consensus());

        let (resident, total) = db.residency();
        assert_eq!((resident, total), (3, 3)); // myorg, acme, internal

        db.evict_idle(now_secs());
        let (resident, total) = db.residency();
        assert_eq!((resident, total), (1, 3));
    }

    // -- concurrency -------------------------------------------------------

    #[test]
    fn concurrent_writes_to_one_value_are_all_counted() {
        const THREADS: usize = 8;
        const PER_THREAD: usize = 500;

        let db = Arc::new(Database::default());
        std::thread::scope(|scope| {
            for _ in 0..THREADS {
                let db = Arc::clone(&db);
                scope.spawn(move || {
                    for i in 0..PER_THREAD {
                        db.write("ns", "shared", at(i as i64), consensus());
                    }
                });
            }
        });

        assert_eq!(db.count("ns", "shared"), (THREADS * PER_THREAD) as u64);
        // Every writer raced on the same first sighting; consensus must still
        // have counted the namespace exactly once.
        assert_eq!(db.count(ALL_NAMESPACE, "shared"), 1);
    }

    #[test]
    fn concurrent_writes_across_namespaces_agree_on_consensus() {
        const THREADS: usize = 8;

        let db = Arc::new(Database::default());
        std::thread::scope(|scope| {
            for t in 0..THREADS {
                let db = Arc::clone(&db);
                scope.spawn(move || {
                    for i in 0..200 {
                        db.write(&format!("ns/{t}"), "shared", at(i), consensus());
                    }
                });
            }
        });

        assert_eq!(db.count(ALL_NAMESPACE, "shared"), THREADS as u64);
        for t in 0..THREADS {
            assert_eq!(db.count(&format!("ns/{t}"), "shared"), 200);
        }
    }

    /// Readers and writers hitting `_all` and a namespace from both directions
    /// at once: the lock-ordering rule is what keeps this from deadlocking.
    #[test]
    fn readers_and_writers_do_not_deadlock() {
        let db = Arc::new(Database::default());
        std::thread::scope(|scope| {
            for t in 0..8 {
                let db = Arc::clone(&db);
                scope.spawn(move || {
                    for i in 0..500 {
                        // 3 and 20 are coprime, so every value really does land
                        // in all three namespaces rather than sticking to one.
                        let value = format!("v{}", i % 20);
                        db.write(&format!("ns/{}", i % 3), &value, at(i), consensus());
                        db.count(ALL_NAMESPACE, &value);
                        db.view(&format!("ns/{}", t % 3), &value, 0, true);
                        db.namespace_views(&format!("ns/{}", i % 3));
                    }
                });
            }
        });

        for v in 0..20 {
            assert_eq!(db.count(ALL_NAMESPACE, &format!("v{v}")), 3);
        }
    }

    /// A sweep running against live writers must never lose a sighting to the
    /// empty-namespace pruning race.
    #[test]
    fn sweeping_concurrently_with_writers_loses_nothing() {
        let db = Arc::new(Database::default());
        let stop = Arc::new(AtomicBool::new(false));

        std::thread::scope(|scope| {
            let sweeper_db = Arc::clone(&db);
            let sweeper_stop = Arc::clone(&stop);
            scope.spawn(move || {
                while !sweeper_stop.load(Ordering::Relaxed) {
                    sweeper_db.sweep(Utc::now());
                }
            });

            for t in 0..4 {
                let db = Arc::clone(&db);
                scope.spawn(move || {
                    for _ in 0..500 {
                        db.write(&format!("ns/{t}"), "v", Utc::now(), consensus());
                    }
                });
            }

            // Writers finish inside the scope; stop the sweeper afterwards.
            scope.spawn({
                let stop = Arc::clone(&stop);
                move || {
                    std::thread::sleep(std::time::Duration::from_millis(300));
                    stop.store(true, Ordering::Relaxed);
                }
            });
        });

        for t in 0..4 {
            assert_eq!(db.count(&format!("ns/{t}"), "v"), 500, "namespace ns/{t}");
        }
    }
}