Skip to main content

risingwave_meta/hummock/manager/
transaction.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::{BTreeMap, HashMap, HashSet};
16use std::ops::{Deref, DerefMut};
17use std::sync::Arc;
18
19use parking_lot::Mutex;
20use risingwave_common::catalog::TableId;
21use risingwave_hummock_sdk::change_log::{EpochNewChangeLog, TableChangeLog};
22use risingwave_hummock_sdk::compaction_group::StaticCompactionGroupId;
23use risingwave_hummock_sdk::sstable_info::SstableInfo;
24use risingwave_hummock_sdk::table_watermark::TableWatermarks;
25use risingwave_hummock_sdk::vector_index::VectorIndexDelta;
26use risingwave_hummock_sdk::version::{GroupDelta, HummockVersion, HummockVersionDelta};
27use risingwave_hummock_sdk::{
28    CompactionGroupId, FrontendHummockVersionDelta, HummockSstableId, HummockVersionId,
29};
30use risingwave_pb::hummock::{
31    CompatibilityVersion, GroupConstruct, HummockVersionDeltas, HummockVersionStats,
32    StateTableInfoDelta,
33};
34use risingwave_pb::meta::subscribe_response::{Info, Operation};
35use sea_orm::{ConnectionTrait, EntityTrait};
36
37use super::TableCommittedEpochNotifiers;
38use super::gc::change_log_retention::RetainedChangeLogBatch;
39use crate::hummock::model::CompactionGroup;
40use crate::hummock::model::ext::to_table_change_log_meta_store_model;
41use crate::manager::{MetaOpts, NotificationManager};
42use crate::model::{
43    InMemValTransaction, MetadataModelResult, Transactional, ValTransaction, VarTransaction,
44};
45use crate::rpc::metrics::MetaMetrics;
46
47fn trigger_delta_log_stats(metrics: &MetaMetrics, total_number: usize) {
48    metrics.delta_log_count.set(total_number as _);
49}
50
51#[derive(Default)]
52struct TableChangeLogTransactionDelta {
53    updates: Vec<HashMap<TableId, EpochNewChangeLog>>,
54    delete_all: HashSet<TableId>,
55}
56
57pub(super) fn trigger_version_stat(metrics: &MetaMetrics, current_version: &HummockVersion) {
58    metrics
59        .version_size
60        .set(current_version.estimated_encode_len() as i64);
61    metrics
62        .current_version_id
63        .set(current_version.id.as_i64_id());
64}
65
66pub(super) struct HummockVersionTransaction<'a> {
67    orig_version: &'a mut Arc<HummockVersion>,
68    orig_deltas: &'a mut BTreeMap<HummockVersionId, HummockVersionDelta>,
69    orig_table_change_log: &'a mut HashMap<TableId, TableChangeLog>,
70    change_log_retention: &'a super::gc::change_log_retention::ChangeLogObjectRetention,
71    notification_manager: &'a NotificationManager,
72    table_committed_epoch_notifiers: Option<&'a Mutex<TableCommittedEpochNotifiers>>,
73    meta_metrics: &'a MetaMetrics,
74    version_stat_tx: &'a tokio::sync::mpsc::UnboundedSender<Arc<HummockVersion>>,
75
76    pre_applied_version: Option<(
77        HummockVersion,
78        Vec<HummockVersionDelta>,
79        TableChangeLogTransactionDelta,
80    )>,
81    disable_apply_to_txn: bool,
82    opts: &'a MetaOpts,
83}
84
85impl<'a> HummockVersionTransaction<'a> {
86    pub(super) fn new(
87        version: &'a mut Arc<HummockVersion>,
88        deltas: &'a mut BTreeMap<HummockVersionId, HummockVersionDelta>,
89        table_change_log: &'a mut HashMap<TableId, TableChangeLog>,
90        change_log_retention: &'a super::gc::change_log_retention::ChangeLogObjectRetention,
91        notification_manager: &'a NotificationManager,
92        table_committed_epoch_notifiers: Option<&'a Mutex<TableCommittedEpochNotifiers>>,
93        meta_metrics: &'a MetaMetrics,
94        opts: &'a MetaOpts,
95        version_stat_tx: &'a tokio::sync::mpsc::UnboundedSender<Arc<HummockVersion>>,
96    ) -> Self {
97        Self {
98            orig_version: version,
99            orig_deltas: deltas,
100            orig_table_change_log: table_change_log,
101            change_log_retention,
102            pre_applied_version: None,
103            disable_apply_to_txn: false,
104            notification_manager,
105            table_committed_epoch_notifiers,
106            meta_metrics,
107            opts,
108            version_stat_tx,
109        }
110    }
111
112    pub(super) fn disable_apply_to_txn(&mut self) {
113        assert!(
114            self.pre_applied_version.is_none(),
115            "should only call disable at the beginning of txn"
116        );
117        self.disable_apply_to_txn = true;
118    }
119
120    pub(super) fn latest_version(&self) -> &HummockVersion {
121        if let Some((version, _, _)) = &self.pre_applied_version {
122            version
123        } else {
124            self.orig_version.as_ref()
125        }
126    }
127
128    pub(super) fn new_delta<'b>(&'b mut self) -> SingleDeltaTransaction<'a, 'b> {
129        let delta = self.latest_version().version_delta_after();
130        SingleDeltaTransaction {
131            version_txn: self,
132            delta: Some((delta, HashMap::new())),
133        }
134    }
135
136    fn pre_apply(
137        &mut self,
138        delta: HummockVersionDelta,
139        change_log_updates: HashMap<TableId, EpochNewChangeLog>,
140    ) {
141        let (version, deltas, table_change_log_delta) =
142            self.pre_applied_version.get_or_insert_with(|| {
143                (
144                    self.orig_version.as_ref().clone(),
145                    Vec::with_capacity(1),
146                    TableChangeLogTransactionDelta::default(),
147                )
148            });
149        let changed_table_info = version.apply_version_delta(&delta);
150        // The in-memory change logs are only updated after the metastore transaction succeeds, so
151        // complete deletion is derived from the original state. A deletion that becomes eligible
152        // after multiple deltas in one transaction may be deferred to the next transaction.
153        let delete_all = HummockVersion::collect_gc_change_log_delta(
154            self.orig_table_change_log.keys(),
155            &change_log_updates,
156            &delta.removed_table_ids,
157            &delta.state_table_info_delta,
158            &changed_table_info,
159        );
160        table_change_log_delta.delete_all.extend(delete_all);
161        if !change_log_updates.is_empty() {
162            table_change_log_delta.updates.push(change_log_updates);
163        }
164        deltas.push(delta);
165    }
166
167    /// Returns a duplicate delta, used by time travel.
168    pub(super) fn pre_commit_epoch(
169        &mut self,
170        tables_to_commit: &HashMap<TableId, u64>,
171        new_compaction_groups: Vec<CompactionGroup>,
172        group_id_to_sub_levels: BTreeMap<CompactionGroupId, Vec<Vec<SstableInfo>>>,
173        new_table_ids: &HashMap<TableId, CompactionGroupId>,
174        new_table_watermarks: HashMap<TableId, TableWatermarks>,
175        change_log_delta: HashMap<TableId, EpochNewChangeLog>,
176        vector_index_delta: HashMap<TableId, VectorIndexDelta>,
177        group_id_to_truncate_tables: HashMap<CompactionGroupId, HashSet<TableId>>,
178    ) -> HummockVersionDelta {
179        let mut new_version_delta = self.new_delta();
180        new_version_delta.new_table_watermarks = new_table_watermarks;
181        new_version_delta.set_change_log_delta(change_log_delta);
182        new_version_delta.vector_index_delta = vector_index_delta;
183
184        for compaction_group in &new_compaction_groups {
185            let group_deltas = &mut new_version_delta
186                .group_deltas
187                .entry(compaction_group.group_id())
188                .or_default()
189                .group_deltas;
190
191            #[expect(deprecated)]
192            group_deltas.push(GroupDelta::GroupConstruct(Box::new(GroupConstruct {
193                group_config: Some(compaction_group.compaction_config().as_ref().clone()),
194                group_id: compaction_group.group_id(),
195                parent_group_id: StaticCompactionGroupId::NewCompactionGroup as CompactionGroupId,
196                new_sst_start_id: HummockSstableId::default(), // No need to set it when `NewCompactionGroup`
197                table_ids: vec![],
198                version: CompatibilityVersion::LATEST as _,
199                split_key: None,
200            })));
201        }
202
203        // Append SSTs to a new version.
204        for (compaction_group_id, sub_levels) in group_id_to_sub_levels {
205            let group_deltas = &mut new_version_delta
206                .group_deltas
207                .entry(compaction_group_id)
208                .or_default()
209                .group_deltas;
210
211            for sub_level in sub_levels {
212                group_deltas.push(GroupDelta::NewL0SubLevel(sub_level));
213            }
214        }
215
216        for (compaction_group_id, table_ids) in group_id_to_truncate_tables {
217            let group_deltas = &mut new_version_delta
218                .group_deltas
219                .entry(compaction_group_id)
220                .or_default()
221                .group_deltas;
222
223            group_deltas.push(GroupDelta::PruneTableIdsFromSsts(
224                table_ids.into_iter().collect(),
225            ));
226        }
227
228        // update state table info
229        new_version_delta.with_latest_version(|version, delta| {
230            for (table_id, cg_id) in new_table_ids {
231                assert!(
232                    !version.state_table_info.info().contains_key(table_id),
233                    "newly added table exists previously: {:?}",
234                    table_id
235                );
236                let committed_epoch = *tables_to_commit.get(table_id).expect("newly added table must exist in tables_to_commit");
237                delta.state_table_info_delta.insert(
238                    *table_id,
239                    StateTableInfoDelta {
240                        committed_epoch,
241                        compaction_group_id: *cg_id,
242                    },
243                );
244            }
245
246            for (table_id, committed_epoch) in tables_to_commit {
247                if new_table_ids.contains_key(table_id) {
248                    continue;
249                }
250                let info = version.state_table_info.info().get(table_id).unwrap_or_else(|| {
251                    panic!("tables_to_commit {:?} contains table_id {} that is not newly added but not exists previously", tables_to_commit, table_id);
252                });
253                assert!(delta
254                    .state_table_info_delta
255                    .insert(
256                        *table_id,
257                        StateTableInfoDelta {
258                            committed_epoch: *committed_epoch,
259                            compaction_group_id: info.compaction_group_id,
260                        }
261                    )
262                    .is_none());
263            }
264        });
265
266        let time_travel_delta = (*new_version_delta).clone();
267        new_version_delta.pre_apply();
268        time_travel_delta
269    }
270}
271
272impl InMemValTransaction for HummockVersionTransaction<'_> {
273    fn commit(self) {
274        if let Some((version, deltas, table_change_log_delta)) = self.pre_applied_version {
275            *self.orig_version = Arc::new(version);
276            for change_log_delta in table_change_log_delta.updates {
277                HummockVersion::apply_change_log_delta(
278                    self.orig_table_change_log,
279                    &change_log_delta,
280                );
281            }
282            for table_id in table_change_log_delta.delete_all {
283                if let Some(change_log) = self.orig_table_change_log.remove(&table_id) {
284                    // Move the whole changelog into retention. GC enumerates its object
285                    // IDs later, outside the tracker mutex and this versioning write lock.
286                    self.change_log_retention
287                        .retain_batch(RetainedChangeLogBatch::ChangeLog(Arc::new(change_log)));
288                }
289            }
290
291            if !self.disable_apply_to_txn {
292                let pb_deltas = deltas.iter().map(|delta| delta.to_protobuf()).collect();
293                self.notification_manager.notify_hummock(
294                    Operation::Add,
295                    Info::HummockVersionDeltas(risingwave_pb::hummock::HummockVersionDeltas {
296                        version_deltas: pb_deltas,
297                    }),
298                );
299                self.notification_manager.notify_frontend_without_version(
300                    Operation::Update,
301                    Info::HummockVersionDeltas(HummockVersionDeltas {
302                        version_deltas: deltas
303                            .iter()
304                            .map(|delta| {
305                                FrontendHummockVersionDelta::from_delta(delta).to_protobuf()
306                            })
307                            .collect(),
308                    }),
309                );
310                if let Some(table_committed_epoch_notifiers) = self.table_committed_epoch_notifiers
311                {
312                    table_committed_epoch_notifiers
313                        .lock()
314                        .notify_deltas(&deltas);
315                }
316            }
317
318            for delta in deltas {
319                assert!(self.orig_deltas.insert(delta.id, delta.clone()).is_none());
320            }
321
322            trigger_delta_log_stats(self.meta_metrics, self.orig_deltas.len());
323            let _ = self.version_stat_tx.send(self.orig_version.clone());
324        }
325    }
326}
327
328impl<TXN> ValTransaction<TXN> for HummockVersionTransaction<'_>
329where
330    TXN: ConnectionTrait,
331    HummockVersionDelta: Transactional<TXN>,
332    HummockVersionStats: Transactional<TXN>,
333{
334    async fn apply_to_txn(&self, txn: &mut TXN) -> MetadataModelResult<()> {
335        if self.disable_apply_to_txn {
336            return Ok(());
337        }
338        if let Some((_, deltas, table_change_log_delta)) = &self.pre_applied_version {
339            // These upsert_in_transaction can be batched. However, we know len(deltas) is always 1 currently.
340            for delta in deltas {
341                delta.upsert_in_transaction(txn).await?;
342            }
343
344            let insert_batch_size = self.opts.table_change_log_insert_batch_size as usize;
345            use futures::stream::{self, StreamExt};
346            use sea_orm::{ColumnTrait, Condition, QueryFilter};
347            let insert_iter = table_change_log_delta
348                .updates
349                .iter()
350                .flat_map(|updates| updates.iter())
351                .map(|(table_id, new_log)| (*table_id, new_log));
352            let mut stream = stream::iter(insert_iter).chunks(insert_batch_size);
353            while let Some(change_log_batch) = stream.next().await {
354                let insert_many = change_log_batch
355                    .into_iter()
356                    .map(|(table_id, change_log)| {
357                        to_table_change_log_meta_store_model(table_id, change_log)
358                    })
359                    .collect::<Vec<_>>();
360                risingwave_meta_model::hummock_table_change_log::Entity::insert_many(insert_many)
361                    .on_empty_do_nothing()
362                    .exec(txn)
363                    .await?;
364            }
365
366            let delete_batch_size = self.opts.table_change_log_delete_batch_size as usize;
367            let delete_iter = table_change_log_delta.delete_all.iter().copied();
368
369            let mut stream = stream::iter(delete_iter).chunks(delete_batch_size);
370            while let Some(change_log_batch) = stream.next().await {
371                let mut condition = Condition::any();
372                for table_id in change_log_batch {
373                    let table_condition = Condition::all().add(
374                        risingwave_meta_model::hummock_table_change_log::Column::TableId
375                            .eq(table_id),
376                    );
377                    condition = condition.add(table_condition);
378                }
379                risingwave_meta_model::hummock_table_change_log::Entity::delete_many()
380                    .filter(condition)
381                    .exec(txn)
382                    .await?;
383            }
384        }
385        Ok(())
386    }
387}
388
389pub(super) struct SingleDeltaTransaction<'a, 'b> {
390    version_txn: &'b mut HummockVersionTransaction<'a>,
391    delta: Option<(HummockVersionDelta, HashMap<TableId, EpochNewChangeLog>)>,
392}
393
394impl SingleDeltaTransaction<'_, '_> {
395    pub(super) fn latest_version(&self) -> &HummockVersion {
396        self.version_txn.latest_version()
397    }
398
399    fn set_change_log_delta(&mut self, change_log_delta: HashMap<TableId, EpochNewChangeLog>) {
400        self.delta.as_mut().expect("should exist").1 = change_log_delta;
401    }
402
403    pub(super) fn pre_apply(mut self) {
404        let (delta, change_log_delta) = self.delta.take().unwrap();
405        self.version_txn.pre_apply(delta, change_log_delta);
406    }
407
408    pub(super) fn with_latest_version(
409        &mut self,
410        f: impl FnOnce(&HummockVersion, &mut HummockVersionDelta),
411    ) {
412        f(
413            self.version_txn.latest_version(),
414            &mut self.delta.as_mut().expect("should exist").0,
415        )
416    }
417}
418
419impl Deref for SingleDeltaTransaction<'_, '_> {
420    type Target = HummockVersionDelta;
421
422    fn deref(&self) -> &Self::Target {
423        &self.delta.as_ref().expect("should exist").0
424    }
425}
426
427impl DerefMut for SingleDeltaTransaction<'_, '_> {
428    fn deref_mut(&mut self) -> &mut Self::Target {
429        &mut self.delta.as_mut().expect("should exist").0
430    }
431}
432
433impl Drop for SingleDeltaTransaction<'_, '_> {
434    fn drop(&mut self) {
435        if let Some((delta, change_log_delta)) = self.delta.take() {
436            self.version_txn.pre_apply(delta, change_log_delta);
437        }
438    }
439}
440
441pub(super) struct HummockVersionStatsTransaction<'a> {
442    stats: VarTransaction<'a, HummockVersionStats>,
443    notification_manager: &'a NotificationManager,
444}
445
446impl<'a> HummockVersionStatsTransaction<'a> {
447    pub(super) fn new(
448        stats: &'a mut HummockVersionStats,
449        notification_manager: &'a NotificationManager,
450    ) -> Self {
451        Self {
452            stats: VarTransaction::new(stats),
453            notification_manager,
454        }
455    }
456}
457
458impl InMemValTransaction for HummockVersionStatsTransaction<'_> {
459    fn commit(self) {
460        if self.stats.has_new_value() {
461            let stats = self.stats.clone();
462            self.stats.commit();
463            self.notification_manager
464                .notify_frontend_without_version(Operation::Update, Info::HummockStats(stats));
465        }
466    }
467}
468
469impl<TXN> ValTransaction<TXN> for HummockVersionStatsTransaction<'_>
470where
471    TXN: ConnectionTrait,
472    HummockVersionStats: Transactional<TXN>,
473{
474    async fn apply_to_txn(&self, txn: &mut TXN) -> MetadataModelResult<()> {
475        self.stats.apply_to_txn(txn).await
476    }
477}
478
479impl Deref for HummockVersionStatsTransaction<'_> {
480    type Target = HummockVersionStats;
481
482    fn deref(&self) -> &Self::Target {
483        self.stats.deref()
484    }
485}
486
487impl DerefMut for HummockVersionStatsTransaction<'_> {
488    fn deref_mut(&mut self) -> &mut Self::Target {
489        self.stats.deref_mut()
490    }
491}
492
493#[cfg(test)]
494mod tests {
495    use itertools::Itertools;
496    use risingwave_hummock_sdk::change_log::EpochNewChangeLog;
497    use risingwave_pb::hummock::StateTableInfo;
498
499    use super::*;
500
501    fn new_change_log(checkpoint_epoch: u64) -> EpochNewChangeLog {
502        EpochNewChangeLog {
503            new_value: vec![],
504            old_value: vec![],
505            non_checkpoint_epochs: vec![],
506            checkpoint_epoch,
507        }
508    }
509
510    #[test]
511    fn test_apply_change_log_delta() {
512        let table_id = TableId::new(1);
513        let mut table_change_logs = HashMap::from([(
514            table_id,
515            TableChangeLog::new([new_change_log(1), new_change_log(2)]),
516        )]);
517        HummockVersion::apply_change_log_delta(
518            &mut table_change_logs,
519            &HashMap::from([(table_id, new_change_log(3))]),
520        );
521
522        assert_eq!(
523            table_change_logs[&table_id].epochs().collect_vec(),
524            vec![1, 2, 3]
525        );
526    }
527
528    #[test]
529    fn test_collect_gc_change_log_delta() {
530        let table_id = TableId::new(1);
531        let removed_table_id = TableId::new(2);
532        let current_table_ids = HashSet::from([table_id, removed_table_id]);
533        let state_table_info_delta = HashMap::from([(
534            table_id,
535            StateTableInfoDelta {
536                committed_epoch: 2,
537                compaction_group_id: 1.into(),
538            },
539        )]);
540        let changed_table_info = HashMap::from([(
541            table_id,
542            Some(StateTableInfo {
543                committed_epoch: 1,
544                compaction_group_id: 1.into(),
545            }),
546        )]);
547
548        assert_eq!(
549            HummockVersion::collect_gc_change_log_delta(
550                current_table_ids.iter(),
551                &HashMap::<TableId, EpochNewChangeLog>::new(),
552                &HashSet::from([removed_table_id]),
553                &state_table_info_delta,
554                &changed_table_info,
555            ),
556            HashSet::from([table_id, removed_table_id])
557        );
558        assert_eq!(
559            HummockVersion::collect_gc_change_log_delta(
560                current_table_ids.iter(),
561                &HashMap::from([(table_id, new_change_log(2))]),
562                &HashSet::new(),
563                &state_table_info_delta,
564                &changed_table_info,
565            ),
566            HashSet::new()
567        );
568    }
569}