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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024-present, fjall-rs
// Copyright (c) 2026-present, Structured World Foundation
mod block_size;
mod compression;
mod filter;
mod hash_ratio;
mod pinning;
mod restart_interval;
pub use block_size::BlockSizePolicy;
pub use compression::CompressionPolicy;
pub use filter::{BloomConstructionPolicy, FilterPolicy, FilterPolicyEntry};
pub use hash_ratio::HashRatioPolicy;
pub use pinning::PinningPolicy;
pub use restart_interval::RestartIntervalPolicy;
/// Partitioning policy for indexes and filters
pub type PartitioningPolicy = PinningPolicy;
use crate::{
AnyTree, BlobTree, Cache, CompressionType, DescriptorTable, SequenceNumberCounter,
SharedSequenceNumberGenerator, Tree,
compaction::filter::Factory,
comparator::{self, SharedComparator},
encryption::EncryptionProvider,
file::TABLES_FOLDER,
fs::{Fs, StdFs, SyncMode},
merge_operator::MergeOperator,
path::absolute_path,
prefix::PrefixExtractor,
version::DEFAULT_LEVEL_COUNT,
};
use std::{
ops::Range,
path::{Path, PathBuf},
sync::Arc,
};
/// Per-level filesystem routing entry for tiered storage.
///
/// Maps a range of LSM levels to a base directory and filesystem backend.
/// Tables at these levels are stored under `path/tables/`.
///
/// # Example
///
/// ```
/// use lsm_tree::config::LevelRoute;
/// use lsm_tree::fs::StdFs;
/// use std::sync::Arc;
///
/// // Hot tier: L0-L1 on NVMe
/// let hot = LevelRoute {
/// levels: 0..2,
/// path: "/mnt/nvme/db".into(),
/// fs: Arc::new(StdFs),
/// };
///
/// // Cold tier: L4-L6 on HDD
/// let cold = LevelRoute {
/// levels: 4..7,
/// path: "/mnt/hdd/db".into(),
/// fs: Arc::new(StdFs),
/// };
/// ```
#[derive(Clone)]
pub struct LevelRoute {
/// LSM levels this route covers (e.g., `0..2` for L0–L1).
pub levels: Range<u8>,
/// Base data directory for tables at these levels.
pub path: PathBuf,
/// Filesystem backend for I/O at these levels.
pub fs: Arc<dyn Fs>,
}
impl std::fmt::Debug for LevelRoute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LevelRoute")
.field("levels", &self.levels)
.field("path", &self.path)
.finish_non_exhaustive()
}
}
/// Policy governing what `Tree::open` does when the on-disk MANIFEST
/// contains corrupt records.
///
/// Mirrors `RocksDB`'s `WALRecoveryMode` semantics, but applied to the
/// manifest layer (`src/version/recovery.rs`) — lsm-tree itself has no
/// WAL (durability lives one layer up in the parent fjall/keyspace
/// crate's `Journal`). The MANIFEST is the equivalent surface where
/// "loss-tolerance vs strict-consistency" matters at open time.
///
/// The default is [`AbsoluteConsistency`](Self::AbsoluteConsistency) —
/// any corrupt record fails the open. Switching to a more permissive
/// mode is an explicit, informed operator decision: you are trading
/// "the tree might silently come up with missing tables / blob files"
/// for "the tree comes up at all". When a non-default mode drops
/// records, the recovery path emits a `warn!` summary with the
/// AGGREGATE dropped count per section (`tables` / `blob_files`) —
/// individual table IDs / blob-file IDs are NOT enumerated, because
/// they were never decoded in the first place. Operators wanting a
/// per-record audit trail should pair tail-tolerant recovery with an
/// out-of-band integrity scan ([`verify_integrity`](crate::verify::verify_integrity))
/// of the recovered tree.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum ManifestRecoveryMode {
/// Production-safe default. Any per-record decode mismatch (bad
/// XXH3, invalid tag, truncated TOC entry, declared-count overrun)
/// aborts the open with the original error. Surfaces every byte
/// of corruption; never silently drops data.
#[default]
AbsoluteConsistency,
/// Power-loss-at-write-tail salvage. If the per-section iteration
/// over the `tables` / `blob_files` records runs out of bytes
/// before the declared count is reached (truncated tail), keep
/// everything that decoded cleanly before the cut and emit a
/// `warn!` listing the dropped record counts.
///
/// A declared count that exceeds the section's payload capacity
/// (e.g. `table_count` claims more entries than the section has
/// bytes for) is treated as the same "writer committed a count
/// header then truncated the entries" shape — the recovery
/// downgrades the original hard fail to a `warn!` and lets the
/// per-entry decode loop walk bytes-actually-present until the
/// first `UnexpectedEof`.
///
/// Any decode error that is NOT a clean tail truncation (bad
/// `checksum_type` tag, etc.) still aborts the open — this mode
/// is specifically for "the writer never finished" scenarios,
/// not for arbitrary bit-rot in already-committed bytes.
TolerateCorruptedTailRecords,
/// Recover the largest consistent prefix and discard the rest.
/// Adapts `RocksDB`'s `kPointInTimeRecovery` accept-the-prefix
/// rule to the level/run/table nesting: on the first
/// record-decode mismatch inside the `tables` section, the
/// recovery keeps the records that decoded cleanly *before*
/// the corrupt one in the current run, plus every complete
/// earlier run in the same level, plus every complete earlier
/// level. "Record-decode mismatch" covers ALL three failure
/// shapes the per-record loop can surface:
///
/// 1. Framing-layer XXH3 mismatch (the 8-byte digest in the
/// record header doesn't match `xxh3_64(payload)`).
/// 2. Framing-header structural failure (`len > MAX_FRAME_PAYLOAD`),
/// surfaced as `BadHeader`. Note: `LenMismatch` (decoded `len`
/// disagrees with a fixed-length pin) is a SEPARATE hard-abort
/// case in every recovery mode, not a record-decode mismatch
/// for the purpose of this mode.
/// 3. Payload decode failure AFTER a clean framing pass —
/// e.g. `Error::InvalidTag` from a corrupt `checksum_type`
/// byte inside an otherwise-framed-OK record. The framing
/// XXH3 happens to cover the corrupt byte too (it's a
/// digest of the whole payload), so the bytes decode
/// cleanly at the framing layer; the corruption only
/// surfaces inside the per-entry decode helper.
///
/// PIT drops the corrupt record itself, the remaining records
/// of that run, and every level not yet read. The same rule
/// applies to the `blob_files` section. Clean tail-truncation
/// is still tolerated, same as
/// [`TolerateCorruptedTailRecords`](Self::TolerateCorruptedTailRecords).
PointInTimeRecovery,
/// Skip each corrupt record individually, keep all others.
/// Maximum-availability, lossy. On any per-record decode
/// mismatch — framing-layer XXH3 mismatch, payload-decode
/// failure inside an otherwise-framed-OK record (e.g.
/// `Error::InvalidTag` on a corrupt `checksum_type` byte), or
/// a framing-header `BadHeader` — the reader logs the skip
/// and advances exactly past the bad record using the
/// framing-supplied length field. If the length field itself
/// is unusable (the recorded length is outside the legal
/// range, so the next-record boundary is unknown), the rest
/// of that section is dropped. Intended companion to the
/// `repair_db` tooling tracked as `#303`: this mode recovers
/// what it can in-place; `repair_db` rebuilds the manifest
/// from the SST files
/// themselves when even this mode can't reach a usable state.
SkipAnyCorruptedRecords,
}
/// LSM-tree type
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum TreeType {
/// Standard LSM-tree, see [`Tree`]
Standard,
/// Key-value separated LSM-tree, see [`BlobTree`]
Blob,
}
impl From<TreeType> for u8 {
fn from(val: TreeType) -> Self {
match val {
TreeType::Standard => 0,
TreeType::Blob => 1,
}
}
}
impl TryFrom<u8> for TreeType {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Self::Standard),
1 => Ok(Self::Blob),
_ => Err(()),
}
}
}
const DEFAULT_FILE_FOLDER: &str = ".lsm.data";
/// Options for key-value separation
#[derive(Clone, Debug, PartialEq)]
pub struct KvSeparationOptions {
/// What type of compression is used for blobs
#[doc(hidden)]
pub compression: CompressionType,
/// Blob file target size in bytes
#[doc(hidden)]
pub file_target_size: u64,
/// Key-value separation threshold in bytes
#[doc(hidden)]
pub separation_threshold: u32,
#[doc(hidden)]
pub staleness_threshold: f32,
#[doc(hidden)]
pub age_cutoff: f32,
/// Pre-trained zstd dictionary for blob-file dictionary compression.
///
/// Required when `compression` is [`CompressionType::ZstdDict`].
/// The `dict_id` in the compression type must match [`ZstdDictionary::id`](crate::ZstdDictionary::id).
#[cfg(zstd_any)]
#[doc(hidden)]
pub zstd_dictionary: Option<std::sync::Arc<crate::compression::ZstdDictionary>>,
}
impl Default for KvSeparationOptions {
fn default() -> Self {
Self {
#[cfg(feature="lz4")]
compression: CompressionType::Lz4,
#[cfg(not(feature="lz4"))]
compression: CompressionType::None,
file_target_size: /* 64 MiB */ 64 * 1_024 * 1_024,
separation_threshold: /* 1 KiB */ 1_024,
staleness_threshold: 0.25,
age_cutoff: 0.25,
#[cfg(zstd_any)]
zstd_dictionary: None,
}
}
}
impl KvSeparationOptions {
/// Sets the blob compression method.
#[must_use]
pub fn compression(mut self, compression: CompressionType) -> Self {
self.compression = compression;
self
}
/// Sets the target size of blob files.
///
/// Smaller blob files allow more granular garbage collection
/// which allows lower space amp for lower write I/O cost.
///
/// Larger blob files decrease the number of files on disk and maintenance
/// overhead.
///
/// Defaults to 64 MiB.
#[must_use]
pub fn file_target_size(mut self, bytes: u64) -> Self {
self.file_target_size = bytes;
self
}
/// Sets the key-value separation threshold in bytes.
///
/// Smaller value will reduce compaction overhead and thus write amplification,
/// at the cost of lower read performance.
///
/// Defaults to 1 KiB.
#[must_use]
pub fn separation_threshold(mut self, bytes: u32) -> Self {
self.separation_threshold = bytes;
self
}
/// Sets the staleness threshold percentage.
///
/// The staleness percentage determines how much a blob file needs to be fragmented to be
/// picked up by the garbage collection.
///
/// Defaults to 33%.
#[must_use]
pub fn staleness_threshold(mut self, ratio: f32) -> Self {
self.staleness_threshold = ratio;
self
}
/// Sets the age cutoff threshold.
///
/// Defaults to 20%.
#[must_use]
pub fn age_cutoff(mut self, ratio: f32) -> Self {
self.age_cutoff = ratio;
self
}
/// Sets the zstd dictionary for blob-file dictionary compression.
///
/// Required when [`compression`](Self::compression) is set to
/// [`CompressionType::ZstdDict`]. The `dict_id` encoded in the
/// compression type must equal [`ZstdDictionary::id()`](crate::ZstdDictionary::id) of the
/// supplied dictionary; [`Config::open`] will return
/// [`Error::ZstdDictMismatch`](crate::Error::ZstdDictMismatch) if
/// they disagree.
#[cfg(zstd_any)]
#[must_use]
pub fn dict(mut self, dictionary: std::sync::Arc<crate::compression::ZstdDictionary>) -> Self {
self.zstd_dictionary = Some(dictionary);
self
}
}
/// Tree configuration builder
pub struct Config {
/// Folder path
#[doc(hidden)]
pub path: PathBuf,
/// Default filesystem backend for levels without an explicit route.
///
/// Defaults to [`StdFs`]. Use [`Config::with_fs`] to plug in an
/// alternative backend such as [`MemFs`](crate::fs::MemFs).
///
/// Both fresh tree creation and reopening (recovery) are supported
/// for any backend that implements [`Fs`].
#[doc(hidden)]
pub fs: Arc<dyn Fs>,
/// Per-level filesystem routing for tiered storage.
///
/// When set, tables at different LSM levels can be stored on different
/// storage devices (e.g., NVMe for L0–L1, SSD for L2–L4, HDD for L5–L6).
/// Each entry maps a range of levels to a base directory and filesystem
/// backend. Uncovered levels fall back to the primary `path` and `fs`.
///
/// Zero additional overhead when `None` — only a single branch check;
/// path construction allocations are unchanged.
#[doc(hidden)]
pub level_routes: Option<Vec<LevelRoute>>,
/// Block cache to use
#[doc(hidden)]
pub cache: Arc<Cache>,
/// Descriptor table to use
#[doc(hidden)]
pub descriptor_table: Option<Arc<DescriptorTable>>,
/// Number of levels of the LSM tree (depth of tree)
///
/// Once set, the level count is fixed (in the "manifest" file)
pub level_count: u8,
/// What type of compression is used for data blocks
pub data_block_compression_policy: CompressionPolicy,
/// What type of compression is used for index blocks
pub index_block_compression_policy: CompressionPolicy,
/// Restart interval inside data blocks
pub data_block_restart_interval_policy: RestartIntervalPolicy,
/// Restart interval inside index blocks
pub index_block_restart_interval_policy: RestartIntervalPolicy,
/// Block size of data blocks
pub data_block_size_policy: BlockSizePolicy,
/// Whether to pin index blocks
pub index_block_pinning_policy: PinningPolicy,
/// Whether to pin filter blocks
pub filter_block_pinning_policy: PinningPolicy,
/// Whether to pin top level index of partitioned index
pub top_level_index_block_pinning_policy: PinningPolicy,
/// Whether to pin top level index of partitioned filter
pub top_level_filter_block_pinning_policy: PinningPolicy,
/// Data block hash ratio
pub data_block_hash_ratio_policy: HashRatioPolicy,
/// Whether to partition index blocks
pub index_block_partitioning_policy: PartitioningPolicy,
/// Whether to partition filter blocks
pub filter_block_partitioning_policy: PartitioningPolicy,
/// Partition size when using partitioned indexes
pub index_block_partition_size_policy: BlockSizePolicy,
/// Partition size when using partitioned filters
pub filter_block_partition_size_policy: BlockSizePolicy,
/// If `true`, the last level will not build filters, reducing the filter size of a database
/// by ~90% typically
pub(crate) expect_point_read_hits: bool,
/// Per-block Reed-Solomon Page ECC. When `true`, every block on
/// disk carries a Reed-Solomon parity trailer; on read, if the
/// block's XXH3 disagrees with the on-disk bytes, the reader
/// attempts RS recovery before surfacing the corruption. Requires
/// the `page_ecc` cargo feature — opening a tree with
/// `page_ecc = true` on a build without the feature returns
/// [`crate::Error::PageEccUnsupported`].
///
/// Off by default. `RocksDB` ships per-block ECC as an operator-
/// chosen knob (typically off on RAID-protected media, on on
/// single-drive) and the cost is non-trivial on the write path,
/// so the default keeps the existing behaviour.
pub(crate) page_ecc: bool,
/// Initial [`crate::runtime_config::RuntimeConfig`] snapshot
/// the tree starts with. Seeds both the first
/// `persist_version` call and the Tree's
/// `RuntimeConfigHandle`, so a non-default value supplied via
/// [`Config::with_runtime_config`] is honoured from byte zero
/// of the manifest. Defaults to `RuntimeConfig::default()` —
/// matches the pre-existing implicit behaviour.
#[expect(
clippy::struct_field_names,
reason = "name mirrors the type for grep-ability across the persist + Tree handle init wiring"
)]
pub(crate) initial_runtime_config: crate::runtime_config::RuntimeConfig,
/// Filter construction policy
pub filter_policy: FilterPolicy,
/// Compaction filter factory
pub compaction_filter_factory: Option<Arc<dyn Factory>>,
/// Prefix extractor for prefix bloom filters.
///
/// When set, the bloom filter indexes extracted prefixes in addition to
/// full keys, allowing prefix scans to skip segments that contain no
/// matching prefixes.
pub prefix_extractor: Option<Arc<dyn PrefixExtractor>>,
/// Merge operator for commutative operations
///
/// When set, enables `merge()` operations that store partial updates
/// which are lazily combined during reads and compaction.
pub merge_operator: Option<Arc<dyn MergeOperator>>,
#[doc(hidden)]
pub kv_separation_opts: Option<KvSeparationOptions>,
/// Custom user key comparator.
///
/// When set, all key comparisons use this comparator instead of the
/// default lexicographic byte ordering. Once a tree is opened with a
/// comparator, it must always be re-opened with the same comparator.
// Not `pub` — use `Config::comparator()` builder method as the public API.
#[doc(hidden)]
pub(crate) comparator: SharedComparator,
/// Block-level encryption provider for encryption at rest.
///
/// When set, all blocks (data, index, filter, meta) are encrypted
/// using this provider after compression and before checksumming.
pub(crate) encryption: Option<Arc<dyn EncryptionProvider>>,
/// Policy governing what `Tree::open` does when the on-disk
/// MANIFEST contains corrupt records. Defaults to
/// [`ManifestRecoveryMode::AbsoluteConsistency`], the only
/// production-safe choice — any corruption aborts the open. Other
/// modes trade strict correctness for partial-availability after a
/// disaster; see the enum doc for the operational scenarios that
/// motivate each mode.
pub(crate) manifest_recovery_mode: ManifestRecoveryMode,
/// Durability level for every fsync the tree issues (SST writes,
/// manifest, version persist, directory syncs).
///
/// Defaults to [`SyncMode::Normal`] (plain `fsync`), matching the
/// out-of-the-box durability of `RocksDB` and `SQLite`. Only observable on
/// macOS, where [`SyncMode::Full`] opts into the much slower
/// `F_FULLFSYNC` barrier; on other platforms both modes are plain
/// `fsync`. Set via [`Config::sync_mode`].
pub(crate) sync_mode: SyncMode,
/// Edit-log size (bytes) past which the next manifest persist rotates: it
/// writes a fresh full snapshot and starts an empty log instead of appending
/// another [`VersionEdit`](crate::version::edit::VersionEdit). Bounds both
/// recovery replay time (edits to re-apply) and log disk use, while keeping
/// the common per-flush path a tiny `O(changed-levels)` append rather than an
/// `O(all-SSTs)` full manifest rewrite.
///
/// Defaults to 1 MiB (≈ tens of thousands of edits). Set via
/// [`Config::manifest_log_rotate_bytes`]. A smaller value rotates more
/// often (shorter recovery, more frequent full-snapshot writes); `0` rotates
/// on every upgrade, degenerating to the full-rewrite-per-version behaviour.
pub(crate) manifest_log_rotate_bytes: u64,
/// Compaction I/O rate limit in bytes per second.
///
/// Caps the rate at which the compaction worker is allowed to issue
/// I/O, so background compaction cannot saturate the device and starve
/// user point reads / range scans (P99 stability). `0` (the default)
/// means unlimited — no throttling, no behaviour change. Flush and
/// user reads are never throttled, only compaction. Set via
/// [`Config::compaction_rate_limit`].
pub(crate) compaction_rate_limit: u64,
/// Worker-thread count for compaction parallelism (`std` only), used two
/// ways: it sizes the per-tree block-compression pool built at open when
/// [`Self::compaction_pool`] is `None`, and it caps how many range-parallel
/// sub-compactions a single compaction is split into. Default
/// `max(1, available_parallelism / 2)` — leaves half the cores for
/// application work. `1` forces the serial path for both. Without the
/// `parallel` feature there is no built-in pool, so block compression and
/// sub-compaction ranges run serially even for a value > 1. Set via
/// [`Config::compaction_threads`].
#[cfg(feature = "std")] // no-std: parallel compaction unavailable (no threads)
pub(crate) compaction_threads: usize,
/// Optional shared compaction thread pool. `None` (default) = a per-tree
/// pool is built at [`crate::Tree::open`] sized by [`Self::compaction_threads`]
/// (predictable, matches the per-DB pattern). `Some` = caller-supplied
/// executor shared across every tree holding this `Arc`, bounding total
/// threads regardless of tree count. Set via [`Config::compaction_pool`].
#[cfg(feature = "std")]
pub(crate) compaction_pool: Option<Arc<dyn crate::table::writer::CompactionSpawner>>,
/// Minimum total input size (bytes) for a compaction to be split into
/// parallel sub-compactions. Below it the compaction stays single-threaded
/// (per-thread setup + extra output tables outweigh the parallelism on small
/// compactions). Default
/// [`SUBCOMPACTION_MIN_INPUT_BYTES`](crate::compaction::worker::SUBCOMPACTION_MIN_INPUT_BYTES)
/// (8 MiB). Set via [`Config::subcompaction_min_bytes`].
#[cfg(feature = "std")]
pub(crate) subcompaction_min_bytes: u64,
/// Test-only failpoint: when armed, the first parallel sub-compaction range
/// that observes it returns an error and disarms it, so the crash-safety
/// rollback paths (sibling output rollback, input restore) can be exercised
/// deterministically. Behind `cfg(test)`, never compiled into release builds.
#[cfg(all(test, feature = "std"))]
pub(crate) fail_one_subcompaction: Arc<std::sync::atomic::AtomicBool>,
/// Pre-trained zstd dictionary for dictionary compression.
///
/// When set together with a [`CompressionType::ZstdDict`] compression
/// policy, data blocks are compressed using this dictionary. The
/// dictionary must remain the same for the lifetime of the tree —
/// opening a tree with a different dictionary will produce
/// [`Error::ZstdDictMismatch`](crate::Error::ZstdDictMismatch) errors.
#[cfg(zstd_any)]
pub(crate) zstd_dictionary: Option<Arc<crate::compression::ZstdDictionary>>,
/// The global sequence number generator.
///
/// Should be shared between multiple trees of a database.
pub(crate) seqno: SharedSequenceNumberGenerator,
/// Sequence number watermark that is visible to readers.
///
/// Used for MVCC snapshots and to control which updates are
/// observable in a given view of the database.
pub(crate) visible_seqno: SharedSequenceNumberGenerator,
}
// TODO: remove default?
impl Default for Config {
fn default() -> Self {
Self {
path: absolute_path(Path::new(DEFAULT_FILE_FOLDER)),
fs: Arc::new(StdFs),
level_routes: None,
descriptor_table: Some(Arc::new(DescriptorTable::new(256))),
seqno: SharedSequenceNumberGenerator::from(SequenceNumberCounter::default()),
visible_seqno: SharedSequenceNumberGenerator::from(SequenceNumberCounter::default()),
cache: Arc::new(Cache::with_capacity_bytes(
/* 16 MiB */ 16 * 1_024 * 1_024,
)),
data_block_restart_interval_policy: RestartIntervalPolicy::all(16),
index_block_restart_interval_policy: RestartIntervalPolicy::all(1),
level_count: DEFAULT_LEVEL_COUNT,
data_block_size_policy: BlockSizePolicy::all(4_096),
index_block_pinning_policy: PinningPolicy::new([true, true, false]),
filter_block_pinning_policy: PinningPolicy::new([true, false]),
top_level_index_block_pinning_policy: PinningPolicy::all(true), // TODO: implement
top_level_filter_block_pinning_policy: PinningPolicy::all(true), // TODO: implement
// Partitioned at every level so a bit-flip inside one
// sub-index block only takes out the keys covered by that
// partition, not the entire SST. A full-index SST has no
// within-block redundancy: one corrupt byte in the single
// index block makes every data block in the table
// unreachable. See tests/partitioned_index_blast_radius.rs
// for the isolation property this default relies on.
index_block_partitioning_policy: PinningPolicy::all(true),
// Filter-block default intentionally left at the pre-#329
// shape (L3+ only). A corrupt filter block can produce a
// false negative (filter says "not present" → read short-
// circuits → caller misses an existing key), which is a
// correctness hazard distinct from index corruption (where
// the read fails loudly). Flipping this default is tracked
// as a separate decision pending a filter blast-radius /
// false-negative analysis; symmetry with index is not
// sufficient justification on its own.
filter_block_partitioning_policy: PinningPolicy::new([false, false, false, true]),
index_block_partition_size_policy: BlockSizePolicy::all(4_096), // TODO: implement
filter_block_partition_size_policy: BlockSizePolicy::all(4_096), // TODO: implement
data_block_compression_policy: ({
#[cfg(feature = "lz4")]
let c = CompressionPolicy::new([CompressionType::None, CompressionType::Lz4]);
#[cfg(not(feature = "lz4"))]
let c = CompressionPolicy::new([CompressionType::None]);
c
}),
index_block_compression_policy: CompressionPolicy::all(CompressionType::None),
data_block_hash_ratio_policy: HashRatioPolicy::all(0.0),
filter_policy: FilterPolicy::all(FilterPolicyEntry::Bloom(
BloomConstructionPolicy::BitsPerKey(10.0),
)),
compaction_filter_factory: None,
merge_operator: None,
prefix_extractor: None,
expect_point_read_hits: false,
page_ecc: false,
initial_runtime_config: crate::runtime_config::RuntimeConfig::default(),
kv_separation_opts: None,
#[cfg(zstd_any)]
zstd_dictionary: None,
comparator: comparator::default_comparator(),
encryption: None,
manifest_recovery_mode: ManifestRecoveryMode::AbsoluteConsistency,
sync_mode: SyncMode::Normal,
manifest_log_rotate_bytes: 1024 * 1024,
compaction_rate_limit: 0,
#[cfg(feature = "std")]
compaction_threads: std::thread::available_parallelism()
.map_or(1, |n| (n.get() / 2).max(1)),
#[cfg(feature = "std")]
compaction_pool: None,
#[cfg(feature = "std")]
subcompaction_min_bytes: crate::compaction::worker::SUBCOMPACTION_MIN_INPUT_BYTES,
#[cfg(all(test, feature = "std"))]
fail_one_subcompaction: Arc::new(std::sync::atomic::AtomicBool::new(false)),
}
}
}
impl Config {
/// Initializes a new config
pub fn new<P: AsRef<Path>>(
path: P,
seqno: SequenceNumberCounter,
visible_seqno: SequenceNumberCounter,
) -> Self {
Self {
path: absolute_path(path.as_ref()),
seqno: Arc::new(seqno),
visible_seqno: Arc::new(visible_seqno),
..Default::default()
}
}
/// Sets the default filesystem backend used for levels without an explicit route.
///
/// Defaults to [`StdFs`]. Use [`MemFs`](crate::fs::MemFs) for
/// in-memory trees (testing, ephemeral indexes).
///
/// # Example
///
/// ```
/// # fn main() -> lsm_tree::Result<()> {
/// use lsm_tree::{Config, SequenceNumberCounter};
/// use lsm_tree::fs::MemFs;
///
/// let tree = Config::new(
/// "/virtual/tree",
/// SequenceNumberCounter::default(),
/// SequenceNumberCounter::default(),
/// )
/// .with_fs(MemFs::new())
/// .open()?;
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn with_fs<F: Fs>(mut self, fs: F) -> Self {
self.fs = Arc::new(fs);
self
}
/// Sets the default filesystem backend from an existing shared handle.
///
/// Useful when multiple configs should reuse the same backend
/// instance, including trait objects and backends that are not `Clone`.
///
#[must_use]
pub fn with_shared_fs(mut self, fs: Arc<dyn Fs>) -> Self {
self.fs = fs;
self
}
/// Opens a tree using the config.
///
/// # Errors
///
/// Will return `Err` if an IO error occurs.
/// Returns [`Error::ZstdDictMismatch`](crate::Error::ZstdDictMismatch) if
/// the compression policy references a `dict_id` that doesn't match the
/// configured dictionary.
pub fn open(self) -> crate::Result<AnyTree> {
#[cfg(zstd_any)]
self.validate_zstd_dictionary()?;
// On a zstd build the live block path seals encrypted blocks through
// the AAD-bound envelope, so the configured provider MUST implement it.
// Reject an opaque-only provider here, at open time, instead of letting
// it fail on the first encrypted read/write.
#[cfg(zstd_any)]
if self
.encryption
.as_ref()
.is_some_and(|enc| !enc.supports_aad_block_path())
{
return Err(crate::Error::Encrypt(
"encryption provider does not implement the AAD-bound block path \
(encrypt_block_aad / decrypt_block_aad) required for encrypted \
blocks on a zstd build",
));
}
Ok(if self.kv_separation_opts.is_some() {
AnyTree::Blob(BlobTree::open(self)?)
} else {
AnyTree::Standard(Tree::open(self)?)
})
}
/// Validates that every `ZstdDict` entry in compression policies references
/// a `dict_id` that matches the configured dictionary. Catches mismatches
/// at open time rather than at first block write/read.
#[cfg(zstd_any)]
fn validate_zstd_dictionary(&self) -> crate::Result<()> {
let dict_id = self.zstd_dictionary.as_ref().map(|d| d.id());
// NOTE: Only data block policies are validated. Index blocks never
// carry a dictionary — Writer::use_index_block_compression() downgrades
// ZstdDict to plain Zstd. Validating index policies here would reject
// configs that use ZstdDict solely for index blocks even though the
// writer handles them correctly.
for ct in self.data_block_compression_policy.iter() {
if let &CompressionType::ZstdDict {
dict_id: required, ..
} = ct
{
match dict_id {
None => {
return Err(crate::Error::ZstdDictMismatch {
expected: required,
got: None,
});
}
Some(actual) if actual != required => {
return Err(crate::Error::ZstdDictMismatch {
expected: required,
got: Some(actual),
});
}
_ => {}
}
}
}
// Blob files with ZstdDict compression must have a matching dictionary.
if let Some(ref kv_opts) = self.kv_separation_opts
&& let CompressionType::ZstdDict {
dict_id: required, ..
} = kv_opts.compression
{
match kv_opts.zstd_dictionary.as_ref().map(|d| d.id()) {
None => {
return Err(crate::Error::ZstdDictMismatch {
expected: required,
got: None,
});
}
Some(actual) if actual != required => {
return Err(crate::Error::ZstdDictMismatch {
expected: required,
got: Some(actual),
});
}
_ => {}
}
}
Ok(())
}
/// Like [`Config::new`], but accepts pre-built shared generators.
///
/// This is useful when the caller already has
/// [`SharedSequenceNumberGenerator`] instances (e.g., from a higher-level
/// database that shares generators across multiple trees).
pub fn new_with_generators<P: AsRef<Path>>(
path: P,
seqno: SharedSequenceNumberGenerator,
visible_seqno: SharedSequenceNumberGenerator,
) -> Self {
Self {
path: absolute_path(path.as_ref()),
seqno,
visible_seqno,
..Default::default()
}
}
}
#[cfg(all(test, zstd_any))]
mod tests {
use super::*;
use crate::{CompressionType, SequenceNumberCounter, compression::ZstdDictionary};
use std::sync::Arc;
#[test]
fn blob_zstd_dict_no_dict_is_rejected() {
// ZstdDict compression for blobs without providing a dictionary must fail.
let folder = tempfile::tempdir().unwrap_or_else(|err| panic!("tempdir failed: {err}"));
let cfg = Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
.with_kv_separation(Some(KvSeparationOptions::default().compression(
CompressionType::ZstdDict {
level: 3,
dict_id: 7,
},
)));
assert!(
matches!(
cfg.validate_zstd_dictionary(),
Err(crate::Error::ZstdDictMismatch {
expected: 7,
got: None
})
),
"expected ZstdDictMismatch when no dictionary is supplied",
);
}
#[test]
fn blob_zstd_dict_id_mismatch_is_rejected() {
// ZstdDict compression with a dictionary whose id doesn't match the
// compression type's dict_id must fail.
let folder = tempfile::tempdir().unwrap_or_else(|err| panic!("tempdir failed: {err}"));
let dict = Arc::new(ZstdDictionary::new(b"sample training data for test"));
let wrong_dict_id = dict.id().wrapping_add(1);
let cfg = Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
.with_kv_separation(Some(
KvSeparationOptions::default()
.compression(CompressionType::ZstdDict {
level: 3,
dict_id: wrong_dict_id,
})
.dict(Arc::clone(&dict)),
));
assert!(
matches!(
cfg.validate_zstd_dictionary(),
Err(crate::Error::ZstdDictMismatch { .. })
),
"expected ZstdDictMismatch when dict_id doesn't match dictionary",
);
}
#[test]
fn blob_zstd_dict_matching_dict_is_accepted() {
// ZstdDict compression with a correctly matching dictionary must succeed.
let folder = tempfile::tempdir().unwrap_or_else(|err| panic!("tempdir failed: {err}"));
let dict = Arc::new(ZstdDictionary::new(b"sample training data for test"));
let cfg = Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
.with_kv_separation(Some(
KvSeparationOptions::default()
.compression(CompressionType::ZstdDict {
level: 3,
dict_id: dict.id(),
})
.dict(Arc::clone(&dict)),
));
assert!(
cfg.validate_zstd_dictionary().is_ok(),
"matching dictionary must be accepted",
);
}
}
impl Config {
/// Returns the tables folder path and [`Fs`] backend for the given level.
///
/// If [`level_routes`](Self::level_routes) has an entry covering this
/// level, uses that entry's path and `Fs`. Otherwise falls back to the
/// primary [`path`](Self::path) and [`fs`](Self::fs).
#[must_use]
pub fn tables_folder_for_level(&self, level: u8) -> (PathBuf, Arc<dyn Fs>) {
if let Some(routes) = &self.level_routes {
for route in routes {
if route.levels.contains(&level) {
return (route.path.join(TABLES_FOLDER), route.fs.clone());
}
}
}
(self.path.join(TABLES_FOLDER), self.fs.clone())
}
/// Returns all unique tables folders that need to be scanned during
/// recovery: the primary folder plus every [`LevelRoute`] folder.
#[must_use]
pub fn all_tables_folders(&self) -> Vec<(PathBuf, Arc<dyn Fs>)> {
let primary_fs: Arc<dyn Fs> = self.fs.clone();
let mut folders: Vec<(PathBuf, Arc<dyn Fs>)> =
vec![(self.path.join(TABLES_FOLDER), primary_fs)];
if let Some(routes) = &self.level_routes {
for route in routes {
let folder = route.path.join(TABLES_FOLDER);
// Dedup by path: scanning the same directory twice would cause
// already-recovered tables to be classified as orphans and
// deleted. Routing the same path through different Fs backends
// is a configuration error (level_routes validation in
// Config::level_routes rejects overlapping ranges).
if !folders.iter().any(|(p, _)| *p == folder) {
folders.push((folder, route.fs.clone()));
}
}
}
folders
}
/// Configures per-level filesystem routing for tiered storage.
///
/// Each [`LevelRoute`] maps a range of LSM levels to a base directory
/// and filesystem backend. Levels not covered by any route fall back to
/// the primary `path` and `fs`.
///
/// # Reopen contract
///
/// The route configuration is **not persisted** in the manifest.
/// On reopen, the [`Config`] must specify `level_routes` such that
/// [`all_tables_folders`](Self::all_tables_folders) includes every
/// directory and filesystem pair that may contain existing SST files
/// for this tree.
///
/// Changing the mapping from levels to paths is allowed as long as
/// the previously used folders remain covered. If old folders are
/// omitted, recovery may fail with
/// [`RouteMismatch`](crate::Error::RouteMismatch) (when all missing
/// tables are on uncovered levels) or
/// [`Unrecoverable`](crate::Error::Unrecoverable) (when some missing
/// tables are on levels that are still covered).
///
/// # Panics
///
/// Panics if any route has an empty range or if any two routes have
/// overlapping level ranges.
#[must_use]
pub fn level_routes(mut self, routes: Vec<LevelRoute>) -> Self {
// Validate no empty/inverted ranges
for route in &routes {
assert!(
route.levels.start < route.levels.end,
"empty or inverted level route range: {:?}",
route.levels,
);
}
// Validate no overlapping ranges
for (i, a) in routes.iter().enumerate() {
for b in routes.iter().skip(i + 1) {
assert!(
a.levels.end <= b.levels.start || b.levels.end <= a.levels.start,
"overlapping level routes: {:?} and {:?}",
a.levels,
b.levels,
);
}
}
self.level_routes = if routes.is_empty() {
None
} else {
// Normalize paths the same way Config::new normalizes self.path
Some(
routes
.into_iter()
.map(|mut r| {
r.path = absolute_path(&r.path);
r
})
.collect(),
)
};
self
}
/// Overrides the sequence number generator.
///
/// By default, [`SequenceNumberCounter`] is used. This allows plugging in
/// a custom generator (e.g., HLC for distributed databases).
#[must_use]
pub fn seqno_generator(mut self, generator: SharedSequenceNumberGenerator) -> Self {
self.seqno = generator;
self
}
/// Overrides the visible sequence number generator.
#[must_use]
pub fn visible_seqno_generator(mut self, generator: SharedSequenceNumberGenerator) -> Self {
self.visible_seqno = generator;
self
}
/// Sets the global cache.
///
/// You can create a global [`Cache`] and share it between multiple
/// trees to cap global cache memory usage.
///
/// Defaults to a cache with 16 MiB of capacity *per tree*.
#[must_use]
pub fn use_cache(mut self, cache: Arc<Cache>) -> Self {
self.cache = cache;
self
}
/// Sets the file descriptor cache.
///
/// Can be shared across trees.
#[must_use]
pub fn use_descriptor_table(mut self, descriptor_table: Option<Arc<DescriptorTable>>) -> Self {
self.descriptor_table = descriptor_table;
self
}
/// If `true`, the last level will not build filters, reducing the filter size of a database
/// by ~90% typically.
///
/// **Enable this only if you know that point reads generally are expected to find a key-value pair.**
#[must_use]
pub fn expect_point_read_hits(mut self, b: bool) -> Self {
self.expect_point_read_hits = b;
self
}
/// Enables per-block Reed-Solomon Page ECC.
///
/// When enabled, every block written by this tree carries a
/// Reed-Solomon parity trailer; on read, if the block's XXH3
/// disagrees with the on-disk bytes, the reader attempts RS
/// recovery before surfacing the corruption.
///
/// Opening a tree with `page_ecc = true` on a build that does not
/// have the `page_ecc` cargo feature enabled returns
/// [`crate::Error::PageEccUnsupported`] at `Tree::open` — the
/// reader has no way to honour the parity trailer without the
/// codec, so silently downgrading integrity is not an option.
///
/// Wired into the on-disk write path via `MultiWriter::use_page_ecc`
/// at every `Tree::open` / `Tree::ingestion` / compaction-worker
/// `MultiWriter` construction site. With this flag set, every
/// `Block::write_into` call those writers make upgrades its
/// `BlockTransform` to the matching `*Ecc` variant — emitting a
/// Reed-Solomon parity trailer and setting the `ECC_PARITY` flag in
/// each block header (the trailer length is derived from
/// `data_length`, not stored).
#[must_use]
pub fn page_ecc(mut self, enabled: bool) -> Self {
self.page_ecc = enabled;
self
}
/// Sets the Page ECC scheme used when [`Self::page_ecc`] is enabled.
///
/// ECC is off until `page_ecc(true)`. When on, this picks the
/// algorithm: [`EccScheme::Xor`] (RAID-5 single-parity) or
/// [`EccScheme::ReedSolomon`]. The default
/// [`EccScheme::Secded`](crate::runtime_config::EccScheme::Secded) is
/// not yet wired (#255), so enabling ECC without choosing a shard
/// scheme fails validation — pick `Xor`/`ReedSolomon` explicitly.
/// There is no implicit RS(4,2) default.
#[must_use]
pub fn ecc_scheme(mut self, scheme: crate::runtime_config::EccScheme) -> Self {
self.initial_runtime_config.ecc_scheme = scheme;
self
}
/// Sets whether the writer clears per-file copy-on-write on newly created
/// SST / blob files when the backing filesystem is copy-on-write (Btrfs).
///
/// Default `true`: write-once SSTs gain no benefit from `CoW` but suffer a
/// fragmentation penalty (~20% write throughput on Btrfs), so clearing it
/// recovers the ext4-equivalent baseline. A no-op on non-`CoW` filesystems.
/// Set `false` to preserve `CoW` (e.g. Btrfs subvolume snapshots that depend
/// on it). See [`crate::runtime_config::RuntimeConfig::disable_cow_on_sst_files`].
#[must_use]
pub fn disable_cow_on_sst_files(mut self, enabled: bool) -> Self {
self.initial_runtime_config.disable_cow_on_sst_files = enabled;
self
}
/// Sets whether [`crate::AbstractTree::create_checkpoint`] clones files via
/// reflink (`FICLONE` / `clonefile`) when the filesystem supports it,
/// falling back to a hard link otherwise.
///
/// Default `true`: a reflinked checkpoint has an independent inode (no
/// max-links constraint, modifications never touch the original) at O(1)
/// cost via copy-on-write block sharing. A no-op (hard-link path) on
/// filesystems without reflink. See
/// [`crate::runtime_config::RuntimeConfig::use_reflink_for_checkpoint`].
#[must_use]
pub fn use_reflink_for_checkpoint(mut self, enabled: bool) -> Self {
self.initial_runtime_config.use_reflink_for_checkpoint = enabled;
self
}
/// Sets the initial [`crate::runtime_config::RuntimeConfig`]
/// snapshot the tree will start with.
///
/// Seeds both the first manifest write and the live
/// `RuntimeConfigHandle` exposed via
/// [`crate::Tree::runtime_config`].
///
/// **Manifest-hardening toggles** in the supplied snapshot
/// that are currently wired through the writer
/// (`manifest_footer_mirror`, `page_ecc` *as consumed by
/// `manifest_blocks::writer` when picking the `BlockTransform`
/// variant*) take effect from byte zero of the on-disk
/// manifest rather than waiting for a post-open
/// [`crate::Tree::update_runtime_config`] call. Subsequent
/// updates still flow through the live handle and apply to
/// the next manifest write.
///
/// `manifest_kv_checksums` is plumbed in the snapshot but the
/// writer does NOT yet consult or persist it (per-entry
/// framing + footer-flag slot land in a follow-up). Setting
/// it here today has no on-disk effect; it is exposed for
/// forward-compat with no behaviour break.
///
/// **Note on data-block ECC:** `RuntimeConfig::page_ecc`
/// currently affects manifest Blocks only — data-block ECC is
/// still gated by [`Config::page_ecc`] at tree-open time. The
/// SST writer path consumes the tree-static config, not the
/// runtime handle. Wiring through SST emission is a follow-up.
#[must_use]
pub fn with_runtime_config(mut self, runtime: crate::runtime_config::RuntimeConfig) -> Self {
self.initial_runtime_config = runtime;
self
}
/// Sets the partitioning policy for filter blocks.
#[must_use]
pub fn filter_block_partitioning_policy(mut self, policy: PinningPolicy) -> Self {
self.filter_block_partitioning_policy = policy;
self
}
/// Sets the partitioning policy for index blocks.
#[must_use]
pub fn index_block_partitioning_policy(mut self, policy: PinningPolicy) -> Self {
self.index_block_partitioning_policy = policy;
self
}
/// Sets the pinning policy for filter blocks.
#[must_use]
pub fn filter_block_pinning_policy(mut self, policy: PinningPolicy) -> Self {
self.filter_block_pinning_policy = policy;
self
}
/// Sets the pinning policy for index blocks.
#[must_use]
pub fn index_block_pinning_policy(mut self, policy: PinningPolicy) -> Self {
self.index_block_pinning_policy = policy;
self
}
/// Sets the restart interval inside data blocks.
///
/// A higher restart interval saves space while increasing lookup times
/// inside data blocks.
///
/// Default = 16
///
/// # Panics
///
/// Panics if any restart interval in `policy` is zero.
#[must_use]
pub fn data_block_restart_interval_policy(mut self, policy: RestartIntervalPolicy) -> Self {
assert!(
policy.iter().all(|interval| *interval > 0),
"data block restart interval must be greater than zero",
);
self.data_block_restart_interval_policy = policy;
self
}
/// Sets the restart interval inside index blocks.
///
/// A higher restart interval saves space while increasing lookup times
/// inside index blocks.
///
/// Default = 1
///
/// # Panics
///
/// Panics if any restart interval in `policy` is zero.
#[must_use]
pub fn index_block_restart_interval_policy(mut self, policy: RestartIntervalPolicy) -> Self {
assert!(
policy.iter().all(|interval| *interval > 0),
"index block restart interval must be greater than zero",
);
self.index_block_restart_interval_policy = policy;
self
}
/// Sets the filter construction policy.
#[must_use]
pub fn filter_policy(mut self, policy: FilterPolicy) -> Self {
self.filter_policy = policy;
self
}
/// Sets the compression method for data blocks.
#[must_use]
pub fn data_block_compression_policy(mut self, policy: CompressionPolicy) -> Self {
self.data_block_compression_policy = policy;
self
}
/// Sets the compression method for index blocks.
#[must_use]
pub fn index_block_compression_policy(mut self, policy: CompressionPolicy) -> Self {
self.index_block_compression_policy = policy;
self
}
// TODO: level count is fixed to 7 right now
// /// Sets the number of levels of the LSM tree (depth of tree).
// ///
// /// Defaults to 7, like `LevelDB` and `RocksDB`.
// ///
// /// Cannot be changed once set.
// ///
// /// # Panics
// ///
// /// Panics if `n` is 0.
// #[must_use]
// pub fn level_count(mut self, n: u8) -> Self {
// assert!(n > 0);
// self.level_count = n;
// self
// }
/// Sets the data block size policy.
#[must_use]
pub fn data_block_size_policy(mut self, policy: BlockSizePolicy) -> Self {
self.data_block_size_policy = policy;
self
}
/// Sets the hash ratio policy for data blocks.
///
/// If greater than 0.0, a hash index is embedded into data blocks that can speed up reads
/// inside the data block.
#[must_use]
pub fn data_block_hash_ratio_policy(mut self, policy: HashRatioPolicy) -> Self {
self.data_block_hash_ratio_policy = policy;
self
}
/// Toggles key-value separation.
#[must_use]
pub fn with_kv_separation(mut self, opts: Option<KvSeparationOptions>) -> Self {
self.kv_separation_opts = opts;
self
}
/// Installs a custom compaction filter.
#[must_use]
pub fn with_compaction_filter_factory(mut self, factory: Option<Arc<dyn Factory>>) -> Self {
self.compaction_filter_factory = factory;
self
}
/// Sets the prefix extractor for prefix bloom filters.
///
/// When configured, bloom filters will index key prefixes returned by
/// the extractor. Prefix scans can then skip segments whose bloom
/// filter reports no match for the scan prefix.
#[must_use]
pub fn prefix_extractor(mut self, extractor: Arc<dyn PrefixExtractor>) -> Self {
self.prefix_extractor = Some(extractor);
self
}
/// Installs a merge operator for commutative operations.
///
/// When set, enables [`crate::AbstractTree::merge`] which stores partial updates
/// (operands) that are lazily combined during reads and compaction.
#[must_use]
pub fn with_merge_operator(mut self, op: Option<Arc<dyn MergeOperator>>) -> Self {
self.merge_operator = op;
self
}
/// Sets a custom user key comparator.
///
/// When configured, all key ordering (memtable, block index, merge,
/// range scans) uses this comparator instead of the default lexicographic
/// byte ordering.
///
/// # Important
///
/// The comparator's [`crate::UserComparator::name`] is persisted when a tree is
/// first created. On subsequent opens the stored name is compared against
/// the supplied comparator's name — a mismatch causes the open to fail
/// with [`Error::ComparatorMismatch`](crate::Error::ComparatorMismatch).
#[must_use]
pub fn comparator(mut self, comparator: SharedComparator) -> Self {
self.comparator = comparator;
self
}
/// Sets the block-level encryption provider for encryption at rest.
///
/// When set, all blocks written to SST files are encrypted after
/// compression and before checksumming, using the provided
/// [`EncryptionProvider`].
///
/// The caller is responsible for key management and rotation.
/// See [`crate::Aes256GcmProvider`] (behind the `encryption` feature)
/// for a ready-to-use AES-256-GCM implementation.
///
/// **Important constraints:**
/// - Encryption state is NOT recorded in SST metadata. Opening an
/// encrypted tree without the correct provider (or vice versa) will
/// cause block validation errors, not silent corruption.
/// - Blob files (KV-separated large values) are NOT covered by
/// block-level encryption. Large values stored via KV separation
/// remain in plaintext on disk.
#[must_use]
pub fn with_encryption(mut self, encryption: Option<Arc<dyn EncryptionProvider>>) -> Self {
self.encryption = encryption;
self
}
/// Sets the MANIFEST recovery policy for `Tree::open`.
///
/// The default ([`ManifestRecoveryMode::AbsoluteConsistency`]) is the
/// only choice that's safe for live production: any corrupt record
/// in the on-disk manifest aborts the open. Switching to a more
/// permissive mode trades strict correctness for partial
/// availability after a disaster. The recovery path emits a
/// `warn!` summary per affected section (aggregate counts: total
/// table records dropped, total blob-file records dropped,
/// header truncations) rather than one log line per dropped
/// record — the dropped records were never decoded in the first
/// place, so no per-record IDs are available. Always pair the
/// non-default modes with an out-of-band integrity scan
/// ([`verify_integrity`](crate::verify::verify_integrity) for
/// whole-file XXH3 over every SST + blob file, or
/// [`verify_block_checksums`](crate::verify::verify_block_checksums)
/// for per-block granularity) before trusting the recovered tree
/// for writes.
///
/// See the [`ManifestRecoveryMode`] doc for per-variant semantics.
#[must_use]
pub fn manifest_recovery_mode(mut self, mode: ManifestRecoveryMode) -> Self {
self.manifest_recovery_mode = mode;
self
}
/// Sets the durability level for every fsync the tree issues.
///
/// Defaults to [`SyncMode::Normal`] (plain `fsync`, matching `RocksDB` /
/// `SQLite` defaults). Pass [`SyncMode::Full`] to force `F_FULLFSYNC` on
/// macOS for power-loss durability without an external journal — at a
/// large per-flush cost. On non-macOS platforms both modes are
/// identical (plain `fsync`).
#[must_use]
pub fn sync_mode(mut self, mode: SyncMode) -> Self {
self.sync_mode = mode;
self
}
/// Sets the edit-log rotation threshold in bytes (default 1 MiB).
///
/// Once the manifest edit log exceeds this size, the next version upgrade
/// writes a fresh full snapshot and starts an empty log instead of appending
/// another edit. Lower it to shorten recovery replay and cap log size at the
/// cost of more frequent full-snapshot writes; `0` rotates on every upgrade.
#[must_use]
pub fn manifest_log_rotate_bytes(mut self, bytes: u64) -> Self {
self.manifest_log_rotate_bytes = bytes;
self
}
/// Sets the compaction I/O rate limit in bytes per second.
///
/// Caps how fast the compaction worker may issue I/O so background
/// compaction does not saturate the device and spike user read P99.
/// `0` (the default) disables throttling. Only compaction is limited;
/// flush and user reads always pass through.
#[must_use]
pub fn compaction_rate_limit(mut self, bytes_per_sec: u64) -> Self {
self.compaction_rate_limit = bytes_per_sec;
self
}
/// Sets the compaction worker-thread count.
///
/// Under `std` this both sizes the per-tree block-compression pool built at
/// open when no shared pool is supplied (see [`Self::compaction_pool`]) and
/// caps how many range-parallel sub-compactions a compaction splits into.
/// `1` keeps compaction serial. Default is `max(1, available_parallelism /
/// 2)`. Without the `parallel` feature there is no built-in pool, so the
/// work runs serially even for a value > 1.
#[cfg(feature = "std")]
#[must_use]
pub fn compaction_threads(mut self, threads: usize) -> Self {
// Clamp to >= 1: the documented semantics treat `1` as "serial", and a
// 0-thread pool would be an invalid state.
self.compaction_threads = threads.max(1);
self
}
/// Sets the minimum total input size (bytes) for a compaction to be split
/// into parallel sub-compactions. Default 8 MiB. `0` splits every eligible
/// compaction; a large value effectively disables sub-compaction (block
/// compression still parallelizes via [`Self::compaction_threads`]).
#[cfg(feature = "std")]
#[must_use]
pub fn subcompaction_min_bytes(mut self, bytes: u64) -> Self {
self.subcompaction_min_bytes = bytes;
self
}
/// Supplies a shared compaction thread pool, used in place of the per-tree
/// default. Pass one [`crate::table::writer::CompactionSpawner`] (e.g. a
/// `RayonSpawner` wrapping a shared rayon thread pool) to several trees so
/// the total worker-thread count stays bounded by the pool size rather than
/// the number of open trees.
#[cfg(feature = "std")]
#[must_use]
pub fn compaction_pool(
mut self,
pool: Option<Arc<dyn crate::table::writer::CompactionSpawner>>,
) -> Self {
self.compaction_pool = pool;
self
}
/// Sets the pre-trained zstd dictionary for dictionary compression.
///
/// When set, data blocks using [`CompressionType::ZstdDict`] will be
/// compressed and decompressed with this dictionary. The dictionary
/// should be trained on representative data samples for best results.
///
/// Create a dictionary with [`ZstdDictionary::new`](crate::ZstdDictionary::new),
/// then use [`CompressionType::zstd_dict`] to create a matching
/// compression type:
///
/// ```ignore
/// use lsm_tree::{CompressionType, ZstdDictionary};
///
/// let dict = ZstdDictionary::new(&training_data);
/// let compression = CompressionType::zstd_dict(3, dict.id()).unwrap();
///
/// config
/// .zstd_dictionary(Some(Arc::new(dict)))
/// .data_block_compression_policy(CompressionPolicy::all(compression));
/// ```
#[cfg(zstd_any)]
#[must_use]
pub fn zstd_dictionary(
mut self,
dictionary: Option<Arc<crate::compression::ZstdDictionary>>,
) -> Self {
self.zstd_dictionary = dictionary;
self
}
}
#[cfg(test)]
mod builder_tests {
use super::*;
use crate::SequenceNumberCounter;
#[test]
fn restart_interval_policies_can_be_overridden_independently() {
let folder = match tempfile::tempdir() {
Ok(folder) => folder,
Err(err) => panic!("tempdir failed: {err}"),
};
let cfg = Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
.data_block_restart_interval_policy(RestartIntervalPolicy::all(7))
.index_block_restart_interval_policy(RestartIntervalPolicy::all(3));
assert_eq!(cfg.data_block_restart_interval_policy.first(), Some(&7));
assert_eq!(cfg.index_block_restart_interval_policy.first(), Some(&3));
}
#[test]
fn fs_aware_builders_thread_to_initial_runtime_config() -> crate::Result<()> {
// The CoW-disable + reflink toggles default ON and flip via the builder
// (AC: "controlled via builder"). Verifies the builder threads to the
// initial RuntimeConfig the Tree opens with; a wiring regression would
// silently ignore the user's setting. Lives in the ungated builder
// tests (the behaviour is unrelated to zstd).
let folder = tempfile::tempdir()?;
let mk = || {
Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
};
let dflt = mk();
assert!(dflt.initial_runtime_config.disable_cow_on_sst_files);
assert!(dflt.initial_runtime_config.use_reflink_for_checkpoint);
let off = mk()
.disable_cow_on_sst_files(false)
.use_reflink_for_checkpoint(false);
assert!(!off.initial_runtime_config.disable_cow_on_sst_files);
assert!(!off.initial_runtime_config.use_reflink_for_checkpoint);
Ok(())
}
#[test]
#[should_panic(expected = "index block restart interval must be greater than zero")]
fn index_restart_interval_policy_rejects_zero_values() {
let folder = match tempfile::tempdir() {
Ok(folder) => folder,
Err(err) => panic!("tempdir failed: {err}"),
};
let _cfg = Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
.index_block_restart_interval_policy(RestartIntervalPolicy::all(0));
}
#[test]
#[should_panic(expected = "data block restart interval must be greater than zero")]
fn data_restart_interval_policy_rejects_zero_values() {
let folder = match tempfile::tempdir() {
Ok(folder) => folder,
Err(err) => panic!("tempdir failed: {err}"),
};
let _cfg = Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
.data_block_restart_interval_policy(RestartIntervalPolicy::all(0));
}
#[test]
#[should_panic(expected = "restart interval policy may not be empty")]
fn index_restart_interval_policy_rejects_empty() {
let folder = match tempfile::tempdir() {
Ok(folder) => folder,
Err(err) => panic!("tempdir failed: {err}"),
};
let _cfg = Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
.index_block_restart_interval_policy(RestartIntervalPolicy::new([]));
}
#[test]
#[should_panic(expected = "restart interval policy may not be empty")]
fn data_restart_interval_policy_rejects_empty() {
let folder = match tempfile::tempdir() {
Ok(folder) => folder,
Err(err) => panic!("tempdir failed: {err}"),
};
let _cfg = Config::new(
folder.path(),
SequenceNumberCounter::default(),
SequenceNumberCounter::default(),
)
.data_block_restart_interval_policy(RestartIntervalPolicy::new([]));
}
}