risingwave_meta/hummock/manager/
transaction.rs1use std::collections::{BTreeMap, HashMap};
16use std::ops::{Deref, DerefMut};
17
18use parking_lot::Mutex;
19use risingwave_common::catalog::TableId;
20use risingwave_hummock_sdk::change_log::ChangeLogDelta;
21use risingwave_hummock_sdk::compaction_group::StaticCompactionGroupId;
22use risingwave_hummock_sdk::sstable_info::SstableInfo;
23use risingwave_hummock_sdk::table_watermark::TableWatermarks;
24use risingwave_hummock_sdk::vector_index::VectorIndexDelta;
25use risingwave_hummock_sdk::version::{GroupDelta, HummockVersion, HummockVersionDelta};
26use risingwave_hummock_sdk::{CompactionGroupId, FrontendHummockVersionDelta, HummockVersionId};
27use risingwave_pb::hummock::{
28 CompatibilityVersion, GroupConstruct, HummockVersionDeltas, HummockVersionStats,
29 StateTableInfoDelta,
30};
31use risingwave_pb::meta::subscribe_response::{Info, Operation};
32
33use super::TableCommittedEpochNotifiers;
34use crate::hummock::model::CompactionGroup;
35use crate::manager::NotificationManager;
36use crate::model::{
37 InMemValTransaction, MetadataModelResult, Transactional, ValTransaction, VarTransaction,
38};
39use crate::rpc::metrics::MetaMetrics;
40
41fn trigger_delta_log_stats(metrics: &MetaMetrics, total_number: usize) {
42 metrics.delta_log_count.set(total_number as _);
43}
44
45fn trigger_version_stat(metrics: &MetaMetrics, current_version: &HummockVersion) {
46 metrics
47 .version_size
48 .set(current_version.estimated_encode_len() as i64);
49 metrics
50 .current_version_id
51 .set(current_version.id.to_u64() as i64);
52}
53
54pub(super) struct HummockVersionTransaction<'a> {
55 orig_version: &'a mut HummockVersion,
56 orig_deltas: &'a mut BTreeMap<HummockVersionId, HummockVersionDelta>,
57 notification_manager: &'a NotificationManager,
58 table_committed_epoch_notifiers: Option<&'a Mutex<TableCommittedEpochNotifiers>>,
59 meta_metrics: &'a MetaMetrics,
60
61 pre_applied_version: Option<(HummockVersion, Vec<HummockVersionDelta>)>,
62 disable_apply_to_txn: bool,
63}
64
65impl<'a> HummockVersionTransaction<'a> {
66 pub(super) fn new(
67 version: &'a mut HummockVersion,
68 deltas: &'a mut BTreeMap<HummockVersionId, HummockVersionDelta>,
69 notification_manager: &'a NotificationManager,
70 table_committed_epoch_notifiers: Option<&'a Mutex<TableCommittedEpochNotifiers>>,
71 meta_metrics: &'a MetaMetrics,
72 ) -> Self {
73 Self {
74 orig_version: version,
75 orig_deltas: deltas,
76 pre_applied_version: None,
77 disable_apply_to_txn: false,
78 notification_manager,
79 table_committed_epoch_notifiers,
80 meta_metrics,
81 }
82 }
83
84 pub(super) fn disable_apply_to_txn(&mut self) {
85 assert!(
86 self.pre_applied_version.is_none(),
87 "should only call disable at the beginning of txn"
88 );
89 self.disable_apply_to_txn = true;
90 }
91
92 pub(super) fn latest_version(&self) -> &HummockVersion {
93 if let Some((version, _)) = &self.pre_applied_version {
94 version
95 } else {
96 self.orig_version
97 }
98 }
99
100 pub(super) fn new_delta<'b>(&'b mut self) -> SingleDeltaTransaction<'a, 'b> {
101 let delta = self.latest_version().version_delta_after();
102 SingleDeltaTransaction {
103 version_txn: self,
104 delta: Some(delta),
105 }
106 }
107
108 fn pre_apply(&mut self, delta: HummockVersionDelta) {
109 let (version, deltas) = self
110 .pre_applied_version
111 .get_or_insert_with(|| (self.orig_version.clone(), Vec::with_capacity(1)));
112 version.apply_version_delta(&delta);
113 deltas.push(delta);
114 }
115
116 pub(super) fn pre_commit_epoch(
118 &mut self,
119 tables_to_commit: &HashMap<TableId, u64>,
120 new_compaction_groups: Vec<CompactionGroup>,
121 group_id_to_sub_levels: BTreeMap<CompactionGroupId, Vec<Vec<SstableInfo>>>,
122 new_table_ids: &HashMap<TableId, CompactionGroupId>,
123 new_table_watermarks: HashMap<TableId, TableWatermarks>,
124 change_log_delta: HashMap<TableId, ChangeLogDelta>,
125 vector_index_delta: HashMap<TableId, VectorIndexDelta>,
126 ) -> HummockVersionDelta {
127 let mut new_version_delta = self.new_delta();
128 new_version_delta.new_table_watermarks = new_table_watermarks;
129 new_version_delta.change_log_delta = change_log_delta;
130 new_version_delta.vector_index_delta = vector_index_delta;
131
132 for compaction_group in &new_compaction_groups {
133 let group_deltas = &mut new_version_delta
134 .group_deltas
135 .entry(compaction_group.group_id())
136 .or_default()
137 .group_deltas;
138
139 #[expect(deprecated)]
140 group_deltas.push(GroupDelta::GroupConstruct(Box::new(GroupConstruct {
141 group_config: Some(compaction_group.compaction_config().as_ref().clone()),
142 group_id: compaction_group.group_id(),
143 parent_group_id: StaticCompactionGroupId::NewCompactionGroup as CompactionGroupId,
144 new_sst_start_id: 0, table_ids: vec![],
146 version: CompatibilityVersion::LATEST as _,
147 split_key: None,
148 })));
149 }
150
151 for (compaction_group_id, sub_levels) in group_id_to_sub_levels {
153 let group_deltas = &mut new_version_delta
154 .group_deltas
155 .entry(compaction_group_id)
156 .or_default()
157 .group_deltas;
158
159 for sub_level in sub_levels {
160 group_deltas.push(GroupDelta::NewL0SubLevel(sub_level));
161 }
162 }
163
164 new_version_delta.with_latest_version(|version, delta| {
166 for (table_id, cg_id) in new_table_ids {
167 assert!(
168 !version.state_table_info.info().contains_key(table_id),
169 "newly added table exists previously: {:?}",
170 table_id
171 );
172 let committed_epoch = *tables_to_commit.get(table_id).expect("newly added table must exist in tables_to_commit");
173 delta.state_table_info_delta.insert(
174 *table_id,
175 StateTableInfoDelta {
176 committed_epoch,
177 compaction_group_id: *cg_id,
178 },
179 );
180 }
181
182 for (table_id, committed_epoch) in tables_to_commit {
183 if new_table_ids.contains_key(table_id) {
184 continue;
185 }
186 let info = version.state_table_info.info().get(table_id).unwrap_or_else(|| {
187 panic!("tables_to_commit {:?} contains table_id {} that is not newly added but not exists previously", tables_to_commit, table_id);
188 });
189 assert!(delta
190 .state_table_info_delta
191 .insert(
192 *table_id,
193 StateTableInfoDelta {
194 committed_epoch: *committed_epoch,
195 compaction_group_id: info.compaction_group_id,
196 }
197 )
198 .is_none());
199 }
200 });
201
202 let time_travel_delta = (*new_version_delta).clone();
203 new_version_delta.pre_apply();
204 time_travel_delta
205 }
206}
207
208impl InMemValTransaction for HummockVersionTransaction<'_> {
209 fn commit(self) {
210 if let Some((version, deltas)) = self.pre_applied_version {
211 *self.orig_version = version;
212 if !self.disable_apply_to_txn {
213 let pb_deltas = deltas.iter().map(|delta| delta.to_protobuf()).collect();
214 self.notification_manager.notify_hummock_without_version(
215 Operation::Add,
216 Info::HummockVersionDeltas(risingwave_pb::hummock::HummockVersionDeltas {
217 version_deltas: pb_deltas,
218 }),
219 );
220 self.notification_manager.notify_frontend_without_version(
221 Operation::Update,
222 Info::HummockVersionDeltas(HummockVersionDeltas {
223 version_deltas: deltas
224 .iter()
225 .map(|delta| {
226 FrontendHummockVersionDelta::from_delta(delta).to_protobuf()
227 })
228 .collect(),
229 }),
230 );
231 if let Some(table_committed_epoch_notifiers) = self.table_committed_epoch_notifiers
232 {
233 table_committed_epoch_notifiers
234 .lock()
235 .notify_deltas(&deltas);
236 }
237 }
238 for delta in deltas {
239 assert!(self.orig_deltas.insert(delta.id, delta.clone()).is_none());
240 }
241
242 trigger_delta_log_stats(self.meta_metrics, self.orig_deltas.len());
243 trigger_version_stat(self.meta_metrics, self.orig_version);
244 }
245 }
246}
247
248impl<TXN> ValTransaction<TXN> for HummockVersionTransaction<'_>
249where
250 HummockVersionDelta: Transactional<TXN>,
251 HummockVersionStats: Transactional<TXN>,
252{
253 async fn apply_to_txn(&self, txn: &mut TXN) -> MetadataModelResult<()> {
254 if self.disable_apply_to_txn {
255 return Ok(());
256 }
257 for delta in self
258 .pre_applied_version
259 .iter()
260 .flat_map(|(_, deltas)| deltas.iter())
261 {
262 delta.upsert_in_transaction(txn).await?;
263 }
264 Ok(())
265 }
266}
267
268pub(super) struct SingleDeltaTransaction<'a, 'b> {
269 version_txn: &'b mut HummockVersionTransaction<'a>,
270 delta: Option<HummockVersionDelta>,
271}
272
273impl SingleDeltaTransaction<'_, '_> {
274 pub(super) fn latest_version(&self) -> &HummockVersion {
275 self.version_txn.latest_version()
276 }
277
278 pub(super) fn pre_apply(mut self) {
279 self.version_txn.pre_apply(self.delta.take().unwrap());
280 }
281
282 pub(super) fn with_latest_version(
283 &mut self,
284 f: impl FnOnce(&HummockVersion, &mut HummockVersionDelta),
285 ) {
286 f(
287 self.version_txn.latest_version(),
288 self.delta.as_mut().expect("should exist"),
289 )
290 }
291}
292
293impl Deref for SingleDeltaTransaction<'_, '_> {
294 type Target = HummockVersionDelta;
295
296 fn deref(&self) -> &Self::Target {
297 self.delta.as_ref().expect("should exist")
298 }
299}
300
301impl DerefMut for SingleDeltaTransaction<'_, '_> {
302 fn deref_mut(&mut self) -> &mut Self::Target {
303 self.delta.as_mut().expect("should exist")
304 }
305}
306
307impl Drop for SingleDeltaTransaction<'_, '_> {
308 fn drop(&mut self) {
309 if let Some(delta) = self.delta.take() {
310 self.version_txn.pre_apply(delta);
311 }
312 }
313}
314
315pub(super) struct HummockVersionStatsTransaction<'a> {
316 stats: VarTransaction<'a, HummockVersionStats>,
317 notification_manager: &'a NotificationManager,
318}
319
320impl<'a> HummockVersionStatsTransaction<'a> {
321 pub(super) fn new(
322 stats: &'a mut HummockVersionStats,
323 notification_manager: &'a NotificationManager,
324 ) -> Self {
325 Self {
326 stats: VarTransaction::new(stats),
327 notification_manager,
328 }
329 }
330}
331
332impl InMemValTransaction for HummockVersionStatsTransaction<'_> {
333 fn commit(self) {
334 if self.stats.has_new_value() {
335 let stats = self.stats.clone();
336 self.stats.commit();
337 self.notification_manager
338 .notify_frontend_without_version(Operation::Update, Info::HummockStats(stats));
339 }
340 }
341}
342
343impl<TXN> ValTransaction<TXN> for HummockVersionStatsTransaction<'_>
344where
345 HummockVersionStats: Transactional<TXN>,
346{
347 async fn apply_to_txn(&self, txn: &mut TXN) -> MetadataModelResult<()> {
348 self.stats.apply_to_txn(txn).await
349 }
350}
351
352impl Deref for HummockVersionStatsTransaction<'_> {
353 type Target = HummockVersionStats;
354
355 fn deref(&self) -> &Self::Target {
356 self.stats.deref()
357 }
358}
359
360impl DerefMut for HummockVersionStatsTransaction<'_> {
361 fn deref_mut(&mut self) -> &mut Self::Target {
362 self.stats.deref_mut()
363 }
364}