Skip to main content

risingwave_hummock_sdk/
change_log.rs

1// Copyright 2024 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::collections::{HashMap, VecDeque};
16use std::ops::RangeBounds;
17
18use risingwave_common::catalog::TableId;
19use risingwave_pb::hummock::{PbEpochNewChangeLog, PbSstableInfo, PbTableChangeLog};
20use tracing::warn;
21
22use crate::HummockObjectId;
23use crate::sstable_info::SstableInfo;
24use crate::version::ObjectIdReader;
25
26#[derive(Debug, Clone, PartialEq)]
27pub struct TableChangeLogCommon<T>(
28    // older log at the front
29    VecDeque<EpochNewChangeLogCommon<T>>,
30);
31
32impl<T> TableChangeLogCommon<T> {
33    pub fn new(logs: impl IntoIterator<Item = EpochNewChangeLogCommon<T>>) -> Self {
34        let logs = logs.into_iter().collect::<VecDeque<_>>();
35        debug_assert!(logs.iter().flat_map(|log| log.epochs()).is_sorted());
36        Self(logs)
37    }
38
39    pub fn iter(&self) -> impl Iterator<Item = &EpochNewChangeLogCommon<T>> {
40        self.0.iter()
41    }
42
43    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut EpochNewChangeLogCommon<T>> {
44        self.0.iter_mut()
45    }
46
47    pub fn first(&self) -> Option<&EpochNewChangeLogCommon<T>> {
48        self.0.front()
49    }
50
51    pub fn last(&self) -> Option<&EpochNewChangeLogCommon<T>> {
52        self.0.back()
53    }
54
55    pub fn get(&self, index: usize) -> Option<&EpochNewChangeLogCommon<T>> {
56        self.0.get(index)
57    }
58
59    pub fn range(
60        &self,
61        range: impl RangeBounds<usize>,
62    ) -> impl Iterator<Item = &EpochNewChangeLogCommon<T>> + '_ {
63        self.0.range(range)
64    }
65
66    pub fn add_change_log(&mut self, new_change_log: EpochNewChangeLogCommon<T>) {
67        if let Some(prev_log) = self.0.back() {
68            assert!(prev_log.checkpoint_epoch < new_change_log.first_epoch());
69        }
70        self.0.push_back(new_change_log);
71    }
72
73    pub fn epochs(&self) -> impl Iterator<Item = u64> + '_ {
74        self.0
75            .iter()
76            .flat_map(|epoch_change_log| epoch_change_log.epochs())
77    }
78
79    pub fn is_empty(&self) -> bool {
80        self.0.is_empty()
81    }
82
83    pub fn binary_search_by_checkpoint_epoch(&self, epoch: u64) -> Result<usize, usize> {
84        self.0
85            .binary_search_by_key(&epoch, |log| log.checkpoint_epoch)
86    }
87}
88
89impl<T> IntoIterator for TableChangeLogCommon<T> {
90    type Item = EpochNewChangeLogCommon<T>;
91
92    type IntoIter = impl Iterator<Item = EpochNewChangeLogCommon<T>>;
93
94    fn into_iter(self) -> Self::IntoIter {
95        self.0.into_iter()
96    }
97}
98
99pub type TableChangeLog = TableChangeLogCommon<SstableInfo>;
100pub type TableChangeLogs = HashMap<TableId, TableChangeLog>;
101
102impl TableChangeLog {
103    pub fn get_object_ids(&self) -> impl Iterator<Item = HummockObjectId> + '_ {
104        self.0.iter().flat_map(|c| {
105            c.old_value
106                .iter()
107                .chain(c.new_value.iter())
108                .map(|t| HummockObjectId::Sstable(t.object_id()))
109        })
110    }
111}
112
113#[derive(Debug, Clone, PartialEq)]
114pub struct EpochNewChangeLogCommon<T> {
115    pub new_value: Vec<T>,
116    pub old_value: Vec<T>,
117    // epochs are sorted in ascending order
118    pub non_checkpoint_epochs: Vec<u64>,
119    pub checkpoint_epoch: u64,
120}
121
122impl EpochNewChangeLog {
123    pub fn change_log_ssts(&self) -> impl Iterator<Item = &SstableInfo> + '_ {
124        self.new_value.iter().chain(self.old_value.iter())
125    }
126}
127
128pub(crate) fn resolve_pb_log_epochs(epochs: &Vec<u64>) -> (Vec<u64>, u64) {
129    (
130        Vec::from(&epochs[0..(epochs.len() - 1)]),
131        *epochs.last().expect("non-empty"),
132    )
133}
134
135impl<T> EpochNewChangeLogCommon<T> {
136    pub fn epochs(&self) -> impl Iterator<Item = u64> + '_ {
137        self.non_checkpoint_epochs
138            .iter()
139            .cloned()
140            .chain([self.checkpoint_epoch])
141    }
142
143    pub fn first_epoch(&self) -> u64 {
144        self.non_checkpoint_epochs
145            .first()
146            .cloned()
147            .unwrap_or(self.checkpoint_epoch)
148    }
149}
150
151pub type EpochNewChangeLog = EpochNewChangeLogCommon<SstableInfo>;
152
153impl<T> From<&EpochNewChangeLogCommon<T>> for PbEpochNewChangeLog
154where
155    PbSstableInfo: for<'a> From<&'a T>,
156{
157    fn from(val: &EpochNewChangeLogCommon<T>) -> Self {
158        Self {
159            new_value: val.new_value.iter().map(|a| a.into()).collect(),
160            old_value: val.old_value.iter().map(|a| a.into()).collect(),
161            epochs: val.epochs().collect(),
162        }
163    }
164}
165
166impl<T> From<&PbEpochNewChangeLog> for EpochNewChangeLogCommon<T>
167where
168    T: for<'a> From<&'a PbSstableInfo>,
169{
170    fn from(value: &PbEpochNewChangeLog) -> Self {
171        let (non_checkpoint_epochs, checkpoint_epoch) = resolve_pb_log_epochs(&value.epochs);
172        Self {
173            new_value: value.new_value.iter().map(|a| a.into()).collect(),
174            old_value: value.old_value.iter().map(|a| a.into()).collect(),
175            non_checkpoint_epochs,
176            checkpoint_epoch,
177        }
178    }
179}
180
181impl<T> From<EpochNewChangeLogCommon<T>> for PbEpochNewChangeLog
182where
183    PbSstableInfo: From<T>,
184{
185    fn from(val: EpochNewChangeLogCommon<T>) -> Self {
186        Self {
187            epochs: val.epochs().collect(),
188            new_value: val.new_value.into_iter().map(|a| a.into()).collect(),
189            old_value: val.old_value.into_iter().map(|a| a.into()).collect(),
190        }
191    }
192}
193
194impl<T> From<PbEpochNewChangeLog> for EpochNewChangeLogCommon<T>
195where
196    T: From<PbSstableInfo>,
197{
198    fn from(value: PbEpochNewChangeLog) -> Self {
199        let (non_checkpoint_epochs, checkpoint_epoch) = resolve_pb_log_epochs(&value.epochs);
200        Self {
201            new_value: value.new_value.into_iter().map(|a| a.into()).collect(),
202            old_value: value.old_value.into_iter().map(|a| a.into()).collect(),
203            non_checkpoint_epochs,
204            checkpoint_epoch,
205        }
206    }
207}
208
209impl<T> TableChangeLogCommon<T> {
210    pub fn filter_epoch(
211        &self,
212        (min_epoch, max_epoch): (u64, u64),
213    ) -> impl Iterator<Item = &EpochNewChangeLogCommon<T>> + '_ {
214        assert!(
215            min_epoch <= max_epoch,
216            "invalid epoch range: {min_epoch}..={max_epoch}"
217        );
218        let start = self
219            .0
220            .partition_point(|epoch_change_log| epoch_change_log.checkpoint_epoch < min_epoch);
221        let end = self
222            .0
223            .partition_point(|epoch_change_log| epoch_change_log.first_epoch() <= max_epoch);
224        self.0.range(start..end)
225    }
226
227    /// Get the `next_epoch` of the given `epoch`
228    /// Return:
229    ///     - Ok(Some(`next_epoch`)): the `next_epoch` of `epoch`
230    ///     - Ok(None): `next_epoch` of `epoch` is not added to change log yet
231    ///     - Err(()): `epoch` is not an existing or to exist one
232    #[expect(clippy::result_unit_err)]
233    pub fn next_epoch(&self, epoch: u64) -> Result<Option<u64>, ()> {
234        let start = self
235            .0
236            .partition_point(|epoch_change_log| epoch_change_log.checkpoint_epoch < epoch);
237        debug_assert!(
238            self.0
239                .range(start..)
240                .flat_map(|epoch_change_log| epoch_change_log.epochs())
241                .is_sorted()
242        );
243        let mut later_epochs = self
244            .0
245            .range(start..)
246            .flat_map(|epoch_change_log| epoch_change_log.epochs())
247            .skip_while(|log_epoch| *log_epoch < epoch);
248        if let Some(first_epoch) = later_epochs.next() {
249            assert!(
250                first_epoch >= epoch,
251                "first_epoch {} < epoch {}",
252                first_epoch,
253                epoch
254            );
255            if first_epoch != epoch {
256                return Err(());
257            }
258            if let Some(next_epoch) = later_epochs.next() {
259                assert!(
260                    next_epoch > epoch,
261                    "next_epoch {} not exceed epoch {}",
262                    next_epoch,
263                    epoch
264                );
265                Ok(Some(next_epoch))
266            } else {
267                // `epoch` is latest
268                Ok(None)
269            }
270        } else {
271            // all epochs are less than `epoch`
272            Ok(None)
273        }
274    }
275
276    pub fn truncate(&mut self, truncate_epoch: u64) {
277        while let Some(change_log) = self.0.front()
278            && change_log.checkpoint_epoch < truncate_epoch
279        {
280            let _change_log = self.0.pop_front().expect("non-empty");
281        }
282        if let Some(first_log) = self.0.front_mut() {
283            first_log
284                .non_checkpoint_epochs
285                .retain(|epoch| *epoch >= truncate_epoch);
286        }
287    }
288}
289
290impl<T> TableChangeLogCommon<T>
291where
292    PbSstableInfo: for<'a> From<&'a T>,
293{
294    pub fn to_protobuf(&self) -> PbTableChangeLog {
295        PbTableChangeLog {
296            change_logs: self.0.iter().map(|a| a.into()).collect(),
297        }
298    }
299}
300
301impl<T> TableChangeLogCommon<T>
302where
303    T: for<'a> From<&'a PbSstableInfo>,
304{
305    pub fn from_protobuf(val: &PbTableChangeLog) -> Self {
306        Self(val.change_logs.iter().map(|a| a.into()).collect())
307    }
308}
309
310impl<T> TableChangeLogCommon<T>
311where
312    T: From<PbSstableInfo>,
313{
314    pub fn from_protobuf_owned(val: PbTableChangeLog) -> Self {
315        Self(val.change_logs.into_iter().map(|a| a.into()).collect())
316    }
317}
318
319pub fn build_table_change_log_delta<'a>(
320    old_value_ssts: impl Iterator<Item = SstableInfo>,
321    new_value_ssts: impl Iterator<Item = &'a SstableInfo>,
322    epochs: &Vec<u64>,
323    log_store_table_ids: impl Iterator<Item = TableId>,
324) -> HashMap<TableId, EpochNewChangeLog> {
325    let mut table_change_log: HashMap<_, _> = log_store_table_ids
326        .map(|table_id| {
327            let (non_checkpoint_epochs, checkpoint_epoch) = resolve_pb_log_epochs(epochs);
328            (
329                table_id,
330                EpochNewChangeLog {
331                    new_value: vec![],
332                    old_value: vec![],
333                    non_checkpoint_epochs,
334                    checkpoint_epoch,
335                },
336            )
337        })
338        .collect();
339    for sst in old_value_ssts {
340        for table_id in &sst.table_ids {
341            match table_change_log.get_mut(table_id) {
342                Some(log) => {
343                    log.old_value.push(sst.clone());
344                }
345                None => {
346                    warn!(%table_id, ?sst, "old value sst contains non-log-store table");
347                }
348            }
349        }
350    }
351    for sst in new_value_ssts {
352        for table_id in &sst.table_ids {
353            if let Some(log) = table_change_log.get_mut(table_id) {
354                log.new_value.push(sst.clone());
355            }
356        }
357    }
358    table_change_log
359}
360
361#[cfg(test)]
362mod tests {
363    use itertools::Itertools;
364
365    use crate::change_log::{EpochNewChangeLog, TableChangeLogCommon};
366    use crate::sstable_info::SstableInfo;
367
368    #[test]
369    fn test_filter_epoch() {
370        let table_change_log = TableChangeLogCommon::<SstableInfo>::new([
371            EpochNewChangeLog {
372                new_value: vec![],
373                old_value: vec![],
374                non_checkpoint_epochs: vec![],
375                checkpoint_epoch: 2,
376            },
377            EpochNewChangeLog {
378                new_value: vec![],
379                old_value: vec![],
380                non_checkpoint_epochs: vec![3],
381                checkpoint_epoch: 4,
382            },
383            EpochNewChangeLog {
384                new_value: vec![],
385                old_value: vec![],
386                non_checkpoint_epochs: vec![],
387                checkpoint_epoch: 6,
388            },
389            EpochNewChangeLog {
390                new_value: vec![],
391                old_value: vec![],
392                non_checkpoint_epochs: vec![8],
393                checkpoint_epoch: 10,
394            },
395        ]);
396
397        let epochs = (1..=11).collect_vec();
398        for i in 0..epochs.len() {
399            for j in i..epochs.len() {
400                let min_epoch = epochs[i];
401                let max_epoch = epochs[j];
402                let expected = table_change_log
403                    .0
404                    .iter()
405                    .filter(|log| {
406                        min_epoch <= log.checkpoint_epoch && log.first_epoch() <= max_epoch
407                    })
408                    .cloned()
409                    .collect_vec();
410                let actual = table_change_log
411                    .filter_epoch((min_epoch, max_epoch))
412                    .cloned()
413                    .collect_vec();
414                assert_eq!(expected, actual, "{:?}", (min_epoch, max_epoch));
415            }
416        }
417
418        let existing_epochs = table_change_log.epochs().collect_vec();
419        assert!(existing_epochs.is_sorted());
420        for &epoch in &epochs {
421            let expected = match existing_epochs
422                .iter()
423                .position(|existing_epoch| *existing_epoch >= epoch)
424            {
425                None => {
426                    // all existing epochs are less than epoch
427                    Ok(None)
428                }
429                Some(i) => {
430                    let this_epoch = existing_epochs[i];
431                    assert!(this_epoch >= epoch);
432                    if this_epoch == epoch {
433                        if i + 1 == existing_epochs.len() {
434                            // epoch is the latest epoch
435                            Ok(None)
436                        } else {
437                            Ok(Some(existing_epochs[i + 1]))
438                        }
439                    } else {
440                        // epoch not a existing epoch
441                        Err(())
442                    }
443                }
444            };
445            assert_eq!(expected, table_change_log.next_epoch(epoch));
446        }
447    }
448
449    #[test]
450    fn test_truncate() {
451        let mut table_change_log = TableChangeLogCommon::<SstableInfo>::new([
452            EpochNewChangeLog {
453                new_value: vec![],
454                old_value: vec![],
455                non_checkpoint_epochs: vec![],
456                checkpoint_epoch: 1,
457            },
458            EpochNewChangeLog {
459                new_value: vec![],
460                old_value: vec![],
461                non_checkpoint_epochs: vec![],
462                checkpoint_epoch: 2,
463            },
464            EpochNewChangeLog {
465                new_value: vec![],
466                old_value: vec![],
467                non_checkpoint_epochs: vec![3],
468                checkpoint_epoch: 4,
469            },
470            EpochNewChangeLog {
471                new_value: vec![],
472                old_value: vec![],
473                non_checkpoint_epochs: vec![],
474                checkpoint_epoch: 5,
475            },
476        ]);
477        let origin_table_change_log = table_change_log.clone();
478        for truncate_epoch in 0..6 {
479            table_change_log.truncate(truncate_epoch);
480            let expected_table_change_log = TableChangeLogCommon(
481                origin_table_change_log
482                    .0
483                    .iter()
484                    .filter_map(|epoch_change_log| {
485                        let mut epoch_change_log = epoch_change_log.clone();
486                        epoch_change_log
487                            .non_checkpoint_epochs
488                            .retain(|epoch| *epoch >= truncate_epoch);
489                        if epoch_change_log.non_checkpoint_epochs.is_empty()
490                            && epoch_change_log.checkpoint_epoch < truncate_epoch
491                        {
492                            None
493                        } else {
494                            Some(epoch_change_log)
495                        }
496                    })
497                    .collect(),
498            );
499            assert_eq!(expected_table_change_log, table_change_log);
500        }
501    }
502}