cross-stream 0.14.2

An event stream store for personal, local-first use, specializing in event sourcing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
//! The event stream store.
//!
//! A [`Store`] is an append-only log of [`Frame`]s persisted to a directory on
//! disk. Append events with [`Store::append`], replay and follow them with
//! [`Store::read`], and stash payload bytes in the content-addressed store with
//! the `cas_*` methods.
//!
//! ## Topics
//!
//! Every frame has a dot-delimited `topic` (for example `clip.add`). Topics form
//! a hierarchy: a reader can ask for an exact topic, a prefix wildcard like
//! `clip.*`, `*` for everything, or a comma-separated list of such patterns
//! (`game.move.*,game.create`). See [`validate_topic`](crate::store::validate_topic)
//! for the allowed characters and [`ReadOptions::topic`] for querying.
//!
//! ## Retention
//!
//! Each frame carries a [`TTL`] that controls how long it is kept: forever, for
//! a fixed duration, only the last N per topic, or ephemeral (broadcast to live
//! readers but never stored). A `time:` frame is indexed by its expiry and a
//! background sweeper removes it within one sweep interval (the default, one
//! second, is set with [`StoreOptions::ttl_sweep`]). Reads never return an
//! expired frame, even one the sweeper has not reached yet.
//!
//! ## Durability
//!
//! Every append commits to the on-disk journal before it returns, so a process
//! crash loses nothing. Only power loss or a kernel crash can lose the part of
//! the journal not yet fsynced, and recovery then yields a stable prefix of the
//! stream. An [`Fsync`] policy, set with [`Store::with_fsync`], decides when
//! that fsync happens: after every append, on a timer (the default, one
//! second), or never. [`Store::flush`] fsyncs on demand.

mod fsync;
pub use fsync::*;
mod ttl;
pub use ttl::*;

#[cfg(test)]
mod tests;

use std::collections::{HashMap, HashSet};
use std::ops::Bound;
use std::path::PathBuf;
use std::time::Duration;

use tokio::sync::broadcast;
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};

use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use nu_protocol::engine::EngineState;
use scru128::Scru128Id;

use serde::{Deserialize, Deserializer, Serialize};

use fjall::{
    config::{BlockSizePolicy, HashRatioPolicy, RestartIntervalPolicy},
    Database, Error as FjallError, Keyspace, KeyspaceCreateOptions, OwnedWriteBatch, PersistMode,
};

/// Error returned when opening a [`Store`].
#[derive(Debug)]
pub enum StoreError {
    /// The store directory is already open in another process.
    Locked,
    /// An error from the underlying `fjall` database.
    Other(FjallError),
}

impl std::fmt::Display for StoreError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StoreError::Locked => write!(f, "Store is locked by another process"),
            StoreError::Other(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for StoreError {}

/// A single event in the stream.
///
/// A frame is metadata; the payload bytes (if any) live in the content-addressed
/// store and are referenced by [`hash`](Frame::hash). Build one with the
/// [`bon`](https://docs.rs/bon) builder, where the topic is the required
/// starting argument:
///
/// ```
/// use xs::{Frame, TTL};
///
/// let frame = Frame::builder("clip.add")
///     .meta(serde_json::json!({ "source": "keyboard" }))
///     .ttl(TTL::Last(100))
///     .build();
///
/// assert_eq!(frame.topic, "clip.add");
/// ```
///
/// The [`id`](Frame::id) is assigned by [`Store::append`] at write time, so the
/// value you set on a builder is ignored when appending.
#[derive(PartialEq, Eq, Serialize, Deserialize, Clone, Default, bon::Builder)]
pub struct Frame {
    /// Dot-delimited topic this frame belongs to (for example `clip.add`).
    ///
    /// Must satisfy [`validate_topic`]; [`Store::append`] rejects invalid topics.
    #[builder(start_fn, into)]
    pub topic: String,
    /// Time-sortable identifier. Assigned by [`Store::append`]; any value set
    /// before appending is overwritten.
    #[builder(default)]
    pub id: Scru128Id,
    /// Integrity hash of the payload in the content-addressed store, if this
    /// frame has one. Produce it with [`Store::cas_insert`].
    pub hash: Option<ssri::Integrity>,
    /// Arbitrary JSON metadata carried inline with the frame.
    pub meta: Option<serde_json::Value>,
    /// Retention policy for this frame. Defaults to [`TTL::Forever`] when unset.
    pub ttl: Option<TTL>,
}

use std::fmt;

impl fmt::Debug for Frame {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Frame")
            .field("id", &format!("{id}", id = self.id))
            .field("topic", &self.topic)
            .field("hash", &self.hash.as_ref().map(|x| format!("{x}")))
            .field("meta", &self.meta)
            .field("ttl", &self.ttl)
            .finish()
    }
}

impl<'de> Deserialize<'de> for FollowOption {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s: String = Deserialize::deserialize(deserializer)?;
        if s.is_empty() || s == "yes" {
            Ok(FollowOption::On)
        } else if let Ok(duration) = s.parse::<u64>() {
            Ok(FollowOption::WithHeartbeat(Duration::from_millis(duration)))
        } else {
            match s.as_str() {
                "true" => Ok(FollowOption::On),
                "false" | "no" => Ok(FollowOption::Off),
                _ => Err(serde::de::Error::custom("Invalid value for follow option")),
            }
        }
    }
}

fn deserialize_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    match s.as_str() {
        "false" | "no" | "0" => Ok(false),
        _ => Ok(true),
    }
}

/// Options controlling a [`Store::read`] or [`Store::read_sync`] call.
///
/// Defaults replay every stored frame once, oldest first, then stop. Build a
/// query with the [`bon`](https://docs.rs/bon) builder:
///
/// ```
/// use xs::{ReadOptions, FollowOption};
///
/// // Replay history for one topic, then keep streaming new appends.
/// let opts = ReadOptions::builder()
///     .topic("clip.*".to_string())
///     .follow(FollowOption::On)
///     .build();
/// ```
#[derive(PartialEq, Deserialize, Clone, Debug, Default, bon::Builder)]
pub struct ReadOptions {
    /// Whether to keep streaming live appends after history is replayed.
    /// Defaults to [`FollowOption::Off`].
    #[serde(default)]
    #[builder(default)]
    pub follow: FollowOption,
    /// Skip historical frames and emit only appends made after the read starts.
    #[serde(default, deserialize_with = "deserialize_bool")]
    #[builder(default)]
    pub new: bool,
    /// Start after this ID (exclusive).
    #[serde(rename = "after")]
    pub after: Option<Scru128Id>,
    /// Start from this ID (inclusive).
    pub from: Option<Scru128Id>,
    /// Stop after emitting this many historical frames.
    pub limit: Option<usize>,
    /// Return the last N frames (most recent), in chronological order.
    pub last: Option<usize>,
    /// Restrict to one or more topic patterns, comma-separated. Each pattern
    /// is an exact name, a `prefix.*` wildcard, or `*` for all, e.g.
    /// `clip.add` or `game.move.*,game.create`. Commas are a safe separator
    /// because [`validate_topic`] forbids them in topic names.
    pub topic: Option<String>,
}

/// A single topic pattern: an exact topic name or a `prefix.*` wildcard.
#[derive(Clone, Debug, PartialEq)]
pub enum Pattern {
    /// Matches the topic exactly.
    Exact(String),
    /// Matches any topic starting with this prefix. Stored with the trailing
    /// dot, so `a.*` becomes `Prefix("a.")` and matches `a.b` but not `a`.
    Prefix(String),
}

impl Pattern {
    fn matches(&self, topic: &str) -> bool {
        match self {
            Pattern::Exact(t) => t == topic,
            Pattern::Prefix(p) => topic.starts_with(p.as_str()),
        }
    }
}

/// A parsed topic filter: the value of [`ReadOptions::topic`] split on commas
/// into individual [`Pattern`]s.
///
/// Note that synthetic control frames emitted by a following read --
/// `xs.threshold` and heartbeat `xs.pulse` -- are delivered directly on the
/// read channel and are never subject to this filter.
#[derive(Clone, Debug, PartialEq)]
pub enum TopicFilter {
    /// Match every topic (no filter, or some element was `*`).
    All,
    /// Match topics satisfying at least one of these patterns.
    Patterns(Vec<Pattern>),
}

impl TopicFilter {
    /// Parse a comma-separated pattern list. Empty elements are ignored; an
    /// empty or all-`*` spec yields [`TopicFilter::All`].
    pub fn parse(spec: &str) -> TopicFilter {
        let mut patterns = Vec::new();
        for part in spec.split(',') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            if part == "*" {
                return TopicFilter::All;
            }
            if let Some(prefix) = part.strip_suffix(".*") {
                patterns.push(Pattern::Prefix(format!("{prefix}.")));
            } else {
                patterns.push(Pattern::Exact(part.to_string()));
            }
        }
        if patterns.is_empty() {
            TopicFilter::All
        } else {
            TopicFilter::Patterns(patterns)
        }
    }

    /// Parse an optional spec; `None` means no filter.
    pub fn from_option(spec: Option<&str>) -> TopicFilter {
        match spec {
            Some(s) => TopicFilter::parse(s),
            None => TopicFilter::All,
        }
    }

    /// Does `topic` match this filter?
    pub fn matches(&self, topic: &str) -> bool {
        match self {
            TopicFilter::All => true,
            TopicFilter::Patterns(patterns) => patterns.iter().any(|p| p.matches(topic)),
        }
    }
}

/// K-way merge of per-pattern frame iterators, ordered by frame id, with
/// dedupe when overlapping patterns yield the same frame from more than one
/// iterator. Each input iterator must itself be sorted by id (ascending when
/// `descending` is false, descending otherwise).
struct MergeById<'a> {
    iters: Vec<Box<dyn Iterator<Item = Frame> + 'a>>,
    heap: std::collections::BinaryHeap<MergeEntry>,
    descending: bool,
    last_emitted: Option<Scru128Id>,
}

struct MergeEntry {
    key: u128,
    idx: usize,
    frame: Frame,
}

impl PartialEq for MergeEntry {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key && self.idx == other.idx
    }
}
impl Eq for MergeEntry {}
impl PartialOrd for MergeEntry {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for MergeEntry {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.key.cmp(&other.key).then(self.idx.cmp(&other.idx))
    }
}

/// BinaryHeap is a max-heap; for ascending merges flip the bits so the
/// smallest id pops first.
fn merge_key(id: &Scru128Id, descending: bool) -> u128 {
    let raw = u128::from_be_bytes(id.to_bytes());
    if descending {
        raw
    } else {
        !raw
    }
}

impl<'a> MergeById<'a> {
    fn new(mut iters: Vec<Box<dyn Iterator<Item = Frame> + 'a>>, descending: bool) -> Self {
        let mut heap = std::collections::BinaryHeap::with_capacity(iters.len());
        for (idx, iter) in iters.iter_mut().enumerate() {
            if let Some(frame) = iter.next() {
                heap.push(MergeEntry {
                    key: merge_key(&frame.id, descending),
                    idx,
                    frame,
                });
            }
        }
        MergeById {
            iters,
            heap,
            descending,
            last_emitted: None,
        }
    }
}

impl Iterator for MergeById<'_> {
    type Item = Frame;

    fn next(&mut self) -> Option<Frame> {
        loop {
            let entry = self.heap.pop()?;
            if let Some(frame) = self.iters[entry.idx].next() {
                self.heap.push(MergeEntry {
                    key: merge_key(&frame.id, self.descending),
                    idx: entry.idx,
                    frame,
                });
            }
            // Overlapping patterns can yield the same frame from more than
            // one iterator; emit it once.
            if self.last_emitted == Some(entry.frame.id) {
                continue;
            }
            self.last_emitted = Some(entry.frame.id);
            return Some(entry.frame);
        }
    }
}

impl ReadOptions {
    /// Parse options from a URL query string (the form used by the HTTP API),
    /// for example `follow=true&topic=clip.*&last=10`. `None` yields the
    /// defaults.
    pub fn from_query(query: Option<&str>) -> Result<Self, crate::error::Error> {
        match query {
            Some(q) => Ok(serde_urlencoded::from_str(q)?),
            None => Ok(Self::default()),
        }
    }

    /// Render these options back into a URL query string, the inverse of
    /// [`from_query`](ReadOptions::from_query). Returns an empty string when no
    /// options are set.
    pub fn to_query_string(&self) -> String {
        let mut params = Vec::new();

        // Add follow parameter with heartbeat if specified
        match self.follow {
            FollowOption::Off => {}
            FollowOption::On => params.push(("follow", "true".to_string())),
            FollowOption::WithHeartbeat(duration) => {
                params.push(("follow", duration.as_millis().to_string()));
            }
        }

        // Add new if true
        if self.new {
            params.push(("new", "true".to_string()));
        }

        // Add after if present
        if let Some(after) = self.after {
            params.push(("after", after.to_string()));
        }

        // Add from if present
        if let Some(from) = self.from {
            params.push(("from", from.to_string()));
        }

        // Add limit if present
        if let Some(limit) = self.limit {
            params.push(("limit", limit.to_string()));
        }

        // Add last if present
        if let Some(last) = self.last {
            params.push(("last", last.to_string()));
        }

        if let Some(topic) = &self.topic {
            params.push(("topic", topic.clone()));
        }

        // Return empty string if no params
        if params.is_empty() {
            String::new()
        } else {
            url::form_urlencoded::Serializer::new(String::new())
                .extend_pairs(params)
                .finish()
        }
    }
}

/// Whether a read keeps streaming after history is replayed.
#[derive(Default, PartialEq, Clone, Debug)]
pub enum FollowOption {
    /// Stop once historical frames are exhausted.
    #[default]
    Off,
    /// Replay history, then stream live appends indefinitely.
    On,
    /// Like [`On`](FollowOption::On), but also emit a periodic heartbeat frame
    /// at the given interval so idle readers can detect a live connection.
    WithHeartbeat(Duration),
}

#[derive(Debug)]
enum GCTask {
    CheckLastTTL {
        topic: String,
        keep: u32,
    },
    /// Remove every `time:` frame whose expiry has passed, up to
    /// `MAX_SWEEP_PER_DRAIN`. Sent by the sweep tick.
    Sweep,
    Drain(tokio::sync::oneshot::Sender<()>),
}

/// A frame the gc worker is about to delete.
enum Removal {
    /// Only the id is known. The frame is fetched to learn its keys.
    Id(Scru128Id),
    /// An index hit that already carries every key the removal needs, so no
    /// point read into `stream` is required. `expires_at` is `None` when the
    /// frame has no `time:` ttl and so has no expiry index entry.
    Indexed {
        id: Scru128Id,
        topic: String,
        expires_at: Option<u64>,
    },
}

impl Removal {
    fn id(&self) -> Scru128Id {
        match self {
            Removal::Id(id) | Removal::Indexed { id, .. } => *id,
        }
    }
}

/// Where the next expiry sweep starts scanning. Everything below it has been
/// swept, so the sweep steps over the tombstones earlier sweeps left instead
/// of walking them again.
///
/// It only ever moves up to a key a sweep actually removed, and a sweep never
/// looks past the frames that are due, so it can never come to rest above an
/// entry that is still waiting for its expiry to pass. The one way an entry
/// can appear below it is an index write, which
/// [`note_indexed_expiry`](Store::note_indexed_expiry) moves it back for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct SweepStart {
    key: [u8; 24],
    /// Whether `key` itself still has to be swept: false on the key a sweep
    /// removed, true on one a later index write put back in play.
    inclusive: bool,
}

impl SweepStart {
    fn bound(&self) -> Bound<[u8; 24]> {
        if self.inclusive {
            Bound::Included(self.key)
        } else {
            Bound::Excluded(self.key)
        }
    }

    /// Sort position, so two starts can be compared. An inclusive start sits
    /// before an exclusive one on the same key: it covers one more entry.
    fn rank(&self) -> ([u8; 24], u8) {
        (self.key, u8::from(!self.inclusive))
    }
}

/// Where a `last:n` trim scan of a topic starts. Below it the topic holds no
/// live frame, only the tombstones of ones a trim or another removal path
/// took, so a scan that starts here counts and trims exactly what a scan of
/// the whole topic would.
///
/// A trim proves that of everything it removed. A scan that reaches the end of
/// the topic without finding `keep` live frames proves it of everything under
/// the oldest entry it saw, which is why the bound can be inclusive.
///
/// The one way a live frame can appear below it is an index write, which
/// [`note_indexed_topic`](Store::note_indexed_topic) drops the floor for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct TrimFloor {
    id: Scru128Id,
    /// Whether `id` itself is still on the topic and in scope for the scan.
    inclusive: bool,
}

/// Options for opening a [`Store`]. Build one with the
/// [`bon`](https://docs.rs/bon) builder; every field has a default.
///
/// ```
/// use std::time::Duration;
/// use xs::{Fsync, StoreOptions};
///
/// let options = StoreOptions::builder()
///     .fsync(Fsync::Always)
///     .ttl_sweep(Duration::from_millis(250))
///     .build();
/// assert_eq!(options.fsync, Fsync::Always);
/// assert_eq!(StoreOptions::default().ttl_sweep, Duration::from_millis(1000));
/// ```
#[derive(Clone, Debug, PartialEq, Eq, bon::Builder)]
pub struct StoreOptions {
    /// When the journal is fsynced. See [`Fsync`].
    #[builder(default)]
    pub fsync: Fsync,
    /// How often expired `time:` frames are swept from disk. Default 1000 ms.
    /// Zero disables the sweeper; expired frames are then only hidden from
    /// reads, never removed.
    #[builder(default = Duration::from_millis(1000))]
    pub ttl_sweep: Duration,
}

impl Default for StoreOptions {
    fn default() -> Self {
        StoreOptions::builder().build()
    }
}

/// An append-only event stream backed by a directory on disk.
///
/// Open one with [`new`](Store::new). `Store` is cheaply [`Clone`]able: every
/// clone shares the same underlying database, broadcast channel, and
/// content-addressed store, so clone it freely across tasks and threads instead
/// of wrapping it in an `Arc`.
///
/// See the [module docs](crate::store) for the topic and retention model.
#[derive(Clone)]
pub struct Store {
    /// Directory backing this store (the path passed to [`new`](Store::new)).
    pub path: PathBuf,
    db: Database,
    stream: Keyspace,
    idx_topic: Keyspace,
    /// `time:` frames keyed by expiry then id, valued by topic. The sweeper
    /// range-scans it from [`sweep_start`](Store::sweep_start) up to now. See
    /// [`idx_expiry_key`].
    idx_expiry: Keyspace,
    /// Where the next sweep resumes in `idx_expiry`; `None` is the start of
    /// the index. In memory only: a reopened store sweeps from the start
    /// again, which costs one walk of whatever tombstones outlived it and can
    /// never skip a frame. See [`SweepStart`].
    sweep_start: Arc<Mutex<Option<SweepStart>>>,
    /// Per-topic `last:n` trim floor: every frame on the topic with an id at
    /// or below it has been removed, so a trim scan stops there rather than
    /// running on into the tombstones of the frames it trimmed last time. In
    /// memory only, on the same reasoning as
    /// [`sweep_start`](Store::sweep_start). See
    /// [`last_overflow`](Store::last_overflow).
    trim_floor: Arc<Mutex<HashMap<String, TrimFloor>>>,
    broadcast_tx: broadcast::Sender<Frame>,
    gc_tx: UnboundedSender<GCTask>,
    /// Joins the background workers when the last caller-held clone drops.
    /// Declared after `gc_tx` on purpose: fields drop in order, so the gc
    /// channel closes before the join, and the gc worker can exit.
    workers: Option<Arc<Workers>>,
    append_lock: Arc<Mutex<()>>,
    /// Runtime handle captured at [`new`](Store::new), used to spawn the follow
    /// and heartbeat tasks from the now-sync [`read`](Store::read). `Handle` is
    /// cheaply `Clone`, so every `Store` clone shares the same runtime.
    rt: Option<tokio::runtime::Handle>,
    /// Optional base engine the processors clone, set via [`with_base_engine`].
    /// `None` falls back to `Engine::new()`. See
    /// [`prepared_base`](crate::nu::prepared_base) and ADR 0007.
    base_engine: Option<Arc<EngineState>>,
    /// Fsync policy and dirty flag, shared by every clone and the fsync worker.
    fsync: Arc<FsyncState>,
    /// Counters about this store's own work, shared by every clone and by
    /// the gc worker. See [`StoreStats`].
    stats: Arc<StoreStats>,
}

/// Counters the store keeps about its own work, always on.
///
/// Relaxed atomics on paths that already touch the database, so the cost is
/// noise next to the work being counted. Cumulative for the life of the
/// process, with no way to reset: a caller wanting a rate subtracts two
/// reads.
#[derive(Debug, Default)]
pub struct StoreStats {
    /// Frames accepted by [`append`](Store::append), including ephemeral ones
    /// that were broadcast but never stored.
    pub appends: AtomicUsize,
    /// Frames pulled from a keyspace iterator by a read. Larger than the
    /// number returned whenever a read filters: the gap is wasted work.
    pub frames_scanned: AtomicUsize,
    /// Point reads into `stream`. A topic read does one per frame it returns,
    /// so this over `frames_scanned` says how well the index is filtering.
    pub stream_reads: AtomicUsize,
    /// Frames removed by [`remove_many`](Store::remove_many).
    pub removed_frames: AtomicUsize,
    /// Batches committed by [`remove_many`](Store::remove_many). One per gc
    /// drain that had anything to do.
    pub remove_commits: AtomicUsize,
    /// Times the gc worker drained its queue.
    pub gc_drains: AtomicUsize,
    /// Nanoseconds the gc worker spent inside a drain. Against `gc_drains`
    /// this is the cost of retention, which is otherwise invisible.
    pub gc_nanos: AtomicU64,
}

/// A serializable read of [`StoreStats`]. See its fields for what each counts.
#[derive(Debug, Clone, serde::Serialize)]
pub struct StoreStatsSnapshot {
    pub appends: u64,
    pub frames_scanned: u64,
    pub stream_reads: u64,
    pub removed_frames: u64,
    pub remove_commits: u64,
    pub gc_drains: u64,
    pub gc_nanos: u64,
}

impl StoreStats {
    fn snapshot(&self) -> StoreStatsSnapshot {
        let n = |c: &AtomicUsize| c.load(Ordering::Relaxed) as u64;
        StoreStatsSnapshot {
            appends: n(&self.appends),
            frames_scanned: n(&self.frames_scanned),
            stream_reads: n(&self.stream_reads),
            removed_frames: n(&self.removed_frames),
            remove_commits: n(&self.remove_commits),
            gc_drains: n(&self.gc_drains),
            gc_nanos: self.gc_nanos.load(Ordering::Relaxed),
        }
    }
}

/// Cache hit rates for one keyspace, each `None` until that layer has been
/// asked for something.
#[derive(Debug, Clone, serde::Serialize)]
pub struct KeyspaceRates {
    pub block_cache_hit: Option<f64>,
    pub data_block_cache_hit: Option<f64>,
    pub index_block_cache_hit: Option<f64>,
    pub filter_block_cache_hit: Option<f64>,
    pub table_file_cache_hit: Option<f64>,
    /// Share of filter lookups that saved a read. Only counted when the
    /// filter reports a miss: a filter costs nothing on a hit, so this is
    /// what it is worth, not how often it ran.
    pub filter_efficiency: Option<f64>,
}

/// A rate is meaningless with no observations behind it.
fn rate(observations: usize, value: f64) -> Option<f64> {
    (observations > 0).then_some(value)
}

/// A point-in-time read of one keyspace's cache and filter counters.
///
/// Every rate is a fraction in `0.0..=1.0`, or `0.0` when nothing has been
/// asked of that layer yet. The counters are cumulative since the process
/// started; fjall has no way to reset them, so a caller comparing two reads
/// should subtract.
#[derive(Debug, Clone, serde::Serialize)]
pub struct KeyspaceMetrics {
    pub keyspace: &'static str,

    /// Hit rates, or `null` where nothing has been asked of that layer yet.
    /// fjall returns 1.0 for a rate with no observations, which reads as a
    /// perfect cache on a store that has done no work.
    pub rates: KeyspaceRates,

    pub filter_queries: usize,
    pub io_skipped_by_filter: usize,

    /// Blocks asked for, and how many of those reached the filesystem.
    pub block_loads: usize,
    pub block_load_io: usize,
    pub data_block_io: u64,
    pub index_block_io: u64,
    pub filter_block_io: u64,
}

impl KeyspaceMetrics {
    fn read(keyspace: &'static str, ks: &Keyspace) -> Self {
        // `Keyspace::metrics` hands back an `lsm_tree::Metrics`, a type fjall
        // does not re-export, so the reference is never named.
        let m = ks.metrics();
        Self {
            keyspace,
            rates: KeyspaceRates {
                block_cache_hit: rate(m.block_loads(), m.block_cache_hit_rate()),
                data_block_cache_hit: rate(
                    m.data_block_load_count(),
                    m.data_block_cache_hit_rate(),
                ),
                index_block_cache_hit: rate(
                    m.index_block_load_count(),
                    m.index_block_cache_hit_rate(),
                ),
                filter_block_cache_hit: rate(
                    m.filter_block_load_count(),
                    m.filter_block_cache_hit_rate(),
                ),
                // No public count of table opens, so borrow the block loads:
                // no block was loaded means no file was opened either.
                table_file_cache_hit: rate(m.block_loads(), m.table_file_cache_hit_rate()),
                filter_efficiency: rate(m.filter_queries(), m.filter_efficiency()),
            },
            filter_queries: m.filter_queries(),
            io_skipped_by_filter: m.io_skipped_by_filter(),
            block_loads: m.block_loads(),
            block_load_io: m.block_load_io_count(),
            data_block_io: m.data_block_io(),
            index_block_io: m.index_block_io(),
            filter_block_io: m.filter_block_io(),
        }
    }
}

/// Joins the background workers when the last caller-held `Store` drops.
/// The gc worker's own clone carries `None`, so it never joins itself. The
/// ticks stop first: the sweep tick holds a gc sender, and the gc worker
/// only exits once every sender is gone. Once the joins return every worker
/// has dropped its database handle, the database is closed, and the path
/// can be reopened.
struct Workers {
    gc: Option<std::thread::JoinHandle<()>>,
    fsync: Option<Tick>,
    sweep: Option<Tick>,
}

impl Drop for Workers {
    fn drop(&mut self) {
        drop(self.fsync.take());
        drop(self.sweep.take());
        if let Some(handle) = self.gc.take() {
            let _ = handle.join();
        }
    }
}

/// A thread that runs a closure every `interval` until dropped. Dropping it
/// sets `stop`, unparks the thread, and joins it, so the join waits for at
/// most one in-flight run of the closure.
struct Tick {
    stop: Arc<AtomicBool>,
    handle: Option<std::thread::JoinHandle<()>>,
}

impl Tick {
    fn spawn(interval: Duration, mut run: impl FnMut() + Send + 'static) -> Tick {
        let stop = Arc::new(AtomicBool::new(false));
        let handle = std::thread::spawn({
            let stop = stop.clone();
            move || loop {
                // park_timeout may wake early; the flags checked by each
                // closure make that harmless.
                std::thread::park_timeout(interval);
                if stop.load(Ordering::Acquire) {
                    break;
                }
                run();
            }
        });
        Tick {
            stop,
            handle: Some(handle),
        }
    }
}

impl Drop for Tick {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Release);
        if let Some(handle) = self.handle.take() {
            handle.thread().unpark();
            let _ = handle.join();
        }
    }
}

/// Shared fsync bookkeeping.
struct FsyncState {
    mode: Fsync,
    /// Set after every commit under `interval`; the tick clears it.
    dirty: AtomicBool,
}

impl Store {
    /// Open the store at `path`, creating the directory layout if it does not
    /// exist. Spawns a background worker that garbage-collects expired frames.
    /// Uses the default [`Fsync`] policy; see [`with_fsync`](Store::with_fsync)
    /// to choose one.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::Locked`] if another process already holds the
    /// store open, or [`StoreError::Other`] for any other database error.
    ///
    /// ```no_run
    /// use xs::Store;
    ///
    /// let store = Store::new("./clipboard-store".into())?;
    /// # Ok::<(), xs::StoreError>(())
    /// ```
    pub fn new(path: PathBuf) -> Result<Store, StoreError> {
        Store::open(path, StoreOptions::default())
    }

    /// Open the store at `path` with an explicit [`Fsync`] policy. Otherwise
    /// the same as [`new`](Store::new).
    ///
    /// ```no_run
    /// use xs::{Store, Fsync};
    ///
    /// let store = Store::with_fsync("./clipboard-store".into(), Fsync::Always)?;
    /// # Ok::<(), xs::StoreError>(())
    /// ```
    pub fn with_fsync(path: PathBuf, fsync: Fsync) -> Result<Store, StoreError> {
        Store::open(path, StoreOptions::builder().fsync(fsync).build())
    }

    /// Open the store at `path` with explicit [`StoreOptions`]. Otherwise the
    /// same as [`new`](Store::new).
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use xs::{Store, StoreOptions};
    ///
    /// let options = StoreOptions::builder()
    ///     .ttl_sweep(Duration::from_millis(250))
    ///     .build();
    /// let store = Store::open("./clipboard-store".into(), options)?;
    /// # Ok::<(), xs::StoreError>(())
    /// ```
    pub fn open(path: PathBuf, options: StoreOptions) -> Result<Store, StoreError> {
        let fsync = options.fsync;
        let db = match Database::builder(path.join("fjall"))
            .cache_size(32 * 1024 * 1024) // 32 MiB
            // One worker cannot keep up: every append writes three keyspaces, each
            // calls check_memtable_rotate, and all of them queue into the single
            // shared channel that worker also has to drain. At 1, flushes starve --
            // 1M appends put only 10.7% of their bytes into segments, and 1.0% with
            // the sweeper also committing. See BUGS-FOUND.md.
            .worker_threads(2)
            .open()
        {
            Ok(db) => db,
            Err(FjallError::Locked) => return Err(StoreError::Locked),
            Err(e) => return Err(StoreError::Other(e)),
        };

        // Options for stream keyspace: point reads by frame ID
        let stream_opts = || {
            KeyspaceCreateOptions::default()
                .max_memtable_size(8 * 1024 * 1024) // 8 MiB
                .data_block_size_policy(BlockSizePolicy::all(16 * 1024)) // 16 KiB
                .data_block_hash_ratio_policy(HashRatioPolicy::all(8.0))
                .expect_point_read_hits(true)
        };

        // Options for idx_topic keyspace: prefix scans only
        let idx_opts = || {
            KeyspaceCreateOptions::default()
                .max_memtable_size(8 * 1024 * 1024) // 8 MiB
                .data_block_size_policy(BlockSizePolicy::all(16 * 1024)) // 16 KiB
                .data_block_hash_ratio_policy(HashRatioPolicy::all(0.0)) // no point reads
                .expect_point_read_hits(true)
        };

        // An idx_topic key is `<topic>\0<id>`, so one topic repeats across
        // every entry it has. A restart point writes a key in full instead of
        // against the one before it, so fewer of them is a smaller index, and
        // nothing binary-searches inside these blocks to pay for it.
        let idx_topic_opts =
            || idx_opts().data_block_restart_interval_policy(RestartIntervalPolicy::all(32));

        // An idx_expiry key is `<expiry><id>`: consecutive keys share a prefix
        // only when frames expire in the same millisecond, so the same change
        // buys much less. Left at the default.
        let stream = db.keyspace("stream", stream_opts).unwrap();
        let idx_topic = db.keyspace("idx_topic", idx_topic_opts).unwrap();
        let idx_expiry = db.keyspace("idx_expiry", idx_opts).unwrap();

        let (broadcast_tx, _) = broadcast::channel(FOLLOW_BUFFER);
        let (gc_tx, gc_rx) = mpsc::unbounded_channel();

        let fsync_state = Arc::new(FsyncState {
            mode: fsync,
            dirty: AtomicBool::new(false),
        });

        let mut store = Store {
            path: path.clone(),
            db,
            stream,
            idx_topic,
            idx_expiry,
            sweep_start: Arc::new(Mutex::new(None)),
            trim_floor: Arc::new(Mutex::new(HashMap::new())),
            broadcast_tx,
            gc_tx,
            workers: None,
            append_lock: Arc::new(Mutex::new(())),
            rt: tokio::runtime::Handle::try_current().ok(),
            base_engine: None,
            fsync: fsync_state,
            stats: Arc::new(StoreStats::default()),
        };

        // Spawn the workers. The gc worker's clone is taken while `workers` is
        // still `None`, so only callers' clones join them.
        let gc = spawn_gc_worker(gc_rx, store.clone());
        let fsync_tick = match fsync {
            Fsync::Interval(interval) => Some(spawn_fsync_tick(
                store.db.clone(),
                store.fsync.clone(),
                interval,
            )),
            Fsync::Always | Fsync::Never => None,
        };
        let sweep_tick = if options.ttl_sweep.is_zero() {
            None
        } else {
            Some(spawn_sweep_tick(store.gc_tx.clone(), options.ttl_sweep))
        };
        store.workers = Some(Arc::new(Workers {
            gc: Some(gc),
            fsync: fsync_tick,
            sweep: sweep_tick,
        }));

        Ok(store)
    }

    /// Counters about this store's own work: appends, how much a read
    /// scanned against how much it returned, and what retention cost.
    pub fn stats(&self) -> StoreStatsSnapshot {
        self.stats.snapshot()
    }

    /// Cache and filter counters for each keyspace, for tuning
    /// `cache_size`, `max_cached_files`, and the filter and pinning policies.
    ///
    /// Cumulative since the process started. See [`KeyspaceMetrics`].
    pub fn metrics(&self) -> Vec<KeyspaceMetrics> {
        vec![
            KeyspaceMetrics::read("stream", &self.stream),
            KeyspaceMetrics::read("idx_topic", &self.idx_topic),
            KeyspaceMetrics::read("idx_expiry", &self.idx_expiry),
        ]
    }

    /// The runtime this store's tasks run on, if it was opened inside one.
    ///
    /// A following read needs it to wait on its receiver with a timeout, so
    /// it can notice an interrupt instead of parking until the next frame.
    pub fn runtime(&self) -> Option<tokio::runtime::Handle> {
        self.rt.clone()
    }

    /// The [`Fsync`] policy this store was opened with.
    pub fn fsync(&self) -> Fsync {
        self.fsync.mode
    }

    /// Fsync the journal now, whatever the [`Fsync`] policy. Every append
    /// that has returned is durable once this returns. Use it before a
    /// planned shutdown, or in tests that reopen a store.
    pub fn flush(&self) -> Result<(), crate::error::Error> {
        // Clear before persisting: a write that lands during the persist sets
        // the flag again, so the next tick still covers it.
        self.fsync.dirty.store(false, Ordering::Release);
        self.db.persist(PersistMode::SyncAll)?;
        Ok(())
    }

    /// Apply the [`Fsync`] policy after a committed batch: sync inline under
    /// `always`, mark the journal dirty for the tick under `interval`, and do
    /// nothing under `never`.
    fn after_commit(&self) -> Result<(), crate::error::Error> {
        match self.fsync.mode {
            Fsync::Always => self.db.persist(PersistMode::SyncAll)?,
            Fsync::Interval(_) => self.fsync.dirty.store(true, Ordering::Release),
            Fsync::Never => {}
        }
        Ok(())
    }

    /// Set a base engine the processor engines clone.
    ///
    /// A program that embeds xs prepares an [`EngineState`] with its own
    /// commands, env, and consts;
    /// [`prepared_base`](crate::nu::prepared_base) clones it per spawn and adds
    /// the store commands, so the actor, service, and action processors get
    /// those commands. Shared across `Store` clones, so set it once, before the
    /// processors spawn. No base set: `Engine::new()`.
    pub fn with_base_engine(mut self, base: EngineState) -> Self {
        self.base_engine = Some(Arc::new(base));
        self
    }

    /// The base engine an embedder attached via [`with_base_engine`], if any.
    pub fn base_engine(&self) -> Option<&EngineState> {
        self.base_engine.as_deref()
    }

    /// Wait until the background garbage-collection worker has processed every
    /// task queued so far. Useful in tests to observe TTL eviction
    /// deterministically.
    pub async fn wait_for_gc(&self) {
        let (tx, rx) = tokio::sync::oneshot::channel();
        let _ = self.gc_tx.send(GCTask::Drain(tx));
        let _ = rx.await;
    }

    /// Queue a sweep now, as the sweep tick would. Follow it with
    /// [`wait_for_gc`](Store::wait_for_gc) to observe the removals.
    #[cfg(test)]
    fn sweep(&self) {
        let _ = self.gc_tx.send(GCTask::Sweep);
    }

    /// Number of entries in the expiry index.
    #[cfg(test)]
    fn idx_expiry_len(&self) -> usize {
        self.idx_expiry.len().unwrap()
    }

    /// Read frames into an async channel according to `options`.
    ///
    /// By default this replays matching historical frames oldest-first and then
    /// closes the channel. With [`FollowOption::On`] it instead keeps the
    /// channel open and streams new appends as they arrive. When following, a
    /// single ephemeral `xs.threshold` frame is emitted to mark the boundary
    /// between replayed history and live events.
    ///
    /// The returned [`Receiver`](tokio::sync::mpsc::Receiver) is bounded;
    /// dropping it stops the read. For a blocking, non-async caller use
    /// [`read_sync`](Store::read_sync).
    ///
    /// ```no_run
    /// use xs::{Store, ReadOptions, FollowOption};
    ///
    /// # async fn run(store: Store) {
    /// let mut rx = store.read(ReadOptions::builder().follow(FollowOption::On).build());
    /// while let Some(frame) = rx.recv().await {
    ///     if frame.topic == "xs.threshold" {
    ///         // caught up to live; everything after this is new
    ///         continue;
    ///     }
    ///     println!("{} {}", frame.id, frame.topic);
    /// }
    /// # }
    /// ```
    #[tracing::instrument(skip(self))]
    pub fn read(&self, options: ReadOptions) -> tokio::sync::mpsc::Receiver<Frame> {
        let (tx, rx) = tokio::sync::mpsc::channel(100);

        let should_follow = matches!(
            options.follow,
            FollowOption::On | FollowOption::WithHeartbeat(_)
        );

        // Only take broadcast subscription if following. We initate the subscription here to
        // ensure we don't miss any messages between historical processing and starting the
        // broadcast subscription.
        let broadcast_rx = if should_follow {
            Some(self.broadcast_tx.subscribe())
        } else {
            None
        };

        // Only create done channel if we're doing historical processing
        let done_rx = if !options.new {
            let (done_tx, done_rx) = tokio::sync::oneshot::channel();
            let tx_clone = tx.clone();
            let store = self.clone();
            let options = options.clone();
            let should_follow_clone = should_follow;

            // Spawn OS thread to handle historical events
            std::thread::spawn(move || {
                let mut last_id = None;
                let mut count = 0;

                // Handle --last N: get the N most recent frames
                let filter = TopicFilter::from_option(options.topic.as_deref());

                if let Some(last_n) = options.last {
                    let iter = store.iter_for_filter_rev(filter);

                    // Collect last N frames (in reverse order), skipping expired
                    let mut frames: Vec<Frame> = Vec::with_capacity(last_n);
                    for frame in iter {
                        if is_expired(&frame) {
                            continue;
                        }
                        frames.push(frame);
                        if frames.len() >= last_n {
                            break;
                        }
                    }

                    // Reverse to chronological order and send
                    for frame in frames.into_iter().rev() {
                        last_id = Some(frame.id);
                        count += 1;
                        if tx_clone.blocking_send(frame).is_err() {
                            return;
                        }
                    }
                } else {
                    // Normal forward iteration
                    // Determine start bound: from (inclusive) takes precedence over after (exclusive)
                    let start_bound = options
                        .from
                        .map(|id| (id, true))
                        .or_else(|| options.after.map(|id| (id, false)));

                    let iter = store.iter_for_filter(filter, start_bound);

                    for frame in iter {
                        if is_expired(&frame) {
                            continue;
                        }

                        last_id = Some(frame.id);

                        if let Some(limit) = options.limit {
                            if count >= limit {
                                return; // Exit early if limit reached
                            }
                        }

                        if tx_clone.blocking_send(frame).is_err() {
                            return;
                        }
                        count += 1;
                    }
                }

                // Send threshold message if following
                if should_follow_clone {
                    let threshold = Frame::builder("xs.threshold")
                        .id(scru128::new())
                        .ttl(TTL::Ephemeral)
                        .build();
                    if tx_clone.blocking_send(threshold).is_err() {
                        return;
                    }
                }

                // Signal completion with the last seen ID and count
                let _ = done_tx.send((last_id, count));
            });

            Some(done_rx)
        } else {
            None
        };

        // Handle broadcast subscription and heartbeat
        if let Some(broadcast_rx) = broadcast_rx {
            let handle = self
                .rt
                .clone()
                .expect("read() with follow needs a runtime handle");

            {
                let tx = tx.clone();
                let limit = options.limit;

                handle.spawn(async move {
                    // If we have a done_rx, wait for historical processing
                    let (last_id, mut count) = match done_rx {
                        Some(done_rx) => match done_rx.await {
                            Ok((id, count)) => (id, count),
                            Err(_) => return, // Historical processing failed/cancelled
                        },
                        None => (None, 0),
                    };

                    let filter = TopicFilter::from_option(options.topic.as_deref());

                    let mut broadcast_rx = broadcast_rx;
                    loop {
                        tokio::select! {
                            _ = tx.closed() => break,
                            r = broadcast_rx.recv() => match r {
                                Ok(frame) => {
                                    // Filter by topic (any-match against the parsed patterns)
                                    if !filter.matches(&frame.topic) {
                                        continue;
                                    }

                                    // Skip if we've already seen this frame during historical scan
                                    if let Some(last_scanned_id) = last_id {
                                        if frame.id <= last_scanned_id {
                                            continue;
                                        }
                                    }

                                    if tx.send(frame).await.is_err() {
                                        break;
                                    }

                                    if let Some(limit) = limit {
                                        count += 1;
                                        if count >= limit {
                                            break;
                                        }
                                    }
                                }
                                // The reader fell more than FOLLOW_BUFFER frames
                                // behind and the channel overwrote what it had not
                                // taken. Carrying on would hand it the frames after
                                // the gap as though nothing were missing, and the
                                // read channel carries frames only, so there is no
                                // way to say otherwise in band. End the read instead:
                                // a closed stream is a signal the reader cannot
                                // mistake for a complete one. It resumes with
                                // `after` set to the last id it received.
                                Err(broadcast::error::RecvError::Lagged(skipped)) => {
                                    tracing::warn!(
                                        skipped,
                                        "follow fell behind the live buffer, ending the read"
                                    );
                                    break;
                                }
                                Err(broadcast::error::RecvError::Closed) => break,
                            }
                        }
                    }
                });
            }

            // Handle heartbeat if requested
            if let FollowOption::WithHeartbeat(duration) = options.follow {
                let heartbeat_tx = tx;
                handle.spawn(async move {
                    loop {
                        tokio::select! {
                            _ = heartbeat_tx.closed() => break,
                            _ = tokio::time::sleep(duration) => {
                                let frame = Frame::builder("xs.pulse")
                                    .id(scru128::new())
                                    .ttl(TTL::Ephemeral)
                                    .build();
                                if heartbeat_tx.send(frame).await.is_err() {
                                    break;
                                }
                            }
                        }
                    }
                });
            }
        }

        rx
    }

    /// Replay matching historical frames as a blocking iterator.
    ///
    /// This honours the `topic`, `from`, `after`, `limit`, and `last` parts of
    /// [`ReadOptions`] but ignores [`follow`](ReadOptions::follow): it never
    /// streams live appends. Use [`read`](Store::read) when you need to follow.
    ///
    /// The iterator is lazy: it reads a frame per `next`, so a caller that
    /// stops early only pays for what it pulled. The exception is `last`,
    /// which reads in reverse and buffers its N frames to return them in
    /// chronological order.
    ///
    /// ```no_run
    /// use xs::{Store, ReadOptions};
    ///
    /// # fn run(store: Store) {
    /// let opts = ReadOptions::builder().topic("clip.*".to_string()).last(10).build();
    /// for frame in store.read_sync(opts) {
    ///     println!("{} {}", frame.id, frame.topic);
    /// }
    /// # }
    /// ```
    pub fn read_sync(&self, options: ReadOptions) -> impl Iterator<Item = Frame> + '_ {
        // Hide expired frames the sweeper has not reached yet
        let filter_expired = |frame: Frame| (!is_expired(&frame)).then_some(frame);

        let filter = TopicFilter::from_option(options.topic.as_deref());

        if let Some(last_n) = options.last {
            // Handle --last N: get the N most recent frames. This branch reads
            // in reverse and re-orders, so it has to collect, but it is bounded
            // by last_n.
            let iter = self.iter_for_filter_rev(filter);

            // Collect last N frames (in reverse order), skipping expired
            let mut frames: Vec<Frame> = Vec::with_capacity(last_n);
            for frame in iter {
                if let Some(frame) = filter_expired(frame) {
                    frames.push(frame);
                    if frames.len() >= last_n {
                        break;
                    }
                }
            }

            // Reverse to chronological order
            frames.reverse();
            Box::new(frames.into_iter()) as Box<dyn Iterator<Item = Frame> + '_>
        } else {
            // Normal forward iteration, streamed: the caller only pays for the
            // frames it pulls.
            let start_bound = options
                .from
                .map(|id| (id, true))
                .or_else(|| options.after.map(|id| (id, false)));

            Box::new(
                self.iter_for_filter(filter, start_bound)
                    .filter_map(filter_expired)
                    .take(options.limit.unwrap_or(usize::MAX)),
            )
        }
    }

    /// Returns the current module state as of a given point in the stream.
    ///
    /// Scans all frames up to (and including) `as_of` and returns a mapping of
    /// module name to CAS hash for the latest frame on each `xs.module.<name>`
    /// topic.
    /// Resolve the set of registered Nushell modules as of a given frame ID.
    ///
    /// Scans `xs.module.<name>` frames up to and including `as_of` and returns a
    /// map from module name to the content hash of its latest definition. Used
    /// by the scripting runtime; rarely needed when embedding the store
    /// directly.
    pub fn nu_modules_at(
        &self,
        as_of: &Scru128Id,
    ) -> std::collections::HashMap<String, ssri::Integrity> {
        let mut modules = std::collections::HashMap::new();
        let options = ReadOptions::builder().follow(FollowOption::Off).build();
        for frame in self.read_sync(options) {
            if frame.id > *as_of {
                break;
            }
            if let Some(hash) = frame.hash {
                if let Some(name) = frame.topic.strip_prefix("xs.module.") {
                    if !name.is_empty() {
                        modules.insert(name.to_string(), hash);
                    }
                }
            }
        }
        modules
    }

    /// Fetch a single frame by ID, or `None` if no such frame exists.
    pub fn get(&self, id: &Scru128Id) -> Option<Frame> {
        self.stats.stream_reads.fetch_add(1, Ordering::Relaxed);
        self.stream
            .get(id.to_bytes())
            .unwrap()
            .map(|value| deserialize_frame((id.as_bytes(), value)))
    }

    /// Delete a frame and its topic index entries. Removing a frame that does
    /// not exist is a no-op and returns `Ok(())`.
    ///
    /// This removes the stream entry only; any payload bytes in the
    /// content-addressed store are left in place.
    #[tracing::instrument(skip(self), fields(id = %id.to_string()))]
    pub fn remove(&self, id: &Scru128Id) -> Result<(), crate::error::Error> {
        self.remove_many([Removal::Id(*id)])
    }

    /// Delete every frame in `removals`, with their index entries, in one
    /// batch with one commit. A [`Removal::Id`] whose frame is already gone
    /// is skipped, and nothing is committed when none remain.
    fn remove_many(
        &self,
        removals: impl IntoIterator<Item = Removal>,
    ) -> Result<(), crate::error::Error> {
        let mut batch = self.db.batch();
        for removal in removals {
            match removal {
                Removal::Id(id) => {
                    if let Some(frame) = self.get(&id) {
                        self.remove_frame_keys(
                            &mut batch,
                            &frame.id,
                            &frame.topic,
                            expires_at(&frame),
                        );
                    }
                }
                Removal::Indexed {
                    id,
                    topic,
                    expires_at,
                } => self.remove_frame_keys(&mut batch, &id, &topic, expires_at),
            }
        }
        if batch.is_empty() {
            return Ok(());
        }
        batch.commit()?;
        self.stats.remove_commits.fetch_add(1, Ordering::Relaxed);
        // No inline fsync in any mode. The tombstones reach disk with the next
        // append's sync or the next tick. If power loss brings a frame back,
        // its index entries come back with it, so it is trimmed or swept
        // again.
        if matches!(self.fsync.mode, Fsync::Interval(_)) {
            self.fsync.dirty.store(true, Ordering::Release);
        }
        Ok(())
    }

    /// Queue the stream entry and index keys of a frame for removal on
    /// `batch`. `expires_at` is the frame's expiry index slot, `Some` only for
    /// a `time:` frame. The topic key is built without validation: the frame
    /// exists.
    fn remove_frame_keys(
        &self,
        batch: &mut OwnedWriteBatch,
        id: &Scru128Id,
        topic: &str,
        expires_at: Option<u64>,
    ) {
        self.stats.removed_frames.fetch_add(1, Ordering::Relaxed);
        let mut topic_key = idx_topic_key_prefix(topic);
        topic_key.extend(id.as_bytes());
        batch.remove(&self.stream, id.as_bytes());
        batch.remove(&self.idx_topic, topic_key);
        for prefix_key in idx_topic_prefix_keys(topic, id) {
            batch.remove(&self.idx_topic, prefix_key);
        }
        if let Some(expires_at) = expires_at {
            batch.remove(&self.idx_expiry, idx_expiry_key(expires_at, id));
        }
    }

    /// The oldest `time:` frames whose expiry is at or before `now_ms`, at
    /// most `limit` of them, straight from the expiry index. A full `limit`
    /// means there may be more.
    ///
    /// The scan resumes at [`sweep_start`](Store::sweep_start) rather than at
    /// the start of the index. Everything below that point is the tombstones
    /// of frames earlier sweeps removed, and walking them again on every sweep
    /// is what made draining a backlog cost O(n^2/batch).
    fn expired_at(&self, now_ms: u64, limit: usize) -> Vec<Removal> {
        let last = idx_expiry_key(now_ms, &Scru128Id::from_bytes([0xff; 16]));
        let from = *self.sweep_start.lock().unwrap();
        // A clock that stepped backwards can leave the resume point above the
        // cut-off. Nothing below it is unswept, so there is nothing to do
        // until the clock catches up.
        if from.is_some_and(|start| start.key > last) {
            return Vec::new();
        }
        let start = from.map_or(Bound::Unbounded, |start| start.bound());

        let mut removals = Vec::new();
        let mut swept = None;
        for guard in self
            .idx_expiry
            .range((start, Bound::Included(last)))
            .take(limit)
        {
            // Stop on a read error rather than skipping the entry: the resume
            // point may never pass an entry this sweep did not remove.
            let Ok((key, value)) = guard.into_inner() else {
                break;
            };
            let Ok(key) = <[u8; 24]>::try_from(key.as_ref()) else {
                break;
            };
            let (expires_at, id) = idx_expiry_parse_key(&key);
            removals.push(Removal::Indexed {
                id,
                topic: String::from_utf8_lossy(&value).into_owned(),
                expires_at: Some(expires_at),
            });
            swept = Some(key);
        }

        if let Some(key) = swept {
            let mut start = self.sweep_start.lock().unwrap();
            // Only advance from the point this scan started at. An index write
            // that moved it back while the scan ran wins: the next sweep
            // covers this ground again, and covering it twice is cheap next to
            // leaving a frame behind.
            if *start == from {
                *start = Some(SweepStart {
                    key,
                    inclusive: false,
                });
            }
        }
        removals
    }

    /// Ids on `topic` past the newest `keep`, oldest first, at most `limit` of
    /// them, ignoring frames already in `pending` so a batch drops exactly
    /// what applying its tasks one by one would. A full `limit` means there
    /// may be more.
    ///
    /// Two bounded scans, both floored at the topic's
    /// [`trim_floor`](Store::trim_floor), below which the topic holds nothing
    /// but the tombstones of frames an earlier trim removed:
    ///
    /// 1. backwards from the newest entry for the `keep`-th newest live id,
    ///    the high-water mark everything older than which is overflow;
    /// 2. forwards from the floor for the ids to remove.
    ///
    /// Taking the removals in forward order is what keeps trimming a backlog
    /// linear. A truncated pass leaves the floor on the newest id it removed,
    /// so the next pass starts above its own tombstones instead of walking
    /// them to reach what it left.
    ///
    /// Both scans read index keys only. The expiry an `idx_topic` value now
    /// carries is for the read path: a trim counts entries, so a `time:` frame
    /// the sweeper has not reached yet still holds one of the `keep` slots,
    /// exactly as it did when those values were empty.
    fn last_overflow(
        &self,
        topic: &str,
        keep: u32,
        pending: &HashSet<Scru128Id>,
        limit: usize,
    ) -> Vec<Overflow> {
        let floor = self.trim_floor.lock().unwrap().get(topic).copied();
        // The floor is a bound on the id, so it is a bound on the key: both
        // scans open at it and never reach the tombstones below it. See
        // [`idx_topic_range`].
        let (low, top) = idx_topic_range(
            idx_topic_key_prefix(topic),
            floor.map(|floor| (floor.id, floor.inclusive)),
        );

        // The keep-th newest live id. Everything below it is overflow; fewer
        // than keep live entries means there is nothing to trim.
        let high = if keep == 0 {
            top
        } else {
            let mut seen = 0;
            let mut hwm = None;
            let mut oldest = None;
            for guard in self.idx_topic.range((low.clone(), top)).rev() {
                // A read error is not the end of the topic: give up on this
                // pass rather than record a floor the scan never reached.
                let Ok(key) = guard.key() else {
                    return Vec::new();
                };
                let id = idx_topic_frame_id_from_key(&key);
                oldest = Some(id);
                if pending.contains(&id) {
                    continue;
                }
                seen += 1;
                if seen == keep {
                    hwm = Some(key.to_vec());
                    break;
                }
            }
            match hwm {
                Some(key) => Bound::Excluded(key),
                None => {
                    // The scan reached the end of the topic without finding
                    // `keep` live frames. Nothing to trim, but everything
                    // below the oldest entry it saw is tombstone, so the next
                    // scan can start there instead of walking it again.
                    if let Some(id) = oldest {
                        self.set_trim_floor(
                            topic,
                            floor,
                            TrimFloor {
                                id,
                                inclusive: true,
                            },
                        );
                    }
                    return Vec::new();
                }
            }
        };

        let mut overflow = Vec::new();
        let mut trimmed = None;
        for guard in self.idx_topic.range((low, high)) {
            // Take the value too: it carries the frame's expiry, so the removal
            // needs no point read into `stream` to learn its keys.
            let Ok((key, value)) = guard.into_inner() else {
                break;
            };
            let id = idx_topic_frame_id_from_key(&key);
            if !pending.contains(&id) {
                overflow.push(Overflow {
                    id,
                    expires_at: idx_topic_expiry_of(&value),
                });
            }
            // A pending id counts: this drain removes it too, so the floor may
            // pass it.
            trimmed = Some(id);
            if overflow.len() == limit {
                break;
            }
        }

        if let Some(id) = trimmed {
            self.set_trim_floor(
                topic,
                floor,
                TrimFloor {
                    id,
                    inclusive: false,
                },
            );
        }
        overflow
    }

    /// Move a topic's trim floor to `to`, unless something moved it since the
    /// scan read `from`. An index write that dropped it while the scan ran
    /// wins: the next trim covers the topic from further back, and covering
    /// ground twice is cheap next to leaving a frame behind.
    fn set_trim_floor(&self, topic: &str, from: Option<TrimFloor>, to: TrimFloor) {
        let mut floors = self.trim_floor.lock().unwrap();
        if floors.get(topic).copied() == from {
            floors.insert(topic.to_string(), to);
        }
    }

    /// Note that a `time:` frame's expiry entry has been committed at `key`.
    ///
    /// A frame restored with an id from the past, or appended in the instant a
    /// sweep passed its slot, lands below the resume point, where no later
    /// sweep would look. Move the resume point back onto it.
    ///
    /// Must be called after the commit: called before, a sweep could run,
    /// find nothing at the key yet, and leave the resume point above it again.
    fn note_indexed_expiry(&self, key: [u8; 24]) {
        let mut start = self.sweep_start.lock().unwrap();
        // Already at the start of the index: nothing can be below it.
        let Some(current) = *start else { return };
        let candidate = SweepStart {
            key,
            inclusive: true,
        };
        if candidate.rank() < current.rank() {
            *start = Some(candidate);
        }
    }

    /// Note that a frame's topic index entry has been committed. An id at or
    /// below the topic's trim floor is in ground a trim scan no longer covers,
    /// so drop the floor and let the next trim scan the topic whole.
    ///
    /// Called after the commit, as
    /// [`note_indexed_expiry`](Store::note_indexed_expiry) is, and for every
    /// frame: `last:n` counts what is on the topic, whatever ttl put it there.
    fn note_indexed_topic(&self, topic: &str, id: &Scru128Id) {
        let mut floors = self.trim_floor.lock().unwrap();
        if floors.is_empty() {
            return;
        }
        if floors.get(topic).is_some_and(|floor| *id <= floor.id) {
            floors.remove(topic);
        }
    }

    /// Forget where the sweep and the `last:n` trims had got to, so each next
    /// scan starts from the beginning of its index again. Called when a
    /// removal batch fails to commit: its frames are still there, but the
    /// resume points have already moved as though they were gone.
    fn reset_gc_resume(&self) {
        *self.sweep_start.lock().unwrap() = None;
        self.trim_floor.lock().unwrap().clear();
    }

    // --- Content-addressed store (CAS) ---
    //
    // Frame payloads live here, keyed by an integrity hash. The typical flow is
    // `cas_insert` to store bytes, stash the returned hash on a `Frame`, then
    // `cas_read` to retrieve them later. Each method has a `_sync` twin for
    // blocking callers; the streaming `cas_reader`/`cas_writer` variants avoid
    // buffering the whole payload in memory.

    /// Open a streaming reader for the payload identified by `hash`.
    pub async fn cas_reader(&self, hash: ssri::Integrity) -> cacache::Result<cacache::Reader> {
        cacache::Reader::open_hash(&self.path.join("cacache"), hash).await
    }

    /// Blocking variant of [`cas_reader`](Store::cas_reader).
    pub fn cas_reader_sync(&self, hash: ssri::Integrity) -> cacache::Result<cacache::SyncReader> {
        cacache::SyncReader::open_hash(self.path.join("cacache"), hash)
    }

    /// Open a streaming writer; finish it to obtain the payload's integrity hash.
    pub async fn cas_writer(&self) -> cacache::Result<cacache::Writer> {
        cacache::WriteOpts::new()
            .open_hash(&self.path.join("cacache"))
            .await
    }

    /// Blocking variant of [`cas_writer`](Store::cas_writer).
    pub fn cas_writer_sync(&self) -> cacache::Result<cacache::SyncWriter> {
        cacache::WriteOpts::new().open_hash_sync(self.path.join("cacache"))
    }

    /// Store `content` and return its integrity hash, ready to attach to a
    /// [`Frame::hash`].
    pub async fn cas_insert(&self, content: impl AsRef<[u8]>) -> cacache::Result<ssri::Integrity> {
        cacache::write_hash(&self.path.join("cacache"), content).await
    }

    /// Blocking variant of [`cas_insert`](Store::cas_insert).
    pub fn cas_insert_sync(&self, content: impl AsRef<[u8]>) -> cacache::Result<ssri::Integrity> {
        cacache::write_hash_sync(self.path.join("cacache"), content)
    }

    /// Convenience wrapper over [`cas_insert`](Store::cas_insert) for a byte slice.
    pub async fn cas_insert_bytes(&self, bytes: &[u8]) -> cacache::Result<ssri::Integrity> {
        self.cas_insert(bytes).await
    }

    /// Blocking variant of [`cas_insert_bytes`](Store::cas_insert_bytes).
    pub fn cas_insert_bytes_sync(&self, bytes: &[u8]) -> cacache::Result<ssri::Integrity> {
        self.cas_insert_sync(bytes)
    }

    /// Read back the full payload for `hash` into a `Vec<u8>`.
    pub async fn cas_read(&self, hash: &ssri::Integrity) -> cacache::Result<Vec<u8>> {
        cacache::read_hash(&self.path.join("cacache"), hash).await
    }

    /// Blocking variant of [`cas_read`](Store::cas_read).
    pub fn cas_read_sync(&self, hash: &ssri::Integrity) -> cacache::Result<Vec<u8>> {
        cacache::read_hash_sync(self.path.join("cacache"), hash)
    }

    /// Persist a frame exactly as given, including its existing
    /// [`id`](Frame::id), without broadcasting it to live readers or scheduling
    /// TTL garbage collection.
    ///
    /// Most callers want [`append`](Store::append) instead, which assigns a
    /// fresh ID, handles ephemeral and `Last` retention, and notifies
    /// subscribers. Use `insert_frame` only when you are reconstructing a stream
    /// with predetermined IDs (for example when restoring a backup).
    #[tracing::instrument(skip(self))]
    pub fn insert_frame(&self, frame: &Frame) -> Result<(), crate::error::Error> {
        let encoded: Vec<u8> = serde_json::to_vec(&frame).unwrap();

        // Get the index topic key (also validates topic)
        let topic_key = idx_topic_key_from_frame(frame)?;

        // Get prefix index keys for hierarchical queries
        let prefix_keys = idx_topic_prefix_keys(&frame.topic, &frame.id);

        // Every idx_topic entry for this frame carries the same expiry, so a
        // topic scan can drop an expired id without reading the frame.
        let idx_value = idx_topic_expiry_value(frame);

        // The id may already be here under a different topic or ttl. This is
        // an upsert, so the stream row is replaced, but the index keys carry
        // the topic and the expiry, so the old ones would survive their frame
        // and answer for a topic it no longer has.
        let superseded = self.get(&frame.id);

        let mut batch = self.db.batch();
        batch.insert(&self.stream, frame.id.as_bytes(), encoded);
        batch.insert(&self.idx_topic, topic_key.clone(), idx_value);
        for prefix_key in &prefix_keys {
            batch.insert(&self.idx_topic, prefix_key, idx_value);
        }
        // A time: frame is also indexed by its expiry, for the sweeper
        let expiry_key = expires_at(frame).map(|at| idx_expiry_key(at, &frame.id));
        if let Some(key) = expiry_key {
            batch.insert(&self.idx_expiry, key, frame.topic.as_bytes());
        }

        if let Some(old) = superseded.as_ref().filter(|old| old.topic != frame.topic) {
            let mut old_key = idx_topic_key_prefix(&old.topic);
            old_key.extend(frame.id.as_bytes());
            // "a.b" and "a.c" share the prefix key "a.", so drop only the keys
            // the write above is not putting straight back: removing and
            // inserting one key in one batch has no defined winner.
            for key in std::iter::once(old_key).chain(idx_topic_prefix_keys(&old.topic, &frame.id))
            {
                if key != topic_key && !prefix_keys.contains(&key) {
                    batch.remove(&self.idx_topic, key);
                }
            }
        }
        // A changed ttl moves the expiry entry, because the expiry is half of
        // its key. An unchanged one is the same key, already rewritten above
        // with whatever topic the frame now carries.
        if let Some(stale) = superseded
            .as_ref()
            .and_then(expires_at)
            .map(|at| idx_expiry_key(at, &frame.id))
            .filter(|stale| Some(*stale) != expiry_key)
        {
            batch.remove(&self.idx_expiry, stale);
        }

        batch.commit()?;
        // Both gc scans resume where they last stopped, and an id from the
        // past can land behind them. Tell them, once the entries are there to
        // be found.
        if let Some(key) = expiry_key {
            self.note_indexed_expiry(key);
        }
        self.note_indexed_topic(&frame.topic, &frame.id);
        self.after_commit()
    }

    /// Append a frame to the stream and return it with its freshly assigned
    /// [`id`](Frame::id).
    ///
    /// This is the primary write path. It:
    ///
    /// - assigns a new time-sortable ID (overwriting any ID on the input);
    /// - validates the topic (see [`validate_topic`]);
    /// - persists the frame, unless its [`TTL`] is [`TTL::Ephemeral`], in which
    ///   case it is only broadcast to live readers;
    /// - schedules garbage collection for [`TTL::Last`] retention;
    /// - broadcasts the frame to everyone currently in a following
    ///   [`read`](Store::read).
    ///
    /// Appends are serialized internally, so frames are assigned IDs and
    /// delivered to subscribers in a consistent order.
    ///
    /// # Errors
    ///
    /// Returns an error if the topic is invalid or the underlying write fails.
    ///
    /// ```no_run
    /// use xs::{Store, Frame, TTL};
    ///
    /// # async fn run(store: Store) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// let hash = store.cas_insert("hello clipboard").await?;
    /// let frame = store.append(
    ///     Frame::builder("clip.add").hash(hash).ttl(TTL::Last(100)).build(),
    /// )?;
    /// println!("appended {}", frame.id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn append(&self, mut frame: Frame) -> Result<Frame, crate::error::Error> {
        // Serialize all appends to ensure ID generation, write, and broadcast
        // happen atomically. This guarantees subscribers receive frames in
        // scru128 ID order.
        let _guard = self.append_lock.lock().unwrap();

        frame.id = scru128::new();

        // Check for null byte in topic (in case we're not storing the frame)
        idx_topic_key_from_frame(&frame)?;

        // only store the frame if it's not ephemeral
        if frame.ttl != Some(TTL::Ephemeral) {
            self.insert_frame(&frame)?;

            // If this is a Last TTL, schedule a gc task
            if let Some(TTL::Last(n)) = frame.ttl {
                let _ = self.gc_tx.send(GCTask::CheckLastTTL {
                    topic: frame.topic.clone(),
                    keep: n,
                });
            }
        }

        self.stats.appends.fetch_add(1, Ordering::Relaxed);
        let _ = self.broadcast_tx.send(frame.clone());
        Ok(frame)
    }

    /// Iterate frames starting from a bound.
    /// `start` is `(id, inclusive)` where inclusive=true means >= and inclusive=false means >.
    fn iter_frames(
        &self,
        start: Option<(Scru128Id, bool)>,
    ) -> Box<dyn Iterator<Item = Frame> + '_> {
        let range = match start {
            Some((id, true)) => (Bound::Included(id.as_bytes().to_vec()), Bound::Unbounded),
            Some((id, false)) => (Bound::Excluded(id.as_bytes().to_vec()), Bound::Unbounded),
            None => (Bound::Unbounded, Bound::Unbounded),
        };

        let scanned = self.stats.clone();
        Box::new(self.stream.range(range).filter_map(move |guard| {
            scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
            let (key, value) = guard.into_inner().ok()?;
            Some(deserialize_frame((key, value)))
        }))
    }

    /// Iterate frames in reverse order (most recent first).
    fn iter_frames_rev(&self) -> Box<dyn Iterator<Item = Frame> + '_> {
        let scanned = self.stats.clone();
        Box::new(self.stream.iter().rev().filter_map(move |guard| {
            scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
            let (key, value) = guard.into_inner().ok()?;
            Some(deserialize_frame((key, value)))
        }))
    }

    /// Iterate frames by topic in reverse order (most recent first).
    fn iter_frames_by_topic_rev(&self, topic: &str) -> Box<dyn Iterator<Item = Frame> + '_> {
        let prefix = idx_topic_key_prefix(topic);
        let now = now_ms();
        let scanned = self.stats.clone();
        Box::new(
            self.idx_topic
                .prefix(prefix)
                .rev()
                .filter_map(move |guard| {
                    scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
                    self.get(&idx_topic_hit_id(guard, now)?)
                }),
        )
    }

    /// Iterate frames by topic prefix in reverse order (most recent first).
    fn iter_frames_by_topic_prefix_rev(
        &self,
        prefix: &str,
    ) -> Box<dyn Iterator<Item = Frame> + '_> {
        let mut index_prefix = Vec::with_capacity(prefix.len() + 1);
        index_prefix.extend(prefix.as_bytes());
        index_prefix.push(NULL_DELIMITER);

        let now = now_ms();
        let scanned = self.stats.clone();

        Box::new(
            self.idx_topic
                .prefix(index_prefix)
                .rev()
                .filter_map(move |guard| {
                    scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
                    self.get(&idx_topic_hit_id(guard, now)?)
                }),
        )
    }

    /// Iterate frames on an exact topic, ascending by frame id, from `start`.
    fn iter_frames_by_topic(
        &self,
        topic: &str,
        start: Option<(Scru128Id, bool)>,
    ) -> Box<dyn Iterator<Item = Frame> + '_> {
        let range = idx_topic_range(idx_topic_key_prefix(topic), start);
        let now = now_ms();
        let scanned = self.stats.clone();
        Box::new(self.idx_topic.range(range).filter_map(move |guard| {
            scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
            self.get(&idx_topic_hit_id(guard, now)?)
        }))
    }

    /// Iterate frames matching a topic prefix (for wildcard queries like "user.*").
    /// The prefix should include the trailing dot (e.g., "user." for "user.*").
    fn iter_frames_by_topic_prefix(
        &self,
        prefix: &str,
        start: Option<(Scru128Id, bool)>,
    ) -> Box<dyn Iterator<Item = Frame> + '_> {
        // Build index prefix: "user.\0" for scanning all "user.*" entries
        let mut index_prefix = Vec::with_capacity(prefix.len() + 1);
        index_prefix.extend(prefix.as_bytes());
        index_prefix.push(NULL_DELIMITER);

        let range = idx_topic_range(index_prefix, start);
        let now = now_ms();
        let scanned = self.stats.clone();

        Box::new(self.idx_topic.range(range).filter_map(move |guard| {
            scanned.frames_scanned.fetch_add(1, Ordering::Relaxed);
            self.get(&idx_topic_hit_id(guard, now)?)
        }))
    }

    /// Forward iterator for a single pattern, using the topic index.
    fn iter_for_pattern(
        &self,
        pattern: Pattern,
        start: Option<(Scru128Id, bool)>,
    ) -> Box<dyn Iterator<Item = Frame> + '_> {
        match pattern {
            Pattern::Exact(topic) => self.iter_frames_by_topic(&topic, start),
            Pattern::Prefix(prefix) => self.iter_frames_by_topic_prefix(&prefix, start),
        }
    }

    /// Reverse (most recent first) iterator for a single pattern.
    fn iter_for_pattern_rev(&self, pattern: Pattern) -> Box<dyn Iterator<Item = Frame> + '_> {
        match pattern {
            Pattern::Exact(topic) => self.iter_frames_by_topic_rev(&topic),
            Pattern::Prefix(prefix) => self.iter_frames_by_topic_prefix_rev(&prefix),
        }
    }

    /// Forward iterator for a parsed topic filter, ascending by frame id.
    /// A single pattern uses the indexed path directly; multiple patterns
    /// are k-way merged with dedupe for overlapping patterns.
    fn iter_for_filter(
        &self,
        filter: TopicFilter,
        start: Option<(Scru128Id, bool)>,
    ) -> Box<dyn Iterator<Item = Frame> + '_> {
        match filter {
            TopicFilter::All => self.iter_frames(start),
            TopicFilter::Patterns(mut patterns) if patterns.len() == 1 => {
                self.iter_for_pattern(patterns.remove(0), start)
            }
            TopicFilter::Patterns(patterns) => {
                let iters = patterns
                    .into_iter()
                    .map(|p| self.iter_for_pattern(p, start))
                    .collect();
                Box::new(MergeById::new(iters, false))
            }
        }
    }

    /// Reverse variant of [`iter_for_filter`](Store::iter_for_filter),
    /// descending by frame id (most recent first).
    fn iter_for_filter_rev(&self, filter: TopicFilter) -> Box<dyn Iterator<Item = Frame> + '_> {
        match filter {
            TopicFilter::All => self.iter_frames_rev(),
            TopicFilter::Patterns(mut patterns) if patterns.len() == 1 => {
                self.iter_for_pattern_rev(patterns.remove(0))
            }
            TopicFilter::Patterns(patterns) => {
                let iters = patterns
                    .into_iter()
                    .map(|p| self.iter_for_pattern_rev(p))
                    .collect();
                Box::new(MergeById::new(iters, true))
            }
        }
    }
}

fn spawn_gc_worker(
    mut gc_rx: UnboundedReceiver<GCTask>,
    mut store: Store,
) -> std::thread::JoinHandle<()> {
    // The worker's own clone must not hold a live `gc_tx`, or the channel
    // never closes and the worker, the database, and the fsync worker outlive
    // every caller's handle. Give it a sender whose receiver is already gone.
    let (closed_tx, _) = mpsc::unbounded_channel();
    store.gc_tx = closed_tx;

    // One drain per wake: take the task that woke us and whatever else is
    // queued, up to the cap, and apply every removal in one batch with one
    // commit. A Drain is answered after that commit, so every task queued
    // before it has been applied by the time its reply lands.
    const MAX_TASKS_PER_DRAIN: usize = 1024;
    // A sweep removes at most this many frames. When it fills the cap the
    // next drain starts with another sweep, without waiting for the tick.
    const MAX_SWEEP_PER_DRAIN: usize = 4096;
    // A last:n trim removes at most this many frames per topic per drain, and
    // is carried over the same way a full sweep is. Without a cap the first
    // trim of a topic with a backlog collects every id past `keep` at once.
    const MAX_TRIM_PER_DRAIN: usize = 4096;

    std::thread::spawn(move || {
        // Tasks a full batch left unfinished, run first in the next drain.
        let mut carried: Vec<GCTask> = Vec::new();
        loop {
            if carried.is_empty() {
                match gc_rx.blocking_recv() {
                    Some(task) => carried.push(task),
                    None => break,
                }
            }

            let drain_started = std::time::Instant::now();

            // Ids in this drain, so a last:n scan and a sweep never count or
            // queue a frame twice.
            let mut pending = HashSet::new();
            let mut removals = Vec::new();
            let mut drains = Vec::new();
            let mut sweep_again = false;
            // Topics whose trim filled its cap, one entry each however many
            // tasks for them this drain took.
            let mut trim_again: HashMap<String, u32> = HashMap::new();
            // Topics this drain must trim, collapsed from however many tasks
            // asked. Scanned after the take loop so every Sweep has already
            // run: an expired frame is hidden from reads, so it must not hold
            // a keep slot.
            let mut trims: HashMap<String, u32> = HashMap::new();
            let mut taken = 0;
            while taken < MAX_TASKS_PER_DRAIN {
                let Some(task) = carried.pop().or_else(|| gc_rx.try_recv().ok()) else {
                    break;
                };
                match task {
                    GCTask::CheckLastTTL { topic, keep } => {
                        // One scan per topic per drain, at the smallest keep
                        // asked for. A second scan for the same topic filters
                        // out everything the first collected, skips keep, and
                        // walks the rest to return nothing.
                        trims
                            .entry(topic)
                            .and_modify(|k| *k = (*k).min(keep))
                            .or_insert(keep);
                    }
                    GCTask::Sweep => {
                        let expired = store.expired_at(now_ms(), MAX_SWEEP_PER_DRAIN);
                        sweep_again |= expired.len() == MAX_SWEEP_PER_DRAIN;
                        for removal in expired {
                            if pending.insert(removal.id()) {
                                removals.push(removal);
                            }
                        }
                    }
                    GCTask::Drain(tx) => drains.push(tx),
                }
                taken += 1;
            }

            // Now that every Sweep in this drain has run, so `pending` holds
            // the expired frames it is removing, trim each topic once.
            for (topic, keep) in trims {
                let overflow = store.last_overflow(&topic, keep, &pending, MAX_TRIM_PER_DRAIN);
                let again = overflow.len() == MAX_TRIM_PER_DRAIN;
                for frame in overflow {
                    if pending.insert(frame.id) {
                        removals.push(Removal::Indexed {
                            id: frame.id,
                            topic: topic.clone(),
                            expires_at: frame.expires_at,
                        });
                    }
                }
                if again {
                    trim_again.insert(topic, keep);
                }
            }

            if let Err(e) = store.remove_many(removals) {
                tracing::error!("gc remove failed: {e}");
                // The batch did not land, so every frame this drain counted as
                // gone is still there, below resume points that have already
                // moved past it. Start both scans over.
                store.reset_gc_resume();
            }
            store.stats.gc_drains.fetch_add(1, Ordering::Relaxed);
            store
                .stats
                .gc_nanos
                .fetch_add(drain_started.elapsed().as_nanos() as u64, Ordering::Relaxed);
            for tx in drains {
                let _ = tx.send(());
            }
            carried.extend(
                trim_again
                    .into_iter()
                    .map(|(topic, keep)| GCTask::CheckLastTTL { topic, keep }),
            );
            if sweep_again {
                carried.push(GCTask::Sweep);
            }
        }
    })
}

/// Fsync the journal every `interval` when something was written since the
/// last tick. No final persist is needed on stop: fjall syncs the journal
/// when the database closes.
fn spawn_fsync_tick(db: Database, state: Arc<FsyncState>, interval: Duration) -> Tick {
    Tick::spawn(interval, move || {
        if state.dirty.swap(false, Ordering::AcqRel) {
            if let Err(e) = db.persist(PersistMode::SyncAll) {
                tracing::error!("fsync failed: {e}");
            }
        }
    })
}

/// Queue a [`GCTask::Sweep`] every `interval`. The gc worker does the scan
/// and the removals, so a slow sweep never blocks the tick.
fn spawn_sweep_tick(gc_tx: UnboundedSender<GCTask>, interval: Duration) -> Tick {
    Tick::spawn(interval, move || {
        let _ = gc_tx.send(GCTask::Sweep);
    })
}

fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64
}

/// When a `time:` frame expires, in ms since the epoch: its id's timestamp
/// plus its ttl. `None` for any other ttl.
fn expires_at(frame: &Frame) -> Option<u64> {
    match frame.ttl.as_ref() {
        Some(TTL::Time(ttl)) => Some(frame.id.timestamp().saturating_add(ttl.as_millis() as u64)),
        _ => None,
    }
}

/// Has this frame's `time:` ttl passed? Matches the sweeper's cut-off, so a
/// frame is hidden from reads from the moment it becomes sweepable.
fn is_expired(frame: &Frame) -> bool {
    matches!(expires_at(frame), Some(at) if now_ms() >= at)
}

/// Expiry index key: expiry in ms as big-endian u64, then the frame id. Sorts
/// by expiry, so a range scan up to now yields exactly the expired frames.
fn idx_expiry_key(expires_at: u64, id: &Scru128Id) -> [u8; 24] {
    let mut key = [0u8; 24];
    key[..8].copy_from_slice(&expires_at.to_be_bytes());
    key[8..].copy_from_slice(id.as_bytes());
    key
}

fn idx_expiry_parse_key(key: &[u8]) -> (u64, Scru128Id) {
    let expires_at = u64::from_be_bytes(key[..8].try_into().unwrap());
    let id = Scru128Id::from_bytes(key[8..24].try_into().unwrap());
    (expires_at, id)
}

/// Live frames held for a following read that has not taken them yet.
///
/// A reader that falls further behind than this has its read ended rather
/// than silently skipped: see the `Lagged` arm in [`read`](Store::read).
/// Raising it buys a slow reader more room before that happens, at a frame
/// of memory per slot per follower.
const FOLLOW_BUFFER: usize = 4096;

const NULL_DELIMITER: u8 = 0;
const MAX_TOPIC_LENGTH: usize = 255;

/// Validate a frame topic (per ADR 0001).
///
/// A topic must be non-empty and at most 255 bytes, start with an ASCII letter
/// or `_`, and contain only `a-z A-Z 0-9 _ - .`. It may not end with `.` or
/// contain consecutive dots. [`Store::append`] runs this automatically; call it
/// directly to validate user input before building a [`Frame`].
///
/// ```
/// use xs::store::validate_topic;
///
/// assert!(validate_topic("clip.add").is_ok());
/// assert!(validate_topic("clip.").is_err());
/// ```
pub fn validate_topic(topic: &str) -> Result<(), crate::error::Error> {
    if topic.is_empty() {
        return Err("Topic cannot be empty".to_string().into());
    }
    if topic.len() > MAX_TOPIC_LENGTH {
        return Err(format!("Topic exceeds max length of {MAX_TOPIC_LENGTH} bytes").into());
    }
    if topic.ends_with('.') {
        return Err("Topic cannot end with '.'".to_string().into());
    }
    if topic.contains("..") {
        return Err("Topic cannot contain consecutive dots".to_string().into());
    }

    let bytes = topic.as_bytes();
    let first = bytes[0];
    if !first.is_ascii_alphabetic() && first != b'_' {
        return Err("Topic must start with a-z, A-Z, or _".to_string().into());
    }

    for &b in bytes {
        if !b.is_ascii_alphanumeric() && b != b'_' && b != b'-' && b != b'.' {
            return Err(format!(
                "Topic contains invalid character: '{}'. Allowed: a-z A-Z 0-9 _ - .",
                b as char
            )
            .into());
        }
    }

    Ok(())
}

/// Validates a topic query (for --topic flag).
/// Accepts a comma-separated list of patterns; each element is an exact
/// topic, a `prefix.*` wildcard, or `*` (match all).
pub fn validate_topic_query(spec: &str) -> Result<(), crate::error::Error> {
    let mut seen = false;
    for part in spec.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        seen = true;
        validate_topic_pattern(part)?;
    }
    if !seen {
        return Err("Topic query cannot be empty".to_string().into());
    }
    Ok(())
}

/// Validate a single topic pattern: "*", "prefix.*", or an exact topic.
fn validate_topic_pattern(topic: &str) -> Result<(), crate::error::Error> {
    if topic == "*" {
        return Ok(());
    }
    if let Some(prefix) = topic.strip_suffix(".*") {
        // Validate the prefix part (e.g., "user" in "user.*")
        // Prefix can be empty edge case: ".*" is not valid
        if prefix.is_empty() {
            return Err("Wildcard '.*' requires a prefix".to_string().into());
        }
        validate_topic(prefix)
    } else {
        validate_topic(topic)
    }
}

/// Generate prefix index keys for hierarchical topic queries.
/// For topic "user.id1.messages", returns keys for prefixes "user." and "user.id1."
fn idx_topic_prefix_keys(topic: &str, frame_id: &scru128::Scru128Id) -> Vec<Vec<u8>> {
    let mut keys = Vec::new();
    let mut pos = 0;
    while let Some(dot_pos) = topic[pos..].find('.') {
        let prefix = &topic[..pos + dot_pos + 1]; // include the dot
        let mut key = Vec::with_capacity(prefix.len() + 1 + 16);
        key.extend(prefix.as_bytes());
        key.push(NULL_DELIMITER);
        key.extend(frame_id.as_bytes());
        keys.push(key);
        pos += dot_pos + 1;
    }
    keys
}

/// An `idx_topic` value meaning "this frame has no `time:` ttl". Distinct from
/// the empty value an older store wrote, which means "unknown".
const IDX_TOPIC_NEVER: u64 = u64::MAX;

/// One frame a `last:n` trim is going to remove, with everything
/// [`Store::remove_many`] needs to delete its keys. The topic is the one being
/// trimmed and the expiry came off the index entry, so no point read is needed.
#[derive(Debug, Clone, Copy)]
struct Overflow {
    id: Scru128Id,
    /// `Some` when the frame has a `time:` ttl and so an expiry index entry.
    /// `None` when it has none, or when the entry predates the index carrying
    /// one -- see [`idx_topic_expiry_of`].
    expires_at: Option<u64>,
}

/// The expiry an `idx_topic` value carries, if it carries one.
///
/// `None` covers two cases the caller must treat alike: a frame with no `time:`
/// ttl, which has no expiry index entry to delete, and an entry written before
/// the index carried an expiry, whose frame may have one. Removing a key that
/// is not there is a no-op, so both are safe to treat as "nothing to delete" --
/// but the second leaves a stale expiry entry, which the sweeper drops on its
/// next pass when the point read finds no frame.
#[inline]
fn idx_topic_expiry_of(value: &[u8]) -> Option<u64> {
    match <[u8; 8]>::try_from(value) {
        Ok(bytes) => match u64::from_be_bytes(bytes) {
            IDX_TOPIC_NEVER => None,
            at => Some(at),
        },
        Err(_) => None,
    }
}

/// The `idx_topic` value for a frame: its expiry in ms as a big-endian u64, or
/// [`IDX_TOPIC_NEVER`]. Every entry for the frame -- the exact topic key and
/// each prefix key -- gets the same eight bytes, so a topic scan can drop an
/// expired id without a point read into `stream`.
fn idx_topic_expiry_value(frame: &Frame) -> [u8; 8] {
    expires_at(frame).unwrap_or(IDX_TOPIC_NEVER).to_be_bytes()
}

/// Has the frame behind this `idx_topic` value expired as of `now`? A value
/// that is not eight bytes -- an entry written before the index carried an
/// expiry -- reads as "unknown" and answers `false`, so the caller falls back
/// to reading the frame and letting [`is_expired`] decide. Both shapes can sit
/// in one index.
///
/// The arithmetic matches [`expires_at`] exactly, so this never hides a frame
/// [`is_expired`] would keep.
#[inline]
fn idx_topic_is_expired(value: &[u8], now: u64) -> bool {
    match <[u8; 8]>::try_from(value) {
        Ok(bytes) => {
            let expires_at = u64::from_be_bytes(bytes);
            expires_at != IDX_TOPIC_NEVER && now >= expires_at
        }
        Err(_) => false,
    }
}

/// The frame id an `idx_topic` hit points at, or `None` to skip the hit
/// entirely.
///
/// The entry's value carries the frame's expiry, so an already expired id is
/// dropped here without the point read into `stream` that seeing its ttl would
/// otherwise take. `now` is sampled once when the iterator is built, which only
/// ever skips fewer frames than a fresh sample would: [`is_expired`] still runs
/// on everything that gets through, so the two never disagree about what is
/// visible.
#[inline]
fn idx_topic_hit_id(guard: fjall::Guard, now: u64) -> Option<Scru128Id> {
    let (key, value) = guard.into_inner().ok()?;
    if idx_topic_is_expired(&value, now) {
        return None;
    }
    Some(idx_topic_frame_id_from_key(&key))
}

/// The `idx_topic` key range covering one index prefix, opening at `start`
/// when there is one.
///
/// Every key under a prefix is that prefix followed by the frame's 16 byte id,
/// and ids sort ascending, so a bound on the id is a bound on the key. Seeking
/// to it beats walking the topic from its first entry and discarding
/// everything below: on a topic holding 500k frames, reading `after` a recent
/// id touches a handful of index entries instead of all 500k.
///
/// The upper bound is the prefix plus all ones, the largest key the prefix can
/// hold. A topic never contains the NUL delimiter, so no other topic's keys
/// fall inside the range.
fn idx_topic_range(
    prefix: Vec<u8>,
    start: Option<(Scru128Id, bool)>,
) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
    fn key_at(prefix: &[u8], id: &[u8; 16]) -> Vec<u8> {
        let mut key = Vec::with_capacity(prefix.len() + 16);
        key.extend_from_slice(prefix);
        key.extend_from_slice(id);
        key
    }

    let hi = Bound::Included(key_at(&prefix, &[0xff; 16]));
    let lo = match start {
        Some((id, true)) => Bound::Included(key_at(&prefix, id.as_bytes())),
        Some((id, false)) => Bound::Excluded(key_at(&prefix, id.as_bytes())),
        // Shorter than every key it covers, so it sorts before all of them.
        None => Bound::Included(prefix),
    };
    (lo, hi)
}

fn idx_topic_key_prefix(topic: &str) -> Vec<u8> {
    let mut v = Vec::with_capacity(topic.len() + 1); // topic bytes + delimiter
    v.extend(topic.as_bytes()); // topic string as UTF-8 bytes
    v.push(NULL_DELIMITER); // Delimiter for variable-sized keys
    v
}

pub(crate) fn idx_topic_key_from_frame(frame: &Frame) -> Result<Vec<u8>, crate::error::Error> {
    validate_topic(&frame.topic)?;
    let mut v = idx_topic_key_prefix(&frame.topic);
    v.extend(frame.id.as_bytes());
    Ok(v)
}

fn idx_topic_frame_id_from_key(key: &[u8]) -> Scru128Id {
    let frame_id_bytes = &key[key.len() - 16..];
    Scru128Id::from_bytes(frame_id_bytes.try_into().unwrap())
}

fn deserialize_frame<B1: AsRef<[u8]> + std::fmt::Debug, B2: AsRef<[u8]>>(
    record: (B1, B2),
) -> Frame {
    serde_json::from_slice(record.1.as_ref()).unwrap_or_else(|e| {
        // Try to convert the key to a Scru128Id and print in a format that can be copied for deletion
        let key_bytes = record.0.as_ref();
        if key_bytes.len() == 16 {
            if let Ok(bytes) = key_bytes.try_into() {
                let id = Scru128Id::from_bytes(bytes);
                eprintln!("CORRUPTED_RECORD_ID: {id}");
            }
        }
        let key = std::str::from_utf8(record.0.as_ref()).unwrap();
        let value = std::str::from_utf8(record.1.as_ref()).unwrap();
        panic!("Failed to deserialize frame: {e} {key} {value}")
    })
}