Skip to main content

risingwave_frontend/optimizer/
optimizer_context.rs

1// Copyright 2022 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 core::fmt::Formatter;
16use std::cell::{Cell, RefCell, RefMut};
17use std::collections::HashMap;
18use std::marker::PhantomData;
19use std::rc::{Rc, Weak};
20use std::sync::Arc;
21
22use risingwave_common::id::SourceId;
23use risingwave_sqlparser::ast::{ExplainFormat, ExplainOptions, ExplainType};
24
25use super::property::WatermarkGroupId;
26use crate::error::Result;
27use crate::expr::{CorrelatedId, SessionTimezone};
28use crate::handler::HandlerArgs;
29use crate::optimizer::plan_node::generic::Share;
30use crate::optimizer::plan_node::{LogicalPlanRef, PlanNodeId, StreamPlanRef};
31use crate::session::SessionImpl;
32use crate::utils::{OverwriteOptions, WithOptions};
33use crate::{Explain, TableCatalog};
34
35const RESERVED_ID_NUM: u16 = 10000;
36
37type PhantomUnsend = PhantomData<Rc<()>>;
38
39/// The stable identity of a shared subplan.
40///
41/// Unlike [`PlanNodeId`], a `ShareId` survives rebuilding the wrapper plan node around a share.
42/// [`OptimizerContext`] tracks the current input used to rebuild wrappers after a DAG pass.
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
44pub struct ShareId(u32);
45
46#[derive(Debug)]
47pub(in crate::optimizer) struct ShareEntry<P> {
48    current: RefCell<P>,
49    plan_node_id: PlanNodeId,
50}
51
52impl<P> ShareEntry<P> {
53    fn update_current(&self, current: P) {
54        *self.current.borrow_mut() = current;
55    }
56
57    pub(in crate::optimizer) fn plan_node_id(&self) -> PlanNodeId {
58        self.plan_node_id
59    }
60}
61
62impl<P: Clone> ShareEntry<P> {
63    fn current(&self) -> P {
64        self.current.borrow().clone()
65    }
66}
67
68pub(in crate::optimizer) type ShareEntryRef<P> = Rc<ShareEntry<P>>;
69
70struct ShareTable<P> {
71    /// Weak entries avoid a reference cycle through `PlanBase::ctx` in the stored plans. A live
72    /// share handle owns the corresponding strong entry.
73    entries: HashMap<ShareId, Weak<ShareEntry<P>>>,
74}
75
76impl<P> Default for ShareTable<P> {
77    fn default() -> Self {
78        Self {
79            entries: HashMap::new(),
80        }
81    }
82}
83
84pub struct OptimizerContext {
85    session_ctx: Arc<SessionImpl>,
86    /// The original SQL string, used for debugging.
87    sql: Arc<str>,
88    /// Normalized SQL string. See [`HandlerArgs::normalize_sql`].
89    normalized_sql: String,
90    /// Explain options
91    explain_options: ExplainOptions,
92    /// Store the trace of optimizer
93    optimizer_trace: RefCell<Vec<String>>,
94    /// Store the optimized logical plan of optimizer
95    logical_explain: RefCell<Option<String>>,
96    /// Store options or properties from the `with` clause
97    with_options: WithOptions,
98    /// Store the Session Timezone and whether it was used.
99    session_timezone: RefCell<SessionTimezone>,
100    /// Total number of optimization rules have been applied.
101    total_rule_applied: RefCell<usize>,
102    /// Store the configs can be overwritten in with clause
103    /// if not specified, use the value from session variable.
104    overwrite_options: OverwriteOptions,
105    /// Mapping from Iceberg table identifier to the current snapshot and its RisingWave commit
106    /// boundary. Used to keep multiple scans of the same table consistent within one query.
107    iceberg_snapshot_info_map: RefCell<HashMap<SourceId, Option<IcebergSnapshotInfo>>>,
108    /// Batch materialized view candidates for exact-match rewriting.
109    batch_mview_candidates: RefCell<Vec<MaterializedViewCandidate>>,
110
111    /// Last assigned plan node ID.
112    last_plan_node_id: Cell<i32>,
113    /// Last assigned share ID.
114    last_share_id: Cell<u32>,
115    /// Last assigned correlated ID.
116    last_correlated_id: Cell<u32>,
117    /// Last assigned expr display ID.
118    last_expr_display_id: Cell<usize>,
119    /// Last assigned watermark group ID.
120    last_watermark_group_id: Cell<u32>,
121
122    /// Tracks the current input of each live share while DAG-aware passes rebuild wrappers.
123    logical_share_table: RefCell<ShareTable<LogicalPlanRef>>,
124    stream_share_table: RefCell<ShareTable<StreamPlanRef>>,
125
126    _phantom: PhantomUnsend,
127}
128
129#[derive(Clone, Debug)]
130pub struct MaterializedViewCandidate {
131    pub plan: LogicalPlanRef,
132    pub table: Arc<TableCatalog>,
133}
134
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136pub(crate) struct IcebergSnapshotInfo {
137    pub(crate) snapshot_id: i64,
138    pub(crate) commit_epoch: Option<u64>,
139}
140
141pub(in crate::optimizer) struct LastAssignedIds {
142    last_plan_node_id: i32,
143    last_correlated_id: u32,
144    last_expr_display_id: usize,
145    last_watermark_group_id: u32,
146}
147
148pub type OptimizerContextRef = Rc<OptimizerContext>;
149
150impl OptimizerContext {
151    /// Create a new [`OptimizerContext`] from the given [`HandlerArgs`], with empty
152    /// [`ExplainOptions`].
153    pub fn from_handler_args(handler_args: HandlerArgs) -> Result<Self> {
154        Self::new(handler_args, ExplainOptions::default())
155    }
156
157    /// Create a new [`OptimizerContext`] from the given [`HandlerArgs`] and [`ExplainOptions`].
158    pub fn new(mut handler_args: HandlerArgs, explain_options: ExplainOptions) -> Result<Self> {
159        let session_timezone = RefCell::new(SessionTimezone::new(
160            handler_args.session.config().timezone(),
161        ));
162        let overwrite_options = OverwriteOptions::new(&mut handler_args)?;
163        Ok(Self {
164            session_ctx: handler_args.session,
165            sql: handler_args.sql,
166            normalized_sql: handler_args.normalized_sql,
167            explain_options,
168            optimizer_trace: RefCell::new(vec![]),
169            logical_explain: RefCell::new(None),
170            with_options: handler_args.with_options,
171            session_timezone,
172            total_rule_applied: RefCell::new(0),
173            overwrite_options,
174            iceberg_snapshot_info_map: RefCell::new(HashMap::new()),
175            batch_mview_candidates: RefCell::new(Vec::new()),
176
177            last_plan_node_id: Cell::new(RESERVED_ID_NUM.into()),
178            last_share_id: Cell::new(0),
179            last_correlated_id: Cell::new(0),
180            last_expr_display_id: Cell::new(RESERVED_ID_NUM.into()),
181            last_watermark_group_id: Cell::new(RESERVED_ID_NUM.into()),
182
183            logical_share_table: RefCell::new(ShareTable::default()),
184            stream_share_table: RefCell::new(ShareTable::default()),
185
186            _phantom: Default::default(),
187        })
188    }
189
190    #[cfg(test)]
191    pub fn mock() -> OptimizerContextRef {
192        Self {
193            session_ctx: Arc::new(SessionImpl::mock()),
194            sql: Arc::from(""),
195            normalized_sql: "".to_owned(),
196            explain_options: ExplainOptions::default(),
197            optimizer_trace: RefCell::new(vec![]),
198            logical_explain: RefCell::new(None),
199            with_options: Default::default(),
200            session_timezone: RefCell::new(SessionTimezone::new("UTC".into())),
201            total_rule_applied: RefCell::new(0),
202            overwrite_options: OverwriteOptions::default(),
203            iceberg_snapshot_info_map: RefCell::new(HashMap::new()),
204            batch_mview_candidates: RefCell::new(Vec::new()),
205
206            last_plan_node_id: Cell::new(0),
207            last_share_id: Cell::new(0),
208            last_correlated_id: Cell::new(0),
209            last_expr_display_id: Cell::new(0),
210            last_watermark_group_id: Cell::new(0),
211
212            logical_share_table: RefCell::new(ShareTable::default()),
213            stream_share_table: RefCell::new(ShareTable::default()),
214
215            _phantom: Default::default(),
216        }
217        .into()
218    }
219
220    pub fn next_plan_node_id(&self) -> PlanNodeId {
221        self.last_plan_node_id.update(|id| id + 1);
222        PlanNodeId(self.last_plan_node_id.get())
223    }
224
225    fn next_share_id(&self) -> ShareId {
226        self.last_share_id.update(|id| id + 1);
227        ShareId(self.last_share_id.get())
228    }
229
230    fn share_entry<P>(
231        table: &RefCell<ShareTable<P>>,
232        share_id: ShareId,
233        convention: &str,
234    ) -> ShareEntryRef<P> {
235        table
236            .borrow()
237            .entries
238            .get(&share_id)
239            .unwrap_or_else(|| panic!("{convention} share {share_id:?} is not registered"))
240            .upgrade()
241            .unwrap_or_else(|| panic!("{convention} share {share_id:?} is no longer live"))
242    }
243
244    fn register_share<P: Clone>(&self, table: &RefCell<ShareTable<P>>, input: P) -> Share<P> {
245        let share_id = self.next_share_id();
246        let entry = Rc::new(ShareEntry {
247            current: RefCell::new(input.clone()),
248            plan_node_id: self.next_plan_node_id(),
249        });
250        table
251            .borrow_mut()
252            .entries
253            .try_insert(share_id, Rc::downgrade(&entry))
254            .expect("share id must be unique");
255        Share::new(share_id, input, entry)
256    }
257
258    fn share<P: Clone>(
259        &self,
260        table: &RefCell<ShareTable<P>>,
261        share_id: ShareId,
262        convention: &str,
263    ) -> Share<P> {
264        let entry = Self::share_entry(table, share_id, convention);
265        let input = entry.current();
266        Share::new(share_id, input, entry)
267    }
268
269    fn update_share<P>(
270        table: &RefCell<ShareTable<P>>,
271        share_id: ShareId,
272        new_input: P,
273        convention: &str,
274    ) {
275        let entry = Self::share_entry(table, share_id, convention);
276        entry.update_current(new_input);
277    }
278
279    pub(in crate::optimizer) fn register_logical_share(
280        &self,
281        input: LogicalPlanRef,
282    ) -> Share<LogicalPlanRef> {
283        self.register_share(&self.logical_share_table, input)
284    }
285
286    pub(in crate::optimizer) fn logical_share(&self, share_id: ShareId) -> Share<LogicalPlanRef> {
287        self.share(&self.logical_share_table, share_id, "logical")
288    }
289
290    pub(in crate::optimizer) fn update_logical_share(
291        &self,
292        share_id: ShareId,
293        new_input: LogicalPlanRef,
294    ) {
295        Self::update_share(&self.logical_share_table, share_id, new_input, "logical");
296    }
297
298    pub(in crate::optimizer) fn register_stream_share(
299        &self,
300        input: StreamPlanRef,
301    ) -> Share<StreamPlanRef> {
302        self.register_share(&self.stream_share_table, input)
303    }
304
305    pub(in crate::optimizer) fn update_stream_share(
306        &self,
307        share_id: ShareId,
308        new_input: StreamPlanRef,
309    ) {
310        Self::update_share(&self.stream_share_table, share_id, new_input, "stream");
311    }
312
313    pub fn next_correlated_id(&self) -> CorrelatedId {
314        self.last_correlated_id.update(|id| id + 1);
315        self.last_correlated_id.get()
316    }
317
318    pub fn next_expr_display_id(&self) -> usize {
319        self.last_expr_display_id.update(|id| id + 1);
320        self.last_expr_display_id.get()
321    }
322
323    pub fn next_watermark_group_id(&self) -> WatermarkGroupId {
324        self.last_watermark_group_id.update(|id| id + 1);
325        self.last_watermark_group_id.get()
326    }
327
328    pub(in crate::optimizer) fn backup_elem_ids(&self) -> LastAssignedIds {
329        LastAssignedIds {
330            last_plan_node_id: self.last_plan_node_id.get(),
331            last_correlated_id: self.last_correlated_id.get(),
332            last_expr_display_id: self.last_expr_display_id.get(),
333            last_watermark_group_id: self.last_watermark_group_id.get(),
334        }
335    }
336
337    /// This should only be called in [`crate::optimizer::plan_node::reorganize_elements_id`].
338    pub(in crate::optimizer) fn reset_elem_ids(&self) {
339        self.last_plan_node_id.set(0);
340        self.last_correlated_id.set(0);
341        self.last_expr_display_id.set(0);
342        self.last_watermark_group_id.set(0);
343    }
344
345    pub(in crate::optimizer) fn restore_elem_ids(&self, backup: LastAssignedIds) {
346        self.last_plan_node_id.set(backup.last_plan_node_id);
347        self.last_correlated_id.set(backup.last_correlated_id);
348        self.last_expr_display_id.set(backup.last_expr_display_id);
349        self.last_watermark_group_id
350            .set(backup.last_watermark_group_id);
351    }
352
353    pub fn add_rule_applied(&self, num: usize) {
354        *self.total_rule_applied.borrow_mut() += num;
355    }
356
357    pub fn total_rule_applied(&self) -> usize {
358        *self.total_rule_applied.borrow()
359    }
360
361    pub fn is_explain_verbose(&self) -> bool {
362        self.explain_options.verbose
363    }
364
365    pub fn is_explain_trace(&self) -> bool {
366        self.explain_options.trace
367    }
368
369    fn is_explain_logical(&self) -> bool {
370        self.explain_options.explain_type == ExplainType::Logical
371    }
372
373    pub fn trace(&self, str: impl Into<String>) {
374        // If explain type is logical, do not store the trace for any optimizations beyond logical.
375        if self.is_explain_logical() && self.logical_explain.borrow().is_some() {
376            return;
377        }
378        let mut optimizer_trace = self.optimizer_trace.borrow_mut();
379        let string = str.into();
380        tracing::info!(target: "explain_trace", "\n{}", string);
381        optimizer_trace.push(string);
382        optimizer_trace.push("\n".to_owned());
383    }
384
385    pub fn warn_to_user(&self, str: impl Into<String>) {
386        self.session_ctx().notice_to_user(str);
387    }
388
389    fn explain_plan_impl(&self, plan: &impl Explain) -> String {
390        match self.explain_options.explain_format {
391            ExplainFormat::Text => plan.explain_to_string(),
392            ExplainFormat::Json => plan.explain_to_json(),
393            ExplainFormat::Xml => plan.explain_to_xml(),
394            ExplainFormat::Yaml => plan.explain_to_yaml(),
395            ExplainFormat::Dot => plan.explain_to_dot(),
396        }
397    }
398
399    pub fn may_store_explain_logical(&self, plan: &LogicalPlanRef) {
400        if self.is_explain_logical() {
401            let str = self.explain_plan_impl(plan);
402            *self.logical_explain.borrow_mut() = Some(str);
403        }
404    }
405
406    pub fn take_logical(&self) -> Option<String> {
407        self.logical_explain.borrow_mut().take()
408    }
409
410    pub fn take_trace(&self) -> Vec<String> {
411        std::mem::take(&mut *self.optimizer_trace.borrow_mut())
412    }
413
414    pub fn with_options(&self) -> &WithOptions {
415        &self.with_options
416    }
417
418    pub fn overwrite_options(&self) -> &OverwriteOptions {
419        &self.overwrite_options
420    }
421
422    pub fn add_batch_mview_candidate(&self, table: Arc<TableCatalog>, plan: LogicalPlanRef) {
423        self.batch_mview_candidates
424            .borrow_mut()
425            .push(MaterializedViewCandidate { plan, table });
426    }
427
428    pub fn batch_mview_candidates(&self) -> std::cell::Ref<'_, Vec<MaterializedViewCandidate>> {
429        self.batch_mview_candidates.borrow()
430    }
431
432    pub fn session_ctx(&self) -> &Arc<SessionImpl> {
433        &self.session_ctx
434    }
435
436    pub fn batch_plan_dml_wait_persistence(&self) -> bool {
437        let session_config = self.session_ctx.config();
438        !session_config.implicit_flush() && session_config.dml_wait_persistence()
439    }
440
441    /// Return the original SQL.
442    pub fn sql(&self) -> &str {
443        &self.sql
444    }
445
446    /// Return the normalized SQL.
447    pub fn normalized_sql(&self) -> &str {
448        &self.normalized_sql
449    }
450
451    pub fn session_timezone(&self) -> RefMut<'_, SessionTimezone> {
452        self.session_timezone.borrow_mut()
453    }
454
455    pub fn get_session_timezone(&self) -> String {
456        self.session_timezone.borrow().timezone()
457    }
458
459    pub(crate) fn iceberg_snapshot_info_map(
460        &self,
461    ) -> RefMut<'_, HashMap<SourceId, Option<IcebergSnapshotInfo>>> {
462        self.iceberg_snapshot_info_map.borrow_mut()
463    }
464}
465
466impl std::fmt::Debug for OptimizerContext {
467    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
468        write!(
469            f,
470            "QueryContext {{ sql = {}, explain_options = {}, with_options = {:?}, last_plan_node_id = {}, last_correlated_id = {} }}",
471            self.sql,
472            self.explain_options,
473            self.with_options,
474            self.last_plan_node_id.get(),
475            self.last_correlated_id.get(),
476        )
477    }
478}