Skip to main content

risingwave_frontend/scheduler/
snapshot.rs

1// Copyright 2023 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, 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/// The storage snapshot to read from in a query, which can be freely cloned.
39#[derive(Clone)]
40pub enum ReadSnapshot {
41    /// A frontend-pinned snapshot.
42    FrontendPinned {
43        snapshot: PinnedSnapshotRef,
44    },
45
46    ReadUncommitted,
47
48    /// Resolve a committed snapshot for each storage read at the serving node.
49    LatestCommitted {
50        hummock_version_id: HummockVersionId,
51    },
52
53    /// Other arbitrary epoch, e.g. user specified.
54    /// Availability and consistency of underlying data should be guaranteed accordingly.
55    /// Currently it's only used for querying meta snapshot backup.
56    Other(Epoch),
57}
58
59impl ReadSnapshot {
60    /// Get the [`BatchQueryEpoch`] for this snapshot.
61    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    /// Returns true if this snapshot is a barrier read.
161    pub fn support_barrier_read(&self) -> bool {
162        matches!(self, ReadSnapshot::ReadUncommitted)
163    }
164}
165
166// DO NOT implement `Clone` for `PinnedSnapshot` because it's a "resource" that should always be a
167// singleton for each snapshot. Use `PinnedSnapshotRef` instead.
168pub 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
178/// A reference to a frontend-pinned snapshot.
179pub 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        // use the min committed epoch of tables involved in the scan
187        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
217/// Returns an invalid snapshot, used for initial values.
218fn invalid_snapshot() -> FrontendHummockVersion {
219    FrontendHummockVersion {
220        id: INVALID_VERSION_ID,
221        state_table_info: HummockVersionStateTableInfo::from_protobuf(&HashMap::new()),
222    }
223}
224
225/// Cache of hummock snapshot in meta.
226pub struct HummockSnapshotManager {
227    /// The latest snapshot synced from the meta service.
228    ///
229    /// The `max_committed_epoch` and `max_current_epoch` are pushed from meta node to reduce rpc
230    /// number.
231    ///
232    /// We have two epoch(committed and current), We only use `committed_epoch` to pin or unpin,
233    /// because `committed_epoch` always less or equal `current_epoch`, and the data with
234    /// `current_epoch` is always in the shared buffer, so it will never be gc before the data
235    /// of `committed_epoch`.
236    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    /// Acquire the latest snapshot by increasing its reference count.
260    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    /// Update the latest snapshot.
271    ///
272    /// Should only be called by the observer manager.
273    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    /// Wait until the latest snapshot is newer than the given one.
328    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        // Include every epoch-bearing read node, at both stage roots and nested children.
403        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    /// Verifies that an already-available seek epoch is observed immediately without waiting for
474    /// another version-update notification.
475    #[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}