Skip to main content

mito2/
config.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Configurations.
16
17use std::cmp;
18use std::path::Path;
19use std::time::Duration;
20
21use common_base::memory_limit::MemoryLimit;
22use common_base::readable_size::ReadableSize;
23use common_memory_manager::OnExhaustedPolicy;
24use common_stat::{get_total_cpu_cores, get_total_memory_readable};
25use common_telemetry::warn;
26use serde::{Deserialize, Serialize};
27use serde_with::serde_as;
28
29use crate::cache::file_cache::DEFAULT_INDEX_CACHE_PERCENT;
30use crate::error::Result;
31use crate::gc::GcConfig;
32use crate::sst::DEFAULT_WRITE_BUFFER_SIZE;
33
34const MULTIPART_UPLOAD_MINIMUM_SIZE: ReadableSize = ReadableSize::mb(5);
35const DEFAULT_SERIES_INDEX_MIN_FILES: usize = 4;
36const DEFAULT_SERIES_INDEX_MAINTENANCE_INTERVAL: Duration = Duration::from_secs(5 * 60);
37/// Default maximum number of SST files to scan concurrently.
38pub(crate) const DEFAULT_MAX_CONCURRENT_SCAN_FILES: usize = 384;
39
40// Use `1/GLOBAL_WRITE_BUFFER_SIZE_FACTOR` of OS memory as global write buffer size in default mode
41const GLOBAL_WRITE_BUFFER_SIZE_FACTOR: u64 = 8;
42/// Use `1/SST_META_CACHE_SIZE_FACTOR` of OS memory size as SST meta cache size in default mode
43const SST_META_CACHE_SIZE_FACTOR: u64 = 8;
44/// Use `1/PREFILTER_RESULT_CACHE_SIZE_FACTOR` of OS memory size as prefilter result cache size in default mode
45const PREFILTER_RESULT_CACHE_SIZE_FACTOR: u64 = 32;
46/// Use `1/INDEX_METADATA_CACHE_SIZE_FACTOR` of OS memory size as index metadata cache size in default mode
47const INDEX_METADATA_CACHE_SIZE_FACTOR: u64 = 32;
48/// Use `1/MEM_CACHE_SIZE_FACTOR` of OS memory size as mem cache size in default mode
49const MEM_CACHE_SIZE_FACTOR: u64 = 16;
50/// Use `1/PAGE_CACHE_SIZE_FACTOR` of OS memory size as page cache size in default mode
51const PAGE_CACHE_SIZE_FACTOR: u64 = 8;
52/// Use `1/INDEX_CREATE_MEM_THRESHOLD_FACTOR` of OS memory size as mem threshold for creating index
53const INDEX_CREATE_MEM_THRESHOLD_FACTOR: u64 = 16;
54
55/// Memory accounted against the shared scan limit.
56#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "snake_case")]
58pub enum ScanMemoryMode {
59    /// Count projected Parquet columns' uncompressed row-group sizes.
60    #[default]
61    Basic,
62    /// Also count cumulative streamed batches.
63    Extended,
64}
65
66/// Fetch option timeout
67pub(crate) const FETCH_OPTION_TIMEOUT: Duration = Duration::from_secs(3);
68
69/// Paired series-index and sample storage selection for the experimental reader.
70#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
71#[serde(rename_all = "lowercase")]
72pub enum SeriesIndexFormat {
73    /// Parquet series indexes and authoritative SST reads.
74    #[default]
75    Legacy,
76    /// Columnar series indexes and daily columnar samples.
77    Columnar,
78}
79
80/// Configuration for [MitoEngine](crate::engine::MitoEngine).
81/// Before using the config, call [`MitoConfig::sanitize()`] to validate and normalize it.
82#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
83#[serde(default)]
84pub struct MitoConfig {
85    // Worker configs:
86    /// Number of region workers (default: 1/2 of cpu cores).
87    /// Sets to 0 to use the default value.
88    pub num_workers: usize,
89    /// Request channel size of each worker (default 128).
90    pub worker_channel_size: usize,
91    /// Max batch size for a worker to handle requests (default 64).
92    pub worker_request_batch_size: usize,
93
94    // Manifest configs:
95    /// Number of meta action updated to trigger a new checkpoint
96    /// for the manifest (default 10).
97    pub manifest_checkpoint_distance: u64,
98    /// Number of removed files to keep in manifest's `removed_files` field before also
99    /// remove them from `removed_files`. Mostly for debugging purpose.
100    /// If set to 0, it will only use `keep_removed_file_ttl` to decide when to remove files
101    /// from `removed_files` field.
102    pub experimental_manifest_keep_removed_file_count: usize,
103    /// How long to keep removed files in the `removed_files` field of manifest
104    /// after they are removed from manifest.
105    /// files will only be removed from `removed_files` field
106    /// if both `keep_removed_file_count` and `keep_removed_file_ttl` is reached.
107    #[serde(with = "humantime_serde")]
108    pub experimental_manifest_keep_removed_file_ttl: Duration,
109    /// Whether to compress manifest and checkpoint file by gzip (default false).
110    pub compress_manifest: bool,
111
112    // Background job configs:
113    /// Max number of running background index build jobs (default: 1/8 of cpu cores).
114    pub max_background_index_builds: usize,
115    /// Under development; do not enable. Whether to enable series indexes (default false).
116    /// Indexes are stored on the local filesystem under `{data_home}/series_index`.
117    pub experimental_enable_series_index: bool,
118    /// Paired artifact format (default legacy).
119    pub experimental_series_index_format: SeriesIndexFormat,
120    /// Approximate size limit for local series and range index sidecars in open regions (default: 5 GiB).
121    /// Workers share a periodically refreshed estimate and defer sidecar builds when full.
122    /// In-flight reconciliation can exceed the limit; closed-region files are not counted.
123    pub experimental_series_index_max_size: ReadableSize,
124    /// Whether to build and query range indexes when series indexes are enabled (default false).
125    /// Obsolete range-index metadata and files are still cleaned up when disabled.
126    pub experimental_enable_range_index: bool,
127    /// Interval between series-index maintenance runs (default 5 min). Zero uses the default.
128    #[serde(with = "humantime_serde")]
129    pub experimental_series_index_maintenance_interval: Duration,
130    /// Under development. Native series indexes persist this window width on first build.
131    /// Local series indexes round up to a multiple of the compaction time window.
132    #[serde(with = "humantime_serde")]
133    pub experimental_series_index_bucket_width: Duration,
134    /// Minimum uncovered live sample SSTs per native series index window.
135    /// Zero uses the default of 4.
136    pub experimental_series_index_min_files: usize,
137    /// Max number of running background flush jobs (default: 1/2 of cpu cores).
138    pub max_background_flushes: usize,
139    /// Max number of running background compaction jobs (default: 1/4 of cpu cores).
140    ///
141    /// The limit applies to the whole engine, not to each region worker. SST compaction
142    /// and background bulk memtable compaction each have their own budget of this size.
143    /// For SST compaction, the same limit bounds engine-wide admission of local compaction
144    /// units and the merge-output budget of each automatic per-region pick. Outputs sharing
145    /// inputs form one unit. Expired SSTs may add one expiration-only unit outside
146    /// the merge-output budget; it still consumes a slot in the same admission limit.
147    /// Manual compaction keeps using the request's `parallelism`.
148    pub max_background_compactions: usize,
149    /// Max number of running background purge jobs (default: number of cpu cores).
150    pub max_background_purges: usize,
151    /// Memory budget for compaction tasks.
152    /// Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").
153    /// Setting it to 0 or "unlimited" disables the limit.
154    pub experimental_compaction_memory_limit: MemoryLimit,
155    /// Behavior when compaction cannot acquire memory from the budget.
156    pub experimental_compaction_on_exhausted: OnExhaustedPolicy,
157    /// Default per-output parallelism for input decoding and SST column encoding,
158    /// bounded independently per stage. Values below 2 disable both.
159    /// Tables can override it with `compaction.experimental_output_parallelism`.
160    pub experimental_compaction_output_parallelism: usize,
161
162    // Flush configs:
163    /// Interval to auto flush a region if it has not flushed yet (default 10 min).
164    #[serde(with = "humantime_serde")]
165    pub auto_flush_interval: Duration,
166    /// Global write buffer size threshold to trigger flush.
167    pub global_write_buffer_size: ReadableSize,
168    /// Global write buffer size threshold to reject write requests.
169    pub global_write_buffer_reject_size: ReadableSize,
170    /// Default write buffer size for each region. Regions stall at this size and
171    /// reject writes at twice this size. Setting it to 0 disables both limits
172    /// unless the table specifies `write_buffer_size`.
173    pub default_region_write_buffer_size: ReadableSize,
174
175    // Cache configs:
176    /// Cache size for SST metadata. Setting it to 0 to disable the cache.
177    pub sst_meta_cache_size: ReadableSize,
178    /// Cache size for vectors and arrow arrays. Setting it to 0 to disable the cache.
179    pub vector_cache_size: ReadableSize,
180    /// Cache size for pages of SST row groups. Setting it to 0 to disable the cache.
181    pub page_cache_size: ReadableSize,
182    /// Cache size for time series selector (e.g. `last_value()`). Setting it to 0 to disable the cache.
183    pub selector_result_cache_size: ReadableSize,
184    /// Cache size for flat range scan results. Setting it to 0 to disable the cache.
185    pub range_result_cache_size: ReadableSize,
186    /// Cache size for prefilter results. Setting it to 0 to disable the cache.
187    pub prefilter_result_cache_size: ReadableSize,
188    /// Whether to enable the write cache.
189    pub enable_write_cache: bool,
190    /// File system path for write cache dir's root, defaults to `{data_home}`.
191    pub write_cache_path: String,
192    /// Capacity for write cache.
193    pub write_cache_size: ReadableSize,
194    /// TTL for write cache.
195    #[serde(with = "humantime_serde")]
196    pub write_cache_ttl: Option<Duration>,
197    /// Preload index (puffin) files into cache on region open (default: true).
198    pub preload_index_cache: bool,
199    /// Percentage of write cache capacity allocated for index (puffin) files (default: 20).
200    /// The remaining capacity is used for data (parquet) files.
201    /// Must be between 0 and 100 (exclusive).
202    pub index_cache_percent: u8,
203    /// Enable background downloading of files to the local cache when accessed during queries (default: true).
204    /// When enabled, files will be asynchronously downloaded to improve performance for subsequent reads.
205    pub enable_refill_cache_on_read: bool,
206    /// Capacity for manifest cache (default: 256MB).
207    pub manifest_cache_size: ReadableSize,
208
209    // Other configs:
210    /// Buffer size for SST writing.
211    // TODO(#9240): Support per-object-store write buffer sizes for backend-specific tuning.
212    pub sst_write_buffer_size: ReadableSize,
213    /// Maximum number of SST files to scan concurrently when memory accounting
214    /// does not cover the scan or the limit is disabled (default 384).
215    pub max_concurrent_scan_files: usize,
216    /// Whether to allow stale entries read during replay.
217    pub allow_stale_entries: bool,
218    /// Memory limit for table scans across all queries (default: 25% of system memory).
219    /// Setting it to 0 or "unlimited" disables the limit.
220    /// Supports absolute size (e.g., "2GB") or percentage of system memory (e.g., "50%").
221    pub scan_memory_limit: MemoryLimit,
222    /// Scan memory accounting: basic counts projected Parquet row groups;
223    /// extended also counts cumulative streamed batches. Limited reservations round up to KB.
224    /// Internal series merges use the query runtime pool in both modes.
225    pub scan_memory_mode: ScanMemoryMode,
226    /// Scan memory exhaustion always fails immediately (default: `fail`).
227    /// Legacy `wait` and `wait(<duration>)` values are accepted but deprecated:
228    /// sanitization warns and replaces them with [`OnExhaustedPolicy::Fail`].
229    pub scan_memory_on_exhausted: OnExhaustedPolicy,
230
231    /// Index configs.
232    pub index: IndexConfig,
233    /// Inverted index configs.
234    pub inverted_index: InvertedIndexConfig,
235    /// Full-text index configs.
236    pub fulltext_index: FulltextIndexConfig,
237    /// Bloom filter index configs.
238    pub bloom_filter_index: BloomFilterConfig,
239
240    /// Minimum time interval between two compactions.
241    /// To align with the old behavior, the default value is 0 (no restrictions).
242    #[serde(with = "humantime_serde")]
243    pub min_compaction_interval: Duration,
244    /// Whether to schedule compaction after applying a region edit.
245    pub schedule_compaction_after_edit: bool,
246
247    /// Whether to enable flat format as the default SST format.
248    /// When enabled, forces using BulkMemtable and BulkMemtableBuilder.
249    pub default_flat_format: bool,
250
251    /// Whether to enable the experimental two-phase mode for eligible metric series scans.
252    pub experimental_series_scan_v2: bool,
253
254    pub gc: GcConfig,
255}
256
257impl Default for MitoConfig {
258    fn default() -> Self {
259        let mut mito_config = MitoConfig {
260            num_workers: divide_num_cpus(2),
261            worker_channel_size: 128,
262            worker_request_batch_size: 64,
263            manifest_checkpoint_distance: 10,
264            experimental_manifest_keep_removed_file_count: 256,
265            experimental_manifest_keep_removed_file_ttl: Duration::from_secs(60 * 60),
266            compress_manifest: false,
267            max_background_index_builds: divide_num_cpus(8),
268            experimental_enable_series_index: false,
269            experimental_series_index_min_files: DEFAULT_SERIES_INDEX_MIN_FILES,
270            experimental_series_index_format: SeriesIndexFormat::Legacy,
271            experimental_series_index_max_size: ReadableSize::gb(5),
272            experimental_enable_range_index: false,
273            experimental_series_index_maintenance_interval:
274                DEFAULT_SERIES_INDEX_MAINTENANCE_INTERVAL,
275            experimental_series_index_bucket_width: Duration::from_secs(5 * 24 * 60 * 60),
276            max_background_flushes: divide_num_cpus(2),
277            max_background_compactions: divide_num_cpus(4),
278            max_background_purges: get_total_cpu_cores(),
279            experimental_compaction_memory_limit: MemoryLimit::Unlimited,
280            experimental_compaction_on_exhausted: OnExhaustedPolicy::default(),
281            experimental_compaction_output_parallelism: 1,
282            auto_flush_interval: Duration::from_secs(10 * 60),
283            global_write_buffer_size: ReadableSize::gb(1),
284            global_write_buffer_reject_size: ReadableSize::gb(2),
285            default_region_write_buffer_size: ReadableSize::mb(0),
286            sst_meta_cache_size: ReadableSize::mb(128),
287            vector_cache_size: ReadableSize::mb(512),
288            page_cache_size: ReadableSize::mb(512),
289            selector_result_cache_size: ReadableSize::mb(512),
290            range_result_cache_size: ReadableSize::mb(512),
291            prefilter_result_cache_size: ReadableSize::mb(128),
292            enable_write_cache: false,
293            write_cache_path: String::new(),
294            write_cache_size: ReadableSize::gb(5),
295            write_cache_ttl: None,
296            preload_index_cache: true,
297            index_cache_percent: DEFAULT_INDEX_CACHE_PERCENT,
298            enable_refill_cache_on_read: true,
299            manifest_cache_size: ReadableSize::mb(256),
300            sst_write_buffer_size: DEFAULT_WRITE_BUFFER_SIZE,
301            max_concurrent_scan_files: DEFAULT_MAX_CONCURRENT_SCAN_FILES,
302            allow_stale_entries: false,
303            scan_memory_limit: MemoryLimit::Percentage(25),
304            scan_memory_mode: ScanMemoryMode::Basic,
305            scan_memory_on_exhausted: OnExhaustedPolicy::Fail,
306            index: IndexConfig::default(),
307            inverted_index: InvertedIndexConfig::default(),
308            fulltext_index: FulltextIndexConfig::default(),
309            bloom_filter_index: BloomFilterConfig::default(),
310            min_compaction_interval: Duration::from_secs(0),
311            schedule_compaction_after_edit: true,
312            default_flat_format: true,
313            // FIXME(#9435): Keep v2 opt-in while long-range scan memory usage is investigated.
314            experimental_series_scan_v2: false,
315            gc: GcConfig::default(),
316        };
317
318        // Adjust buffer and cache size according to system memory if we can.
319        if let Some(sys_memory) = get_total_memory_readable() {
320            mito_config.adjust_buffer_and_cache_size(sys_memory);
321        }
322
323        mito_config
324    }
325}
326
327impl MitoConfig {
328    /// Sanitize incorrect configurations.
329    ///
330    /// Returns an error if there is a configuration that unable to sanitize.
331    pub fn sanitize(&mut self, data_home: &str) -> Result<()> {
332        if matches!(
333            self.scan_memory_on_exhausted,
334            OnExhaustedPolicy::Wait { .. }
335        ) {
336            warn!(
337                "scan_memory_on_exhausted = {:?} is deprecated and is treated as fail; \
338                 scan memory exhaustion now fails immediately. Set scan_memory_on_exhausted = \"fail\"",
339                self.scan_memory_on_exhausted
340            );
341            self.scan_memory_on_exhausted = OnExhaustedPolicy::Fail;
342        }
343
344        if self.experimental_enable_series_index {
345            snafu::ensure!(
346                self.experimental_series_index_max_size.as_bytes() >= 1024,
347                crate::error::InvalidConfigSnafu {
348                    reason: "experimental_series_index_max_size must be at least 1KiB"
349                }
350            );
351        }
352        // Use default value if `num_workers` is 0.
353        if self.num_workers == 0 {
354            self.num_workers = divide_num_cpus(2);
355        }
356
357        // Sanitize channel size.
358        if self.worker_channel_size == 0 {
359            warn!("Sanitize channel size 0 to 1");
360            self.worker_channel_size = 1;
361        }
362
363        if self.max_background_flushes == 0 {
364            warn!(
365                "Sanitize max background flushes 0 to {}",
366                divide_num_cpus(2)
367            );
368            self.max_background_flushes = divide_num_cpus(2);
369        }
370        if self.max_background_compactions == 0 {
371            warn!(
372                "Sanitize max background compactions 0 to {}",
373                divide_num_cpus(4)
374            );
375            self.max_background_compactions = divide_num_cpus(4);
376        }
377        if self.max_background_purges == 0 {
378            let cpu_cores = get_total_cpu_cores();
379            warn!("Sanitize max background purges 0 to {}", cpu_cores);
380            self.max_background_purges = cpu_cores;
381        }
382
383        if self.experimental_series_index_min_files == 0 {
384            self.experimental_series_index_min_files = DEFAULT_SERIES_INDEX_MIN_FILES;
385        }
386
387        if self
388            .experimental_series_index_maintenance_interval
389            .is_zero()
390        {
391            warn!("Sanitize series-index maintenance interval 0 to 5 minutes");
392            self.experimental_series_index_maintenance_interval =
393                DEFAULT_SERIES_INDEX_MAINTENANCE_INTERVAL;
394        }
395
396        if self.global_write_buffer_reject_size <= self.global_write_buffer_size {
397            self.global_write_buffer_reject_size = self.global_write_buffer_size * 2;
398            warn!(
399                "Sanitize global write buffer reject size to {}",
400                self.global_write_buffer_reject_size
401            );
402        }
403
404        if self.sst_write_buffer_size < MULTIPART_UPLOAD_MINIMUM_SIZE {
405            self.sst_write_buffer_size = MULTIPART_UPLOAD_MINIMUM_SIZE;
406            warn!(
407                "Sanitize sst write buffer size to {}",
408                self.sst_write_buffer_size
409            );
410        }
411
412        // Sets write cache path if it is empty.
413        if self.write_cache_path.trim().is_empty() {
414            self.write_cache_path = data_home.to_string();
415        }
416
417        // Validate index_cache_percent is within valid range (0, 100)
418        if self.index_cache_percent == 0 || self.index_cache_percent >= 100 {
419            warn!(
420                "Invalid index_cache_percent {}, resetting to default {}",
421                self.index_cache_percent, DEFAULT_INDEX_CACHE_PERCENT
422            );
423            self.index_cache_percent = DEFAULT_INDEX_CACHE_PERCENT;
424        }
425
426        self.index.sanitize(data_home, &self.inverted_index)?;
427
428        Ok(())
429    }
430
431    fn adjust_buffer_and_cache_size(&mut self, sys_memory: ReadableSize) {
432        // shouldn't be greater than 1G in default mode.
433        let global_write_buffer_size = cmp::min(
434            sys_memory / GLOBAL_WRITE_BUFFER_SIZE_FACTOR,
435            ReadableSize::gb(1),
436        );
437        // Use 2x of global write buffer size as global write buffer reject size.
438        let global_write_buffer_reject_size = global_write_buffer_size * 2;
439        // Page-index-bearing SST metadata can be much larger than footers alone.
440        // Keep the auto-sized default bounded, but allow a larger warm working set.
441        let sst_meta_cache_size = cmp::min(
442            sys_memory / SST_META_CACHE_SIZE_FACTOR,
443            ReadableSize::mb(512),
444        );
445        let prefilter_result_cache_size = cmp::min(
446            sys_memory / PREFILTER_RESULT_CACHE_SIZE_FACTOR,
447            ReadableSize::mb(128),
448        );
449        // shouldn't be greater than 512MB in default mode.
450        let mem_cache_size = cmp::min(sys_memory / MEM_CACHE_SIZE_FACTOR, ReadableSize::mb(512));
451        let page_cache_size = sys_memory / PAGE_CACHE_SIZE_FACTOR;
452
453        self.global_write_buffer_size = global_write_buffer_size;
454        self.global_write_buffer_reject_size = global_write_buffer_reject_size;
455        self.sst_meta_cache_size = sst_meta_cache_size;
456        self.vector_cache_size = mem_cache_size;
457        self.page_cache_size = page_cache_size;
458        self.selector_result_cache_size = mem_cache_size;
459        self.range_result_cache_size = mem_cache_size;
460        // Use a smaller cache size because prefilter result usually should be small.
461        self.prefilter_result_cache_size = prefilter_result_cache_size;
462
463        self.index.adjust_buffer_and_cache_size(sys_memory);
464    }
465
466    /// Enable write cache.
467    #[cfg(test)]
468    pub fn enable_write_cache(
469        mut self,
470        path: String,
471        size: ReadableSize,
472        ttl: Option<Duration>,
473    ) -> Self {
474        self.enable_write_cache = true;
475        self.write_cache_path = path;
476        self.write_cache_size = size;
477        self.write_cache_ttl = ttl;
478        self
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485
486    #[test]
487    fn test_scan_memory_policy_upgrade() {
488        for policy in [
489            None,
490            Some("fail"),
491            Some("skip"),
492            Some("wait"),
493            Some("wait(30s)"),
494        ] {
495            let input = policy
496                .map(|policy| format!("scan_memory_on_exhausted = {policy:?}"))
497                .unwrap_or_default();
498            let mut config: MitoConfig = toml::from_str(&input).unwrap();
499            let compaction_policy = config.experimental_compaction_on_exhausted;
500            config.sanitize("/data").unwrap();
501            assert_eq!(OnExhaustedPolicy::Fail, config.scan_memory_on_exhausted);
502            assert_eq!(
503                compaction_policy,
504                config.experimental_compaction_on_exhausted
505            );
506            let serialized = toml::to_string(&config).unwrap();
507            assert!(serialized.contains("scan_memory_on_exhausted = \"fail\""));
508            config.sanitize("/data").unwrap();
509            assert_eq!(serialized, toml::to_string(&config).unwrap());
510        }
511        for policy in ["unknown", "wait(invalid)", "wait()"] {
512            assert!(
513                toml::from_str::<MitoConfig>(&format!("scan_memory_on_exhausted = {policy:?}"))
514                    .is_err()
515            );
516        }
517    }
518
519    #[test]
520    fn test_default_auto_flush_interval() {
521        assert_eq!(
522            Duration::from_secs(10 * 60),
523            MitoConfig::default().auto_flush_interval
524        );
525    }
526
527    #[test]
528    fn test_adjust_sst_metadata_and_prefilter_cache_caps_independently() {
529        let mut config = MitoConfig::default();
530
531        config.adjust_buffer_and_cache_size(ReadableSize::gb(1));
532        assert_eq!(ReadableSize::mb(128), config.sst_meta_cache_size);
533        assert_eq!(ReadableSize::mb(32), config.prefilter_result_cache_size);
534
535        config.adjust_buffer_and_cache_size(ReadableSize::gb(64));
536        assert_eq!(ReadableSize::mb(512), config.sst_meta_cache_size);
537        assert_eq!(ReadableSize::mb(128), config.prefilter_result_cache_size);
538    }
539
540    #[test]
541    fn test_series_index_config() {
542        let defaults: MitoConfig = toml::from_str("").unwrap();
543        assert_eq!(4, defaults.experimental_series_index_min_files);
544        assert!(!MitoConfig::default().experimental_enable_series_index);
545        assert!(!MitoConfig::default().experimental_enable_range_index);
546        assert_eq!(
547            MitoConfig::default().experimental_series_index_bucket_width,
548            Duration::from_secs(5 * 24 * 60 * 60)
549        );
550        let mut config: MitoConfig = toml::from_str(
551            "experimental_enable_series_index = true
552             experimental_series_index_format = 'columnar'
553             experimental_enable_range_index = false
554             experimental_series_index_max_size = '64MiB'
555             experimental_series_index_maintenance_interval = '30s'
556             experimental_series_index_min_files = 2
557             experimental_series_index_bucket_width = '2days'",
558        )
559        .unwrap();
560        config.sanitize("/data").unwrap();
561        assert_eq!(2, config.experimental_series_index_min_files);
562        assert!(config.experimental_enable_series_index);
563        assert_eq!(
564            config.experimental_series_index_format,
565            SeriesIndexFormat::Columnar
566        );
567        assert_eq!(
568            ReadableSize::mb(64),
569            config.experimental_series_index_max_size
570        );
571        assert!(!config.experimental_enable_range_index);
572        assert_eq!(
573            config.experimental_series_index_maintenance_interval,
574            Duration::from_secs(30)
575        );
576        assert_eq!(
577            config.experimental_series_index_bucket_width,
578            Duration::from_secs(2 * 24 * 60 * 60)
579        );
580        let restored: MitoConfig = toml::from_str(&toml::to_string(&config).unwrap()).unwrap();
581        assert_eq!(config, restored);
582        config.experimental_series_index_min_files = 0;
583        config.sanitize("/data").unwrap();
584        assert_eq!(4, config.experimental_series_index_min_files);
585        config.experimental_series_index_max_size = ReadableSize(1023);
586        assert!(config.sanitize("/data").is_err());
587        config.experimental_series_index_max_size = ReadableSize(1024);
588        config.sanitize("/data").unwrap();
589
590        let mut config: MitoConfig =
591            toml::from_str("experimental_series_index_maintenance_interval = '0s'").unwrap();
592        config.sanitize("/data").unwrap();
593        assert_eq!(
594            config.experimental_series_index_maintenance_interval,
595            MitoConfig::default().experimental_series_index_maintenance_interval
596        );
597    }
598
599    #[test]
600    fn test_range_index_config() {
601        let config: MitoConfig = toml::from_str("experimental_enable_series_index = true").unwrap();
602        assert!(!config.experimental_enable_range_index);
603        for enabled in [false, true] {
604            let config: MitoConfig =
605                toml::from_str(&format!("experimental_enable_range_index = {enabled}")).unwrap();
606            assert_eq!(enabled, config.experimental_enable_range_index);
607            let restored: MitoConfig = toml::from_str(&toml::to_string(&config).unwrap()).unwrap();
608            assert_eq!(config, restored);
609        }
610    }
611}
612
613/// Index build mode.
614#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
615#[serde(rename_all = "snake_case")]
616pub enum IndexBuildMode {
617    /// Build index synchronously.
618    #[default]
619    Sync,
620    /// Build index asynchronously.
621    Async,
622}
623
624#[serde_as]
625#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
626#[serde(default)]
627pub struct IndexConfig {
628    /// Auxiliary directory path for the index in filesystem, used to
629    /// store intermediate files for creating the index and staging files
630    /// for searching the index, defaults to `{data_home}/index_intermediate`.
631    ///
632    /// This path contains two subdirectories:
633    /// - `__intm`: for storing intermediate files used during creating index.
634    /// - `staging`: for storing staging files used during searching index.
635    ///
636    /// The default name for this directory is `index_intermediate` for backward compatibility.
637    pub aux_path: String,
638
639    /// The max capacity of the staging directory.
640    pub staging_size: ReadableSize,
641    /// The TTL of the staging directory.
642    /// Defaults to 7 days.
643    /// Setting it to "0s" to disable TTL.
644    #[serde(with = "humantime_serde")]
645    pub staging_ttl: Option<Duration>,
646
647    /// Index Build Mode
648    pub build_mode: IndexBuildMode,
649
650    /// Write buffer size for creating the index.
651    pub write_buffer_size: ReadableSize,
652
653    /// Cache size for metadata of puffin files. Setting it to 0 to disable the cache.
654    pub metadata_cache_size: ReadableSize,
655    /// Cache size for inverted index content. Setting it to 0 to disable the cache.
656    pub content_cache_size: ReadableSize,
657    /// Page size for inverted index content.
658    pub content_cache_page_size: ReadableSize,
659    /// Cache size for index result. Setting it to 0 to disable the cache.
660    pub result_cache_size: ReadableSize,
661}
662
663impl Default for IndexConfig {
664    fn default() -> Self {
665        Self {
666            aux_path: String::new(),
667            staging_size: ReadableSize::gb(2),
668            staging_ttl: Some(Duration::from_secs(7 * 24 * 60 * 60)),
669            build_mode: IndexBuildMode::default(),
670            write_buffer_size: ReadableSize::mb(8),
671            metadata_cache_size: ReadableSize::mb(64),
672            content_cache_size: ReadableSize::mb(128),
673            content_cache_page_size: ReadableSize::kb(64),
674            result_cache_size: ReadableSize::mb(128),
675        }
676    }
677}
678
679impl IndexConfig {
680    pub fn sanitize(
681        &mut self,
682        data_home: &str,
683        inverted_index: &InvertedIndexConfig,
684    ) -> Result<()> {
685        #[allow(deprecated)]
686        if self.aux_path.is_empty() && !inverted_index.intermediate_path.is_empty() {
687            self.aux_path.clone_from(&inverted_index.intermediate_path);
688            warn!(
689                "`inverted_index.intermediate_path` is deprecated, use
690                 `index.aux_path` instead. Set `index.aux_path` to {}",
691                &inverted_index.intermediate_path
692            )
693        }
694        if self.aux_path.is_empty() {
695            let path = Path::new(data_home).join("index_intermediate");
696            self.aux_path = path.as_os_str().to_string_lossy().to_string();
697        }
698
699        if self.write_buffer_size < MULTIPART_UPLOAD_MINIMUM_SIZE {
700            self.write_buffer_size = MULTIPART_UPLOAD_MINIMUM_SIZE;
701            warn!(
702                "Sanitize index write buffer size to {}",
703                self.write_buffer_size
704            );
705        }
706
707        if self.staging_ttl.map(|ttl| ttl.is_zero()).unwrap_or(false) {
708            self.staging_ttl = None;
709        }
710
711        Ok(())
712    }
713
714    pub fn adjust_buffer_and_cache_size(&mut self, sys_memory: ReadableSize) {
715        let cache_size = cmp::min(sys_memory / MEM_CACHE_SIZE_FACTOR, ReadableSize::mb(128));
716        self.result_cache_size = cmp::min(self.result_cache_size, cache_size);
717        self.content_cache_size = cmp::min(self.content_cache_size, cache_size);
718
719        let metadata_cache_size = cmp::min(
720            sys_memory / INDEX_METADATA_CACHE_SIZE_FACTOR,
721            ReadableSize::mb(64),
722        );
723        self.metadata_cache_size = cmp::min(self.metadata_cache_size, metadata_cache_size);
724    }
725}
726
727/// Operational mode for certain actions.
728#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
729#[serde(rename_all = "snake_case")]
730pub enum Mode {
731    /// The action is performed automatically based on internal criteria.
732    #[default]
733    Auto,
734    /// The action is explicitly disabled.
735    Disable,
736}
737
738impl Mode {
739    /// Whether the action is disabled.
740    pub fn disabled(&self) -> bool {
741        matches!(self, Mode::Disable)
742    }
743
744    /// Whether the action is automatic.
745    pub fn auto(&self) -> bool {
746        matches!(self, Mode::Auto)
747    }
748}
749
750/// Memory threshold for performing certain actions.
751#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
752#[serde(rename_all = "snake_case")]
753pub enum MemoryThreshold {
754    /// Automatically determine the threshold based on internal criteria.
755    #[default]
756    Auto,
757    /// Unlimited memory.
758    Unlimited,
759    /// Fixed memory threshold.
760    #[serde(untagged)]
761    Size(ReadableSize),
762}
763
764/// Configuration options for the inverted index.
765#[serde_as]
766#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
767#[serde(default)]
768pub struct InvertedIndexConfig {
769    /// Whether to create the index on flush: automatically or never.
770    pub create_on_flush: Mode,
771    /// Whether to create the index on compaction: automatically or never.
772    pub create_on_compaction: Mode,
773    /// Whether to apply the index on query: automatically or never.
774    pub apply_on_query: Mode,
775
776    /// Memory threshold for performing an external sort during index creation.
777    pub mem_threshold_on_create: MemoryThreshold,
778
779    #[deprecated = "use [IndexConfig::aux_path] instead"]
780    #[serde(skip_serializing)]
781    pub intermediate_path: String,
782
783    #[deprecated = "use [IndexConfig::write_buffer_size] instead"]
784    #[serde(skip_serializing)]
785    pub write_buffer_size: ReadableSize,
786}
787
788impl Default for InvertedIndexConfig {
789    #[allow(deprecated)]
790    fn default() -> Self {
791        Self {
792            create_on_flush: Mode::Auto,
793            create_on_compaction: Mode::Auto,
794            apply_on_query: Mode::Auto,
795            mem_threshold_on_create: MemoryThreshold::Auto,
796            write_buffer_size: ReadableSize::mb(8),
797            intermediate_path: String::new(),
798        }
799    }
800}
801
802impl InvertedIndexConfig {
803    pub fn mem_threshold_on_create(&self) -> Option<usize> {
804        match self.mem_threshold_on_create {
805            MemoryThreshold::Auto => {
806                if let Some(sys_memory) = get_total_memory_readable() {
807                    Some((sys_memory / INDEX_CREATE_MEM_THRESHOLD_FACTOR).as_bytes() as usize)
808                } else {
809                    Some(ReadableSize::mb(64).as_bytes() as usize)
810                }
811            }
812            MemoryThreshold::Unlimited => None,
813            MemoryThreshold::Size(size) => Some(size.as_bytes() as usize),
814        }
815    }
816}
817
818/// Configuration options for the full-text index.
819#[serde_as]
820#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
821#[serde(default)]
822pub struct FulltextIndexConfig {
823    /// Whether to create the index on flush: automatically or never.
824    pub create_on_flush: Mode,
825    /// Whether to create the index on compaction: automatically or never.
826    pub create_on_compaction: Mode,
827    /// Whether to apply the index on query: automatically or never.
828    pub apply_on_query: Mode,
829    /// Memory threshold for creating the index.
830    pub mem_threshold_on_create: MemoryThreshold,
831    /// Whether to compress the index data.
832    pub compress: bool,
833}
834
835impl Default for FulltextIndexConfig {
836    fn default() -> Self {
837        Self {
838            create_on_flush: Mode::Auto,
839            create_on_compaction: Mode::Auto,
840            apply_on_query: Mode::Auto,
841            mem_threshold_on_create: MemoryThreshold::Auto,
842            compress: true,
843        }
844    }
845}
846
847impl FulltextIndexConfig {
848    pub fn mem_threshold_on_create(&self) -> usize {
849        match self.mem_threshold_on_create {
850            MemoryThreshold::Auto => {
851                if let Some(sys_memory) = get_total_memory_readable() {
852                    (sys_memory / INDEX_CREATE_MEM_THRESHOLD_FACTOR).as_bytes() as _
853                } else {
854                    ReadableSize::mb(64).as_bytes() as _
855                }
856            }
857            MemoryThreshold::Unlimited => usize::MAX,
858            MemoryThreshold::Size(size) => size.as_bytes() as _,
859        }
860    }
861}
862
863/// Configuration options for the bloom filter.
864#[serde_as]
865#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
866#[serde(default)]
867pub struct BloomFilterConfig {
868    /// Whether to create the index on flush: automatically or never.
869    pub create_on_flush: Mode,
870    /// Whether to create the index on compaction: automatically or never.
871    pub create_on_compaction: Mode,
872    /// Whether to apply the index on query: automatically or never.
873    pub apply_on_query: Mode,
874    /// Memory threshold for creating the index.
875    pub mem_threshold_on_create: MemoryThreshold,
876}
877
878impl Default for BloomFilterConfig {
879    fn default() -> Self {
880        Self {
881            create_on_flush: Mode::Auto,
882            create_on_compaction: Mode::Auto,
883            apply_on_query: Mode::Auto,
884            mem_threshold_on_create: MemoryThreshold::Auto,
885        }
886    }
887}
888
889impl BloomFilterConfig {
890    pub fn mem_threshold_on_create(&self) -> Option<usize> {
891        match self.mem_threshold_on_create {
892            MemoryThreshold::Auto => {
893                if let Some(sys_memory) = get_total_memory_readable() {
894                    Some((sys_memory / INDEX_CREATE_MEM_THRESHOLD_FACTOR).as_bytes() as usize)
895                } else {
896                    Some(ReadableSize::mb(64).as_bytes() as usize)
897                }
898            }
899            MemoryThreshold::Unlimited => None,
900            MemoryThreshold::Size(size) => Some(size.as_bytes() as usize),
901        }
902    }
903}
904
905/// Divide cpu num by a non-zero `divisor` and returns at least 1.
906fn divide_num_cpus(divisor: usize) -> usize {
907    debug_assert!(divisor > 0);
908    let cores = get_total_cpu_cores();
909    debug_assert!(cores > 0);
910
911    cores.div_ceil(divisor)
912}