risingwave_frontend/scheduler/
snapshot.rs1use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use anyhow::anyhow;
19use risingwave_common::catalog::TableId;
20use risingwave_common::util::epoch::{Epoch, INVALID_EPOCH};
21use risingwave_hummock_sdk::version::HummockVersionStateTableInfo;
22use risingwave_hummock_sdk::{
23 FrontendHummockVersion, FrontendHummockVersionDelta, HummockVersionId, INVALID_VERSION_ID,
24};
25use risingwave_pb::batch_plan::plan_node::NodeBody;
26use risingwave_pb::common::{
27 BatchQueryCommittedEpoch, BatchQueryEpoch, BatchQueryLatestCommittedEpoch, batch_query_epoch,
28};
29use risingwave_pb::hummock::{HummockVersionDeltas, StateTableInfoDelta};
30use tokio::sync::watch;
31
32use crate::error::{ErrorCode, RwError};
33use crate::expr::InlineNowProcTime;
34use crate::meta_client::FrontendMetaClient;
35use crate::scheduler::plan_fragmenter::{ExecutionPlanNode, Query};
36use crate::scheduler::{SchedulerError, SchedulerResult};
37
38#[derive(Clone)]
40pub enum ReadSnapshot {
41 FrontendPinned {
43 snapshot: PinnedSnapshotRef,
44 },
45
46 ReadUncommitted,
47
48 LatestCommitted {
50 hummock_version_id: HummockVersionId,
51 },
52
53 Other(Epoch),
57}
58
59impl ReadSnapshot {
60 fn batch_query_epoch(
62 &self,
63 read_storage_tables: &HashSet<TableId>,
64 ) -> Result<BatchQueryEpoch, SchedulerError> {
65 Ok(match self {
66 ReadSnapshot::FrontendPinned { snapshot } => BatchQueryEpoch {
67 epoch: Some(batch_query_epoch::Epoch::Committed(
68 BatchQueryCommittedEpoch {
69 epoch: snapshot.batch_query_epoch(read_storage_tables)?.0,
70 hummock_version_id: snapshot.value.id,
71 },
72 )),
73 },
74 ReadSnapshot::LatestCommitted { hummock_version_id } => BatchQueryEpoch {
75 epoch: Some(batch_query_epoch::Epoch::LatestCommitted(
76 BatchQueryLatestCommittedEpoch {
77 hummock_version_id: *hummock_version_id,
78 },
79 )),
80 },
81 ReadSnapshot::ReadUncommitted => BatchQueryEpoch {
82 epoch: Some(batch_query_epoch::Epoch::Current(Epoch::now().0)),
83 },
84 ReadSnapshot::Other(e) => BatchQueryEpoch {
85 epoch: Some(batch_query_epoch::Epoch::Backup(e.0)),
86 },
87 })
88 }
89
90 pub fn fill_batch_query_epoch(&self, query: &mut Query) -> SchedulerResult<()> {
91 fn on_node(
92 execution_plan_node: &mut ExecutionPlanNode,
93 f: &mut impl FnMut(&mut Option<BatchQueryEpoch>, TableId),
94 ) {
95 for node in &mut execution_plan_node.children {
96 on_node(node, f);
97 }
98 let (query_epoch, table_id) = match &mut execution_plan_node.node {
99 NodeBody::RowSeqScan(scan) => (
100 &mut scan.query_epoch,
101 scan.table_desc.as_ref().unwrap().table_id,
102 ),
103 NodeBody::DistributedLookupJoin(join) => (
104 &mut join.query_epoch,
105 join.inner_side_table_desc.as_ref().unwrap().table_id,
106 ),
107 NodeBody::LocalLookupJoin(join) => (
108 &mut join.query_epoch,
109 join.inner_side_table_desc.as_ref().unwrap().table_id,
110 ),
111 NodeBody::VectorIndexNearest(vector_index_read) => (
112 &mut vector_index_read.query_epoch,
113 vector_index_read.reader_desc.as_ref().unwrap().table_id,
114 ),
115 _ => {
116 return;
117 }
118 };
119 f(query_epoch, table_id);
120 }
121
122 fn on_query(query: &mut Query, mut f: impl FnMut(&mut Option<BatchQueryEpoch>, TableId)) {
123 for stage in query.stage_graph.stages.values_mut() {
124 on_node(&mut stage.root, &mut f);
125 }
126 }
127
128 let mut unspecified_epoch_table_ids = HashSet::new();
129 on_query(query, |query_epoch, table_id| {
130 if query_epoch.is_none() {
131 unspecified_epoch_table_ids.insert(table_id);
132 }
133 });
134
135 let query_epoch = self.batch_query_epoch(&unspecified_epoch_table_ids)?;
136
137 on_query(query, |node_query_epoch, _| {
138 if node_query_epoch.is_none() {
139 *node_query_epoch = Some(query_epoch);
140 }
141 });
142
143 Ok(())
144 }
145
146 pub fn inline_now_proc_time(&self) -> InlineNowProcTime {
147 let epoch = match self {
148 ReadSnapshot::FrontendPinned { snapshot } => snapshot
149 .value
150 .state_table_info
151 .max_table_committed_epoch()
152 .map(Epoch)
153 .unwrap_or_else(Epoch::now),
154 ReadSnapshot::ReadUncommitted | ReadSnapshot::LatestCommitted { .. } => Epoch::now(),
155 ReadSnapshot::Other(epoch) => *epoch,
156 };
157 InlineNowProcTime::new(epoch)
158 }
159
160 pub fn support_barrier_read(&self) -> bool {
162 matches!(self, ReadSnapshot::ReadUncommitted)
163 }
164}
165
166pub struct PinnedSnapshot {
169 value: FrontendHummockVersion,
170}
171
172impl std::fmt::Debug for PinnedSnapshot {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 self.value.fmt(f)
175 }
176}
177
178pub type PinnedSnapshotRef = Arc<PinnedSnapshot>;
180
181impl PinnedSnapshot {
182 fn batch_query_epoch(
183 &self,
184 read_storage_tables: &HashSet<TableId>,
185 ) -> Result<Epoch, SchedulerError> {
186 let epoch = read_storage_tables
188 .iter()
189 .map(|table_id| {
190 self.value
191 .state_table_info
192 .info()
193 .get(table_id)
194 .map(|info| Epoch(info.committed_epoch))
195 .ok_or_else(|| anyhow!("table id {table_id} may have been dropped"))
196 })
197 .try_fold(None, |prev_min_committed_epoch, committed_epoch| {
198 committed_epoch.map(|committed_epoch| {
199 if let Some(prev_min_committed_epoch) = prev_min_committed_epoch
200 && prev_min_committed_epoch <= committed_epoch
201 {
202 Some(prev_min_committed_epoch)
203 } else {
204 Some(committed_epoch)
205 }
206 })
207 })?
208 .unwrap_or_else(Epoch::now);
209 Ok(epoch)
210 }
211
212 pub fn version(&self) -> &FrontendHummockVersion {
213 &self.value
214 }
215}
216
217fn invalid_snapshot() -> FrontendHummockVersion {
219 FrontendHummockVersion {
220 id: INVALID_VERSION_ID,
221 state_table_info: HummockVersionStateTableInfo::from_protobuf(&HashMap::new()),
222 }
223}
224
225pub struct HummockSnapshotManager {
227 latest_snapshot: watch::Sender<PinnedSnapshotRef>,
237
238 version_update_notification_sender: watch::Sender<()>,
239}
240
241pub type HummockSnapshotManagerRef = Arc<HummockSnapshotManager>;
242
243impl HummockSnapshotManager {
244 pub fn new(_meta_client: Arc<dyn FrontendMetaClient>) -> Self {
245 let latest_snapshot = Arc::new(PinnedSnapshot {
246 value: invalid_snapshot(),
247 });
248
249 let (latest_snapshot, _) = watch::channel(latest_snapshot);
250
251 let (version_update_notification_sender, _) = watch::channel(());
252
253 Self {
254 latest_snapshot,
255 version_update_notification_sender,
256 }
257 }
258
259 pub fn acquire(&self) -> PinnedSnapshotRef {
261 self.latest_snapshot.borrow().clone()
262 }
263
264 pub fn init(&self, version: FrontendHummockVersion) {
265 self.version_update_notification_sender.send(()).ok();
266
267 self.update_inner(|_| Some(version));
268 }
269
270 pub fn update(&self, deltas: HummockVersionDeltas) {
274 self.update_inner(|old_snapshot| {
275 if deltas.version_deltas.is_empty() {
276 return None;
277 }
278 let mut snapshot = old_snapshot.clone();
279 for delta in deltas.version_deltas {
280 snapshot.apply_delta(FrontendHummockVersionDelta::from_protobuf(delta));
281 }
282 Some(snapshot)
283 });
284 self.version_update_notification_sender.send(()).ok();
285 }
286
287 pub fn add_table_for_test(&self, table_id: TableId) {
288 self.update_inner(|version| {
289 let mut version = version.clone();
290 version.id += 1;
291 version.state_table_info.apply_delta(
292 &HashMap::from_iter([(
293 table_id,
294 StateTableInfoDelta {
295 committed_epoch: INVALID_EPOCH,
296 compaction_group_id: 0.into(),
297 },
298 )]),
299 &HashSet::new(),
300 );
301 Some(version)
302 });
303 }
304
305 fn update_inner(
306 &self,
307 get_new_snapshot: impl FnOnce(&FrontendHummockVersion) -> Option<FrontendHummockVersion>,
308 ) {
309 self.latest_snapshot.send_if_modified(move |old_snapshot| {
310 let new_snapshot = get_new_snapshot(&old_snapshot.value);
311 let Some(snapshot) = new_snapshot else {
312 return false;
313 };
314 if snapshot.id <= old_snapshot.value.id {
315 assert_eq!(
316 snapshot.id, old_snapshot.value.id,
317 "receive stale frontend version"
318 );
319 return false;
320 }
321 *old_snapshot = Arc::new(PinnedSnapshot { value: snapshot });
322
323 true
324 });
325 }
326
327 pub async fn wait(&self, version_id: HummockVersionId) {
329 let mut rx = self.latest_snapshot.subscribe();
330 while rx.borrow_and_update().value.id < version_id {
331 rx.changed().await.unwrap();
332 }
333 }
334
335 pub async fn wait_table_change_log_notification(
336 &self,
337 table_id: TableId,
338 seek_timestamp: u64,
339 ) -> Result<(), RwError> {
340 let mut rx = self.version_update_notification_sender.subscribe();
341 loop {
342 if let Some(info) = self
343 .acquire()
344 .version()
345 .state_table_info
346 .info()
347 .get(&table_id)
348 {
349 if info.committed_epoch >= seek_timestamp {
350 break;
351 }
352 } else {
353 return Err(ErrorCode::InternalError(format!(
354 "Cursor dependent table deleted: table_id is {:?}",
355 table_id
356 ))
357 .into());
358 }
359 rx.changed()
360 .await
361 .map_err(|_| ErrorCode::InternalError("cursor notify channel is closed.".into()))?;
362 let _ = rx.borrow_and_update();
363 }
364 Ok(())
365 }
366}
367
368#[cfg(test)]
369mod tests {
370 use std::time::Duration;
371
372 use super::*;
373 use crate::test_utils::MockFrontendMetaClient;
374
375 #[test]
376 fn test_latest_committed_inlines_wall_clock() {
377 use crate::expr::{ExprRewriter, Now};
378
379 let before = Epoch::now().as_scalar();
380 let value = ReadSnapshot::LatestCommitted {
381 hummock_version_id: 123.into(),
382 }
383 .inline_now_proc_time()
384 .rewrite_now(Now);
385 let after = Epoch::now().as_scalar();
386 let value = value.as_literal().unwrap().get_data().as_ref().unwrap();
387 assert!(before.as_timestamptz() <= value.as_timestamptz());
388 assert!(value.as_timestamptz() <= after.as_timestamptz());
389 }
390
391 #[tokio::test]
392 async fn test_latest_committed_epoch_propagation() {
393 use risingwave_pb::batch_plan::{
394 DistributedLookupJoinNode, LocalLookupJoinNode, LogRowSeqScanNode, RowSeqScanNode,
395 VectorIndexNearestNode,
396 };
397
398 let mut query = crate::scheduler::distributed::tests::create_query().await;
399 let historical = BatchQueryEpoch {
400 epoch: Some(batch_query_epoch::Epoch::TimeTravel(123)),
401 };
402 let nodes = [
404 NodeBody::RowSeqScan(RowSeqScanNode {
405 table_desc: Some(Default::default()),
406 ..Default::default()
407 }),
408 NodeBody::LocalLookupJoin(LocalLookupJoinNode {
409 inner_side_table_desc: Some(Default::default()),
410 ..Default::default()
411 }),
412 NodeBody::DistributedLookupJoin(DistributedLookupJoinNode {
413 inner_side_table_desc: Some(Default::default()),
414 ..Default::default()
415 }),
416 NodeBody::VectorIndexNearest(VectorIndexNearestNode {
417 reader_desc: Some(Default::default()),
418 ..Default::default()
419 }),
420 NodeBody::RowSeqScan(RowSeqScanNode {
421 table_desc: Some(Default::default()),
422 query_epoch: Some(historical),
423 ..Default::default()
424 }),
425 NodeBody::LogRowSeqScan(LogRowSeqScanNode {
426 old_epoch: Some(historical),
427 new_epoch: Some(historical),
428 ..Default::default()
429 }),
430 ];
431 for stage in query.stage_graph.stages.values_mut() {
432 let template = stage.root.clone();
433 stage.root.children = nodes
434 .iter()
435 .map(|node| ExecutionPlanNode {
436 node: node.clone(),
437 children: vec![],
438 ..template.clone()
439 })
440 .collect();
441 }
442 let snapshot = ReadSnapshot::LatestCommitted {
443 hummock_version_id: 123.into(),
444 };
445 assert!(!snapshot.support_barrier_read());
446 snapshot.fill_batch_query_epoch(&mut query).unwrap();
447 let latest = Some(BatchQueryEpoch {
448 epoch: Some(batch_query_epoch::Epoch::LatestCommitted(
449 BatchQueryLatestCommittedEpoch {
450 hummock_version_id: 123.into(),
451 },
452 )),
453 });
454 for stage in query.stage_graph.stages.values() {
455 for (i, child) in stage.root.children.iter().enumerate() {
456 let epoch = match &child.node {
457 NodeBody::RowSeqScan(scan) => scan.query_epoch,
458 NodeBody::LocalLookupJoin(join) => join.query_epoch,
459 NodeBody::DistributedLookupJoin(join) => join.query_epoch,
460 NodeBody::VectorIndexNearest(vector) => vector.query_epoch,
461 NodeBody::LogRowSeqScan(log) => {
462 assert_eq!(log.old_epoch, Some(historical));
463 assert_eq!(log.new_epoch, Some(historical));
464 continue;
465 }
466 _ => unreachable!(),
467 };
468 assert_eq!(epoch, if i == 4 { Some(historical) } else { latest });
469 }
470 }
471 }
472
473 #[tokio::test]
476 async fn test_wait_table_change_log_notification_observes_existing_version() {
477 let manager = HummockSnapshotManager::new(Arc::new(MockFrontendMetaClient {}));
478 let table_id = TableId::new(1);
479 let committed_epoch = 42;
480 manager.add_table_for_test(table_id);
481 manager.update_inner(|version| {
482 let mut version = version.clone();
483 version.id += 1;
484 version.state_table_info.apply_delta(
485 &HashMap::from_iter([(
486 table_id,
487 StateTableInfoDelta {
488 committed_epoch,
489 compaction_group_id: 0.into(),
490 },
491 )]),
492 &HashSet::new(),
493 );
494 Some(version)
495 });
496
497 tokio::time::timeout(
498 Duration::from_secs(1),
499 manager.wait_table_change_log_notification(table_id, committed_epoch),
500 )
501 .await
502 .expect("an existing committed epoch must not wait for another notification")
503 .unwrap();
504 }
505}