mz_adapter/optimize/
peek.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Optimizer implementation for `SELECT` statements.
11
12use std::fmt::Debug;
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15
16use mz_compute_types::ComputeInstanceId;
17use mz_compute_types::dataflows::IndexDesc;
18use mz_compute_types::plan::Plan;
19use mz_expr::{MirRelationExpr, MirScalarExpr, OptimizedMirRelationExpr, RowSetFinishing};
20use mz_ore::soft_assert_or_log;
21use mz_repr::explain::trace_plan;
22use mz_repr::{GlobalId, SqlRelationType, Timestamp};
23use mz_sql::optimizer_metrics::OptimizerMetrics;
24use mz_sql::plan::HirRelationExpr;
25use mz_sql::session::metadata::SessionMetadata;
26use mz_transform::dataflow::DataflowMetainfo;
27use mz_transform::normalize_lets::normalize_lets;
28use mz_transform::reprtypecheck::{
29    SharedContext as ReprTypecheckContext, empty_context as empty_repr_context,
30};
31use mz_transform::{StatisticsOracle, TransformCtx};
32use timely::progress::Antichain;
33use tracing::debug_span;
34
35use crate::TimestampContext;
36use crate::catalog::Catalog;
37use crate::coord::peek::{PeekDataflowPlan, PeekPlan, create_fast_path_plan};
38use crate::optimize::dataflows::{
39    ComputeInstanceSnapshot, DataflowBuilder, EvalTime, ExprPrepStyle, prep_relation_expr,
40    prep_scalar_expr,
41};
42use crate::optimize::{
43    MirDataflowDescription, Optimize, OptimizeMode, OptimizerConfig, OptimizerError,
44    optimize_mir_local, trace_plan,
45};
46
47pub struct Optimizer {
48    /// A representation typechecking context to use throughout the optimizer pipeline.
49    repr_typecheck_ctx: ReprTypecheckContext,
50    /// A snapshot of the catalog state.
51    catalog: Arc<Catalog>,
52    /// A snapshot of the cluster that will run the dataflows.
53    compute_instance: ComputeInstanceSnapshot,
54    /// Optional row-set finishing to be applied to the final result.
55    finishing: RowSetFinishing,
56    /// A transient GlobalId to be used when constructing the dataflow.
57    select_id: GlobalId,
58    /// A transient GlobalId to be used when constructing a PeekPlan.
59    index_id: GlobalId,
60    /// Optimizer config.
61    config: OptimizerConfig,
62    /// Optimizer metrics.
63    metrics: OptimizerMetrics,
64    /// The time spent performing optimization so far.
65    duration: Duration,
66}
67
68impl Optimizer {
69    pub fn new(
70        catalog: Arc<Catalog>,
71        compute_instance: ComputeInstanceSnapshot,
72        finishing: RowSetFinishing,
73        select_id: GlobalId,
74        index_id: GlobalId,
75        config: OptimizerConfig,
76        metrics: OptimizerMetrics,
77    ) -> Self {
78        Self {
79            repr_typecheck_ctx: empty_repr_context(),
80            catalog,
81            compute_instance,
82            finishing,
83            select_id,
84            index_id,
85            config,
86            metrics,
87            duration: Default::default(),
88        }
89    }
90
91    pub fn cluster_id(&self) -> ComputeInstanceId {
92        self.compute_instance.instance_id()
93    }
94
95    pub fn finishing(&self) -> &RowSetFinishing {
96        &self.finishing
97    }
98
99    pub fn select_id(&self) -> GlobalId {
100        self.select_id
101    }
102
103    pub fn index_id(&self) -> GlobalId {
104        self.index_id
105    }
106
107    pub fn config(&self) -> &OptimizerConfig {
108        &self.config
109    }
110
111    pub fn metrics(&self) -> &OptimizerMetrics {
112        &self.metrics
113    }
114
115    pub fn duration(&self) -> Duration {
116        self.duration
117    }
118}
119
120// A bogey `Debug` implementation that hides fields. This is needed to make the
121// `event!` call in `sequence_peek_stage` not emit a lot of data.
122//
123// For now, we skip almost all fields, but we might revisit that bit if it turns
124// out that we really need those for debugging purposes.
125impl Debug for Optimizer {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        f.debug_struct("OptimizePeek")
128            .field("config", &self.config)
129            .finish_non_exhaustive()
130    }
131}
132
133/// Marker type for [`LocalMirPlan`] representing an optimization result without
134/// context.
135pub struct Unresolved;
136
137/// The (sealed intermediate) result after HIR ⇒ MIR lowering and decorrelation
138/// and local MIR optimization.
139#[derive(Clone)]
140pub struct LocalMirPlan<T = Unresolved> {
141    expr: MirRelationExpr,
142    df_meta: DataflowMetainfo,
143    context: T,
144}
145
146/// Marker type for [`LocalMirPlan`] structs representing an optimization result
147/// with attached environment context required for the next optimization stage.
148pub struct Resolved<'s> {
149    timestamp_ctx: TimestampContext<Timestamp>,
150    stats: Box<dyn StatisticsOracle>,
151    session: &'s dyn SessionMetadata,
152}
153
154/// The (final) result after
155///
156/// 1. embedding a [`LocalMirPlan`] into a `DataflowDescription`,
157/// 2. transitively inlining referenced views,
158/// 3. timestamp resolution,
159/// 4. optimizing the resulting `DataflowDescription` with `MIR` plans.
160/// 5. MIR ⇒ LIR lowering, and
161/// 6. optimizing the resulting `DataflowDescription` with `LIR` plans.
162#[derive(Debug)]
163pub struct GlobalLirPlan {
164    peek_plan: PeekPlan,
165    df_meta: DataflowMetainfo,
166    typ: SqlRelationType,
167}
168
169impl Optimize<HirRelationExpr> for Optimizer {
170    type To = LocalMirPlan;
171
172    fn optimize(&mut self, expr: HirRelationExpr) -> Result<Self::To, OptimizerError> {
173        let time = Instant::now();
174
175        // Trace the pipeline input under `optimize/raw`.
176        trace_plan!(at: "raw", &expr);
177
178        // HIR ⇒ MIR lowering and decorrelation
179        let expr = expr.lower(&self.config, Some(&self.metrics))?;
180
181        // MIR ⇒ MIR optimization (local)
182        let mut df_meta = DataflowMetainfo::default();
183        let mut transform_ctx = TransformCtx::local(
184            &self.config.features,
185            &self.repr_typecheck_ctx,
186            &mut df_meta,
187            Some(&mut self.metrics),
188            Some(self.select_id),
189        );
190        let expr = optimize_mir_local(expr, &mut transform_ctx)?.into_inner();
191
192        self.duration += time.elapsed();
193
194        // Return the (sealed) plan at the end of this optimization step.
195        Ok(LocalMirPlan {
196            expr,
197            df_meta,
198            context: Unresolved,
199        })
200    }
201}
202
203impl LocalMirPlan<Unresolved> {
204    /// Produces the [`LocalMirPlan`] with [`Resolved`] contextual information
205    /// required for the next stage.
206    pub fn resolve(
207        self,
208        timestamp_ctx: TimestampContext<Timestamp>,
209        session: &dyn SessionMetadata,
210        stats: Box<dyn StatisticsOracle>,
211    ) -> LocalMirPlan<Resolved<'_>> {
212        LocalMirPlan {
213            expr: self.expr,
214            df_meta: self.df_meta,
215            context: Resolved {
216                timestamp_ctx,
217                session,
218                stats,
219            },
220        }
221    }
222}
223
224impl<'s> Optimize<LocalMirPlan<Resolved<'s>>> for Optimizer {
225    type To = GlobalLirPlan;
226
227    fn optimize(&mut self, plan: LocalMirPlan<Resolved<'s>>) -> Result<Self::To, OptimizerError> {
228        let time = Instant::now();
229
230        let LocalMirPlan {
231            expr,
232            mut df_meta,
233            context:
234                Resolved {
235                    timestamp_ctx,
236                    stats,
237                    session,
238                },
239        } = plan;
240
241        let expr = OptimizedMirRelationExpr(expr);
242
243        // We create a dataflow and optimize it, to determine if we can avoid building it.
244        // This can happen if the result optimizes to a constant, or to a `Get` expression
245        // around a maintained arrangement.
246        let typ = expr.typ();
247        let key = typ
248            .default_key()
249            .iter()
250            .map(|k| MirScalarExpr::column(*k))
251            .collect();
252
253        // The assembled dataflow contains a view and an index of that view.
254        let mut df_builder = {
255            let catalog = self.catalog.state();
256            let compute = self.compute_instance.clone();
257            DataflowBuilder::new(catalog, compute).with_config(&self.config)
258        };
259
260        let debug_name = format!("oneshot-select-{}", self.select_id);
261        let mut df_desc = MirDataflowDescription::new(debug_name.to_string());
262
263        df_builder.import_view_into_dataflow(
264            &self.select_id,
265            &expr,
266            &mut df_desc,
267            &self.config.features,
268        )?;
269        df_builder.maybe_reoptimize_imported_views(&mut df_desc, &self.config)?;
270
271        // Resolve all unmaterializable function calls except mz_now(), because
272        // we don't yet have a timestamp.
273        let style = ExprPrepStyle::OneShot {
274            logical_time: EvalTime::Deferred,
275            session,
276            catalog_state: self.catalog.state(),
277        };
278        df_desc.visit_children(
279            |r| prep_relation_expr(r, style),
280            |s| prep_scalar_expr(s, style),
281        )?;
282
283        // TODO: Instead of conditioning here we should really
284        // reconsider how to render multi-plan peek dataflows. The main
285        // difficulty here is rendering the optional finishing bit.
286        if self.config.mode != OptimizeMode::Explain {
287            df_desc.export_index(
288                self.index_id,
289                IndexDesc {
290                    on_id: self.select_id,
291                    key,
292                },
293                typ.clone(),
294            );
295        }
296
297        // Set the `as_of` and `until` timestamps for the dataflow.
298        df_desc.set_as_of(timestamp_ctx.antichain());
299
300        // Get the single timestamp representing the `as_of` time.
301        let as_of = df_desc
302            .as_of
303            .clone()
304            .expect("as_of antichain")
305            .into_option()
306            .expect("unique as_of element");
307
308        // Resolve all unmaterializable function calls including mz_now().
309        let style = ExprPrepStyle::OneShot {
310            logical_time: EvalTime::Time(as_of),
311            session,
312            catalog_state: self.catalog.state(),
313        };
314        df_desc.visit_children(
315            |r| prep_relation_expr(r, style),
316            |s| prep_scalar_expr(s, style),
317        )?;
318
319        // Use the opportunity to name an `until` frontier that will prevent
320        // work we needn't perform. By default, `until` will be
321        // `Antichain::new()`, which prevents no updates and is safe.
322        //
323        // If `timestamp_ctx.antichain()` is empty, `timestamp_ctx.timestamp()`
324        // will return `None` and we use the default (empty) `until`. Otherwise,
325        // we expect to be able to set `until = as_of + 1` without an overflow, unless
326        // we query at the maximum timestamp. In this case, the default empty `until`
327        // is the correct choice.
328        if let Some(until) = timestamp_ctx
329            .timestamp()
330            .and_then(Timestamp::try_step_forward)
331        {
332            df_desc.until = Antichain::from_elem(until);
333        }
334
335        // Construct TransformCtx for global optimization.
336        let mut transform_ctx = TransformCtx::global(
337            &df_builder,
338            &*stats,
339            &self.config.features,
340            &self.repr_typecheck_ctx,
341            &mut df_meta,
342            Some(&mut self.metrics),
343        );
344
345        // Let's already try creating a fast path plan. If successful, we don't need to run the
346        // whole optimizer pipeline, but just a tiny subset of it. (But we'll need to run
347        // `create_fast_path_plan` later again, because, e.g., running `LiteralConstraints` is still
348        // ahead of us.)
349        let use_fast_path_optimizer = match create_fast_path_plan(
350            &mut df_desc,
351            self.select_id,
352            Some(&self.finishing),
353            self.config.features.persist_fast_path_limit,
354            self.config.persist_fast_path_order,
355        ) {
356            Ok(maybe_fast_path_plan) => maybe_fast_path_plan.is_some(),
357            Err(OptimizerError::InternalUnsafeMfpPlan(_)) => {
358                // This is expected, in that `create_fast_path_plan` can choke on `mz_now`, which we
359                // haven't removed yet.
360                false
361            }
362            Err(e) => {
363                return Err(e);
364            }
365        };
366
367        // Run global optimization.
368        mz_transform::optimize_dataflow(&mut df_desc, &mut transform_ctx, use_fast_path_optimizer)?;
369
370        if self.config.mode == OptimizeMode::Explain {
371            // Collect the list of indexes used by the dataflow at this point.
372            trace_plan!(at: "global", &df_meta.used_indexes(&df_desc));
373        }
374
375        // TODO: use the following code once we can be sure that the
376        // index_exports always exist.
377        //
378        // let typ = self.df_desc
379        //     .index_exports
380        //     .first_key_value()
381        //     .map(|(_key, (_desc, typ))| typ.clone())
382        //     .expect("GlobalMirPlan type");
383
384        let peek_plan = match create_fast_path_plan(
385            &mut df_desc,
386            self.select_id,
387            Some(&self.finishing),
388            self.config.features.persist_fast_path_limit,
389            self.config.persist_fast_path_order,
390        )? {
391            Some(plan) if !self.config.no_fast_path => {
392                if self.config.mode == OptimizeMode::Explain {
393                    // Trace the `used_indexes` for the FastPathPlan.
394                    debug_span!(target: "optimizer", "fast_path").in_scope(|| {
395                        // Fast path plans come with an updated finishing.
396                        let finishing = if !self.finishing.is_trivial(typ.arity()) {
397                            Some(&self.finishing)
398                        } else {
399                            None
400                        };
401                        trace_plan(&plan.used_indexes(finishing));
402                    });
403                }
404                // Trace the FastPathPlan.
405                trace_plan!(at: "fast_path", &plan);
406
407                // Trace the pipeline output under `optimize`.
408                trace_plan(&plan);
409
410                // Build the PeekPlan
411                PeekPlan::FastPath(plan)
412            }
413            _ => {
414                soft_assert_or_log!(
415                    !use_fast_path_optimizer || self.config.no_fast_path,
416                    "The fast_path_optimizer shouldn't make a fast path plan slow path."
417                );
418
419                // Ensure all expressions are normalized before finalizing.
420                for build in df_desc.objects_to_build.iter_mut() {
421                    normalize_lets(&mut build.plan.0, &self.config.features)?
422                }
423
424                // Finalize the dataflow. This includes:
425                // - MIR ⇒ LIR lowering
426                // - LIR ⇒ LIR transforms
427                let df_desc = Plan::finalize_dataflow(df_desc, &self.config.features)?;
428
429                // Trace the pipeline output under `optimize`.
430                trace_plan(&df_desc);
431
432                // Build the PeekPlan
433                PeekPlan::SlowPath(PeekDataflowPlan::new(df_desc, self.index_id(), &typ))
434            }
435        };
436
437        self.duration += time.elapsed();
438        let label = match &peek_plan {
439            PeekPlan::FastPath(_) => "peek:fast_path",
440            PeekPlan::SlowPath(_) => "peek:slow_path",
441        };
442        self.metrics
443            .observe_e2e_optimization_time(label, self.duration);
444
445        Ok(GlobalLirPlan {
446            peek_plan,
447            df_meta,
448            typ,
449        })
450    }
451}
452
453impl GlobalLirPlan {
454    /// Unwraps the parts of the final result of the optimization pipeline.
455    pub fn unapply(self) -> (PeekPlan, DataflowMetainfo, SqlRelationType) {
456        (self.peek_plan, self.df_meta, self.typ)
457    }
458}