sapling-indexedlog 0.2.0

Append-only on-disk storage with integrity checks and radix tree indexing.
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
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! Rotation support for a set of [`Log`]s.

use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::atomic::Ordering::SeqCst;

use minibytes::Bytes;
use tracing::debug;
use tracing::debug_span;
use tracing::info;
use tracing::trace;
use try_once_lock::OnceLock;

use crate::btrfs;
use crate::change_detect::SharedChangeDetector;
use crate::errors::IoResultExt;
use crate::errors::ResultExt;
use crate::lock::READER_LOCK_OPTS;
use crate::lock::ScopedDirLock;
use crate::log;
use crate::log::Appendable;
use crate::log::ExtendWrite;
use crate::log::FlushFilterContext;
use crate::log::FlushFilterFunc;
use crate::log::FlushFilterOutput;
use crate::log::IndexDef;
use crate::log::Log;
use crate::metrics::Counter;
use crate::repair::OpenOptionsOutput;
use crate::repair::OpenOptionsRepair;
use crate::repair::RepairMessage;
use crate::utils;

static ROTATE_COUNT: Counter = Counter::new_counter("indexedlog.rotate");

/// A collection of [`Log`]s that get rotated or deleted automatically when they
/// exceed size or count limits.
///
/// Writes go to the active [`Log`]. Reads scan through all [`Log`]s.
pub struct RotateLog {
    dir: Option<PathBuf>,
    open_options: OpenOptions,
    logs: Vec<OnceLock<Log>>,
    // Logical length of `logs`. It can be smaller than `logs.len()` if some Log
    // fails to load.
    logs_len: AtomicUsize,
    // Set once a lazy log load fails (see `load_log`). Cleared only when
    // `set_logs` replaces the complete log generation.
    load_failed: AtomicBool,
    // Rotated logs we hold on to in "consistent read" mode to provide temporary read-after-write
    // consistency.
    pinned_logs: Vec<Log>,
    latest: u8,
    // Indicate an active reader. Destrictive writes (repair) are unsafe.
    reader_lock: Option<ScopedDirLock>,
    change_detector: Option<SharedChangeDetector>,

    // At what apparent file size we should check the btrfs "physical" size when checking if we
    // should rotate. This is to minimize checks of the btrfs size.
    next_btrfs_size_check: Option<u64>,

    // Run after log.sync(). For testing purpose only.
    #[cfg(test)]
    hook_after_log_sync: Option<Box<dyn Fn()>>,

    // Count of active "with_consistent_reads()" calls.
    consistent_reads: Arc<AtomicU64>,
}

// On disk, a RotateLog is a directory containing:
// - 0/, 1/, 2/, 3/, ...: one Log per directory.
// - latest: a file, the name of the directory that is considered "active".

const LATEST_FILE: &str = "latest";

/// Options used to configure how a [`RotateLog`] is opened.
#[derive(Clone)]
pub struct OpenOptions {
    pub(crate) max_bytes_per_log: u64,
    pub(crate) max_log_count: u8,
    pub(crate) log_open_options: log::OpenOptions,
    pub(crate) auto_sync_threshold: Option<u64>,
}

impl OpenOptions {
    #[allow(clippy::new_without_default)]
    /// Creates a default new set of options ready for configuration.
    ///
    /// The default values are:
    /// - Keep 2 logs.
    /// - A log gets rotated when it exceeds 2GB.
    /// - No indexes.
    /// - Do not create on demand.
    /// - Do not sync automatically on append().
    pub fn new() -> Self {
        // Some "seemingly reasonable" default values. Not scientifically chosen.
        let max_log_count = 2;
        let max_bytes_per_log = 2_000_000_000; // 2 GB
        Self {
            max_bytes_per_log,
            max_log_count,
            log_open_options: log::OpenOptions::new(),
            auto_sync_threshold: None,
        }
    }

    /// Set the maximum [`Log`] count.
    ///
    /// A larger value would hurt lookup performance.
    pub fn max_log_count(mut self, count: u8) -> Self {
        assert!(count >= 1);
        self.max_log_count = count;
        self
    }

    /// Set the maximum bytes per [`Log`].
    pub fn max_bytes_per_log(mut self, bytes: u64) -> Self {
        assert!(bytes > 0);
        self.max_bytes_per_log = bytes;
        self
    }

    /// Set `fysnc` open for underlying [`Log`] objects.
    pub fn fsync(mut self, fsync: bool) -> Self {
        self.log_open_options = self.log_open_options.fsync(fsync);
        self
    }

    /// Sets the checksum type.
    ///
    /// See [log::ChecksumType] for details.
    pub fn checksum_type(mut self, checksum_type: log::ChecksumType) -> Self {
        self.log_open_options = self.log_open_options.checksum_type(checksum_type);
        self
    }

    /// Set whether create the [`RotateLog`] structure if it does not exist.
    pub fn create(mut self, create: bool) -> Self {
        self.log_open_options = self.log_open_options.create(create);
        self
    }

    /// Add an index function.
    pub fn index(mut self, name: &'static str, func: fn(&[u8]) -> Vec<log::IndexOutput>) -> Self {
        self.log_open_options = self.log_open_options.index(name, func);
        self
    }

    /// Set the index definitions.
    ///
    /// See [`IndexDef`] for details.
    pub fn index_defs(mut self, index_defs: Vec<IndexDef>) -> Self {
        self.log_open_options = self.log_open_options.index_defs(index_defs);
        self
    }

    /// Sets the flush filter function.
    ///
    /// The function will be called at [`RotateLog::sync`] time, if there are
    /// changes since `open` (or last `sync`) time.
    ///
    /// The filter function can be used to avoid writing content that already
    /// exists in the latest [`Log`], or rewrite content as needed.
    pub fn flush_filter(mut self, flush_filter: Option<FlushFilterFunc>) -> Self {
        self.log_open_options = self.log_open_options.flush_filter(flush_filter);
        self
    }

    /// Call `sync` automatically if the in-memory buffer size has exceeded
    /// the given size threshold.
    ///
    /// This is useful to make in-memory buffer size bounded.
    pub fn auto_sync_threshold(mut self, threshold: impl Into<Option<u64>>) -> Self {
        self.auto_sync_threshold = threshold.into();
        self
    }

    /// Enable btrfs aware mode where we rotate based on "physical" file size instead of apparent
    /// file size to account for transparent btrfs compression.
    pub fn btrfs_compression(mut self, btrfs: bool) -> Self {
        self.log_open_options = self.log_open_options.btrfs_compression(btrfs);
        self
    }

    /// Open [`RotateLog`] at given location.
    pub fn open(&self, dir: impl AsRef<Path>) -> crate::Result<RotateLog> {
        let dir = dir.as_ref();
        let result: crate::Result<_> = (|| {
            let reader_lock = ScopedDirLock::new_with_options(dir, &READER_LOCK_OPTS)?;
            let change_detector = reader_lock.shared_change_detector()?;
            let span = debug_span!("RotateLog::open", dir = &dir.to_string_lossy().as_ref());
            let _guard = span.enter();

            let latest_and_log = read_latest_and_logs(dir, self);

            let (latest, logs) = match latest_and_log {
                Ok((latest, logs)) => (latest, logs),
                Err(e) => {
                    if !self.log_open_options.create {
                        return Err(e)
                            .context("not creating new logs since OpenOption::create is not set");
                    } else {
                        utils::mkdir_p(dir)?;
                        let lock = ScopedDirLock::new(dir)?;

                        match read_latest_raw(dir) {
                            Ok(latest) => {
                                match read_logs(dir, self, latest) {
                                    Ok(logs) => {
                                        // Both latest and logs are read properly.
                                        (latest, logs)
                                    }
                                    Err(err) => {
                                        // latest is fine, but logs cannot be read.
                                        // Try auto recover by creating an empty log.
                                        let latest = latest.wrapping_add(1);
                                        match create_empty_log(Some(dir), self, latest, &lock) {
                                            Ok(new_log) => {
                                                if let Ok(logs) = read_logs(dir, self, latest) {
                                                    (latest, logs)
                                                } else {
                                                    (latest, vec![create_log_cell(new_log)])
                                                }
                                            }
                                            Err(new_log_err) => {
                                                let msg = "cannot create new empty log after failing to read existing logs";
                                                return Err(new_log_err.message(msg).source(err));
                                            }
                                        }
                                    }
                                }
                            }
                            Err(err) => {
                                if err.kind() == io::ErrorKind::NotFound {
                                    // latest does not exist.
                                    // Most likely, it is a new empty directory.
                                    // Create an empty log and update latest.
                                    let latest = 0;
                                    let new_log = create_empty_log(Some(dir), self, latest, &lock)?;
                                    (latest, vec![create_log_cell(new_log)])
                                } else {
                                    // latest cannot be read for other reasons.
                                    //
                                    // Mark as corrupted, if 'latest' contains a number that cannot be
                                    // parsed.
                                    let corrupted = err.kind() == io::ErrorKind::InvalidData;
                                    let mut result = Err(err).context(dir, "cannot read 'latest'");
                                    if corrupted {
                                        result = result.corruption();
                                    }
                                    return result;
                                }
                            }
                        }
                    }
                }
            };

            let logs_len = AtomicUsize::new(logs.len());
            let mut rotate_log = RotateLog {
                dir: Some(dir.into()),
                open_options: self.clone(),
                logs,
                logs_len,
                load_failed: AtomicBool::new(false),
                pinned_logs: Vec::new(),
                latest,
                reader_lock: Some(reader_lock),
                change_detector: Some(change_detector),
                next_btrfs_size_check: None,
                #[cfg(test)]
                hook_after_log_sync: None,
                consistent_reads: Default::default(),
            };
            rotate_log.update_change_detector_to_match_meta();
            Ok(rotate_log)
        })();

        result.context(|| format!("in rotate::OpenOptions::open({dir:?})"))
    }

    /// Open an-empty [`RotateLog`] in memory. The [`RotateLog`] cannot [`RotateLog::sync`].
    pub fn create_in_memory(&self) -> crate::Result<RotateLog> {
        let result: crate::Result<_> = (|| {
            let cell = create_log_cell(self.log_open_options.open(())?);
            let mut logs = Vec::with_capacity(1);
            logs.push(cell);
            let logs_len = AtomicUsize::new(logs.len());
            Ok(RotateLog {
                dir: None,
                open_options: self.clone(),
                logs,
                logs_len,
                load_failed: AtomicBool::new(false),
                pinned_logs: Vec::new(),
                latest: 0,
                reader_lock: None,
                change_detector: None,
                next_btrfs_size_check: None,
                #[cfg(test)]
                hook_after_log_sync: None,
                consistent_reads: Default::default(),
            })
        })();
        result.context("in rotate::OpenOptions::create_in_memory")
    }

    /// Try repair all logs in the specified directory.
    ///
    /// This just calls into [`log::OpenOptions::repair`] recursively.
    pub fn repair(&self, dir: impl AsRef<Path>) -> crate::Result<String> {
        let dir = dir.as_ref();
        (|| -> crate::Result<_> {
            let _lock = ScopedDirLock::new(dir)?;

            let mut message = RepairMessage::new(dir);
            message += &format!("Processing RotateLog: {dir:?}\n");
            let read_dir = dir.read_dir().context(dir, "cannot readdir")?;
            let mut ids = Vec::new();

            for entry in read_dir {
                let entry = entry.context(dir, "cannot readdir")?;
                let name = entry.file_name();
                if let Some(name) = name.to_str() {
                    if let Ok(id) = name.parse::<u8>() {
                        ids.push(id);
                    }
                }
            }

            ids.sort_unstable();
            for &id in ids.iter() {
                let name = id.to_string();
                message += &format!("Attempt to repair log {name:?}\n");
                match self.log_open_options.repair(dir.join(name)) {
                    Ok(log) => message += &log,
                    Err(err) => message += &format!("Failed: {err}\n"),
                }
            }

            let latest_path = dir.join(LATEST_FILE);
            match read_latest_raw(dir) {
                Ok(latest) => message += &format!("Latest = {latest}\n"),
                Err(err) => match err.kind() {
                    io::ErrorKind::NotFound
                    | io::ErrorKind::InvalidData
                    | io::ErrorKind::UnexpectedEof => {
                        let latest = guess_latest(ids);
                        let content = format!("{latest}");
                        let fsync = false;
                        utils::atomic_write(&latest_path, content, fsync)?;
                        message += &format!("Reset latest to {latest}\n");
                    }
                    _ => return Err(err).context(&latest_path, "cannot read or parse"),
                },
            };

            Ok(message.into_string())
        })()
        .context(|| format!("in rotate::OpenOptions::repair({dir:?})"))
    }
}

impl OpenOptionsRepair for OpenOptions {
    fn open_options_repair(&self, dir: impl AsRef<Path>) -> crate::Result<String> {
        OpenOptions::repair(self, dir.as_ref())
    }
}

impl OpenOptionsOutput for OpenOptions {
    type Output = RotateLog;

    fn open_path(&self, path: &Path) -> crate::Result<Self::Output> {
        self.open(path)
    }
}

impl fmt::Debug for OpenOptions {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "OpenOptions {{ ")?;
        write!(f, "max_bytes_per_log: {}, ", self.max_bytes_per_log)?;
        write!(f, "max_log_count: {}, ", self.max_log_count)?;
        write!(f, "auto_sync_threshold: {:?}, ", self.auto_sync_threshold)?;
        write!(f, "log_open_options: {:?} }}", self.log_open_options)?;
        Ok(())
    }
}

impl RotateLog {
    /// Append data to the writable [`Log`].
    pub fn append(&mut self, data: impl Appendable) -> crate::Result<()> {
        let data_len = data.data_len();
        self.append_internal(|buf| data.write_to(buf), data_len)
    }

    fn append_internal<E>(
        &mut self,
        cb: impl Fn(&mut dyn ExtendWrite) -> Result<(), E>,
        data_len: Option<usize>,
    ) -> crate::Result<()>
    where
        E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
    {
        self.maybe_clear_pinned_logs();

        (|| -> crate::Result<_> {
            let threshold = self.open_options.auto_sync_threshold;
            let log = self.writable_log();
            log.append_internal(cb, data_len)?;
            if let Some(threshold) = threshold {
                if log.mem_buf.len() as u64 >= threshold {
                    self.sync()
                        .context("sync triggered by auto_sync_threshold")?;
                }
            }
            Ok(())
        })()
        .context("in RotateLog::append")
    }

    /// Look up an entry using the given index. The `index_id` is the index of
    /// `index_defs` stored in [`OpenOptions`].
    pub fn lookup(
        &self,
        index_id: usize,
        key: impl Into<Bytes>,
    ) -> crate::Result<RotateLogLookupIter<'_>> {
        let key = key.into();
        let result: crate::Result<_> = (|| {
            Ok(RotateLogLookupIter {
                inner_iter: self.logs[0].get().unwrap().lookup(index_id, &key)?,
                end: false,
                log_rotate: self,
                log_index: 0,
                index_id,
                key: key.clone(),
                pinned_logs: if self.is_consistent_reads() {
                    &self.pinned_logs
                } else {
                    &[]
                },
            })
        })();
        result
            .context(|| format!("in RotateLog::lookup({}, {:?})", index_id, key.as_ref()))
            .context(|| format!("  RotateLog.dir = {:?}", self.dir))
    }

    /// Convert a slice to [`Bytes`].
    ///
    /// Do not copy the slice if it's from the main on-disk buffer of
    /// one of the loaded logs.
    pub fn slice_to_bytes(&self, slice: &[u8]) -> Bytes {
        for log in &self.logs {
            if let Some(log) = log.get() {
                if log.disk_buf.range_of_slice(slice).is_some() {
                    return log.slice_to_bytes(slice);
                }
            }
        }
        Bytes::copy_from_slice(slice)
    }

    /// Look up an entry using the given index. The `index_id` is the index of
    /// `index_defs` stored in [`OpenOptions`].
    ///
    /// Unlike [`RotateLog::lookup`], this function only checks the "latest"
    /// (i.e. "writable") [`Log`] without checking others. It is useful to make
    /// sure certain contents depending on other entries are inserted into
    /// the same [`Log`].
    ///
    /// Practically, a `flush_filter` should also be used to make sure dependent
    /// entries are stored in a same [`Log`]. So this function will panic if
    /// `flush_filter` is not set on [`OpenOptions`].
    pub fn lookup_latest(
        &self,
        index_id: usize,
        key: impl AsRef<[u8]>,
    ) -> crate::Result<log::LogLookupIter<'_>> {
        let key = key.as_ref();
        assert!(
            self.open_options.log_open_options.flush_filter.is_some(),
            "programming error: flush_filter should also be set"
        );
        self.logs[0]
            .get()
            .unwrap()
            .lookup(index_id, key)
            .context(|| format!("in RotateLog::lookup_latest({index_id}, {key:?})"))
            .context(|| format!("  RotateLog.dir = {:?}", self.dir))
    }

    /// Read latest data from disk. Write in-memory entries to disk.
    ///
    /// Return the index of the latest [`Log`].
    ///
    /// For in-memory [`RotateLog`], this function always returns 0.
    pub fn sync(&mut self) -> crate::Result<u8> {
        self.maybe_clear_pinned_logs();

        let result: crate::Result<_> = (|| {
            let span = debug_span!("RotateLog::sync", latest = self.latest as u32);
            if let Some(dir) = &self.dir {
                span.record("dir", dir.to_string_lossy().as_ref());
            }
            let _guard = span.enter();

            if self.dir.is_none() {
                return Ok(0);
            }

            if self.writable_log().iter_dirty().next().is_none() {
                // Read-only path, no need to take directory lock.
                match read_latest(self.dir.as_ref().unwrap()) {
                    Ok(latest) => {
                        if latest != self.latest {
                            // Latest changed. Re-load and write to the real latest Log.
                            // PERF(minor): This can be smarter by avoiding reloading some logs.
                            self.set_logs(
                                latest,
                                read_logs(self.dir.as_ref().unwrap(), &self.open_options, latest)?,
                            );
                        }
                        self.writable_log().sync()?;
                    }
                    Err(err) => {
                        // If latest can not be read, do not error out.
                        // This RotateLog can still be used to answer queries.
                        tracing::error!(?err, "ignoring error reading latest log");
                    }
                }
            } else {
                // Read-write path. Take the directory lock.
                let dir = self.dir.clone().unwrap();
                let lock = ScopedDirLock::new(&dir)?;

                // Re-read latest, since it might have changed after taking the lock.
                let latest = read_latest(self.dir.as_ref().unwrap())?;
                if latest != self.latest {
                    // Latest changed. Re-load and write to the real latest Log.
                    //
                    // This is needed because RotateLog assumes non-latest logs
                    // are read-only. Other processes using RotateLog won't reload
                    // non-latest logs automatically.
                    // PERF(minor): This can be smarter by avoiding reloading some logs.
                    let mut new_logs =
                        read_logs(self.dir.as_ref().unwrap(), &self.open_options, latest)?;
                    if let Some(filter) = self.open_options.log_open_options.flush_filter {
                        let log = new_logs[0].get_mut().unwrap();
                        for entry in self.writable_log().iter_dirty() {
                            let content = entry?;
                            let context = FlushFilterContext { log };
                            match filter(&context, content).map_err(|err| {
                                crate::Error::wrap(err, "failed to run filter function")
                            })? {
                                FlushFilterOutput::Drop => {}
                                FlushFilterOutput::Keep => log.append(content)?,
                                FlushFilterOutput::Replace(content) => log.append(content)?,
                            }
                        }
                    } else {
                        let log = new_logs[0].get_mut().unwrap();
                        // Copy entries to new Logs.
                        for entry in self.writable_log().iter_dirty() {
                            let bytes = entry?;
                            log.append(bytes)?;
                        }
                    }
                    self.set_logs(latest, new_logs);
                }

                let size = self.writable_log().flush()?;

                #[cfg(test)]
                if let Some(func) = self.hook_after_log_sync.as_ref() {
                    func();
                }

                let needs_rotation = if self.open_options.log_open_options.btrfs_compression {
                    self.btrfs_needs_rotation(size)?
                } else {
                    size >= self.open_options.max_bytes_per_log
                };

                if needs_rotation {
                    // `self.writable_log()` will be rotated (i.e., becomes immutable).
                    // Make sure indexes are up-to-date so reading it would not require
                    // building missing indexes in-memory.
                    self.writable_log().finalize_indexes(&lock)?;
                    self.rotate_internal(&lock)?;
                }
            }

            self.update_change_detector_to_match_meta();
            Ok(self.latest)
        })();

        result
            .context("in RotateLog::sync")
            .context(|| format!("  RotateLog.dir = {:?}", self.dir))
    }

    fn btrfs_needs_rotation(&mut self, apparent_size: u64) -> crate::Result<bool> {
        // Use predicted threshold based on btrfs compression ratio, if available.
        let threshold = self
            .next_btrfs_size_check
            .unwrap_or(self.open_options.max_bytes_per_log);

        if apparent_size < threshold {
            // Avoid checking btrfs size if we haven't reached the threshold yet.
            return Ok(false);
        }

        let btrfs_size = self.writable_log().btrfs_size()?;

        debug!(btrfs_size, apparent_size, "btrfs physical size");

        if btrfs_size >= self.open_options.max_bytes_per_log {
            // Physical log size has passed the threshold - time to rotate.
            return Ok(true);
        }

        if btrfs_size > 0 && apparent_size > 0 && !self.open_options.log_open_options.fsync {
            // If we aren't fsyncing, compute compression ratio and predict when we
            // are going to need rotation. This is to minimize btrfs size queries,
            // which are relatively slow because they fsync the file.
            let compression_ratio = (btrfs_size as f64) / (apparent_size as f64);
            if compression_ratio > 0f64 {
                let predicted_threshold =
                    (self.open_options.max_bytes_per_log as f64 / compression_ratio) as u64;

                // Cap our predicted threshold increase to self.open_options.max_bytes_per_log. For
                // example, if max_bytes_per_log=10MB, and after 10MB of writes the log is only
                // 100KB, we would "predict" a new threshold of 1GB based on the 1% compression
                // ratio. Instead, cap the threshold at 20MB, lest the high compression was just
                // temporary.
                let predicted_threshold =
                    predicted_threshold.min(apparent_size + self.open_options.max_bytes_per_log);

                debug!(
                    predicted_threshold,
                    compression_ratio, "setting predicted rotation threshold"
                );
                self.next_btrfs_size_check = Some(predicted_threshold);
            }
        }

        Ok(false)
    }

    fn update_change_detector_to_match_meta(&mut self) {
        let meta = &self.writable_log().meta;
        let value = meta.primary_len ^ meta.epoch ^ ((self.latest as u64) << 56);
        if let Some(detector) = &self.change_detector {
            detector.set(value);
        }
    }

    /// Attempt to remove outdated logs.
    ///
    /// Does nothing if the content of the 'latest' file has changed on disk,
    /// which indicates rotation was triggered elsewhere, or the [`RotateLog`]
    /// is in-memory.
    pub fn remove_old_logs(&mut self) -> crate::Result<()> {
        if let Some(dir) = &self.dir {
            // Optimistic lock-free check: skip the exclusive lock if there
            // are no old logs to clean up, which is the common case.
            let latest = read_latest(dir)?;
            if latest != self.latest || !self.maybe_has_old_logs() {
                return Ok(());
            }
            let lock = ScopedDirLock::new(dir)?;
            let latest = read_latest(dir)?;
            if latest == self.latest {
                self.try_remove_old_logs(&lock);
            }
        }
        Ok(())
    }

    /// Check if there are log directories outside the valid range.
    /// We don't take any locks, so this is a racey "best effort" check.
    fn maybe_has_old_logs(&self) -> bool {
        let dir = match &self.dir {
            Some(dir) => dir,
            None => return false,
        };
        let read_dir = match dir.read_dir() {
            Ok(read_dir) => read_dir,
            Err(_) => return false,
        };
        let latest = self.latest;
        let earliest = latest.wrapping_sub(self.open_options.max_log_count - 1);
        for entry in read_dir {
            if let Ok(entry) = entry {
                if let Some(name) = entry.file_name().to_str() {
                    if let Ok(id) = name.parse::<u8>() {
                        let is_active = if latest >= earliest {
                            id >= earliest && id <= latest
                        } else {
                            id >= earliest || id <= latest
                        };
                        if !is_active {
                            return true;
                        }
                    }
                }
            }
        }
        false
    }

    /// Returns `true` if `sync` will load more data on disk.
    ///
    /// This function is optimized to be called frequently. It does not access
    /// the filesystem directly, but communicate using a shared mmap buffer.
    ///
    /// This is not about testing buffered pending changes. To access buffered
    /// pending changes, use [`RotateLog::iter_dirty`] instead.
    pub fn is_changed_on_disk(&self) -> bool {
        match &self.change_detector {
            Some(detector) => detector.is_changed(),
            None => false,
        }
    }

    /// Force create a new [`Log`]. Bump latest.
    ///
    /// This function requires it's protected by a directory lock, and the
    /// callsite makes sure that [`Log`]s are consistent (ex. up-to-date,
    /// and do not have dirty entries in non-writable logs).
    fn rotate_internal(&mut self, lock: &ScopedDirLock) -> crate::Result<()> {
        ROTATE_COUNT.add(1);

        let dir_name = match &self.dir {
            Some(dir) => dir.to_string_lossy(),
            None => "<none>".into(),
        };

        // This is relative to the primary log, so clear it out when rotating.
        self.next_btrfs_size_check.take();

        let span = debug_span!(
            "RotateLog::rotate",
            dir = %dir_name,
            latest = self.latest as u32
        );
        let _guard = span.enter();

        // Create a new Log. Bump latest.
        let next = self.latest.wrapping_add(1);
        let log = create_empty_log(
            Some(self.dir.as_ref().unwrap()),
            &self.open_options,
            next,
            lock,
        )?;
        if self.logs.len() >= self.open_options.max_log_count as usize {
            if let Some(log) = self.logs.pop().and_then(|mut l| l.take()) {
                info!(
                    %dir_name,
                    len = log.meta.primary_len,
                    "RotateLog dropping log"
                );

                if self.is_consistent_reads() {
                    self.pinned_logs.push(log);
                }
            }
        }

        self.logs.insert(0, create_log_cell(log));
        self.logs_len = AtomicUsize::new(self.logs.len());
        self.latest = next;
        self.try_remove_old_logs(lock);
        Ok(())
    }

    /// Renamed. Use [`RotateLog::sync`] instead.
    pub fn flush(&mut self) -> crate::Result<u8> {
        self.sync()
    }

    fn set_logs(&mut self, latest: u8, logs: Vec<OnceLock<Log>>) {
        // This is relative to the primary log, so clear it out when logs changed.
        self.next_btrfs_size_check.take();

        if self.is_consistent_reads() {
            // If we are in "consistent read" mode, store any Logs we would be rotating out into
            // self.pinned_logs. If "latest" has wrapped more than once, we may not pin the right
            // Logs.
            for mut to_pin in std::mem::take(&mut self.logs)
                .into_iter()
                .rev()
                .take(latest.wrapping_sub(self.latest) as usize)
            {
                match to_pin.take() {
                    Some(log) => self.pinned_logs.push(log),
                    None => break,
                }
            }
        }

        self.logs_len = AtomicUsize::new(logs.len());
        // Fresh, not-yet-loaded log cells: any earlier load failure no
        // longer applies to this generation of `logs`.
        self.load_failed = AtomicBool::new(false);
        self.logs = logs;
        self.latest = latest;
    }

    #[allow(clippy::nonminimal_bool)]
    fn try_remove_old_logs(&self, _lock: &ScopedDirLock) {
        if let Ok(read_dir) = self.dir.as_ref().unwrap().read_dir() {
            let latest = self.latest;
            let earliest = latest.wrapping_sub(self.open_options.max_log_count - 1);
            for entry in read_dir {
                if let Ok(entry) = entry {
                    let name = entry.file_name();
                    debug!("Inspecting {:?} for rotate log removal", name);
                    if let Some(name) = name.to_str() {
                        if let Ok(id) = name.parse::<u8>() {
                            if (latest >= earliest && (id > latest || id < earliest))
                                || (latest < earliest && (id > latest && id < earliest))
                            {
                                // Explicitly delete the `meta` file first. This marks
                                // the log as "deleted" in an atomic way.
                                //
                                // Errors are not fatal. On Windows, this can fail if
                                // other processes have files in entry.path() mmap-ed.
                                // Newly opened or flushed RotateLog will unmap files.
                                // New rotation would trigger remove_dir_all to try
                                // remove old logs again.
                                match fs::remove_file(entry.path().join(log::META_FILE)) {
                                    Ok(()) => {}
                                    Err(e) if e.kind() == io::ErrorKind::NotFound => {
                                        // Meta file is already deleted.
                                    }
                                    Err(e) => {
                                        // Don't delete the log if we were unable to delete the
                                        // meta file.
                                        debug!(
                                            "Error removing rotate log meta: {:?} {:?}",
                                            name, e
                                        );
                                        continue;
                                    }
                                }

                                // Delete the rest of the directory.
                                let res = fs::remove_dir_all(entry.path());
                                match res {
                                    Ok(_) => debug!("Removed rotate log: {:?}", name),
                                    Err(err) => {
                                        debug!("Error removing rotate log directory: {:?}", err)
                                    }
                                };
                            } else {
                                debug!(
                                    "Not removing rotate log: {:?} (latest: {:?}, earliest: {:?})",
                                    name, latest, earliest
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    /// Get the writable [`Log`].
    fn writable_log(&mut self) -> &mut Log {
        self.logs[0].get_mut().unwrap()
    }

    /// Lazily load a log. The 'latest' (or 'writable') log has index 0.
    fn load_log(&self, index: usize) -> crate::Result<Option<&Log>> {
        if index >= self.logs_len.load(SeqCst) {
            return Ok(None);
        }
        match self.logs.get(index) {
            Some(cell) => {
                let id = self.latest.wrapping_sub(index as u8);
                if let Some(dir) = &self.dir {
                    let log = cell.get_or_try_init(|| {
                        let mut open_options = self.open_options.log_open_options.clone();
                        if index > 0 {
                            open_options = open_options.with_zero_index_lag();
                        }
                        let log = load_log(dir, id, open_options);
                        trace!(
                            name = "RotateLog::load_log",
                            index = index,
                            success = log.is_ok()
                        );
                        log
                    });
                    match log {
                        Ok(log) => Ok(Some(log)),
                        Err(err) => {
                            // Record the load failure *before* narrowing
                            // `logs_len` below. `disk_usage()` checks
                            // `load_failed` first, so a concurrent reader
                            // must never be able to observe the narrowed
                            // length without also seeing this flag - doing
                            // it in the other order leaves a window where a
                            // concurrent `disk_usage()` call sees the
                            // already-narrowed `logs_len` but a still-false
                            // `load_failed`, and silently returns the exact
                            // partial sum this flag exists to prevent.
                            self.load_failed.store(true, SeqCst);
                            // Logically truncate self.logs. This avoids loading broken Logs again.
                            self.logs_len.store(index, SeqCst);
                            Err(err)
                        }
                    }
                } else {
                    Ok(cell.get())
                }
            }
            None => unreachable!(),
        }
    }

    /// Iterate over all the entries.
    ///
    /// The entries are returned in FIFO order.
    pub fn iter(&self) -> impl Iterator<Item = crate::Result<&[u8]>> {
        let logs = self.logs();
        logs.into_iter().rev().flat_map(|log| log.iter())
    }

    /// Returns `true` if there are in-memory changes that haven't been flushed to disk.
    pub fn is_dirty(&self) -> bool {
        match self.logs[0].get() {
            Some(log) => log.is_dirty(),
            None => false,
        }
    }

    /// Iterate over all dirty entries.
    pub fn iter_dirty(&self) -> impl Iterator<Item = crate::Result<&[u8]>> {
        self.logs[0].get().unwrap().iter_dirty()
    }

    /// Guarantee read-after-write consistency for this RotateLog while guard is alive. Log rotation
    /// still happens as normal, but this RotateLog avoids dropping Log objects that have been
    /// rotated.
    ///
    /// BUG: This currently does not work properly if there are more than 255 rotations by another
    /// RotateLog instance before we reload from disk. The "latest" number is represented as a u8,
    /// so we can't tell the difference between 1 and 256 rotations.
    pub fn with_consistent_reads(&mut self) -> ConsistentReadGuard {
        self.consistent_reads.fetch_add(1, Ordering::AcqRel);
        ConsistentReadGuard {
            count: self.consistent_reads.clone(),
        }
    }

    /// Return whether we are in "consistent read" mode. This mode means we should not drop any
    /// Logs, lest we lose track of writes we made while consistent read mode was active.
    fn is_consistent_reads(&self) -> bool {
        self.consistent_reads.load(Ordering::Acquire) > 0
    }

    /// If we aren't in "consistent read" mode, clear out any Logs we may have pinned.
    fn maybe_clear_pinned_logs(&mut self) {
        if !self.is_consistent_reads() {
            self.pinned_logs.clear();
        }
    }

    /// Returns the current disk usage in bytes. Disk-backed logs are measured
    /// from their on-disk metadata so a removed or truncated cache cannot be
    /// reported from a stale in-memory snapshot.
    ///
    /// When `btrfs_compression` is configured, this reports the physical
    /// (compressed) size of each log instead of the logical `primary_len`,
    /// matching the unit `btrfs_needs_rotation` compares against
    /// `max_bytes_per_log` - otherwise `disk_usage()`/`max_bytes()` would
    /// mix compressed and uncompressed units and could report over 100%
    /// used on a healthy, compressing filesystem.
    ///
    /// This is O(max_log_count). The non-Btrfs path reads one metadata file
    /// and stats one primary file per log. With `btrfs_compression`, each log
    /// additionally requires an `fsync` and a `BTRFS_IOC_TREE_SEARCH_V2`
    /// extent scan (see `btrfs::physical_size`), so callers should not use it
    /// in a hot path.
    ///
    /// The active generation and `load_failed` are checked before and after
    /// summation so concurrent rotation or lazy-load failure cannot produce a
    /// successful partial result.
    pub fn disk_usage(&self) -> crate::Result<u64> {
        fn load_failed_err() -> crate::Error {
            crate::Error::programming(
                "RotateLog::disk_usage: a log previously failed to load; usage is unavailable \
                 until the logs are fully reloaded",
            )
        }

        if self.load_failed.load(SeqCst) {
            return Err(load_failed_err());
        }

        let logs_len = self.logs_len.load(SeqCst);
        let use_btrfs_physical_size = self.open_options.log_open_options.btrfs_compression;
        let mut total: u64 = 0;

        if let Some(dir) = &self.dir {
            let verify_latest = || -> crate::Result<()> {
                let latest = read_latest(dir)?;
                if latest != self.latest {
                    return Err(crate::Error::path(
                        dir,
                        format!(
                            "latest log changed while measuring disk usage: {} != {}",
                            latest, self.latest
                        ),
                    ));
                }
                Ok(())
            };

            verify_latest()?;
            for i in 0..logs_len {
                let id = self.latest.wrapping_sub(i as u8);
                let log_dir = dir.join(id.to_string());
                total = total.saturating_add(measure_disk_log(&log_dir, use_btrfs_physical_size)?);
            }
            verify_latest()?;
        } else {
            for i in 0..logs_len {
                let log = self
                    .logs
                    .get(i)
                    .and_then(|cell| cell.get())
                    .ok_or_else(|| {
                        crate::Error::programming(
                            "RotateLog::disk_usage: in-memory log was not loaded",
                        )
                    })?;
                total = total.saturating_add(log.meta.disk_usage());
            }
        }

        if self.load_failed.load(SeqCst) {
            return Err(load_failed_err());
        }

        Ok(total)
    }

    /// Returns the configured maximum size in bytes (max_bytes_per_log * max_log_count).
    pub fn max_bytes(&self) -> u64 {
        self.open_options
            .max_bytes_per_log
            .saturating_mul(self.open_options.max_log_count as u64)
    }

    /// Returns the directory path, if this is an on-disk RotateLog.
    pub fn path(&self) -> Option<&Path> {
        self.dir.as_deref()
    }
}

pub struct ConsistentReadGuard {
    count: Arc<AtomicU64>,
}

impl Drop for ConsistentReadGuard {
    fn drop(&mut self) {
        self.count.fetch_sub(1, Ordering::AcqRel);
    }
}

/// Wrap `Log` in a `OnceCell`.
fn create_log_cell(log: Log) -> OnceLock<Log> {
    let cell = OnceLock::new();
    cell.set(log)
        .expect("cell is empty so cell.set cannot fail");
    cell
}

/// Load a single log at the given location.
fn load_log(dir: &Path, id: u8, open_options: log::OpenOptions) -> crate::Result<Log> {
    let name = format!("{id}");
    let log_path = dir.join(name);
    open_options.create(false).open(log_path)
}

/// Get access to internals of [`RotateLog`].
///
/// This can be useful when there are low-level needs. For example:
/// - Get access to individual logs for things like range query.
/// - Rotate logs manually.
pub trait RotateLowLevelExt {
    /// Get a view of all individual logs. Newest first.
    fn logs(&self) -> Vec<&Log>;
}

impl RotateLowLevelExt for RotateLog {
    fn logs(&self) -> Vec<&Log> {
        (0..)
            .map(|i| self.load_log(i))
            .take_while(|res| match res {
                Ok(Some(_)) => true,
                _ => false,
            })
            .map(|res| res.unwrap().unwrap())
            .collect()
    }
}

/// Iterator over [`RotateLog`] entries selected by an index lookup.
pub struct RotateLogLookupIter<'a> {
    inner_iter: log::LogLookupIter<'a>,
    end: bool,
    log_rotate: &'a RotateLog,
    pinned_logs: &'a [Log],
    log_index: usize,
    index_id: usize,
    key: Bytes,
}

impl<'a> RotateLogLookupIter<'a> {
    fn load_next_log(&mut self) -> crate::Result<()> {
        // Iterate over self.log_rotate.logs (active logs) along with self.pinned_logs, which are
        // previously rotated out Logs that we have temporarily held onto to provide
        // read-after-write consistency.
        if self.log_index + 1 >= self.log_rotate.logs.len() + self.pinned_logs.len() {
            self.end = true;
            Ok(())
        } else {
            // Try the next log
            self.log_index += 1;

            let log = if self.log_index >= self.log_rotate.logs.len() {
                Ok(self
                    .pinned_logs
                    .get(self.log_index - self.log_rotate.logs.len()))
            } else {
                self.log_rotate.load_log(self.log_index)
            };

            match log {
                Ok(None) => {
                    self.end = true;
                    Ok(())
                }
                Err(_err) => {
                    self.end = true;
                    // Not fatal (since RotateLog is designed to be able
                    // to drop data).
                    Ok(())
                }
                Ok(Some(log)) => match log.lookup(self.index_id, &self.key) {
                    Err(err) => {
                        self.end = true;
                        Err(err)
                    }
                    Ok(iter) => {
                        self.inner_iter = iter;
                        Ok(())
                    }
                },
            }
        }
    }

    /// Consume iterator, returning whether the iterator has any data.
    pub fn is_empty(mut self) -> crate::Result<bool> {
        while !self.end {
            if !self.inner_iter.is_empty() {
                return Ok(false);
            }
            self.load_next_log()?;
        }
        Ok(true)
    }
}

impl<'a> Iterator for RotateLogLookupIter<'a> {
    type Item = crate::Result<&'a [u8]>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.end {
            return None;
        }
        match self.inner_iter.next() {
            None => {
                if let Err(err) = self.load_next_log() {
                    return Some(Err(err));
                }

                if self.end {
                    return None;
                }

                self.next()
            }
            Some(Err(err)) => {
                self.end = true;
                Some(Err(err))
            }
            Some(Ok(slice)) => Some(Ok(slice)),
        }
    }
}

fn create_empty_log(
    dir: Option<&Path>,
    open_options: &OpenOptions,
    latest: u8,
    _lock: &ScopedDirLock,
) -> crate::Result<Log> {
    Ok(match dir {
        Some(dir) => {
            let latest_path = dir.join(LATEST_FILE);
            let latest_str = format!("{latest}");
            let log_path = dir.join(&latest_str);
            let opts = open_options.log_open_options.clone().create(true);
            opts.delete_content(&log_path)?;
            let log = opts.open(&log_path)?;
            utils::atomic_write(latest_path, latest_str.as_bytes(), false)?;
            log
        }
        None => open_options.log_open_options.clone().open(())?,
    })
}

fn read_latest(dir: &Path) -> crate::Result<u8> {
    read_latest_raw(dir).context(dir, "cannot read latest")
}

/// Measure one on-disk log's disk usage for `RotateLog::disk_usage`, reading
/// from on-disk state rather than any in-memory snapshot so a removed or
/// truncated cache surfaces as an error instead of a stale byte count.
///
/// Errors if the log's metadata is unreadable (e.g. the cache directory was
/// deleted) or its primary file is shorter than the metadata claims (i.e. it
/// was truncated). With `use_btrfs_physical_size`, reports the physical
/// (compressed) extent size; otherwise the logical `primary_len`.
fn measure_disk_log(log_dir: &Path, use_btrfs_physical_size: bool) -> crate::Result<u64> {
    let meta = log::LogMetadata::read_file(log_dir.join(log::META_FILE))?;
    let log_path = log_dir.join(log::PRIMARY_FILE);
    let log_file = fs::File::open(&log_path)
        .context(&log_path, "opening primary log to measure disk usage")?;
    let actual_len = log_file
        .metadata()
        .context(&log_path, "reading primary log length")?
        .len();
    if actual_len < meta.disk_usage() {
        return Err(crate::Error::corruption(
            &log_path,
            format!(
                "primary log is shorter than metadata: {} < {}",
                actual_len,
                meta.disk_usage()
            ),
        ));
    }

    if use_btrfs_physical_size {
        let btrfs_metadata = btrfs::physical_size(&log_file, None)
            .context(&log_path, "reading btrfs physical size")?;
        Ok(btrfs_metadata.size())
    } else {
        Ok(meta.disk_usage())
    }
}

// Unlike read_latest, this function returns io::Result.
fn read_latest_raw(dir: &Path) -> io::Result<u8> {
    let latest_path = dir.join(LATEST_FILE);
    let data = utils::atomic_read(&latest_path)?;
    let content: String = String::from_utf8(data).map_err(|_e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{latest_path:?}: failed to read as utf8 string"),
        )
    })?;
    let id: u8 = content.parse().map_err(|_e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{latest_path:?}: failed to parse {content:?} as u8 integer"),
        )
    })?;
    Ok(id)
}

fn read_logs(
    dir: &Path,
    open_options: &OpenOptions,
    latest: u8,
) -> crate::Result<Vec<OnceLock<Log>>> {
    let mut logs = Vec::with_capacity(open_options.max_log_count as usize);

    // Make sure the first log (latest) can be loaded.
    let log = load_log(dir, latest, open_options.log_open_options.clone())?;
    logs.push(create_log_cell(log));

    // Lazily load the rest of logs.
    for index in 1..open_options.max_log_count {
        let id = latest.wrapping_sub(index);
        // Do a quick check about whether the log exists or not so we
        // can avoid unnecessary `Log::open`.
        let name = format!("{id}");
        let log_path = dir.join(&name);
        if !log_path.is_dir() {
            break;
        }
        logs.push(OnceLock::new());
    }
    trace!(
        name = "RotateLog::read_logs",
        max_log_count = open_options.max_log_count,
        logs_len = logs.len()
    );

    Ok(logs)
}

fn read_latest_and_logs(
    dir: &Path,
    open_options: &OpenOptions,
) -> crate::Result<(u8, Vec<OnceLock<Log>>)> {
    let latest = read_latest(dir)?;
    Ok((latest, read_logs(dir, open_options, latest)?))
}

/// Given a list of ids, guess a `latest`.
fn guess_latest(mut ids: Vec<u8>) -> u8 {
    // Guess a sensible `latest` from `ids`.
    ids.sort_unstable();

    let mut id_to_ignore = 255;
    loop {
        match ids.pop() {
            Some(id) => {
                // Remove 255, 254, at the end, since they might have been wrapped.
                // For example, guess([0, 1, 2, 254, 255]) is 2.
                if id == id_to_ignore {
                    id_to_ignore -= 1;
                    if id_to_ignore == 0 {
                        // All 255 logs exist - rare.
                        break 0;
                    }
                    continue;
                } else {
                    // This is probably the desirable id.
                    // For example, guess([3, 4, 5]) is 5.
                    break id;
                }
            }
            None => {
                // For example, guess([]) is 0.
                break 0;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use log::IndexOutput;
    use tempfile::tempdir;

    use super::*;

    #[cfg(all(target_os = "linux", feature = "btrfs"))]
    fn is_btrfs(path: &Path) -> bool {
        use std::ffi::CString;
        use std::io::Error;
        use std::mem::zeroed;

        let path = CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
        // SAFETY: statfs is a C struct with integer fields and arrays.
        let mut stat: libc::statfs = unsafe { zeroed() };
        // SAFETY: path is NUL-terminated and stat points to writable storage.
        assert_eq!(
            unsafe { libc::statfs(path.as_ptr(), &mut stat) },
            0,
            "statfs: {}",
            Error::last_os_error()
        );
        stat.f_type == libc::BTRFS_SUPER_MAGIC
    }

    #[test]
    fn test_open() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("rotate");

        assert!(OpenOptions::new().create(false).open(&path).is_err());
        assert!(OpenOptions::new().create(true).open(&path).is_ok());
        assert!(
            OpenOptions::new()
                .checksum_type(log::ChecksumType::Xxhash64)
                .create(false)
                .open(&path)
                .is_ok()
        );
    }

    // lookup via index 0
    fn lookup<'a>(rotate: &'a RotateLog, key: &[u8]) -> Vec<&'a [u8]> {
        let values = rotate
            .lookup(0, key.to_vec())
            .unwrap()
            .collect::<crate::Result<Vec<&[u8]>>>()
            .unwrap();
        for value in &values {
            let b1 = rotate.slice_to_bytes(value);
            let b2 = rotate.slice_to_bytes(value);
            // Dirty entries cannot be zero-copied.
            if rotate
                .iter_dirty()
                .any(|i| i.unwrap().as_ptr() == value.as_ptr())
            {
                continue;
            }
            assert_eq!(
                b1.as_ptr(),
                b2.as_ptr(),
                "slice_to_bytes should return zero-copy"
            );
        }
        values
    }

    fn iter(rotate: &RotateLog) -> Vec<&[u8]> {
        rotate
            .iter()
            .collect::<crate::Result<Vec<&[u8]>>>()
            .unwrap()
    }

    #[test]
    fn test_trivial_append_lookup() {
        let dir = tempdir().unwrap();
        let opts = OpenOptions::new()
            .create(true)
            .index_defs(vec![IndexDef::new("two-bytes", |_| {
                vec![IndexOutput::Reference(0..2)]
            })]);

        let rotate = opts.open(&dir).unwrap();
        let rotate_mem = opts.create_in_memory().unwrap();

        for rotate in &mut [rotate, rotate_mem] {
            rotate.append(b"aaa").unwrap();
            rotate.append(b"abbb").unwrap();
            rotate.append(b"abc").unwrap();

            assert_eq!(lookup(rotate, b"aa"), vec![b"aaa"]);
            assert_eq!(lookup(rotate, b"ab"), vec![&b"abc"[..], b"abbb"]);
            assert_eq!(lookup(rotate, b"ac"), Vec::<&[u8]>::new());
        }
    }

    #[test]
    fn test_simple_rotate() {
        let dir = tempdir().unwrap();
        let mut rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .max_log_count(2)
            .index("first-byte", |_| vec![IndexOutput::Reference(0..1)])
            .open(&dir)
            .unwrap();

        // No rotate.
        rotate.append(b"a").unwrap();
        assert_eq!(rotate.sync().unwrap(), 0);
        rotate.append(b"a").unwrap();
        assert_eq!(rotate.sync().unwrap(), 0);

        // Trigger rotate. "a" is still accessible.
        rotate.append(vec![b'b'; 100]).unwrap();
        assert_eq!(rotate.sync().unwrap(), 1);
        assert_eq!(lookup(&rotate, b"a").len(), 2);

        // Trigger rotate again. Only new entries are accessible.
        // Older directories should be deleted automatically.
        rotate.append(vec![b'c'; 50]).unwrap();
        assert_eq!(rotate.sync().unwrap(), 1);
        rotate.append(vec![b'd'; 50]).unwrap();
        assert_eq!(rotate.sync().unwrap(), 2);
        assert_eq!(lookup(&rotate, b"a").len(), 0);
        assert_eq!(lookup(&rotate, b"b").len(), 0);
        assert_eq!(lookup(&rotate, b"c").len(), 1);
        assert_eq!(lookup(&rotate, b"d").len(), 1);
        assert!(!dir.path().join("0").exists());
    }

    #[test]
    fn test_disk_usage_includes_unloaded_logs() {
        let dir = tempdir().unwrap();
        let opts = || {
            OpenOptions::new()
                .create(true)
                .max_bytes_per_log(100)
                .max_log_count(4)
        };
        let mut rotate = opts().open(&dir).unwrap();

        // Force rotations so multiple on-disk logs exist.
        rotate.append(vec![b'a'; 120]).unwrap();
        assert!(rotate.sync().unwrap() >= 1, "expected a rotation");
        rotate.append(vec![b'b'; 120]).unwrap();
        assert!(rotate.sync().unwrap() >= 1, "expected a rotation");
        rotate.append(b"c").unwrap();
        rotate.sync().unwrap();
        let usage_all_loaded = rotate.disk_usage().unwrap();
        assert!(
            usage_all_loaded >= 240,
            "all-loaded usage should cover both rotated logs, got {usage_all_loaded}"
        );

        // A freshly opened RotateLog eagerly loads only the active log; the
        // rotated logs are lazy. disk_usage must still account for them by
        // reading their on-disk meta.
        let reopened = opts().open(&dir).unwrap();
        assert_eq!(
            reopened.disk_usage().unwrap(),
            usage_all_loaded,
            "disk_usage must not under-report lazily-unloaded logs"
        );
    }

    #[test]
    fn test_disk_usage_errors_once_a_log_fails_to_load() {
        let dir = tempdir().unwrap();
        let rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .max_log_count(4)
            .open(&dir)
            .unwrap();
        assert!(rotate.disk_usage().is_ok());

        rotate.load_failed.store(true, SeqCst);

        assert!(
            rotate.disk_usage().is_err(),
            "disk_usage must error, not silently sum a narrowed range, once a log has failed to load"
        );
    }

    #[test]
    fn test_disk_usage_errors_when_loaded_cache_metadata_disappears() {
        let dir = tempdir().unwrap();
        let mut rotate = OpenOptions::new().create(true).open(&dir).unwrap();
        rotate.append(b"data").unwrap();
        rotate.sync().unwrap();
        assert!(rotate.disk_usage().is_ok());

        let meta_path = dir
            .path()
            .join(rotate.latest.to_string())
            .join(log::META_FILE);
        fs::remove_file(meta_path).unwrap();

        assert!(rotate.disk_usage().is_err());
    }

    #[test]
    fn test_disk_usage_errors_when_latest_disappears() {
        let dir = tempdir().unwrap();
        let rotate = OpenOptions::new().create(true).open(&dir).unwrap();
        assert!(rotate.disk_usage().is_ok());

        fs::remove_file(dir.path().join(LATEST_FILE)).unwrap();

        assert!(rotate.disk_usage().is_err());
    }

    #[test]
    fn test_disk_usage_errors_when_primary_is_shorter_than_metadata() {
        let dir = tempdir().unwrap();
        let mut rotate = OpenOptions::new().create(true).open(&dir).unwrap();
        rotate.append(b"data").unwrap();
        rotate.sync().unwrap();

        let log_dir = dir.path().join(rotate.latest.to_string());
        let primary_path = log_dir.join(log::PRIMARY_FILE);
        let meta_path = log_dir.join(log::META_FILE);
        let mut meta = log::LogMetadata::read_file(&meta_path).unwrap();
        meta.primary_len = fs::metadata(primary_path).unwrap().len() + 1;
        meta.write_file(meta_path, false).unwrap();

        assert!(rotate.disk_usage().is_err());
    }

    #[test]
    fn test_rotation_does_not_clear_load_failure() {
        let dir = tempdir().unwrap();
        let mut rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(1)
            .max_log_count(4)
            .open(&dir)
            .unwrap();
        rotate.load_failed.store(true, SeqCst);

        rotate.append(b"data").unwrap();
        assert!(rotate.sync().unwrap() > 0, "expected a rotation");

        assert!(rotate.load_failed.load(SeqCst));
        assert!(rotate.disk_usage().is_err());
    }

    #[test]
    fn test_max_bytes() {
        let dir = tempdir().unwrap();
        let rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .max_log_count(4)
            .open(&dir)
            .unwrap();

        assert_eq!(rotate.max_bytes(), 400);
    }

    #[test]
    fn test_manual_remove_old_logs() {
        let dir = tempdir().unwrap();
        let dir = &dir;
        let open = |n: u8| -> RotateLog {
            OpenOptions::new()
                .create(true)
                .max_bytes_per_log(1)
                .max_log_count(n)
                .open(dir)
                .unwrap()
        };
        let read_all =
            |log: &RotateLog| -> Vec<Vec<u8>> { log.iter().map(|v| v.unwrap().to_vec()).collect() };

        // Create 5 logs
        {
            let mut rotate = open(5);
            for i in 0..5 {
                rotate.append(vec![i]).unwrap();
                rotate.sync().unwrap();
            }
        }

        // Content depends on max_log_count.
        {
            let rotate = open(4);
            assert_eq!(read_all(&rotate), [[2], [3], [4]]);
            let rotate = open(3);
            assert_eq!(read_all(&rotate), [[3], [4]]);
        }

        // Remove old logs.
        {
            let mut rotate = open(3);
            rotate.remove_old_logs().unwrap();
        }

        // Verify that [2] is removed.
        {
            let rotate = open(4);
            assert_eq!(read_all(&rotate), [[3], [4]]);
        }
    }

    #[test]
    fn test_remove_old_logs_skips_exclusive_lock() {
        let dir = tempdir().unwrap();
        let dir = &dir;

        // Create a RotateLog with no old logs to clean up.
        let mut rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .max_log_count(3)
            .open(dir)
            .unwrap();
        rotate.append(b"data").unwrap();
        rotate.sync().unwrap();

        // Hold the exclusive write lock. If remove_old_logs tries to
        // take it, the test will deadlock (caught as a test timeout).
        let _write_lock = ScopedDirLock::new(dir.as_ref()).unwrap();

        // Should succeed without needing the exclusive lock since
        // there are no old logs to remove.
        rotate.remove_old_logs().unwrap();
    }

    fn test_wrapping_rotate(max_log_count: u8) {
        let dir = tempdir().unwrap();
        let mut rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(10)
            .max_log_count(max_log_count)
            .open(&dir)
            .unwrap();

        let count = || {
            fs::read_dir(&dir)
                .unwrap()
                .map(|entry| entry.unwrap().file_name().into_string().unwrap())
                // On Windows, the "lock" file was created by open_dir.
                .filter(|name| name != "lock" && name != "rlock")
                .count()
        };

        for i in 1..=(max_log_count - 1) {
            rotate.append(b"abcdefghijklmn").unwrap();
            assert_eq!(rotate.sync().unwrap(), i);
            assert_eq!(count(), (i as usize) + 2);
        }

        for i in max_log_count..=255 {
            rotate.append(b"abcdefghijklmn").unwrap();
            assert_eq!(rotate.sync().unwrap(), i);
            assert_eq!(count(), (max_log_count as usize) + 1);
        }

        for _ in 0..=max_log_count {
            rotate.append(b"abcdefghijklmn").unwrap();
            assert_eq!(count(), (max_log_count as usize) + 1);
        }
    }

    #[test]
    fn test_wrapping_rotate_10() {
        test_wrapping_rotate(10)
    }

    #[test]
    fn test_wrapping_rotate_255() {
        test_wrapping_rotate(255)
    }

    #[test]
    fn test_lookup_rotated() {
        // Look up or iteration should work with rotated logs.
        let dir = tempdir().unwrap();
        let open_opts = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(1)
            .max_log_count(3)
            .index("first-byte", |_| vec![IndexOutput::Reference(0..1)]);

        // Prepare test data
        let mut rotate1 = open_opts.open(&dir).unwrap();
        rotate1.append(b"a1").unwrap();
        assert_eq!(rotate1.sync().unwrap(), 1);
        rotate1.append(b"a2").unwrap();
        assert_eq!(rotate1.sync().unwrap(), 2);

        // Warm up rotate1.
        assert_eq!(lookup(&rotate1, b"a"), vec![b"a2", b"a1"]);
        assert_eq!(iter(&rotate1), vec![b"a1", b"a2"]);

        // rotate2 has lazy logs
        let rotate2 = open_opts.open(&dir).unwrap();

        // Trigger rotate from another RotateLog
        let mut rotate3 = open_opts.open(&dir).unwrap();
        rotate3.append(b"a3").unwrap();
        assert_eq!(rotate3.sync().unwrap(), 3);

        // rotate1 can still use its existing indexes even if "a1"
        // might have been deleted (on Unix).
        assert_eq!(lookup(&rotate1, b"a"), vec![b"a2", b"a1"]);
        assert_eq!(iter(&rotate1), vec![b"a1", b"a2"]);

        // rotate2 does not have access to the deleted "a1".
        // (on Windows, 'meta' can be deleted, while mmap-ed files cannot)
        assert_eq!(lookup(&rotate2, b"a"), vec![b"a2"]);
        assert_eq!(iter(&rotate2), vec![b"a2"]);
    }

    #[test]
    fn test_is_empty() -> crate::Result<()> {
        let dir = tempdir().unwrap();
        let open_opts = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(2)
            .max_log_count(4)
            .index("first-byte", |_| vec![IndexOutput::Reference(0..1)]);

        let mut rotate = open_opts.open(&dir)?;
        rotate.append(b"a1")?;
        assert_eq!(rotate.sync()?, 1);

        rotate.append(b"a2")?;
        assert_eq!(rotate.sync()?, 2);

        rotate.append(b"b1")?;
        assert_eq!(rotate.sync()?, 3);

        assert_eq!(lookup(&rotate, b"a"), vec![b"a2", b"a1"]);
        assert_eq!(lookup(&rotate, b"b"), vec![b"b1"]);

        assert!(!rotate.lookup(0, b"a".to_vec())?.is_empty()?);
        assert!(!rotate.lookup(0, b"b".to_vec())?.is_empty()?);
        assert!(rotate.lookup(0, b"c".to_vec())?.is_empty()?);

        Ok(())
    }

    #[test]
    fn test_lookup_truncated_meta() {
        // Look up or iteration should work with rotated logs.
        let dir = tempdir().unwrap();
        let open_opts = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(1)
            .max_log_count(3)
            .index("first-byte", |_| vec![IndexOutput::Reference(0..1)]);

        // Prepare test data
        let mut rotate1 = open_opts.open(&dir).unwrap();
        rotate1.append(b"a1").unwrap();
        assert_eq!(rotate1.sync().unwrap(), 1);
        rotate1.append(b"a2").unwrap();
        assert_eq!(rotate1.sync().unwrap(), 2);

        // Warm up rotate1
        assert_eq!(lookup(&rotate1, b"a"), vec![b"a2", b"a1"]);
        assert_eq!(iter(&rotate1), vec![b"a1", b"a2"]);

        // rotate2 has lazy logs
        let rotate2 = open_opts.open(&dir).unwrap();

        // Break logs by truncating "meta".
        utils::atomic_write(dir.path().join("0").join(log::META_FILE), "", false).unwrap();

        // rotate1 can still use its existing indexes even if "a1"
        // might have been deleted (on Unix).
        assert_eq!(lookup(&rotate1, b"a"), vec![b"a2", b"a1"]);
        assert_eq!(iter(&rotate1), vec![b"a1", b"a2"]);

        // rotate2 does not have access to the deleted "a1".
        assert_eq!(lookup(&rotate2, b"a"), vec![b"a2"]);
        assert_eq!(iter(&rotate2), vec![b"a2"]);
    }

    #[test]
    fn test_concurrent_writes() {
        let dir = tempdir().unwrap();
        let mut rotate1 = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .max_log_count(2)
            .open(&dir)
            .unwrap();
        let mut rotate2 = OpenOptions::new()
            .max_bytes_per_log(100)
            .max_log_count(2)
            .open(&dir)
            .unwrap();

        // rotate1 triggers a rotation.
        rotate1.append(vec![b'a'; 100]).unwrap();
        assert_eq!(rotate1.sync().unwrap(), 1);

        let size = |log_index: u64| {
            dir.path()
                .join(format!("{log_index}"))
                .join(log::PRIMARY_FILE)
                .metadata()
                .unwrap()
                .len()
        };

        let size1 = size(1);

        // rotate2 writes to the right location ("1"), not "0";
        rotate2.append(vec![b'b'; 100]).unwrap();
        assert_eq!(rotate2.sync().unwrap(), 2);

        #[cfg(unix)]
        {
            assert!(!dir.path().join("0").exists());
        }
        assert!(size(1) > size1 + 100);
        assert!(size(2) > 0);
    }

    #[test]
    fn test_flush_filter() {
        let dir = tempdir().unwrap();

        let read_log = |name: &str| -> Vec<Vec<u8>> {
            let log = Log::open(dir.path().join(name), Vec::new()).unwrap();
            log.iter().map(|v| v.unwrap().to_vec()).collect()
        };

        let mut rotate1 = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .flush_filter(Some(|ctx, bytes| {
                // 'aa' is not inserted yet. It should not exist in the log.
                assert!(!ctx.log.iter().any(|x| x.unwrap() == b"aa"));
                Ok(match bytes.len() {
                    1 => FlushFilterOutput::Replace(b"xx".to_vec()),
                    _ => FlushFilterOutput::Keep,
                })
            }))
            .open(&dir)
            .unwrap();

        let mut rotate2 = OpenOptions::new()
            .max_bytes_per_log(100)
            .open(&dir)
            .unwrap();

        rotate2.append(vec![b'a'; 3]).unwrap();
        rotate2.sync().unwrap();

        rotate1.append(vec![b'a'; 1]).unwrap(); // replaced to 'xx'
        rotate1.append(vec![b'a'; 2]).unwrap();
        assert_eq!(rotate1.sync().unwrap(), 0); // trigger flush filter by Log
        assert_eq!(read_log("0"), vec![&b"aaa"[..], b"xx", b"aa"]);

        rotate1.append(vec![b'a'; 1]).unwrap(); // not replaced
        assert_eq!(rotate1.sync().unwrap(), 0); // do not trigger flush filter
        assert_eq!(read_log("0").last().unwrap(), b"a");

        rotate1.append(vec![b'a'; 1]).unwrap(); // replaced to 'xx'
        rotate1.append(vec![b'a'; 2]).unwrap();

        rotate2.append(vec![b'a'; 100]).unwrap(); // rotate
        assert_eq!(rotate2.sync().unwrap(), 1);

        assert_eq!(rotate1.sync().unwrap(), 1); // trigger flush filter by RotateLog
        assert_eq!(read_log("1"), vec![b"xx", b"aa"]);
    }

    #[test]
    fn test_is_changed_on_disk() {
        let dir = tempdir().unwrap();
        let open_opts = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(5000)
            .max_log_count(2);

        // Repeat a few times to trigger rotation.
        for _ in 0..10 {
            let mut rotate1 = open_opts.open(&dir).unwrap();
            let mut rotate2 = open_opts.open(&dir).unwrap();

            assert!(!rotate1.is_changed_on_disk());
            assert!(!rotate2.is_changed_on_disk());

            // no-op sync() does not set is_changed().
            rotate1.sync().unwrap();
            assert!(!rotate2.is_changed_on_disk());

            // change before flush does not set is_changed().
            rotate1.append([b'a'; 1000]).unwrap();

            assert!(!rotate1.is_changed_on_disk());
            assert!(!rotate2.is_changed_on_disk());

            // sync() does not set is_changed().
            rotate1.sync().unwrap();
            assert!(!rotate1.is_changed_on_disk());

            // rotate2 should be able to detect the on-disk change from rotate1.
            assert!(rotate2.is_changed_on_disk());

            // is_changed() does not clear is_changed().
            assert!(rotate2.is_changed_on_disk());

            // read-only sync() should clear is_changed().
            rotate2.sync().unwrap();
            assert!(!rotate2.is_changed_on_disk());
            // ... and not set other Logs' is_changed().
            assert!(!rotate1.is_changed_on_disk());

            rotate2.append([b'a'; 1000]).unwrap();
            rotate2.sync().unwrap();

            // rotate1 should be able to detect the on-disk change from rotate2.
            assert!(rotate1.is_changed_on_disk());

            // read-write sync() should clear is_changed().
            rotate1.append([b'a'; 1000]).unwrap();
            rotate1.sync().unwrap();
            assert!(!rotate1.is_changed_on_disk());
        }
    }

    #[test]
    fn test_lookup_latest() {
        let dir = tempdir().unwrap();
        let mut rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .flush_filter(Some(|_, _| panic!()))
            .index("first-byte", |_| vec![IndexOutput::Reference(0..1)])
            .open(&dir)
            .unwrap();

        rotate.append(vec![b'a'; 101]).unwrap();
        rotate.sync().unwrap(); // trigger rotate
        rotate.append(vec![b'b'; 10]).unwrap();

        assert_eq!(rotate.lookup_latest(0, b"b").unwrap().count(), 1);
        assert_eq!(rotate.lookup_latest(0, b"a").unwrap().count(), 0);

        rotate.append(vec![b'c'; 101]).unwrap();
        rotate.sync().unwrap(); // trigger rotate again

        rotate.append(vec![b'd'; 10]).unwrap();
        rotate.sync().unwrap(); // not trigger rotate
        rotate.append(vec![b'e'; 10]).unwrap();

        assert_eq!(rotate.lookup_latest(0, b"c").unwrap().count(), 0);
        assert_eq!(rotate.lookup_latest(0, b"d").unwrap().count(), 1);
        assert_eq!(rotate.lookup_latest(0, b"e").unwrap().count(), 1);
    }

    #[test]
    #[should_panic]
    fn test_lookup_latest_panic() {
        let dir = tempdir().unwrap();
        let rotate = OpenOptions::new()
            .create(true)
            .index("first-byte", |_| vec![IndexOutput::Reference(0..1)])
            .open(&dir)
            .unwrap();
        rotate.lookup_latest(0, b"a").unwrap(); // flush_filter is not set
    }

    #[test]
    fn test_iter() {
        let dir = tempdir().unwrap();
        let mut rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .open(&dir)
            .unwrap();

        let a = vec![b'a'; 101];
        let b = vec![b'b'; 10];

        rotate.append(a.clone()).unwrap();
        assert_eq!(
            rotate.iter_dirty().collect::<Result<Vec<_>, _>>().unwrap(),
            vec![&a[..]]
        );

        rotate.sync().unwrap(); // trigger rotate
        rotate.append(b.clone()).unwrap();
        rotate.append(a.clone()).unwrap();
        rotate.append(a.clone()).unwrap();
        assert_eq!(
            rotate.iter_dirty().collect::<Result<Vec<_>, _>>().unwrap(),
            vec![&b[..], &a, &a]
        );

        assert_eq!(
            rotate.iter().map(|e| e.unwrap()).collect::<Vec<&[u8]>>(),
            vec![&a[..], &b, &a, &a],
        );

        rotate.sync().unwrap(); // trigger rotate
        assert_eq!(
            rotate.iter().map(|e| e.unwrap()).collect::<Vec<&[u8]>>(),
            vec![&b[..], &a, &a],
        );
    }

    #[test]
    fn test_recover_from_empty_logs() {
        let dir = tempdir().unwrap();
        let rotate = OpenOptions::new().create(true).open(&dir).unwrap();
        drop(rotate);

        // Delete all logs, but keep "latest".
        for dirent in fs::read_dir(&dir).unwrap() {
            let dirent = dirent.unwrap();
            let path = dirent.path();
            if path.is_dir() {
                fs::remove_dir_all(path).unwrap();
            }
        }

        let _ = OpenOptions::new().create(true).open(&dir).unwrap();
    }

    #[test]
    fn test_recover_from_occupied_logs() {
        let dir = tempdir().unwrap();

        // Take the "1" spot.
        // Note: Cannot use "2" - it will be deleted by rotate -> try_remove_old_logs.
        {
            let mut log = log::OpenOptions::new()
                .create(true)
                .open(dir.path().join("1"))
                .unwrap();
            log.append(&[b'b'; 100][..]).unwrap();
            log.append(&[b'c'; 100][..]).unwrap();
            log.sync().unwrap();
        }

        // Rotate to "1" and "2".
        let mut rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(100)
            .max_log_count(3)
            .open(&dir)
            .unwrap();
        for i in [1, 2] {
            rotate.append(vec![b'a'; 101]).unwrap();
            assert_eq!(rotate.sync().unwrap(), i); // trigger rotate
        }

        // Content in the old "1" log should not appear here.
        assert_eq!(
            rotate.iter().map(|b| b.unwrap()[0]).collect::<Vec<_>>(),
            vec![b'a'; 2]
        );
    }

    #[test]
    fn test_index_lag() {
        let dir = tempdir().unwrap();
        let opts = OpenOptions::new()
            .create(true)
            .index_defs(vec![
                IndexDef::new("idx", |_| vec![IndexOutput::Reference(0..2)])
                    .lag_threshold(u64::MAX),
            ])
            .max_bytes_per_log(100)
            .max_log_count(3);

        let size = |name: &str| dir.path().join(name).metadata().unwrap().len();

        let mut rotate = opts.open(&dir).unwrap();
        rotate.append(vec![b'x'; 200]).unwrap();
        rotate.sync().unwrap();
        rotate.append(vec![b'y'; 200]).unwrap();
        rotate.sync().unwrap();
        rotate.append(vec![b'z'; 10]).unwrap();
        rotate.sync().unwrap();

        // First 2 logs become immutable, indexes are written regardless of
        // lag_threshold.
        assert!(size("0/index2-idx") > 0);
        assert!(size("0/log") > 100);

        assert!(size("1/index2-idx") > 0);
        assert!(size("1/log") > 100);

        // The "current" log is still mutable. Its index respects lag_threshold,
        // and is logically empty (because side effect of delete_content, the
        // index has some bytes in it).
        assert_eq!(size("2/index2-idx"), 25);
        assert!(size("2/log") < 100);
    }

    #[test]
    fn test_sync_missing_latest() {
        let dir = tempdir().unwrap();
        let opts = OpenOptions::new()
            .max_bytes_per_log(10000)
            .max_log_count(10);
        let mut rotate = opts.clone().create(true).open(&dir).unwrap();
        rotate.append(vec![b'x'; 200]).unwrap();
        rotate.sync().unwrap();

        let mut rotate2 = opts.open(&dir).unwrap();
        fs::remove_file(dir.path().join(LATEST_FILE)).unwrap();
        rotate2.sync().unwrap(); // not a failure
        rotate2.append(vec![b'y'; 200]).unwrap();
        rotate2.sync().unwrap_err(); // a failure
    }

    #[test]
    fn test_auto_sync_threshold() {
        let dir = tempdir().unwrap();
        let opts = OpenOptions::new().auto_sync_threshold(100).create(true);

        let mut rotate = opts.create(true).open(&dir).unwrap();
        rotate.append(vec![b'x'; 50]).unwrap();
        assert_eq!(rotate.logs()[0].iter_dirty().count(), 1);
        rotate.append(vec![b'x'; 50]).unwrap(); // trigger sync
        assert_eq!(rotate.logs()[0].iter_dirty().count(), 0);
    }

    #[test]
    fn test_auto_sync_threshold_with_racy_index_update_on_open() {
        fn index_defs(lag_threshold: u64) -> Vec<IndexDef> {
            let index_names = ["a"];
            (0..index_names.len())
                .map(|i| {
                    IndexDef::new(index_names[i], |_| vec![IndexOutput::Reference(0..1)])
                        .lag_threshold(lag_threshold)
                })
                .collect()
        }

        fn open_opts(lag_threshold: u64) -> OpenOptions {
            let index_defs = index_defs(lag_threshold);
            OpenOptions::new()
                .auto_sync_threshold(1000)
                .max_bytes_per_log(400)
                .max_log_count(10)
                .create(true)
                .index_defs(index_defs)
        }

        let dir = tempdir().unwrap();
        let path = dir.path();
        let data: &[u8] = &[b'x'; 100];
        let n = 10;
        for _i in 0..n {
            let mut rotate1 = open_opts(300).open(path).unwrap();
            rotate1.hook_after_log_sync = Some({
                let path = path.to_path_buf();
                Box::new(move || {
                    // This might updating indexes (see D20042046 and D20286509).
                    let rotate2 = open_opts(100).open(&path).unwrap();
                    // Force loading "lazy" indexes.
                    let _all = rotate2.iter().collect::<Result<Vec<_>, _>>().unwrap();
                })
            });
            rotate1.append(data).unwrap();
            rotate1.sync().unwrap();
        }

        // Verify that data can be read through index.
        let rotate1 = open_opts(300).open(path).unwrap();
        let mut count = 0;
        for entry in rotate1.lookup(0, b"x" as &[u8]).unwrap() {
            let entry = entry.unwrap();
            assert_eq!(entry, data);
            count += 1;
        }
        assert_eq!(count, n);
    }

    #[test]
    fn test_reindex_old_logs() {
        let dir = tempdir().unwrap();
        let opts = OpenOptions::new()
            .max_bytes_per_log(10)
            .max_log_count(10)
            .create(true);

        let mut rotate = opts.clone().create(true).open(&dir).unwrap();
        for i in 0..2u8 {
            rotate.append(vec![i; 50]).unwrap();
            rotate.sync().unwrap(); // rotate
        }

        // New OpenOptions: With indexes.
        let opts = opts.index("a", |_data| vec![IndexOutput::Reference(0..1)]);

        // Triggers rebuilding indexes.
        let rotate = opts.create(true).open(&dir).unwrap();

        // Because older log is lazy. It hasn't been loaded yet. So it does not have the index.
        assert!(!dir.path().join("1/index2-a").exists());
        assert!(!dir.path().join("0/index2-a").exists());

        // Do an index lookup. This will trigger loading old logs.
        let mut iter = rotate.lookup(0, b"\x00".to_vec()).unwrap();

        // The iterator is lazy. So it does not build the index immediately.
        assert!(!dir.path().join("1/index2-a").exists());

        // Iterate through all logs.
        assert_eq!(iter.next().unwrap().unwrap(), &[0; 50][..]);

        // Now the index is built for older logs.
        assert!(dir.path().join("1/index2-a").exists());
        assert!(dir.path().join("0/index2-a").exists());
    }

    #[test]
    fn test_repair_latest() {
        assert_eq!(guess_latest(vec![]), 0);
        assert_eq!(guess_latest(vec![3, 4, 5]), 5);
        assert_eq!(guess_latest(vec![0, 1, 2, 254, 255]), 2);
        assert_eq!(guess_latest((0..=255).collect::<Vec<_>>()), 0);

        let dir = tempdir().unwrap();
        let opts = OpenOptions::new().max_bytes_per_log(100).max_log_count(10);
        let mut rotate = opts.clone().create(true).open(&dir).unwrap();
        for i in 1..=2 {
            rotate.append(vec![b'x'; 200]).unwrap();
            assert_eq!(rotate.sync().unwrap(), i);
        }

        // Corrupt "latest".
        let latest_path = dir.path().join(LATEST_FILE);
        utils::atomic_write(latest_path, "NaN", false).unwrap();
        assert!(opts.open(&dir).is_err());
        assert_eq!(
            opts.repair(&dir)
                .unwrap()
                .lines()
                .filter(|l| !l.contains("Processing"))
                .collect::<Vec<_>>()
                .join("\n"),
            r#"Attempt to repair log "0"
Verified 1 entries, 223 bytes in log
Attempt to repair log "1"
Verified 1 entries, 223 bytes in log
Attempt to repair log "2"
Verified 0 entries, 12 bytes in log
Reset latest to 2"#
        );
        opts.open(&dir).unwrap();

        // Delete "latest".
        fs::remove_file(dir.path().join(LATEST_FILE)).unwrap();
        assert!(opts.open(&dir).is_err());

        // Repair can fix it.
        assert_eq!(
            opts.repair(&dir)
                .unwrap()
                .lines()
                .filter(|l| !l.contains("Processing"))
                .collect::<Vec<_>>()
                .join("\n"),
            r#"Attempt to repair log "0"
Verified 1 entries, 223 bytes in log
Attempt to repair log "1"
Verified 1 entries, 223 bytes in log
Attempt to repair log "2"
Verified 0 entries, 12 bytes in log
Reset latest to 2"#
        );
        opts.open(&dir).unwrap();
    }

    #[test]
    fn test_load_broken_logs_once() {
        let dir = tempdir().unwrap();
        let open_opts = OpenOptions::new()
            .create(true)
            .max_log_count(10)
            .max_bytes_per_log(100);
        let mut log = open_opts.open(dir.path()).unwrap();

        // Create 0, 1, 2, 3 logs
        for i in 0..4 {
            log.append(&[i; 200][..]).unwrap();
            log.sync().unwrap();
        }

        // Break 1/
        utils::atomic_write(dir.path().join("1").join("meta"), "foo", false).unwrap();
        let log = open_opts.open(dir.path()).unwrap();

        // The broken log should only be loaded once.
        assert!(log.load_log(3).is_err()); // Reports error loading the broken Log.
        assert!(log.load_log(3).is_ok()); // The error is "cached" - not loading the Log again.

        // Logs iteration will only have 2, no 0 or 1.
        assert_eq!(
            log.iter().map(|i| i.unwrap()[0]).collect::<Vec<_>>(),
            [2, 3]
        );
    }

    #[test]
    fn test_multithread_sync() {
        let dir = tempdir().unwrap();

        // Release mode runs much faster.
        const THREAD_COUNT: u8 = if cfg!(debug_assertions) { 10 } else { 30 };
        const WRITE_COUNT_PER_THREAD: u8 = if cfg!(debug_assertions) { 10 } else { 50 };

        // Some indexes. They have different lag_threshold.
        fn index_ref(data: &[u8]) -> Vec<IndexOutput> {
            vec![IndexOutput::Reference(0..data.len() as u64)]
        }
        fn index_copy(data: &[u8]) -> Vec<IndexOutput> {
            vec![IndexOutput::Owned(data.to_vec().into_boxed_slice())]
        }
        let indexes = vec![
            IndexDef::new("key1", index_ref).lag_threshold(1),
            IndexDef::new("key2", index_ref).lag_threshold(50),
            IndexDef::new("key3", index_ref).lag_threshold(1000),
            IndexDef::new("key4", index_copy).lag_threshold(1),
            IndexDef::new("key5", index_copy).lag_threshold(50),
            IndexDef::new("key6", index_copy).lag_threshold(1000),
        ];
        let index_len = indexes.len();
        let open_opts = OpenOptions::new()
            .create(true)
            .max_log_count(200)
            .max_bytes_per_log(200)
            .index_defs(indexes);

        use std::sync::Arc;
        use std::sync::Barrier;
        let barrier = Arc::new(Barrier::new(THREAD_COUNT as usize));
        let threads: Vec<_> = (0..THREAD_COUNT)
            .map(|i| {
                let barrier = barrier.clone();
                let open_opts = open_opts.clone();
                let path = dir.path().to_path_buf();
                std::thread::spawn(move || {
                    barrier.wait();
                    let mut log = open_opts.open(path).unwrap();
                    for j in 1..=WRITE_COUNT_PER_THREAD {
                        let buf = [i, j];
                        log.append(buf).unwrap();
                        if j % (i + 1) == 0 || j == WRITE_COUNT_PER_THREAD {
                            log.sync().unwrap();
                            // Verify that the indexes match the entries.
                            for entry in log.iter().map(|d| d.unwrap()) {
                                for index_id in 0..index_len {
                                    for index_value in log.lookup(index_id, entry.to_vec()).unwrap()
                                    {
                                        assert_eq!(index_value.unwrap(), entry);
                                    }
                                }
                            }
                        }
                    }
                })
            })
            .collect();

        // Wait for them.
        for thread in threads {
            thread.join().expect("joined");
        }

        // Check how many entries were written.
        let log = open_opts.open(dir.path()).unwrap();
        let count = log.iter().count() as u64;
        assert_eq!(count, THREAD_COUNT as u64 * WRITE_COUNT_PER_THREAD as u64);
    }

    // see lib.rs - dummy_btrfs won't run this test
    #[cfg(all(target_os = "linux", feature = "btrfs"))]
    #[test]
    fn test_btrfs_rotate() {
        let dir = tempdir().unwrap();

        if !is_btrfs(dir.path()) {
            eprintln!(
                "skipping test_btrfs_rotate: {:?} is not a btrfs filesystem",
                dir.path()
            );
            return;
        }

        #[cfg(target_os = "linux")]
        {
            use rand::Rng as _;

            let mut rotate = OpenOptions::new()
                .create(true)
                .max_bytes_per_log(500)
                .max_log_count(2)
                .index("first-byte", |_| vec![IndexOutput::Reference(0..1)])
                .btrfs_compression(true)
                .open(&dir)
                .unwrap();

            // No rotation - log is compressed well.
            let aaa = vec![b'a'; 1000];
            rotate.append(&aaa).unwrap();
            assert_eq!(rotate.sync().unwrap(), 0);
            assert_eq!(lookup(&rotate, b"a"), vec![&aaa]);

            // Sanity check we compressed well.
            let btrfs_size = rotate.writable_log().btrfs_size().unwrap();
            assert!(btrfs_size > 0);
            assert!(btrfs_size < 500);

            // Rotate triggered.
            let mut random_bytes = vec![0u8; 1000];
            rand::rng().fill_bytes(&mut random_bytes);
            random_bytes[0] = b'b';
            rotate.append(&random_bytes).unwrap();
            assert_eq!(rotate.sync().unwrap(), 1);
            assert_eq!(lookup(&rotate, b"a"), vec![&aaa]);
            assert_eq!(lookup(&rotate, b"b"), vec![&random_bytes]);

            let rotated_btrfs_size = rotate.logs[1].get_mut().unwrap().btrfs_size().unwrap();
            assert!(rotated_btrfs_size >= 500);
        }
    }

    // see lib.rs - dummy_btrfs won't run this test
    #[cfg(all(target_os = "linux", feature = "btrfs"))]
    #[test]
    fn test_disk_usage_reports_physical_size_on_btrfs() {
        let dir = tempdir().unwrap();

        if !is_btrfs(dir.path()) {
            eprintln!(
                "skipping test_disk_usage_reports_physical_size_on_btrfs: {:?} is not a btrfs filesystem",
                dir.path()
            );
            return;
        }

        // Highly compressible data: physical (compressed) size should end up
        // far smaller than the logical byte count written.
        let mut rotate = OpenOptions::new()
            .create(true)
            .max_bytes_per_log(1_000_000)
            .max_log_count(2)
            .btrfs_compression(true)
            .open(&dir)
            .unwrap();
        let compressible = vec![b'a'; 500_000];
        rotate.append(&compressible).unwrap();
        rotate.sync().unwrap();

        let logical_len = rotate.logs[0].get().unwrap().meta.disk_usage();
        let reported = rotate.disk_usage().unwrap();

        // disk_usage() must track the same (physical/compressed) unit that
        // the rotation threshold compares against max_bytes_per_log, not the
        // logical primary_len - otherwise used/max_bytes mixes units and can
        // exceed 100% on a healthy, compressing filesystem.
        assert!(
            reported < logical_len,
            "expected compressed disk_usage ({reported}) to be smaller than logical length ({logical_len})"
        );
    }

    #[test]
    fn test_consistent_reads() {
        // Set threshold low so we get a lot of rotation
        let open_opts = OpenOptions::new()
            .create(true)
            .max_log_count(2)
            .max_bytes_per_log(1)
            .auto_sync_threshold(0)
            .index_defs(vec![IndexDef::new("key", |data| {
                vec![IndexOutput::Reference(0..data.len() as u64)]
            })]);

        let get = |log: &RotateLog, key: &[u8]| -> Option<Vec<u8>> {
            Some(
                log.lookup(0, key.to_vec())
                    .unwrap()
                    .next()?
                    .unwrap()
                    .to_vec(),
            )
        };

        // Sanity check how rotation is working.
        {
            let dir = tempdir().unwrap();

            let mut log = open_opts.open(dir.path()).unwrap();

            // Log 0 is rotated immediately to log 1.
            log.append(b"a").unwrap();
            assert_eq!(get(&log, b"a"), Some(vec![b'a']));

            // Log 1 is dropped - log 0 rotated to log 1.
            log.append(b"b").unwrap();
            assert_eq!(get(&log, b"b"), Some(vec![b'b']));
            assert_eq!(get(&log, b"a"), None);
        }

        // Now again with consistent reads enabled.
        {
            let dir = tempdir().unwrap();

            let mut log = open_opts.open(dir.path()).unwrap();

            let _guard = log.with_consistent_reads();

            log.append(b"a").unwrap();
            assert_eq!(get(&log, b"a"), Some(vec![b'a']));

            // All entries still readable.
            log.append(b"b").unwrap();
            log.append(b"c").unwrap();
            assert_eq!(get(&log, b"c"), Some(vec![b'c']));
            assert_eq!(get(&log, b"b"), Some(vec![b'b']));
            assert_eq!(get(&log, b"a"), Some(vec![b'a']));

            // Drop consistent guard - rotated data is gone.
            drop(_guard);
            assert_eq!(get(&log, b"a"), None);
        }

        // Now with consistent reads and another writer to the log.
        {
            let dir = tempdir().unwrap();

            let mut log1 = open_opts.open(dir.path()).unwrap();
            let mut log2 = open_opts.open(dir.path()).unwrap();

            let _guard = log1.with_consistent_reads();

            log1.append(b"a").unwrap();

            log2.append(b"z").unwrap();
            log2.append(b"z").unwrap();
            log2.append(b"z").unwrap();

            log1.append(b"b").unwrap();

            log2.append(b"z").unwrap();
            log2.append(b"z").unwrap();
            log2.append(b"z").unwrap();

            log1.append(b"c").unwrap();

            log2.append(b"z").unwrap();
            log2.append(b"z").unwrap();
            log2.append(b"z").unwrap();

            assert_eq!(get(&log1, b"c"), Some(vec![b'c']));
            assert_eq!(get(&log1, b"b"), Some(vec![b'b']));
            assert_eq!(get(&log1, b"a"), Some(vec![b'a']));
            // Can't see "z" - it was rotated out when we appended "c".
            assert_eq!(get(&log1, b"z"), None);

            // Not buffering anything.
            assert!(log1.writable_log().mem_buf.is_empty());

            log1.sync().unwrap();
            assert_eq!(get(&log1, b"c"), Some(vec![b'c']));
            assert_eq!(get(&log1, b"b"), Some(vec![b'b']));
            assert_eq!(get(&log1, b"a"), Some(vec![b'a']));
            // Now we can see "z" since we reloaded logs from disk.
            assert_eq!(get(&log1, b"z"), Some(vec![b'z']));

            // Drop consistent guard - rotated data is gone.
            drop(_guard);
            assert_eq!(get(&log1, b"a"), None);
            assert_eq!(get(&log1, b"z"), Some(vec![b'z']));

            // Pinned logs haven't been cleaned up yet.
            assert!(!log1.pinned_logs.is_empty());

            // But they get cleaned at the next chance.
            log1.sync().unwrap();
            assert!(log1.pinned_logs.is_empty());
        }
    }
}