Skip to main content

mito2/sst/index/
statistics.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::time::{Duration, Instant};
16
17use crate::metrics::{INDEX_CREATE_BYTES_TOTAL, INDEX_CREATE_ELAPSED, INDEX_CREATE_ROWS_TOTAL};
18
19pub type ByteCount = u64;
20pub type RowCount = usize;
21
22/// Stage of the index creation process.
23enum Stage {
24    Update,
25    #[cfg(feature = "enterprise")]
26    Merge,
27    Finish,
28    Cleanup,
29}
30
31/// Statistics for index creation. Flush metrics when dropped.
32pub struct Statistics {
33    /// Index type.
34    index_type: &'static str,
35    /// Accumulated elapsed time for the index update stage.
36    update_elapsed: Duration,
37    /// Whether update and total elapsed time can be attributed to this index.
38    update_timing_available: bool,
39    /// Accumulated time spent merging existing index states.
40    merge_elapsed: Duration,
41    /// Accumulated elapsed time for the index finish stage.
42    finish_elapsed: Duration,
43    /// Accumulated elapsed time for the cleanup stage.
44    cleanup_eplased: Duration,
45    /// Number of rows in the index.
46    row_count: RowCount,
47    /// Number of bytes in the index.
48    byte_count: ByteCount,
49}
50
51impl Statistics {
52    /// Creates index statistics whose accumulated metrics are published on drop.
53    pub fn new(index_type: &'static str) -> Self {
54        Self {
55            index_type,
56            update_elapsed: Duration::default(),
57            update_timing_available: true,
58            merge_elapsed: Duration::default(),
59            finish_elapsed: Duration::default(),
60            cleanup_eplased: Duration::default(),
61            row_count: 0,
62            byte_count: 0,
63        }
64    }
65
66    /// Creates counters for interleaved work whose update time cannot be attributed
67    /// to this index. Update and total histograms remain absent until `record_update`.
68    #[cfg(feature = "enterprise")]
69    pub fn new_without_update_timing(index_type: &'static str) -> Self {
70        let mut stats = Self::new(index_type);
71        stats.update_timing_available = false;
72        stats
73    }
74
75    /// Counts rows without taking a clock sample or claiming an update duration.
76    #[cfg(feature = "enterprise")]
77    pub fn inc_row_count(&mut self, rows: RowCount) {
78        self.row_count += rows;
79    }
80
81    /// Starts timing the update stage, returning a `TimerGuard` to automatically record duration.
82    #[must_use]
83    pub fn record_update(&mut self) -> TimerGuard<'_> {
84        self.update_timing_available = true;
85        TimerGuard::new(self, Stage::Update)
86    }
87
88    /// Starts timing merges of existing index states.
89    ///
90    /// Merged input rows are represented rows, not newly scanned output rows. Callers
91    /// count actual output rows separately through the update or finish guard.
92    #[must_use]
93    #[cfg(feature = "enterprise")]
94    pub fn record_merge(&mut self) -> TimerGuard<'_> {
95        TimerGuard::new(self, Stage::Merge)
96    }
97
98    /// Starts timing the finish stage, returning a `TimerGuard` to automatically record duration.
99    #[must_use]
100    pub fn record_finish(&mut self) -> TimerGuard<'_> {
101        TimerGuard::new(self, Stage::Finish)
102    }
103
104    /// Starts timing the cleanup stage, returning a `TimerGuard` to automatically record duration.
105    #[must_use]
106    pub fn record_cleanup(&mut self) -> TimerGuard<'_> {
107        TimerGuard::new(self, Stage::Cleanup)
108    }
109
110    /// Returns row count.
111    pub fn row_count(&self) -> RowCount {
112        self.row_count
113    }
114
115    /// Returns byte count.
116    pub fn byte_count(&self) -> ByteCount {
117        self.byte_count
118    }
119}
120
121impl Drop for Statistics {
122    fn drop(&mut self) {
123        if self.update_timing_available {
124            INDEX_CREATE_ELAPSED
125                .with_label_values(&["update", self.index_type])
126                .observe(self.update_elapsed.as_secs_f64());
127        }
128        if !self.merge_elapsed.is_zero() {
129            INDEX_CREATE_ELAPSED
130                .with_label_values(&["merge", self.index_type])
131                .observe(self.merge_elapsed.as_secs_f64());
132        }
133        INDEX_CREATE_ELAPSED
134            .with_label_values(&["finish", self.index_type])
135            .observe(self.finish_elapsed.as_secs_f64());
136        INDEX_CREATE_ELAPSED
137            .with_label_values(&["cleanup", self.index_type])
138            .observe(self.cleanup_eplased.as_secs_f64());
139        if self.update_timing_available {
140            INDEX_CREATE_ELAPSED
141                .with_label_values(&["total", self.index_type])
142                .observe(
143                    (self.update_elapsed
144                        + self.merge_elapsed
145                        + self.finish_elapsed
146                        + self.cleanup_eplased)
147                        .as_secs_f64(),
148                );
149        }
150
151        INDEX_CREATE_ROWS_TOTAL
152            .with_label_values(&[self.index_type])
153            .inc_by(self.row_count as _);
154        INDEX_CREATE_BYTES_TOTAL
155            .with_label_values(&[self.index_type])
156            .inc_by(self.byte_count as _);
157    }
158}
159
160/// `TimerGuard` is a RAII struct that ensures elapsed time
161/// is recorded when it goes out of scope.
162pub struct TimerGuard<'a> {
163    stats: &'a mut Statistics,
164    stage: Stage,
165    timer: Instant,
166}
167
168impl<'a> TimerGuard<'a> {
169    /// Creates a new `TimerGuard`,
170    fn new(stats: &'a mut Statistics, stage: Stage) -> Self {
171        Self {
172            stats,
173            stage,
174            timer: Instant::now(),
175        }
176    }
177
178    /// Increases the row count of the index creation statistics.
179    pub fn inc_row_count(&mut self, n: usize) {
180        self.stats.row_count += n;
181    }
182
183    /// Increases the byte count of the index creation statistics.
184    pub fn inc_byte_count(&mut self, n: u64) {
185        self.stats.byte_count += n;
186    }
187}
188
189impl Drop for TimerGuard<'_> {
190    fn drop(&mut self) {
191        match self.stage {
192            Stage::Update => {
193                self.stats.update_elapsed += self.timer.elapsed();
194            }
195            #[cfg(feature = "enterprise")]
196            Stage::Merge => {
197                self.stats.merge_elapsed += self.timer.elapsed();
198            }
199            Stage::Finish => {
200                self.stats.finish_elapsed += self.timer.elapsed();
201            }
202            Stage::Cleanup => {
203                self.stats.cleanup_eplased += self.timer.elapsed();
204            }
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[cfg(feature = "enterprise")]
214    #[test]
215    fn test_unmeasured_updates_do_not_publish_zero_durations() {
216        let name = "test_sketch_fused_counter_only";
217        let update = INDEX_CREATE_ELAPSED.with_label_values(&["update", name]);
218        let total = INDEX_CREATE_ELAPSED.with_label_values(&["total", name]);
219        let update_before = update.get_sample_count();
220        let total_before = total.get_sample_count();
221        let mut stats = Statistics::new_without_update_timing(name);
222        stats.inc_row_count(7);
223        assert_eq!(stats.row_count(), 7);
224        drop(stats);
225        assert_eq!(update.get_sample_count(), update_before);
226        assert_eq!(total.get_sample_count(), total_before);
227        let mut measured = Statistics::new_without_update_timing(name);
228        {
229            let _timer = measured.record_update();
230        }
231        drop(measured);
232        assert_eq!(update.get_sample_count(), update_before + 1);
233        assert_eq!(total.get_sample_count(), total_before + 1);
234    }
235
236    #[cfg(feature = "enterprise")]
237    #[test]
238    fn test_merge_does_not_count_input_rows_as_output_rows() {
239        let mut stats = Statistics::new("test_merge");
240        {
241            let _guard = stats.record_merge();
242        }
243        assert_eq!(stats.row_count(), 0);
244        {
245            let mut guard = stats.record_finish();
246            guard.inc_row_count(7);
247            guard.inc_byte_count(32);
248        }
249        assert_eq!(stats.row_count(), 7);
250        assert_eq!(stats.byte_count(), 32);
251    }
252
253    #[test]
254    fn test_statistics_basic() {
255        let mut stats = Statistics::new("test");
256        {
257            let mut guard = stats.record_update();
258            guard.inc_byte_count(100);
259            guard.inc_row_count(10);
260
261            let now = Instant::now();
262            while now.elapsed().is_zero() {
263                // busy loop
264            }
265        }
266        {
267            let _guard = stats.record_finish();
268            let now = Instant::now();
269            while now.elapsed().is_zero() {
270                // busy loop
271            }
272        }
273        {
274            let _guard = stats.record_cleanup();
275            let now = Instant::now();
276            while now.elapsed().is_zero() {
277                // busy loop
278            }
279        }
280        assert_eq!(stats.row_count(), 10);
281        assert_eq!(stats.byte_count(), 100);
282        assert!(stats.update_elapsed > Duration::default());
283        assert!(stats.finish_elapsed > Duration::default());
284        assert!(stats.cleanup_eplased > Duration::default());
285    }
286}