Skip to main content

risingwave_meta/hummock/manager/
versioning.rs

1// Copyright 2022 RisingWave Labs
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::cmp;
16use std::collections::Bound::{Excluded, Included};
17use std::collections::{BTreeMap, HashMap, HashSet};
18use std::sync::Arc;
19
20use itertools::Itertools;
21use risingwave_common::monitor::MonitoredRwLockGuard;
22use risingwave_hummock_sdk::change_log::{EpochNewChangeLog, TableChangeLog, TableChangeLogs};
23use risingwave_hummock_sdk::compaction_group::StateTableId;
24use risingwave_hummock_sdk::compaction_group::hummock_version_ext::{
25    BranchedSstInfo, get_compaction_group_ids, get_table_compaction_group_id_mapping,
26};
27use risingwave_hummock_sdk::sstable_info::SstableInfo;
28use risingwave_hummock_sdk::table_stats::{PbTableStatsMap, add_prost_table_stats_map};
29use risingwave_hummock_sdk::version::{
30    HummockVersion, HummockVersionDelta, MAX_HUMMOCK_VERSION_ID,
31};
32use risingwave_hummock_sdk::{
33    CompactionGroupId, HummockContextId, HummockObjectId, HummockSstableId, HummockSstableObjectId,
34    HummockVersionId, get_stale_object_ids,
35};
36use risingwave_pb::common::WorkerNode;
37use risingwave_pb::hummock::write_limits::WriteLimit;
38use risingwave_pb::hummock::{HummockPinnedVersion, HummockVersionStats};
39use risingwave_pb::id::TableId;
40use risingwave_pb::meta::subscribe_response::{Info, Operation};
41use tokio::sync::RwLockReadGuard;
42
43use super::{CompactionGroupManager, GroupStateValidator};
44use crate::MetaResult;
45use crate::hummock::HummockManager;
46use crate::hummock::error::{Error, Result};
47use crate::hummock::manager::checkpoint::HummockVersionCheckpoint;
48use crate::hummock::manager::commit_multi_var;
49use crate::hummock::manager::context::ContextInfo;
50use crate::hummock::manager::transaction::HummockVersionTransaction;
51use crate::hummock::metrics_utils::{LocalTableMetrics, trigger_write_stop_stats};
52use crate::hummock::model::CompactionGroup;
53use crate::model::VarTransaction;
54
55/// Holds the compaction group manager read lock, protecting write limits until dropped.
56pub struct HummockWriteLimitsReadGuard<'a> {
57    guard: MonitoredRwLockGuard<RwLockReadGuard<'a, CompactionGroupManager>>,
58}
59
60impl HummockWriteLimitsReadGuard<'_> {
61    pub fn write_limits(&self) -> &HashMap<CompactionGroupId, WriteLimit> {
62        &self.guard.write_limit
63    }
64}
65
66#[derive(Default)]
67pub struct Versioning {
68    // Volatile states below
69    /// Avoid commit epoch epochs
70    /// Don't persist compaction version delta to meta store
71    pub disable_commit_epochs: bool,
72    /// Latest hummock version
73    pub current_version: Arc<HummockVersion>,
74    pub local_metrics: HashMap<TableId, LocalTableMetrics>,
75    pub time_travel_snapshot_interval_counter: u64,
76    /// Used to avoid the attempts to rewrite the same SST to meta store
77    pub last_time_travel_snapshot_sst_ids: HashSet<HummockSstableId>,
78
79    // Persistent states below
80    pub hummock_version_deltas: BTreeMap<HummockVersionId, HummockVersionDelta>,
81    /// Stats for latest hummock version.
82    pub version_stats: HummockVersionStats,
83    pub checkpoint: HummockVersionCheckpoint,
84    pub table_change_log: HashMap<TableId, TableChangeLog>,
85}
86
87impl ContextInfo {
88    pub fn min_pinned_version_id(&self) -> HummockVersionId {
89        let mut min_pinned_version_id = MAX_HUMMOCK_VERSION_ID;
90        for id in self
91            .pinned_versions
92            .values()
93            .map(|v| v.min_pinned_id)
94            .chain(self.version_safe_points.iter().cloned())
95        {
96            min_pinned_version_id = cmp::min(id, min_pinned_version_id);
97        }
98        min_pinned_version_id
99    }
100}
101
102impl Versioning {
103    pub(super) fn mark_next_time_travel_version_snapshot(&mut self) {
104        self.time_travel_snapshot_interval_counter = u64::MAX;
105    }
106
107    pub fn get_tracked_object_ids(
108        &self,
109        min_pinned_version_id: HummockVersionId,
110    ) -> HashSet<HummockObjectId> {
111        // object ids in checkpoint version
112        let mut tracked_object_ids = self
113            .checkpoint
114            .version
115            .get_object_ids()
116            .chain(
117                self.table_change_log
118                    .values()
119                    .flat_map(|c| c.get_object_ids()),
120            )
121            .collect::<HashSet<_>>();
122        // add object ids added between checkpoint version and current version
123        for (_, delta) in self.hummock_version_deltas.range((
124            Excluded(self.checkpoint.version.id),
125            Included(self.current_version.id),
126        )) {
127            tracked_object_ids.extend(delta.newly_added_object_ids());
128        }
129        // add stale object ids before the checkpoint version
130        tracked_object_ids.extend(
131            self.checkpoint
132                .stale_objects
133                .iter()
134                .filter(|(version_id, _)| **version_id >= min_pinned_version_id)
135                .flat_map(|(_, objects)| get_stale_object_ids(objects)),
136        );
137        tracked_object_ids
138    }
139}
140
141impl HummockManager {
142    pub async fn list_pinned_version(&self) -> Vec<HummockPinnedVersion> {
143        self.context_info
144            .read_with_process_name("list_pinned_version")
145            .await
146            .pinned_versions
147            .values()
148            .cloned()
149            .collect_vec()
150    }
151
152    pub async fn list_workers(
153        &self,
154        context_ids: &[HummockContextId],
155    ) -> MetaResult<HashMap<HummockContextId, WorkerNode>> {
156        let mut workers = HashMap::new();
157        for context_id in context_ids {
158            if let Some(worker_node) = self
159                .metadata_manager()
160                .get_worker_by_id(*context_id as _)
161                .await?
162            {
163                workers.insert(*context_id, worker_node);
164            }
165        }
166        Ok(workers)
167    }
168
169    /// Gets current version without pinning it.
170    /// Should not be called inside [`HummockManager`], because it requests locks internally.
171    ///
172    /// Note: this method can hurt performance because it will clone a large object.
173    #[cfg(any(test, feature = "test"))]
174    pub async fn get_current_version(&self) -> HummockVersion {
175        self.on_current_version(|version| version.clone()).await
176    }
177
178    pub async fn on_current_version<T>(&self, mut f: impl FnMut(&HummockVersion) -> T) -> T {
179        self.on_current_version_arc(|version| f(version)).await
180    }
181
182    /// Access the shared version under its read lock, allowing a cheap clone before conversion.
183    pub async fn on_current_version_arc<T>(
184        &self,
185        mut f: impl FnMut(&Arc<HummockVersion>) -> T,
186    ) -> T {
187        let guard = self
188            .versioning
189            .read_with_process_name("on_current_version")
190            .await;
191        f(&guard.current_version)
192    }
193
194    pub async fn on_current_version_and_table_change_log<T>(
195        &self,
196        mut f: impl FnMut(&HummockVersion, &TableChangeLogs) -> T,
197    ) -> T {
198        let guard = self
199            .versioning
200            .read_with_process_name("on_current_version_and_table_change_log")
201            .await;
202        f(&guard.current_version, &guard.table_change_log)
203    }
204
205    pub async fn get_version_id(&self) -> HummockVersionId {
206        self.on_current_version(|version| version.id).await
207    }
208
209    /// Gets the mapping from table id to compaction group id
210    pub async fn get_table_compaction_group_id_mapping(
211        &self,
212    ) -> HashMap<StateTableId, CompactionGroupId> {
213        get_table_compaction_group_id_mapping(
214            &self
215                .versioning
216                .read_with_process_name("get_table_compaction_group_id_mapping")
217                .await
218                .current_version,
219        )
220    }
221
222    /// Get version deltas from meta store
223    pub async fn list_version_deltas(
224        &self,
225        start_id: HummockVersionId,
226        num_limit: u32,
227    ) -> Result<Vec<HummockVersionDelta>> {
228        let versioning = self
229            .versioning
230            .read_with_process_name("list_version_deltas")
231            .await;
232        let version_deltas = versioning
233            .hummock_version_deltas
234            .range(start_id..)
235            .map(|(_id, delta)| delta)
236            .take(num_limit as _)
237            .cloned()
238            .collect();
239        Ok(version_deltas)
240    }
241
242    pub async fn get_version_stats(&self) -> HummockVersionStats {
243        self.versioning
244            .read_with_process_name("get_version_stats")
245            .await
246            .version_stats
247            .clone()
248    }
249
250    /// Updates write limits for `target_groups` and sends notification.
251    /// Returns true if `write_limit` has been modified.
252    /// The implementation acquires `versioning` lock and `compaction_group_manager` lock.
253    pub(super) async fn try_update_write_limits(
254        &self,
255        target_group_ids: &[CompactionGroupId],
256    ) -> bool {
257        let versioning = self
258            .versioning
259            .read_with_process_name("try_update_write_limits")
260            .await;
261        let mut cg_manager = self
262            .compaction_group_manager
263            .write_with_process_name("try_update_write_limits")
264            .await;
265        let target_group_configs = target_group_ids
266            .iter()
267            .filter_map(|id| {
268                cg_manager
269                    .try_get_compaction_group_config(*id)
270                    .map(|config| (*id, config))
271            })
272            .collect();
273        let mut new_write_limits = calc_new_write_limits(
274            target_group_configs,
275            cg_manager.write_limit.clone(),
276            &versioning.current_version,
277        );
278        let all_group_ids: HashSet<_> =
279            HashSet::from_iter(get_compaction_group_ids(&versioning.current_version));
280        new_write_limits.retain(|group_id, _| all_group_ids.contains(group_id));
281        if new_write_limits == cg_manager.write_limit {
282            return false;
283        }
284        tracing::debug!("Hummock stopped write is updated: {:#?}", new_write_limits);
285        trigger_write_stop_stats(&self.metrics, &new_write_limits);
286        cg_manager.write_limit = new_write_limits;
287        self.env.notification_manager().notify_hummock(
288            Operation::Add,
289            Info::HummockWriteLimits(risingwave_pb::hummock::WriteLimits {
290                write_limits: cg_manager.write_limit.clone(),
291            }),
292        );
293        true
294    }
295
296    /// Gets write limits.
297    /// The implementation acquires `versioning` lock.
298    pub async fn write_limits(&self) -> HashMap<CompactionGroupId, WriteLimit> {
299        let guard = self
300            .compaction_group_manager
301            .read_with_process_name("write_limits")
302            .await;
303        guard.write_limit.clone()
304    }
305
306    /// Retain through reading the write-limit snapshot and sending its marker; release before
307    /// sampling another snapshot part.
308    pub async fn read_write_limits(&self) -> HummockWriteLimitsReadGuard<'_> {
309        HummockWriteLimitsReadGuard {
310            guard: self
311                .compaction_group_manager
312                .read_with_process_name("notification_snapshot")
313                .await,
314        }
315    }
316
317    pub async fn list_branched_objects(&self) -> BTreeMap<HummockSstableObjectId, BranchedSstInfo> {
318        let guard = self
319            .versioning
320            .read_with_process_name("list_branched_objects")
321            .await;
322        guard.current_version.build_branched_sst_info()
323    }
324
325    pub async fn rebuild_table_stats(&self) -> Result<()> {
326        let mut versioning = self
327            .versioning
328            .write_with_process_name("rebuild_table_stats")
329            .await;
330        let new_stats = rebuild_table_stats(&versioning.current_version);
331        let mut version_stats = VarTransaction::new(&mut versioning.version_stats);
332        // version_stats.hummock_version_id is always 0 in meta store.
333        version_stats.table_stats = new_stats.table_stats;
334        commit_multi_var!(self.meta_store_ref(), version_stats)?;
335        Ok(())
336    }
337
338    pub async fn may_fill_backward_state_table_info(&self) -> Result<()> {
339        let mut versioning = self
340            .versioning
341            .write_with_process_name("may_fill_backward_state_table_info")
342            .await;
343        if versioning
344            .current_version
345            .need_fill_backward_compatible_state_table_info_delta()
346        {
347            let versioning: &mut Versioning = &mut versioning;
348            let mut version = HummockVersionTransaction::new(
349                &mut versioning.current_version,
350                &mut versioning.hummock_version_deltas,
351                &mut versioning.table_change_log,
352                &self.gc_manager.change_log_retention,
353                self.env.notification_manager(),
354                None,
355                &self.metrics,
356                &self.env.opts,
357                &self.version_stat_tx,
358            );
359            let mut new_version_delta = version.new_delta();
360            new_version_delta.with_latest_version(|version, delta| {
361                version.may_fill_backward_compatible_state_table_info_delta(delta)
362            });
363            new_version_delta.pre_apply();
364            commit_multi_var!(self.meta_store_ref(), version)?;
365        }
366        Ok(())
367    }
368
369    pub async fn get_table_change_logs(
370        &self,
371        epoch_only: bool,
372        start_epoch_inclusive: Option<u64>,
373        end_epoch_inclusive: Option<u64>,
374        table_ids: Option<HashSet<TableId>>,
375        exclude_empty: bool,
376        limit: Option<u32>,
377    ) -> Result<TableChangeLogs> {
378        let _timer = self.metrics.table_change_log_get_latency.start_timer();
379        let start_epoch = start_epoch_inclusive.unwrap_or(0);
380        let end_epoch = end_epoch_inclusive.unwrap_or(u64::MAX);
381        if start_epoch > end_epoch {
382            return Err(Error::InvalidEpochRange {
383                start_epoch,
384                end_epoch,
385            });
386        }
387        let table_change_logs = self
388            .on_current_version_and_table_change_log(|_, table_change_logs| {
389                table_change_logs
390                    .iter()
391                    .filter_map(|(id, change_log)| {
392                        if let Some(table_filter) = &table_ids
393                            && !table_filter.contains(id)
394                        {
395                            return None;
396                        }
397                        let filtered_change_logs = change_log
398                            .filter_epoch((start_epoch, end_epoch))
399                            .filter(|change_log| {
400                                if exclude_empty
401                                    && change_log.new_value.is_empty()
402                                    && change_log.old_value.is_empty()
403                                {
404                                    return false;
405                                }
406                                true
407                            })
408                            .take(limit.map(|l| l as usize).unwrap_or(usize::MAX))
409                            .map(|change_log| {
410                                if epoch_only {
411                                    EpochNewChangeLog {
412                                        new_value: vec![],
413                                        old_value: vec![],
414                                        non_checkpoint_epochs: change_log
415                                            .non_checkpoint_epochs
416                                            .clone(),
417                                        checkpoint_epoch: change_log.checkpoint_epoch,
418                                    }
419                                } else {
420                                    change_log.clone()
421                                }
422                            });
423                        Some((id.to_owned(), TableChangeLog::new(filtered_change_logs)))
424                    })
425                    .collect()
426            })
427            .await;
428        Ok(table_change_logs)
429    }
430}
431
432/// Calculates write limits for `target_groups`.
433/// Returns a new complete write limits snapshot based on `origin_snapshot` and `version`.
434pub(super) fn calc_new_write_limits(
435    target_groups: HashMap<CompactionGroupId, CompactionGroup>,
436    origin_snapshot: HashMap<CompactionGroupId, WriteLimit>,
437    version: &HummockVersion,
438) -> HashMap<CompactionGroupId, WriteLimit> {
439    let mut new_write_limits = origin_snapshot;
440    for (id, config) in &target_groups {
441        let levels = match version.levels.get(id) {
442            None => {
443                new_write_limits.remove(id);
444                continue;
445            }
446            Some(levels) => levels,
447        };
448
449        let group_state = GroupStateValidator::check_single_group_write_stop(
450            levels,
451            config.compaction_config.as_ref(),
452        );
453
454        if group_state.is_write_stop() {
455            new_write_limits.insert(
456                *id,
457                WriteLimit {
458                    table_ids: version
459                        .state_table_info
460                        .compaction_group_member_table_ids(*id)
461                        .iter()
462                        .copied()
463                        .collect(),
464                    reason: group_state.reason().unwrap().to_owned(),
465                },
466            );
467            continue;
468        }
469        // No condition is met.
470        new_write_limits.remove(id);
471    }
472    new_write_limits
473}
474
475/// Rebuilds table stats from the given version.
476/// Note that the result is approximate value. See `estimate_table_stats`.
477fn rebuild_table_stats(version: &HummockVersion) -> HummockVersionStats {
478    let mut stats = HummockVersionStats {
479        hummock_version_id: version.id,
480        table_stats: Default::default(),
481    };
482    for level in version.get_combined_levels() {
483        for sst in &level.table_infos {
484            let changes = estimate_table_stats(sst);
485            add_prost_table_stats_map(&mut stats.table_stats, &changes);
486        }
487    }
488    stats
489}
490
491/// Estimates table stats change from the given file.
492/// - The file stats is evenly distributed among multiple tables within the file.
493/// - The total key size and total value size are estimated based on key range and file size.
494/// - Branched files may lead to an overestimation.
495fn estimate_table_stats(sst: &SstableInfo) -> PbTableStatsMap {
496    let mut changes: PbTableStatsMap = HashMap::default();
497    let weighted_value =
498        |value: i64| -> i64 { (value as f64 / sst.table_ids.len() as f64).ceil() as i64 };
499    let key_range = &sst.key_range;
500    let estimated_key_size: u64 = (key_range.left.len() + key_range.right.len()) as u64 / 2;
501    let mut estimated_total_key_size = estimated_key_size * sst.total_key_count;
502    if estimated_total_key_size > sst.uncompressed_file_size {
503        estimated_total_key_size = sst.uncompressed_file_size / 2;
504        tracing::warn!(
505            %sst.sst_id,
506            "Calculated estimated_total_key_size {} > uncompressed_file_size {}. Use uncompressed_file_size/2 as estimated_total_key_size instead.",
507            estimated_total_key_size,
508            sst.uncompressed_file_size
509        );
510    }
511    let estimated_total_value_size = sst.uncompressed_file_size - estimated_total_key_size;
512    for table_id in &sst.table_ids {
513        let e = changes.entry(*table_id).or_default();
514        e.total_key_count += weighted_value(sst.total_key_count as i64);
515        e.total_key_size += weighted_value(estimated_total_key_size as i64);
516        e.total_value_size += weighted_value(estimated_total_value_size as i64);
517    }
518    changes
519}
520
521#[cfg(test)]
522mod tests {
523    use std::collections::HashMap;
524    use std::sync::Arc;
525
526    use itertools::Itertools;
527    use risingwave_hummock_sdk::key_range::KeyRange;
528    use risingwave_hummock_sdk::level::{Level, Levels};
529    use risingwave_hummock_sdk::sstable_info::SstableInfoInner;
530    use risingwave_hummock_sdk::version::{HummockVersion, MAX_HUMMOCK_VERSION_ID};
531    use risingwave_hummock_sdk::{CompactionGroupId, HummockVersionId};
532    use risingwave_pb::hummock::write_limits::WriteLimit;
533    use risingwave_pb::hummock::{HummockPinnedVersion, HummockVersionStats};
534
535    use crate::hummock::compaction::compaction_config::CompactionConfigBuilder;
536    use crate::hummock::manager::context::ContextInfo;
537    use crate::hummock::manager::versioning::{
538        calc_new_write_limits, estimate_table_stats, rebuild_table_stats,
539    };
540    use crate::hummock::model::CompactionGroup;
541
542    #[test]
543    fn test_min_pinned_version_id() {
544        let mut context_info = ContextInfo::default();
545        assert_eq!(context_info.min_pinned_version_id(), MAX_HUMMOCK_VERSION_ID);
546        context_info.pinned_versions.insert(
547            1.into(),
548            HummockPinnedVersion {
549                context_id: 1.into(),
550                min_pinned_id: 10.into(),
551            },
552        );
553        assert_eq!(context_info.min_pinned_version_id(), 10);
554        context_info
555            .version_safe_points
556            .push(HummockVersionId::new(5));
557        assert_eq!(context_info.min_pinned_version_id(), 5);
558        context_info.version_safe_points.clear();
559        assert_eq!(context_info.min_pinned_version_id(), 10);
560        context_info.pinned_versions.clear();
561        assert_eq!(context_info.min_pinned_version_id(), MAX_HUMMOCK_VERSION_ID);
562    }
563
564    #[test]
565    fn test_calc_new_write_limits() {
566        let add_level_to_l0 = |levels: &mut Levels| {
567            levels.l0.sub_levels.push(Level::default());
568        };
569        let set_sub_level_number_threshold_for_group_1 =
570            |target_groups: &mut HashMap<CompactionGroupId, CompactionGroup>,
571             sub_level_number_threshold: u64| {
572                target_groups.insert(
573                    1.into(),
574                    CompactionGroup {
575                        group_id: 1.into(),
576                        compaction_config: Arc::new(
577                            CompactionConfigBuilder::new()
578                                .level0_stop_write_threshold_sub_level_number(
579                                    sub_level_number_threshold,
580                                )
581                                .build(),
582                        ),
583                    },
584                );
585            };
586
587        let set_level_0_max_sst_count_threshold_for_group_1 =
588            |target_groups: &mut HashMap<CompactionGroupId, CompactionGroup>,
589             max_sst_count_threshold: u32| {
590                target_groups.insert(
591                    1.into(),
592                    CompactionGroup {
593                        group_id: 1.into(),
594                        compaction_config: Arc::new(
595                            CompactionConfigBuilder::new()
596                                .level0_stop_write_threshold_max_sst_count(Some(
597                                    max_sst_count_threshold,
598                                ))
599                                .build(),
600                        ),
601                    },
602                );
603            };
604
605        let set_level_0_max_size_threshold_for_group_1 =
606            |target_groups: &mut HashMap<CompactionGroupId, CompactionGroup>,
607             max_size_threshold: u64| {
608                target_groups.insert(
609                    1.into(),
610                    CompactionGroup {
611                        group_id: 1.into(),
612                        compaction_config: Arc::new(
613                            CompactionConfigBuilder::new()
614                                .level0_stop_write_threshold_max_size(Some(max_size_threshold))
615                                .build(),
616                        ),
617                    },
618                );
619            };
620
621        let mut target_groups: HashMap<CompactionGroupId, CompactionGroup> = Default::default();
622        set_sub_level_number_threshold_for_group_1(&mut target_groups, 10);
623        let origin_snapshot: HashMap<CompactionGroupId, WriteLimit> = [(
624            2.into(),
625            WriteLimit {
626                table_ids: [1, 2, 3].into_iter().map_into().collect(),
627                reason: "for test".to_owned(),
628            },
629        )]
630        .into_iter()
631        .collect();
632        let mut version: HummockVersion = Default::default();
633        for group_id in 1..=3 {
634            version.levels.insert(group_id.into(), Levels::default());
635        }
636        let new_write_limits =
637            calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
638        assert_eq!(
639            new_write_limits, origin_snapshot,
640            "write limit should not be triggered for group 1"
641        );
642        assert_eq!(new_write_limits.len(), 1);
643        for _ in 1..=10 {
644            add_level_to_l0(version.levels.get_mut(&1).unwrap());
645            let new_write_limits =
646                calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
647            assert_eq!(
648                new_write_limits, origin_snapshot,
649                "write limit should not be triggered for group 1"
650            );
651        }
652        add_level_to_l0(version.levels.get_mut(&1).unwrap());
653        let new_write_limits =
654            calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
655        assert_ne!(
656            new_write_limits, origin_snapshot,
657            "write limit should be triggered for group 1"
658        );
659        assert_eq!(
660            new_write_limits.get(&1).as_ref().unwrap().reason,
661            "WriteStop(l0_level_count: 11, threshold: 10) too many L0 sub levels"
662        );
663        assert_eq!(new_write_limits.len(), 2);
664
665        set_sub_level_number_threshold_for_group_1(&mut target_groups, 100);
666        let new_write_limits =
667            calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
668        assert_eq!(
669            new_write_limits, origin_snapshot,
670            "write limit should not be triggered for group 1"
671        );
672
673        set_sub_level_number_threshold_for_group_1(&mut target_groups, 5);
674        let new_write_limits =
675            calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
676        assert_ne!(
677            new_write_limits, origin_snapshot,
678            "write limit should be triggered for group 1"
679        );
680        assert_eq!(
681            new_write_limits.get(&1).as_ref().unwrap().reason,
682            "WriteStop(l0_level_count: 11, threshold: 5) too many L0 sub levels"
683        );
684
685        set_sub_level_number_threshold_for_group_1(&mut target_groups, 100);
686        let last_level = version
687            .levels
688            .get_mut(&1)
689            .unwrap()
690            .l0
691            .sub_levels
692            .last_mut()
693            .unwrap();
694        last_level.table_infos.extend(vec![
695            SstableInfoInner {
696                key_range: KeyRange::default(),
697                table_ids: vec![1.into(), 2.into(), 3.into()],
698                total_key_count: 100,
699                sst_size: 100,
700                uncompressed_file_size: 100,
701                ..Default::default()
702            }
703            .into(),
704            SstableInfoInner {
705                key_range: KeyRange::default(),
706                table_ids: vec![1.into(), 2.into(), 3.into()],
707                total_key_count: 100,
708                sst_size: 100,
709                uncompressed_file_size: 100,
710                ..Default::default()
711            }
712            .into(),
713        ]);
714        version.levels.get_mut(&1).unwrap().l0.total_file_size += 200;
715        let new_write_limits =
716            calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
717        assert_eq!(
718            new_write_limits, origin_snapshot,
719            "write limit should not be triggered for group 1"
720        );
721
722        set_level_0_max_size_threshold_for_group_1(&mut target_groups, 10);
723        let new_write_limits =
724            calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
725        assert_ne!(
726            new_write_limits, origin_snapshot,
727            "write limit should be triggered for group 1"
728        );
729        assert_eq!(
730            new_write_limits.get(&1).as_ref().unwrap().reason,
731            "WriteStop(l0_size: 200, threshold: 10) too large L0 size"
732        );
733
734        set_level_0_max_size_threshold_for_group_1(&mut target_groups, 10000);
735        let new_write_limits =
736            calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
737        assert_eq!(
738            new_write_limits, origin_snapshot,
739            "write limit should not be triggered for group 1"
740        );
741
742        set_level_0_max_sst_count_threshold_for_group_1(&mut target_groups, 1);
743        let new_write_limits =
744            calc_new_write_limits(target_groups.clone(), origin_snapshot.clone(), &version);
745        assert_ne!(
746            new_write_limits, origin_snapshot,
747            "write limit should be triggered for group 1"
748        );
749        assert_eq!(
750            new_write_limits.get(&1).as_ref().unwrap().reason,
751            "WriteStop(l0_sst_count: 2, threshold: 1) too many L0 sst files"
752        );
753
754        set_level_0_max_sst_count_threshold_for_group_1(&mut target_groups, 100);
755        let new_write_limits =
756            calc_new_write_limits(target_groups, origin_snapshot.clone(), &version);
757
758        assert_eq!(
759            new_write_limits, origin_snapshot,
760            "write limit should not be triggered for group 1"
761        );
762    }
763
764    #[test]
765    fn test_estimate_table_stats() {
766        let sst = SstableInfoInner {
767            key_range: KeyRange {
768                left: vec![1; 10].into(),
769                right: vec![1; 20].into(),
770                ..Default::default()
771            },
772            table_ids: vec![1.into(), 2.into(), 3.into()],
773            total_key_count: 6000,
774            uncompressed_file_size: 6_000_000,
775            ..Default::default()
776        }
777        .into();
778        let changes = estimate_table_stats(&sst);
779        assert_eq!(changes.len(), 3);
780        for stats in changes.values() {
781            assert_eq!(stats.total_key_count, 6000 / 3);
782            assert_eq!(stats.total_key_size, (10 + 20) / 2 * 6000 / 3);
783            assert_eq!(
784                stats.total_value_size,
785                (6_000_000 - (10 + 20) / 2 * 6000) / 3
786            );
787        }
788
789        let mut version = HummockVersion::default();
790        version.id = HummockVersionId::new(123);
791
792        for cg in 1..3 {
793            version.levels.insert(
794                cg.into(),
795                Levels {
796                    levels: vec![Level {
797                        table_infos: vec![sst.clone()],
798                        ..Default::default()
799                    }],
800                    ..Default::default()
801                },
802            );
803        }
804        let HummockVersionStats {
805            hummock_version_id,
806            table_stats,
807        } = rebuild_table_stats(&version);
808        assert_eq!(hummock_version_id, version.id);
809        assert_eq!(table_stats.len(), 3);
810        for (tid, stats) in table_stats {
811            assert_eq!(
812                stats.total_key_count,
813                changes.get(&tid).unwrap().total_key_count * 2
814            );
815            assert_eq!(
816                stats.total_key_size,
817                changes.get(&tid).unwrap().total_key_size * 2
818            );
819            assert_eq!(
820                stats.total_value_size,
821                changes.get(&tid).unwrap().total_value_size * 2
822            );
823        }
824    }
825
826    #[test]
827    fn test_estimate_table_stats_large_key_range() {
828        let sst = SstableInfoInner {
829            key_range: KeyRange {
830                left: vec![1; 1000].into(),
831                right: vec![1; 2000].into(),
832                ..Default::default()
833            },
834            table_ids: vec![1.into(), 2.into(), 3.into()],
835            total_key_count: 6000,
836            uncompressed_file_size: 60_000,
837            ..Default::default()
838        }
839        .into();
840        let changes = estimate_table_stats(&sst);
841        assert_eq!(changes.len(), 3);
842        for t in &sst.table_ids {
843            let stats = changes.get(t).unwrap();
844            assert_eq!(stats.total_key_count, 6000 / 3);
845            assert_eq!(stats.total_key_size, 60_000 / 2 / 3);
846            assert_eq!(stats.total_value_size, (60_000 - 60_000 / 2) / 3);
847        }
848    }
849}