Skip to main content

metric_engine/
utils.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
15use std::collections::HashMap;
16
17use common_telemetry::{info, warn};
18use mito2::engine::MitoEngine;
19use snafu::ResultExt;
20use store_api::metric_engine_consts::{
21    MANIFEST_INFO_EXTENSION_KEY, METRIC_DATA_REGION_GROUP, METRIC_METADATA_REGION_GROUP,
22};
23use store_api::region_engine::{RegionEngine, RegionManifestInfo, RegionStatistic};
24use store_api::storage::RegionId;
25
26use crate::error::{Result, SerializeRegionManifestInfoSnafu};
27
28/// Change the given [RegionId]'s region group to [METRIC_METADATA_REGION_GROUP].
29pub fn to_metadata_region_id(region_id: RegionId) -> RegionId {
30    let table_id = region_id.table_id();
31    let region_sequence = region_id.region_sequence();
32    RegionId::with_group_and_seq(table_id, METRIC_METADATA_REGION_GROUP, region_sequence)
33}
34
35/// Change the given [RegionId]'s region group to [METRIC_DATA_REGION_GROUP].
36pub fn to_data_region_id(region_id: RegionId) -> RegionId {
37    let table_id = region_id.table_id();
38    let region_sequence = region_id.region_sequence();
39    RegionId::with_group_and_seq(table_id, METRIC_DATA_REGION_GROUP, region_sequence)
40}
41
42/// Get the region statistic of the given [RegionId].
43pub fn get_region_statistic(mito: &MitoEngine, region_id: RegionId) -> Option<RegionStatistic> {
44    let metadata_region_id = to_metadata_region_id(region_id);
45    let data_region_id = to_data_region_id(region_id);
46
47    let metadata_stat = mito.region_statistic(metadata_region_id);
48    let data_stat = mito.region_statistic(data_region_id);
49
50    match (&metadata_stat, &data_stat) {
51        (Some(metadata_stat), Some(data_stat)) => {
52            Some(merge_region_statistic(metadata_stat, data_stat))
53        }
54        _ => {
55            warn!(
56                "Failed to get region statistic for region {}, metadata_stat: {:?}, data_stat: {:?}",
57                region_id, metadata_stat, data_stat
58            );
59            None
60        }
61    }
62}
63
64fn merge_region_statistic(
65    metadata_stat: &RegionStatistic,
66    data_stat: &RegionStatistic,
67) -> RegionStatistic {
68    RegionStatistic {
69        num_rows: metadata_stat.num_rows + data_stat.num_rows,
70        memtable_size: metadata_stat.memtable_size + data_stat.memtable_size,
71        wal_size: metadata_stat.wal_size + data_stat.wal_size,
72        manifest_size: metadata_stat.manifest_size + data_stat.manifest_size,
73        sst_size: metadata_stat.sst_size + data_stat.sst_size,
74        sst_num: metadata_stat.sst_num + data_stat.sst_num,
75        index_size: metadata_stat.index_size + data_stat.index_size,
76        manifest: RegionManifestInfo::Metric {
77            data_flushed_entry_id: data_stat.manifest.data_flushed_entry_id(),
78            data_manifest_version: data_stat.manifest.data_manifest_version(),
79            metadata_flushed_entry_id: metadata_stat.manifest.data_flushed_entry_id(),
80            metadata_manifest_version: metadata_stat.manifest.data_manifest_version(),
81        },
82        written_bytes: metadata_stat.written_bytes + data_stat.written_bytes,
83        ingested_parquet_bytes: metadata_stat.ingested_parquet_bytes
84            + data_stat.ingested_parquet_bytes,
85        query_cpu_time: data_stat.query_cpu_time,
86        query_scanned_bytes: data_stat.query_scanned_bytes,
87        data_topic_latest_entry_id: data_stat.data_topic_latest_entry_id,
88        metadata_topic_latest_entry_id: metadata_stat.metadata_topic_latest_entry_id,
89        // Metadata rows are written at timestamp 0, so merging their bounds would
90        // pin every metric region's minimum to the epoch.
91        min_timestamp: data_stat.min_timestamp,
92        max_timestamp: data_stat.max_timestamp,
93        // A repartition flushes the metadata region too, and that flush refuses pending
94        // tails, so the metadata region's tails count as well.
95        has_pending_tails: metadata_stat.has_pending_tails || data_stat.has_pending_tails,
96    }
97}
98
99/// Appends the given [RegionId]'s manifest info to the given list.
100pub(crate) fn append_manifest_info(
101    mito: &MitoEngine,
102    region_id: RegionId,
103    manifest_infos: &mut Vec<(RegionId, RegionManifestInfo)>,
104) {
105    if let Some(statistic) = get_region_statistic(mito, region_id) {
106        manifest_infos.push((region_id, statistic.manifest));
107    }
108}
109
110/// Encodes the given list of ([RegionId], [RegionManifestInfo]) to extensions(key: MANIFEST_INFO_EXTENSION_KEY).
111pub(crate) fn encode_manifest_info_to_extensions(
112    manifest_infos: &[(RegionId, RegionManifestInfo)],
113    extensions: &mut HashMap<String, Vec<u8>>,
114) -> Result<()> {
115    extensions.insert(
116        MANIFEST_INFO_EXTENSION_KEY.to_string(),
117        RegionManifestInfo::encode_list(manifest_infos)
118            .context(SerializeRegionManifestInfoSnafu)?,
119    );
120    for (region_id, manifest_info) in manifest_infos {
121        info!(
122            "Added manifest info: {:?} to extensions, region_id: {:?}",
123            manifest_info, region_id
124        );
125    }
126    Ok(())
127}
128
129#[cfg(test)]
130mod tests {
131
132    use common_time::Timestamp;
133
134    use super::*;
135
136    #[test]
137    fn test_to_metadata_region_id() {
138        let region_id = RegionId::new(1, 2);
139        let expected_region_id = RegionId::with_group_and_seq(1, METRIC_METADATA_REGION_GROUP, 2);
140        assert_eq!(to_metadata_region_id(region_id), expected_region_id);
141
142        let region_id = RegionId::with_group_and_seq(1, 243, 2);
143        let expected_region_id = RegionId::with_group_and_seq(1, METRIC_METADATA_REGION_GROUP, 2);
144        assert_eq!(to_metadata_region_id(region_id), expected_region_id);
145    }
146
147    #[test]
148    fn test_to_data_region_id() {
149        let region_id = RegionId::new(1, 2);
150        let expected_region_id = RegionId::with_group_and_seq(1, METRIC_DATA_REGION_GROUP, 2);
151        assert_eq!(to_data_region_id(region_id), expected_region_id);
152
153        let region_id = RegionId::with_group_and_seq(1, 243, 2);
154        let expected_region_id = RegionId::with_group_and_seq(1, METRIC_DATA_REGION_GROUP, 2);
155        assert_eq!(to_data_region_id(region_id), expected_region_id);
156    }
157
158    #[test]
159    fn merge_region_statistic_sums_ingested_parquet_bytes() {
160        let metadata_stat = RegionStatistic {
161            ingested_parquet_bytes: 123,
162            ..Default::default()
163        };
164        let data_stat = RegionStatistic {
165            ingested_parquet_bytes: 456,
166            ..Default::default()
167        };
168        assert_eq!(
169            merge_region_statistic(&metadata_stat, &data_stat).ingested_parquet_bytes,
170            579
171        );
172    }
173
174    #[test]
175    fn merge_region_statistic_has_pending_tails_of_either_region() {
176        for (metadata, data) in [(false, false), (true, false), (false, true), (true, true)] {
177            let metadata_stat = RegionStatistic {
178                has_pending_tails: metadata,
179                ..Default::default()
180            };
181            let data_stat = RegionStatistic {
182                has_pending_tails: data,
183                ..Default::default()
184            };
185            assert_eq!(
186                merge_region_statistic(&metadata_stat, &data_stat).has_pending_tails,
187                metadata || data
188            );
189        }
190    }
191
192    #[test]
193    fn merge_region_statistic_ignores_metadata_timestamps() {
194        // Metadata rows are written at timestamp 0; folding them in would report
195        // 1970 as the minimum for a region holding only modern samples.
196        let metadata_stat = RegionStatistic {
197            min_timestamp: Some(Timestamp::new_millisecond(0)),
198            max_timestamp: Some(Timestamp::new_millisecond(0)),
199            ..Default::default()
200        };
201        let data_stat = RegionStatistic {
202            min_timestamp: Some(Timestamp::new_millisecond(1_700_000_000_000)),
203            max_timestamp: Some(Timestamp::new_millisecond(1_700_000_001_000)),
204            ..Default::default()
205        };
206
207        let statistic = merge_region_statistic(&metadata_stat, &data_stat);
208
209        assert_eq!(
210            statistic.min_timestamp,
211            Some(Timestamp::new_millisecond(1_700_000_000_000))
212        );
213        assert_eq!(
214            statistic.max_timestamp,
215            Some(Timestamp::new_millisecond(1_700_000_001_000))
216        );
217    }
218
219    #[test]
220    fn merge_region_statistic_reports_no_range_for_an_empty_data_region() {
221        // Metadata present but no samples: the region has no data to bound, so
222        // both ends must stay NULL rather than collapsing onto the epoch.
223        let metadata_stat = RegionStatistic {
224            min_timestamp: Some(Timestamp::new_millisecond(0)),
225            max_timestamp: Some(Timestamp::new_millisecond(0)),
226            ..Default::default()
227        };
228
229        let statistic = merge_region_statistic(&metadata_stat, &RegionStatistic::default());
230
231        assert_eq!(statistic.min_timestamp, None);
232        assert_eq!(statistic.max_timestamp, None);
233    }
234
235    #[test]
236    fn merge_region_statistic_keeps_pre_epoch_samples() {
237        // Samples entirely before 1970 must not have their maximum pulled up to
238        // the metadata timestamp.
239        let metadata_stat = RegionStatistic {
240            min_timestamp: Some(Timestamp::new_millisecond(0)),
241            max_timestamp: Some(Timestamp::new_millisecond(0)),
242            ..Default::default()
243        };
244        let data_stat = RegionStatistic {
245            min_timestamp: Some(Timestamp::new_millisecond(-2_000)),
246            max_timestamp: Some(Timestamp::new_millisecond(-1_000)),
247            ..Default::default()
248        };
249
250        let statistic = merge_region_statistic(&metadata_stat, &data_stat);
251
252        assert_eq!(
253            statistic.min_timestamp,
254            Some(Timestamp::new_millisecond(-2_000))
255        );
256        assert_eq!(
257            statistic.max_timestamp,
258            Some(Timestamp::new_millisecond(-1_000))
259        );
260    }
261
262    #[test]
263    fn merge_region_statistic_uses_data_region_query_stats() {
264        let metadata_stat = RegionStatistic {
265            query_cpu_time: 100,
266            query_scanned_bytes: 200,
267            manifest: RegionManifestInfo::mito(1, 2, 0),
268            ..Default::default()
269        };
270        let data_stat = RegionStatistic {
271            query_cpu_time: 10,
272            query_scanned_bytes: 20,
273            manifest: RegionManifestInfo::mito(3, 4, 0),
274            ..Default::default()
275        };
276
277        let statistic = merge_region_statistic(&metadata_stat, &data_stat);
278
279        assert_eq!(statistic.query_cpu_time, 10);
280        assert_eq!(statistic.query_scanned_bytes, 20);
281    }
282}