Skip to main content

metric_engine/engine/
options.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//! Specific options for the metric engine to create or open a region.
16
17use std::collections::HashMap;
18
19use store_api::metric_engine_consts::{
20    MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING,
21    METRIC_ENGINE_INDEX_SKIPPING_INDEX_FALSE_POSITIVE_RATE_OPTION,
22    METRIC_ENGINE_INDEX_SKIPPING_INDEX_FALSE_POSITIVE_RATE_OPTION_DEFAULT,
23    METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION,
24    METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION_DEFAULT, METRIC_ENGINE_INDEX_TYPE_OPTION,
25    PRIMARY_KEY_ENCODING,
26};
27use store_api::mito_engine_options::{COMPACTION_TYPE, COMPACTION_TYPE_TWCS, TWCS_TIME_WINDOW};
28
29/// Prefix for legacy `memtable.partition_tree.*` option keys. These keys are
30/// silently dropped by the metric engine; the partition tree memtable is gone.
31const LEGACY_PARTITION_TREE_OPTION_PREFIX: &str = "memtable.partition_tree.";
32
33use crate::error::{Error, ParseRegionOptionsSnafu, Result};
34
35/// The empirical value for the seg row count of the metric data region.
36/// Compared to the mito engine, the pattern of the metric engine constructs smaller indices.
37/// Therefore, compared to the default seg row count of 1024, by adjusting it to a smaller
38/// value and appropriately increasing the size of the index, it results in an improved indexing effect.
39const SEG_ROW_COUNT_FOR_DATA_REGION: u32 = 256;
40
41/// The default compaction time window for metric engine data regions.
42const DEFAULT_DATA_REGION_COMPACTION_TIME_WINDOW: &str = "1d";
43
44/// Physical region options.
45#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct PhysicalRegionOptions {
47    pub index: IndexOptions,
48}
49
50/// Index options for auto created columns
51#[derive(Debug, Clone, Copy, Default, PartialEq)]
52pub enum IndexOptions {
53    #[default]
54    None,
55    Inverted,
56    Skipping {
57        granularity: u32,
58        false_positive_rate: f64,
59    },
60}
61
62/// Sets data region specific options.
63pub fn set_data_region_options(options: &mut HashMap<String, String>) {
64    options.remove(METRIC_ENGINE_INDEX_TYPE_OPTION);
65    options.remove(METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION);
66    options.remove(METRIC_ENGINE_INDEX_SKIPPING_INDEX_FALSE_POSITIVE_RATE_OPTION);
67    options.insert(
68        "index.inverted_index.segment_row_count".to_string(),
69        SEG_ROW_COUNT_FOR_DATA_REGION.to_string(),
70    );
71
72    // Extract primary key encoding from the legacy nested key before dropping
73    // all `memtable.partition_tree.*` keys.
74    let legacy_encoding = options.remove(MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING);
75    options.retain(|k, _| !k.starts_with(LEGACY_PARTITION_TREE_OPTION_PREFIX));
76
77    // Bulk memtables support both flat Parquet and Narthex samples. Preserve
78    // explicit Narthex storage while keeping the existing Parquet default.
79    options.insert("memtable.type".to_string(), "bulk".to_string());
80    let sst_format = match options.get("sst_format").map(String::as_str) {
81        Some("narthex") => "narthex",
82        _ => "flat",
83    };
84    options.insert("sst_format".to_string(), sst_format.to_string());
85
86    // Decide the top-level primary key encoding: caller-supplied top-level key wins,
87    // then extracted legacy value, then the `sparse` default.
88    if !options.contains_key(PRIMARY_KEY_ENCODING) {
89        if let Some(encoding) = legacy_encoding {
90            options.insert(PRIMARY_KEY_ENCODING.to_string(), encoding);
91        } else {
92            options.insert(PRIMARY_KEY_ENCODING.to_string(), "sparse".to_string());
93        }
94    }
95
96    if !options.contains_key(TWCS_TIME_WINDOW) {
97        options.insert(
98            COMPACTION_TYPE.to_string(),
99            COMPACTION_TYPE_TWCS.to_string(),
100        );
101        options.insert(
102            TWCS_TIME_WINDOW.to_string(),
103            DEFAULT_DATA_REGION_COMPACTION_TIME_WINDOW.to_string(),
104        );
105    }
106}
107
108impl TryFrom<&HashMap<String, String>> for PhysicalRegionOptions {
109    type Error = Error;
110
111    fn try_from(value: &HashMap<String, String>) -> Result<Self> {
112        let index = match value
113            .get(METRIC_ENGINE_INDEX_TYPE_OPTION)
114            .map(|s| s.to_lowercase())
115        {
116            Some(ref index_type) if index_type == "inverted" => Ok(IndexOptions::Inverted),
117            Some(ref index_type) if index_type == "skipping" => {
118                let granularity = value
119                    .get(METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION)
120                    .map_or(
121                        Ok(METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION_DEFAULT),
122                        |g| {
123                            g.parse().map_err(|_| {
124                                ParseRegionOptionsSnafu {
125                                    reason: format!("Invalid granularity: {}", g),
126                                }
127                                .build()
128                            })
129                        },
130                    )?;
131                let false_positive_rate = value
132                    .get(METRIC_ENGINE_INDEX_SKIPPING_INDEX_FALSE_POSITIVE_RATE_OPTION)
133                    .map_or(
134                        Ok(METRIC_ENGINE_INDEX_SKIPPING_INDEX_FALSE_POSITIVE_RATE_OPTION_DEFAULT),
135                        |f| {
136                            f.parse().ok().filter(|f| *f > 0.0 && *f <= 1.0).ok_or(
137                                ParseRegionOptionsSnafu {
138                                    reason: format!("Invalid false positive rate: {}", f),
139                                }
140                                .build(),
141                            )
142                        },
143                    )?;
144                Ok(IndexOptions::Skipping {
145                    granularity,
146                    false_positive_rate,
147                })
148            }
149            Some(index_type) => ParseRegionOptionsSnafu {
150                reason: format!("Invalid index type: {}", index_type),
151            }
152            .fail(),
153            None => Ok(IndexOptions::default()),
154        }?;
155
156        Ok(PhysicalRegionOptions { index })
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn test_set_data_region_options_preserves_narthex_storage() {
166        let format = "narthex";
167        let mut options = HashMap::from([("sst_format".to_string(), format.to_string())]);
168        set_data_region_options(&mut options);
169        assert_eq!(options.get("sst_format").unwrap(), "narthex");
170        assert_eq!(options.get("memtable.type").unwrap(), "bulk");
171        assert_eq!(options.get(PRIMARY_KEY_ENCODING).unwrap(), "sparse");
172    }
173
174    #[test]
175    fn test_set_data_region_options_should_remove_metric_engine_options() {
176        let mut options = HashMap::new();
177        options.insert(
178            METRIC_ENGINE_INDEX_TYPE_OPTION.to_string(),
179            "inverted".to_string(),
180        );
181        options.insert(
182            METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION.to_string(),
183            "102400".to_string(),
184        );
185        options.insert(
186            METRIC_ENGINE_INDEX_SKIPPING_INDEX_FALSE_POSITIVE_RATE_OPTION.to_string(),
187            "0.01".to_string(),
188        );
189        set_data_region_options(&mut options);
190
191        for key in [
192            METRIC_ENGINE_INDEX_TYPE_OPTION,
193            METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION,
194            METRIC_ENGINE_INDEX_SKIPPING_INDEX_FALSE_POSITIVE_RATE_OPTION,
195        ] {
196            assert_eq!(options.get(key), None);
197        }
198    }
199
200    #[test]
201    fn test_deserialize_physical_region_options_from_hashmap() {
202        let mut options = HashMap::new();
203        options.insert(
204            METRIC_ENGINE_INDEX_TYPE_OPTION.to_string(),
205            "inverted".to_string(),
206        );
207        options.insert(
208            METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION.to_string(),
209            "102400".to_string(),
210        );
211        let physical_region_options = PhysicalRegionOptions::try_from(&options).unwrap();
212        assert_eq!(physical_region_options.index, IndexOptions::Inverted);
213
214        let mut options = HashMap::new();
215        options.insert(
216            METRIC_ENGINE_INDEX_TYPE_OPTION.to_string(),
217            "skipping".to_string(),
218        );
219        options.insert(
220            METRIC_ENGINE_INDEX_SKIPPING_INDEX_GRANULARITY_OPTION.to_string(),
221            "102400".to_string(),
222        );
223        options.insert(
224            METRIC_ENGINE_INDEX_SKIPPING_INDEX_FALSE_POSITIVE_RATE_OPTION.to_string(),
225            "0.01".to_string(),
226        );
227        let physical_region_options = PhysicalRegionOptions::try_from(&options).unwrap();
228        assert_eq!(
229            physical_region_options.index,
230            IndexOptions::Skipping {
231                granularity: 102400,
232                false_positive_rate: 0.01,
233            }
234        );
235    }
236
237    #[test]
238    fn test_set_data_region_options_default_compaction_time_window() {
239        // Test that default time window is set when not specified
240        let mut options = HashMap::new();
241        set_data_region_options(&mut options);
242
243        assert_eq!(options.get("memtable.type"), Some(&"bulk".to_string()));
244        assert_eq!(options.get("sst_format"), Some(&"flat".to_string()));
245        assert_eq!(
246            options.get(COMPACTION_TYPE),
247            Some(&COMPACTION_TYPE_TWCS.to_string())
248        );
249        assert_eq!(options.get(TWCS_TIME_WINDOW), Some(&"1d".to_string()));
250    }
251
252    #[test]
253    fn test_set_data_region_options_sparse_primary_key_encoding() {
254        let mut options = HashMap::new();
255        set_data_region_options(&mut options);
256
257        assert_eq!(options.get("memtable.type"), Some(&"bulk".to_string()));
258        assert_eq!(options.get("sst_format"), Some(&"flat".to_string()));
259        assert_eq!(
260            options.get(PRIMARY_KEY_ENCODING),
261            Some(&"sparse".to_string())
262        );
263        assert!(!options.contains_key(MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING));
264    }
265
266    #[test]
267    fn test_set_data_region_options_migrates_legacy_partition_tree_options() {
268        let mut options = HashMap::new();
269        options.insert("memtable.type".to_string(), "partition_tree".to_string());
270        options.insert(
271            MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING.to_string(),
272            "sparse".to_string(),
273        );
274        options.insert(
275            "memtable.partition_tree.index_max_keys_per_shard".to_string(),
276            "2048".to_string(),
277        );
278        set_data_region_options(&mut options);
279
280        assert_eq!(options.get("memtable.type"), Some(&"bulk".to_string()));
281        assert_eq!(options.get("sst_format"), Some(&"flat".to_string()));
282        assert_eq!(
283            options.get(PRIMARY_KEY_ENCODING),
284            Some(&"sparse".to_string())
285        );
286        // All legacy partition-tree-specific keys should be stripped.
287        assert!(!options.contains_key(MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING));
288        assert!(!options.contains_key("memtable.partition_tree.index_max_keys_per_shard"));
289    }
290
291    #[test]
292    fn test_set_data_region_options_preserves_existing_top_level_encoding() {
293        let mut options = HashMap::new();
294        options.insert(PRIMARY_KEY_ENCODING.to_string(), "dense".to_string());
295        // Sparse flag is on but caller already specified dense.
296        set_data_region_options(&mut options);
297
298        assert_eq!(
299            options.get(PRIMARY_KEY_ENCODING),
300            Some(&"dense".to_string())
301        );
302    }
303
304    #[test]
305    fn test_set_data_region_options_respects_user_compaction_time_window() {
306        // Test that user-specified time window is preserved
307        let mut options = HashMap::new();
308        options.insert(TWCS_TIME_WINDOW.to_string(), "2h".to_string());
309        options.insert(COMPACTION_TYPE.to_string(), "twcs".to_string());
310        set_data_region_options(&mut options);
311
312        // User's time window should be preserved
313        assert_eq!(options.get(TWCS_TIME_WINDOW), Some(&"2h".to_string()));
314    }
315}