risingwave_meta/hummock/manager/
versioning.rs

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