Skip to main content

typed_store/rocks/
options.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2026 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    collections::BTreeMap,
7    env,
8    sync::atomic::{AtomicBool, Ordering},
9};
10
11use iota_macros::nondeterministic;
12use rocksdb::{BlockBasedOptions, Cache, ReadOptions, SliceTransform};
13use sysinfo::{MemoryRefreshKind, RefreshKind, System};
14use tap::TapFallible;
15use tracing::{debug, info, warn};
16
17// Write buffer size per RocksDB instance can be set via the env var below.
18// If the env var is not set, use the default value in MiB.
19const ENV_VAR_DB_WRITE_BUFFER_SIZE: &str = "DB_WRITE_BUFFER_SIZE_MB";
20const DEFAULT_DB_WRITE_BUFFER_SIZE: usize = 1024;
21
22// Write ahead log size per RocksDB instance can be set via the env var below.
23// If the env var is not set, use the default value in MiB.
24const ENV_VAR_DB_WAL_SIZE: &str = "DB_WAL_SIZE_MB";
25const DEFAULT_DB_WAL_SIZE: usize = 1024;
26
27// Environment variable to control behavior of write throughput optimized
28// tables.
29const ENV_VAR_L0_NUM_FILES_COMPACTION_TRIGGER: &str = "L0_NUM_FILES_COMPACTION_TRIGGER";
30const DEFAULT_L0_NUM_FILES_COMPACTION_TRIGGER: usize = 4;
31const DEFAULT_UNIVERSAL_COMPACTION_L0_NUM_FILES_COMPACTION_TRIGGER: usize = 80;
32const ENV_VAR_MAX_WRITE_BUFFER_SIZE_MB: &str = "MAX_WRITE_BUFFER_SIZE_MB";
33const DEFAULT_MAX_WRITE_BUFFER_SIZE_MB: usize = 256;
34const ENV_VAR_MAX_WRITE_BUFFER_NUMBER: &str = "MAX_WRITE_BUFFER_NUMBER";
35const DEFAULT_MAX_WRITE_BUFFER_NUMBER: usize = 6;
36const ENV_VAR_TARGET_FILE_SIZE_BASE_MB: &str = "TARGET_FILE_SIZE_BASE_MB";
37const DEFAULT_TARGET_FILE_SIZE_BASE_MB: usize = 128;
38
39// Set to 1 to disable blob storage for transactions and effects.
40const ENV_VAR_DISABLE_BLOB_STORAGE: &str = "DISABLE_BLOB_STORAGE";
41const ENV_VAR_DB_PARALLELISM: &str = "DB_PARALLELISM";
42
43static FALLOCATE_DISABLED: AtomicBool = AtomicBool::new(false);
44
45/// Stops RocksDB from preallocating file space in databases opened afterwards
46/// with [`default_db_options`] or [`bulk_ingestion_options`].
47///
48/// For tests that run many nodes in one process: on Linux, each write-ahead
49/// log otherwise reserves up to 1.1 × the write buffer size on disk.
50pub fn disable_fallocate() {
51    FALLOCATE_DISABLED.store(true, Ordering::Relaxed);
52}
53
54/// Returns the RocksDB default options, with `allow_fallocate` turned off if
55/// [`disable_fallocate`] was called.
56pub(crate) fn base_db_options() -> rocksdb::Options {
57    let mut options = rocksdb::Options::default();
58    if !FALLOCATE_DISABLED.load(Ordering::Relaxed) {
59        return options;
60    }
61    // The crate has no setter for `allow_fallocate`. The parsed copy drops the
62    // objects attached to the original, so this must run before any are set.
63    options
64        .get_options_from_string("allow_fallocate=false")
65        .expect("allow_fallocate should be a valid RocksDB option")
66}
67
68#[derive(Clone, Debug, Default)]
69pub struct ReadWriteOptions {
70    /// When set, debug log the hash of the key and value bytes when inserting
71    /// to this table.
72    pub log_value_hash: bool,
73    /// The length of the fixed prefix extractor installed by
74    /// [`DBOptions::with_fixed_prefix_extractor`], if any. Iterators then
75    /// seek in total order unless their bounds stay within one prefix.
76    pub prefix_len: Option<usize>,
77}
78
79impl ReadWriteOptions {
80    /// Read options for point reads and for iterators whose bounds are not
81    /// known to stay within one prefix. With a prefix extractor installed,
82    /// a seek outside total order may skip memtables and files whose prefix
83    /// bloom filter rejects the seek key's prefix, which is wrong for a scan
84    /// that crosses prefixes. Bounded iterators decide per scan.
85    ///
86    /// Total order is set whether or not `prefix_len` is, so a table whose
87    /// extractor was installed some other way is read correctly too. It has
88    /// no effect on a table without an extractor.
89    pub fn readopts(&self) -> ReadOptions {
90        let mut read_options = ReadOptions::default();
91        read_options.set_total_order_seek(true);
92        read_options
93    }
94
95    pub fn set_log_value_hash(mut self, log_value_hash: bool) -> Self {
96        self.log_value_hash = log_value_hash;
97        self
98    }
99}
100
101#[derive(Default, Clone)]
102pub struct DBOptions {
103    pub options: rocksdb::Options,
104    pub rw_options: ReadWriteOptions,
105}
106
107/// Write options for a record that must be on disk before the write returns,
108/// rather than in the operating system's cache until some later sync.
109pub fn synced_write_options() -> rocksdb::WriteOptions {
110    let mut opts = rocksdb::WriteOptions::default();
111    opts.set_sync(true);
112    opts
113}
114
115/// The smallest SST file buffer limit, so a small memory budget does not
116/// split the rows into many tiny files.
117const MIN_SST_BUFFER_SIZE: usize = 64 << 20;
118
119/// RocksDB options tuned for one-shot bulk ingestion into a freshly created
120/// store, e.g. initial index building, inserting the genesis snapshot, or
121/// restoring a formal snapshot.
122pub struct BulkIngestionOptions {
123    pub db_options: rocksdb::Options,
124    pub column_family_options: DBOptions,
125    /// The memtable memory one column family may take.
126    cf_memory_budget: usize,
127}
128
129impl BulkIngestionOptions {
130    /// How much memory each of `writers` concurrent
131    /// [`SstFileBuffer`](crate::rocks::SstFileBuffer)s may fill before writing
132    /// a file: one column family's memtable budget, shared between them.
133    pub fn sst_buffer_limit(&self, writers: usize) -> usize {
134        (self.cf_memory_budget / writers.max(1)).max(MIN_SST_BUFFER_SIZE)
135    }
136
137    /// Per-table config applying the bulk column-family options to every
138    /// listed table.
139    pub fn table_config(
140        &self,
141        table_names: impl IntoIterator<Item = String>,
142    ) -> DBMapTableConfigMap {
143        DBMapTableConfigMap::new(
144            table_names
145                .into_iter()
146                .map(|name| (name, self.column_family_options.clone()))
147                .collect(),
148        )
149    }
150}
151
152/// Memtable budget for a bulk-ingestion store, as `(db_write_buffer_size,
153/// cf_memory_budget)`: 80% of system RAM across the whole database and 25%
154/// for a single column family.
155fn write_buffer_budget(total_memory_bytes: u64) -> (usize, usize) {
156    // A failed memory probe reports 0, and RocksDB reads a whole-database cap
157    // of 0 as unlimited; a measured limit is used as is, however small.
158    const FALLBACK_TOTAL_MEMORY_BYTES: u64 = 4 << 30;
159
160    let total_memory_bytes = if total_memory_bytes == 0 {
161        FALLBACK_TOTAL_MEMORY_BYTES as f64
162    } else {
163        total_memory_bytes as f64
164    };
165    (
166        (total_memory_bytes * 0.8) as usize,
167        (total_memory_bytes * 0.25) as usize,
168    )
169}
170
171pub fn bulk_ingestion_options() -> BulkIngestionOptions {
172    let total_memory_bytes = available_memory_bytes();
173    let num_cpus = num_cpus::get();
174    let (db_write_buffer_size, cf_memory_budget) = write_buffer_budget(total_memory_bytes);
175
176    let mut db_options = base_db_options();
177
178    // `unordered_write` gives a large speedup for bulk writes; relaxed write
179    // ordering is acceptable because the store is rebuilt from scratch on
180    // failure.
181    db_options.set_unordered_write(true);
182
183    // Allow CPU-intensive flushing to use all cores.
184    db_options.set_max_background_jobs(num_cpus as i32);
185
186    // Upper bound on memtable memory: 80% of RAM, sized so flushing keeps up
187    // with the writers.
188    db_options.set_db_write_buffer_size(db_write_buffer_size);
189
190    // Per-column-family options: Create options with compactions disabled and large
191    // write buffers. Each CF can use up to 25% of system RAM, but total is
192    // still limited by set_db_write_buffer_size configured above.
193    let mut column_family_options = default_db_options();
194    column_family_options
195        .options
196        .set_disable_auto_compactions(true);
197
198    // Disable the write backpressure that kicks in as L0 files build up: `-1`
199    // turns off the compaction and slowdown triggers, and the stop trigger is
200    // pushed out of reach. These are per-column-family options, so they must be
201    // set here rather than on `db_options` to reach the index CFs. Compaction
202    // itself is disabled above, so no L0 files are ever compacted away.
203    column_family_options
204        .options
205        .set_level_zero_file_num_compaction_trigger(-1);
206    column_family_options
207        .options
208        .set_level_zero_slowdown_writes_trigger(-1);
209    column_family_options
210        .options
211        .set_level_zero_stop_writes_trigger(i32::MAX);
212
213    const MIN_BUFFER_SIZE: usize = 64 * 1024 * 1024; // 64 MiB
214    // More CPUs means more parallel flushing capacity, so target more buffers,
215    // but never shrink a buffer below the minimum.
216    let target_buffer_count = num_cpus.max(2);
217    let buffer_size = (cf_memory_budget / target_buffer_count).max(MIN_BUFFER_SIZE);
218    let buffer_count = (cf_memory_budget / buffer_size).clamp(2, target_buffer_count) as i32;
219    column_family_options
220        .options
221        .set_write_buffer_size(buffer_size);
222    column_family_options
223        .options
224        .set_max_write_buffer_number(buffer_count);
225
226    debug!(
227        total_memory_bytes,
228        num_cpus,
229        db_write_buffer_size,
230        buffer_size,
231        buffer_count,
232        "configured bulk ingestion options"
233    );
234
235    BulkIngestionOptions {
236        db_options,
237        column_family_options,
238        cf_memory_budget,
239    }
240}
241
242/// Available memory in bytes, honoring cgroup limits in containerized
243/// environments and falling back to total system memory.
244fn available_memory_bytes() -> u64 {
245    // Under the simulator sysinfo must run off the test thread, where the
246    // intercepted clock and rng would make its probes a source of
247    // non-determinism. No-op outside msim.
248    nondeterministic!({
249        // `RefreshKind::nothing().with_memory(..)` avoids collecting other,
250        // slower stats.
251        let mut sys = System::new_with_specifics(
252            RefreshKind::nothing().with_memory(MemoryRefreshKind::everything()),
253        );
254        sys.refresh_memory();
255
256        if let Some(cgroup_limits) = sys.cgroup_limits() {
257            // `total_memory` is 0 when there is no cgroup limit.
258            if cgroup_limits.total_memory > 0 {
259                debug!(
260                    limit = cgroup_limits.total_memory,
261                    "using cgroup memory limit"
262                );
263                return cgroup_limits.total_memory;
264            }
265        }
266
267        let total = sys.total_memory();
268        debug!(total, "using total system memory");
269        total
270    })
271}
272
273#[derive(Clone)]
274pub struct DBMapTableConfigMap(BTreeMap<String, DBOptions>);
275impl DBMapTableConfigMap {
276    pub fn new(map: BTreeMap<String, DBOptions>) -> Self {
277        Self(map)
278    }
279
280    pub fn to_map(&self) -> BTreeMap<String, DBOptions> {
281        self.0.clone()
282    }
283}
284
285impl DBOptions {
286    // Optimize lookup perf for tables where no scans are performed.
287    // If non-trivial number of values can be > 512B in size, it is beneficial to
288    // also specify optimize_for_large_values_no_scan().
289    pub fn optimize_for_point_lookup(mut self, block_cache_size_mb: usize) -> DBOptions {
290        // NOTE: this overwrites the block options.
291        self.options
292            .optimize_for_point_lookup(block_cache_size_mb as u64);
293        self
294    }
295
296    // Optimize write and lookup perf for tables which are rarely scanned, and have
297    // large values. https://rocksdb.org/blog/2021/05/26/integrated-blob-db.html
298    pub fn optimize_for_large_values_no_scan(mut self, min_blob_size: u64) -> DBOptions {
299        if env::var(ENV_VAR_DISABLE_BLOB_STORAGE).is_ok() {
300            info!("Large value blob storage optimization is disabled via env var.");
301            return self;
302        }
303
304        // Blob settings.
305        self.options.set_enable_blob_files(true);
306        self.options
307            .set_blob_compression_type(rocksdb::DBCompressionType::Lz4);
308        self.options.set_enable_blob_gc(true);
309        // Since each blob can have non-trivial size overhead, and compression does not
310        // work across blobs, set a min blob size in bytes to so small
311        // transactions and effects are kept in sst files.
312        self.options.set_min_blob_size(min_blob_size);
313
314        // Increase write buffer size to 256MiB.
315        let write_buffer_size = read_size_from_env(ENV_VAR_MAX_WRITE_BUFFER_SIZE_MB)
316            .unwrap_or(DEFAULT_MAX_WRITE_BUFFER_SIZE_MB)
317            * 1024
318            * 1024;
319        self.options.set_write_buffer_size(write_buffer_size);
320        // Since large blobs are not in sst files, reduce the target file size and base
321        // level target size.
322        let target_file_size_base = 64 << 20;
323        self.options
324            .set_target_file_size_base(target_file_size_base);
325        // Level 1 default to 64MiB * 4 ~ 256MiB.
326        let max_level_zero_file_num = read_size_from_env(ENV_VAR_L0_NUM_FILES_COMPACTION_TRIGGER)
327            .unwrap_or(DEFAULT_L0_NUM_FILES_COMPACTION_TRIGGER);
328        self.options
329            .set_max_bytes_for_level_base(target_file_size_base * max_level_zero_file_num as u64);
330
331        self
332    }
333
334    // Optimize tables with a mix of lookup and scan workloads.
335    pub fn optimize_for_read(mut self, block_cache_size_mb: usize) -> DBOptions {
336        self.options
337            .set_block_based_table_factory(&get_block_options(block_cache_size_mb, 16 << 10));
338        self
339    }
340
341    // Optimize DB receiving significant insertions.
342    pub fn optimize_db_for_write_throughput(mut self, db_max_write_buffer_gb: u64) -> DBOptions {
343        self.options
344            .set_db_write_buffer_size(db_max_write_buffer_gb as usize * 1024 * 1024 * 1024);
345        self.options
346            .set_max_total_wal_size(db_max_write_buffer_gb * 1024 * 1024 * 1024);
347        self
348    }
349
350    // Optimize tables receiving significant insertions.
351    pub fn optimize_for_write_throughput(mut self) -> DBOptions {
352        // Increase write buffer size to 256MiB.
353        let write_buffer_size = read_size_from_env(ENV_VAR_MAX_WRITE_BUFFER_SIZE_MB)
354            .unwrap_or(DEFAULT_MAX_WRITE_BUFFER_SIZE_MB)
355            * 1024
356            * 1024;
357        self.options.set_write_buffer_size(write_buffer_size);
358        // Increase write buffers to keep to 6 before slowing down writes.
359        let max_write_buffer_number = read_size_from_env(ENV_VAR_MAX_WRITE_BUFFER_NUMBER)
360            .unwrap_or(DEFAULT_MAX_WRITE_BUFFER_NUMBER);
361        self.options
362            .set_max_write_buffer_number(max_write_buffer_number.try_into().unwrap());
363        // Keep 1 write buffer so recent writes can be read from memory.
364        self.options
365            .set_max_write_buffer_size_to_maintain((write_buffer_size).try_into().unwrap());
366
367        // Increase compaction trigger for level 0 to 6.
368        let max_level_zero_file_num = read_size_from_env(ENV_VAR_L0_NUM_FILES_COMPACTION_TRIGGER)
369            .unwrap_or(DEFAULT_L0_NUM_FILES_COMPACTION_TRIGGER);
370        self.options.set_level_zero_file_num_compaction_trigger(
371            max_level_zero_file_num.try_into().unwrap(),
372        );
373        self.options.set_level_zero_slowdown_writes_trigger(
374            (max_level_zero_file_num * 12).try_into().unwrap(),
375        );
376        self.options
377            .set_level_zero_stop_writes_trigger((max_level_zero_file_num * 16).try_into().unwrap());
378
379        // Increase sst file size to 128MiB.
380        self.options
381            .set_target_file_size_base(target_file_size_base());
382
383        // Increase level 1 target size to 256MiB * 6 ~ 1.5GiB.
384        self.options
385            .set_max_bytes_for_level_base((write_buffer_size * max_level_zero_file_num) as u64);
386
387        self
388    }
389
390    // Optimize tables receiving significant insertions, without any deletions.
391    // TODO: merge this function with optimize_for_write_throughput(), and use a
392    // flag to indicate if deletion is received.
393    pub fn optimize_for_write_throughput_no_deletion(mut self) -> DBOptions {
394        // Increase write buffer size to 256MiB.
395        let write_buffer_size = read_size_from_env(ENV_VAR_MAX_WRITE_BUFFER_SIZE_MB)
396            .unwrap_or(DEFAULT_MAX_WRITE_BUFFER_SIZE_MB)
397            * 1024
398            * 1024;
399        self.options.set_write_buffer_size(write_buffer_size);
400        // Increase write buffers to keep to 6 before slowing down writes.
401        let max_write_buffer_number = read_size_from_env(ENV_VAR_MAX_WRITE_BUFFER_NUMBER)
402            .unwrap_or(DEFAULT_MAX_WRITE_BUFFER_NUMBER);
403        self.options
404            .set_max_write_buffer_number(max_write_buffer_number.try_into().unwrap());
405        // Keep 1 write buffer so recent writes can be read from memory.
406        self.options
407            .set_max_write_buffer_size_to_maintain((write_buffer_size).try_into().unwrap());
408
409        // Switch to universal compactions.
410        self.options
411            .set_compaction_style(rocksdb::DBCompactionStyle::Universal);
412        let mut compaction_options = rocksdb::UniversalCompactOptions::default();
413        compaction_options.set_max_size_amplification_percent(10000);
414        compaction_options.set_stop_style(rocksdb::UniversalCompactionStopStyle::Similar);
415        self.options
416            .set_universal_compaction_options(&compaction_options);
417
418        let max_level_zero_file_num = read_size_from_env(ENV_VAR_L0_NUM_FILES_COMPACTION_TRIGGER)
419            .unwrap_or(DEFAULT_UNIVERSAL_COMPACTION_L0_NUM_FILES_COMPACTION_TRIGGER);
420        self.options.set_level_zero_file_num_compaction_trigger(
421            max_level_zero_file_num.try_into().unwrap(),
422        );
423        self.options.set_level_zero_slowdown_writes_trigger(
424            (max_level_zero_file_num * 12).try_into().unwrap(),
425        );
426        self.options
427            .set_level_zero_stop_writes_trigger((max_level_zero_file_num * 16).try_into().unwrap());
428
429        // Increase sst file size to 128MiB.
430        self.options
431            .set_target_file_size_base(target_file_size_base());
432
433        // This should be a no-op for universal compaction but increasing it to be safe.
434        self.options
435            .set_max_bytes_for_level_base((write_buffer_size * max_level_zero_file_num) as u64);
436
437        self
438    }
439
440    // Overrides the block options with different block cache size and block size.
441    pub fn set_block_options(
442        mut self,
443        block_cache_size_mb: usize,
444        block_size_bytes: usize,
445    ) -> DBOptions {
446        self.options
447            .set_block_based_table_factory(&get_block_options(
448                block_cache_size_mb,
449                block_size_bytes,
450            ));
451        self
452    }
453
454    // Disables write stalling and stopping based on pending compaction bytes.
455    pub fn disable_write_throttling(mut self) -> DBOptions {
456        self.options.set_soft_pending_compaction_bytes_limit(0);
457        self.options.set_hard_pending_compaction_bytes_limit(0);
458        self.options.set_level_zero_slowdown_writes_trigger(512);
459        self.options.set_level_zero_stop_writes_trigger(1024);
460        self
461    }
462
463    /// Indexes the table by the first `prefix_len` bytes of each key, for
464    /// tables scanned by a leading key field of fixed size, such as the
465    /// object id of an `(ObjectId, Version)` key.
466    ///
467    /// A prefix scan skips the memtables and files that hold no key of that
468    /// prefix instead of seeking in each of them. Point reads keep using the
469    /// whole-key filter.
470    ///
471    /// `prefix_len` must be the serialized size of the leading field, under
472    /// [`crate::be_fix_int_ser`]. The table's iterators use the extractor
473    /// only when their bounds stay within one prefix, and seek in total
474    /// order otherwise, so scans that cross prefixes stay correct.
475    pub fn with_fixed_prefix_extractor(mut self, prefix_len: usize) -> DBOptions {
476        self.options
477            .set_prefix_extractor(SliceTransform::create_fixed_prefix(prefix_len));
478        self.rw_options.prefix_len = Some(prefix_len);
479        self
480    }
481}
482
483/// Creates a default RocksDB option, to be used when RocksDB option is
484/// unspecified.
485pub fn default_db_options() -> DBOptions {
486    let mut opt = base_db_options();
487
488    // One common issue when running tests on Mac is that the default ulimit is too
489    // low, leading to I/O errors such as "Too many open files". Raising fdlimit
490    // to bypass it.
491    if let Some(limit) = fdlimit::raise_fd_limit() {
492        // on windows raise_fd_limit return None
493        opt.set_max_open_files((limit / 8) as i32);
494    }
495
496    // The table cache is locked for updates and this determines the number
497    // of shards, ie 2^10. Increase in case of lock contentions.
498    opt.set_table_cache_num_shard_bits(10);
499
500    // LSM compression settings
501    opt.set_compression_type(rocksdb::DBCompressionType::Lz4);
502    opt.set_bottommost_compression_type(rocksdb::DBCompressionType::Zstd);
503    opt.set_bottommost_zstd_max_train_bytes(1024 * 1024, true);
504
505    // IOTA uses multiple RocksDB in a node, so total sizes of write buffers and WAL
506    // can be higher than the limits below.
507    //
508    // RocksDB also exposes the option to configure total write buffer size across
509    // multiple instances via `write_buffer_manager`. But the write buffer flush
510    // policy (flushing the buffer receiving the next write) may not work well.
511    // So sticking to per-db write buffer size limit for now.
512    //
513    // The environment variables are only meant to be emergency overrides. They may
514    // go away in future. It is preferable to update the default value, or
515    // override the option in code.
516    opt.set_db_write_buffer_size(
517        read_size_from_env(ENV_VAR_DB_WRITE_BUFFER_SIZE).unwrap_or(DEFAULT_DB_WRITE_BUFFER_SIZE)
518            * 1024
519            * 1024,
520    );
521    opt.set_max_total_wal_size(
522        read_size_from_env(ENV_VAR_DB_WAL_SIZE).unwrap_or(DEFAULT_DB_WAL_SIZE) as u64 * 1024 * 1024,
523    );
524
525    // Num threads for compactions and memtable flushes.
526    opt.increase_parallelism(read_size_from_env(ENV_VAR_DB_PARALLELISM).unwrap_or(8) as i32);
527
528    opt.set_enable_pipelined_write(true);
529
530    // Increase block size to 16KiB.
531    // https://github.com/EighteenZi/rocksdb_wiki/blob/master/Memory-usage-in-RocksDB.md#indexes-and-filter-blocks
532    opt.set_block_based_table_factory(&get_block_options(128, 16 << 10));
533
534    // Set memtable bloomfilter.
535    opt.set_memtable_prefix_bloom_ratio(0.02);
536
537    DBOptions {
538        options: opt,
539        rw_options: ReadWriteOptions::default(),
540    }
541}
542
543fn get_block_options(block_cache_size_mb: usize, block_size_bytes: usize) -> BlockBasedOptions {
544    // Set options mostly similar to those used in optimize_for_point_lookup(),
545    // except non-default binary and hash index, to hopefully reduce lookup
546    // latencies without causing any regression for scanning, with slightly more
547    // memory usages. https://github.com/facebook/rocksdb/blob/11cb6af6e5009c51794641905ca40ce5beec7fee/options/options.cc#L611-L621
548    let mut block_options = BlockBasedOptions::default();
549    // Overrides block size.
550    block_options.set_block_size(block_size_bytes);
551    // Configure a block cache.
552    block_options.set_block_cache(&Cache::new_lru_cache(block_cache_size_mb << 20));
553    // Set a bloomfilter with 1% false positive rate.
554    block_options.set_bloom_filter(10.0, false);
555    // From https://github.com/EighteenZi/rocksdb_wiki/blob/master/Block-Cache.md#caching-index-and-filter-blocks
556    block_options.set_pin_l0_filter_and_index_blocks_in_cache(true);
557    block_options
558}
559
560pub fn list_tables(path: std::path::PathBuf) -> eyre::Result<Vec<String>> {
561    const DB_DEFAULT_CF_NAME: &str = "default";
562
563    let opts = rocksdb::Options::default();
564    rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::list_cf(&opts, path)
565        .map_err(|e| e.into())
566        .map(|q| {
567            q.iter()
568                .filter_map(|s| {
569                    // The `default` table is not used
570                    if s != DB_DEFAULT_CF_NAME {
571                        Some(s.clone())
572                    } else {
573                        None
574                    }
575                })
576                .collect()
577        })
578}
579
580/// The size, in bytes, at which compactions under
581/// [`DBOptions::optimize_for_write_throughput`] and
582/// [`DBOptions::optimize_for_write_throughput_no_deletion`] cut their output
583/// files.
584pub fn target_file_size_base() -> u64 {
585    read_size_from_env(ENV_VAR_TARGET_FILE_SIZE_BASE_MB).unwrap_or(DEFAULT_TARGET_FILE_SIZE_BASE_MB)
586        as u64
587        * 1024
588        * 1024
589}
590
591pub fn read_size_from_env(var_name: &str) -> Option<usize> {
592    env::var(var_name)
593        .ok()?
594        .parse::<usize>()
595        .tap_err(|e| {
596            warn!(
597                "Env var {} does not contain valid usize integer: {}",
598                var_name, e
599            )
600        })
601        .ok()
602}
603
604#[cfg(test)]
605mod tests {
606    use super::*;
607
608    /// The memtable budget is a fixed share of the measured memory, with a
609    /// safe fallback when the probe fails.
610    #[test]
611    fn write_buffer_budget_scales_with_available_memory() {
612        const TOTAL: u64 = 64 << 30;
613
614        let (db_one, cf_one) = write_buffer_budget(TOTAL);
615        assert_eq!(db_one, (TOTAL as f64 * 0.8) as usize);
616        assert_eq!(cf_one, (TOTAL as f64 * 0.25) as usize);
617
618        // A failed memory probe must not turn the whole-database cap into
619        // RocksDB's unlimited.
620        let (db_unknown, cf_unknown) = write_buffer_budget(0);
621        assert_eq!(write_buffer_budget(4 << 30), (db_unknown, cf_unknown));
622        assert!(db_unknown > 0 && cf_unknown > 0);
623
624        // A measured limit below the fallback is used as is: budgeting above
625        // a cgroup limit would get the process killed.
626        const SMALL: u64 = 2 << 30;
627        let (db_small, cf_small) = write_buffer_budget(SMALL);
628        assert_eq!(db_small, (SMALL as f64 * 0.8) as usize);
629        assert_eq!(cf_small, (SMALL as f64 * 0.25) as usize);
630        assert!(db_small < db_unknown);
631    }
632}