mz_adapter/optimize/
subscribe.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 `SUBSCRIBE` statements.
11
12use std::marker::PhantomData;
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15
16use differential_dataflow::lattice::Lattice;
17use mz_adapter_types::connection::ConnectionId;
18use mz_compute_types::ComputeInstanceId;
19use mz_compute_types::plan::Plan;
20use mz_compute_types::sinks::{ComputeSinkConnection, ComputeSinkDesc, SubscribeSinkConnection};
21use mz_ore::collections::CollectionExt;
22use mz_ore::soft_assert_or_log;
23use mz_repr::{GlobalId, RelationDesc, Timestamp};
24use mz_sql::optimizer_metrics::OptimizerMetrics;
25use mz_sql::plan::SubscribeFrom;
26use mz_transform::TransformCtx;
27use mz_transform::dataflow::DataflowMetainfo;
28use mz_transform::normalize_lets::normalize_lets;
29use mz_transform::typecheck::{SharedContext as TypecheckContext, empty_context};
30use timely::progress::Antichain;
31
32use crate::CollectionIdBundle;
33use crate::optimize::dataflows::{
34    ComputeInstanceSnapshot, DataflowBuilder, ExprPrepStyle, dataflow_import_id_bundle,
35    prep_relation_expr, prep_scalar_expr,
36};
37use crate::optimize::{
38    LirDataflowDescription, MirDataflowDescription, Optimize, OptimizeMode, OptimizerCatalog,
39    OptimizerConfig, OptimizerError, optimize_mir_local, trace_plan,
40};
41
42pub struct Optimizer {
43    /// A typechecking context to use throughout the optimizer pipeline.
44    typecheck_ctx: TypecheckContext,
45    /// A snapshot of the catalog state.
46    catalog: Arc<dyn OptimizerCatalog>,
47    /// A snapshot of the cluster that will run the dataflows.
48    compute_instance: ComputeInstanceSnapshot,
49    /// A transient GlobalId to be used for the exported sink.
50    sink_id: GlobalId,
51    /// A transient GlobalId to be used when constructing a dataflow for
52    /// `SUBSCRIBE FROM <SELECT>` variants.
53    view_id: GlobalId,
54    /// The id of the session connection in which the optimizer will run.
55    conn_id: Option<ConnectionId>,
56    /// Should the plan produce an initial snapshot?
57    with_snapshot: bool,
58    /// Sink timestamp.
59    up_to: Option<Timestamp>,
60    /// A human-readable name exposed internally (useful for debugging).
61    debug_name: String,
62    /// Optimizer config.
63    config: OptimizerConfig,
64    /// Optimizer metrics.
65    metrics: OptimizerMetrics,
66    /// The time spent performing optimization so far.
67    duration: Duration,
68}
69
70// A bogey `Debug` implementation that hides fields. This is needed to make the
71// `event!` call in `sequence_peek_stage` not emit a lot of data.
72//
73// For now, we skip almost all fields, but we might revisit that bit if it turns
74// out that we really need those for debugging purposes.
75impl std::fmt::Debug for Optimizer {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("Optimizer")
78            .field("config", &self.config)
79            .finish_non_exhaustive()
80    }
81}
82
83impl Optimizer {
84    pub fn new(
85        catalog: Arc<dyn OptimizerCatalog>,
86        compute_instance: ComputeInstanceSnapshot,
87        view_id: GlobalId,
88        sink_id: GlobalId,
89        conn_id: Option<ConnectionId>,
90        with_snapshot: bool,
91        up_to: Option<Timestamp>,
92        debug_name: String,
93        config: OptimizerConfig,
94        metrics: OptimizerMetrics,
95    ) -> Self {
96        Self {
97            typecheck_ctx: empty_context(),
98            catalog,
99            compute_instance,
100            view_id,
101            sink_id,
102            conn_id,
103            with_snapshot,
104            up_to,
105            debug_name,
106            config,
107            metrics,
108            duration: Default::default(),
109        }
110    }
111
112    pub fn cluster_id(&self) -> ComputeInstanceId {
113        self.compute_instance.instance_id()
114    }
115
116    pub fn up_to(&self) -> Option<Timestamp> {
117        self.up_to.clone()
118    }
119}
120
121/// The (sealed intermediate) result after:
122///
123/// 1. embedding a [`SubscribeFrom`] plan into a [`MirDataflowDescription`],
124/// 2. transitively inlining referenced views, and
125/// 3. jointly optimizing the `MIR` plans in the [`MirDataflowDescription`].
126#[derive(Clone, Debug)]
127pub struct GlobalMirPlan<T: Clone> {
128    df_desc: MirDataflowDescription,
129    df_meta: DataflowMetainfo,
130    phantom: PhantomData<T>,
131}
132
133impl<T: Clone> GlobalMirPlan<T> {
134    /// Computes the [`CollectionIdBundle`] of the wrapped dataflow.
135    pub fn id_bundle(&self, compute_instance_id: ComputeInstanceId) -> CollectionIdBundle {
136        dataflow_import_id_bundle(&self.df_desc, compute_instance_id)
137    }
138}
139
140/// The (final) result after MIR ⇒ LIR lowering and optimizing the resulting
141/// `DataflowDescription` with `LIR` plans.
142#[derive(Clone, Debug)]
143pub struct GlobalLirPlan {
144    df_desc: LirDataflowDescription,
145    df_meta: DataflowMetainfo,
146}
147
148impl GlobalLirPlan {
149    pub fn sink_id(&self) -> GlobalId {
150        let sink_exports = &self.df_desc.sink_exports;
151        let sink_id = sink_exports.keys().next().expect("valid sink");
152        *sink_id
153    }
154
155    pub fn as_of(&self) -> Option<Timestamp> {
156        self.df_desc.as_of.clone().map(|as_of| as_of.into_element())
157    }
158
159    pub fn sink_desc(&self) -> &ComputeSinkDesc {
160        let sink_exports = &self.df_desc.sink_exports;
161        let sink_desc = sink_exports.values().next().expect("valid sink");
162        sink_desc
163    }
164}
165
166/// Marker type for [`GlobalMirPlan`] structs representing an optimization
167/// result without a resolved timestamp.
168#[derive(Clone, Debug)]
169pub struct Unresolved;
170
171/// Marker type for [`GlobalMirPlan`] structs representing an optimization
172/// result with a resolved timestamp.
173///
174/// The actual timestamp value is set in the [`MirDataflowDescription`] of the
175/// surrounding [`GlobalMirPlan`] when we call `resolve()`.
176#[derive(Clone, Debug)]
177pub struct Resolved;
178
179impl Optimize<SubscribeFrom> for Optimizer {
180    type To = GlobalMirPlan<Unresolved>;
181
182    fn optimize(&mut self, plan: SubscribeFrom) -> Result<Self::To, OptimizerError> {
183        let time = Instant::now();
184
185        let mut df_builder = {
186            let compute = self.compute_instance.clone();
187            DataflowBuilder::new(&*self.catalog, compute).with_config(&self.config)
188        };
189        let mut df_desc = MirDataflowDescription::new(self.debug_name.clone());
190        let mut df_meta = DataflowMetainfo::default();
191
192        match plan {
193            SubscribeFrom::Id(from_id) => {
194                let from = self.catalog.get_entry(&from_id);
195                let from_desc = from
196                    .desc(
197                        &self
198                            .catalog
199                            .resolve_full_name(from.name(), self.conn_id.as_ref()),
200                    )
201                    .expect("subscribes can only be run on items with descs")
202                    .into_owned();
203
204                df_builder.import_into_dataflow(&from_id, &mut df_desc, &self.config.features)?;
205                df_builder.maybe_reoptimize_imported_views(&mut df_desc, &self.config)?;
206
207                // Make SinkDesc
208                let sink_description = ComputeSinkDesc {
209                    from: from_id,
210                    from_desc,
211                    connection: ComputeSinkConnection::Subscribe(SubscribeSinkConnection::default()),
212                    with_snapshot: self.with_snapshot,
213                    up_to: self.up_to.map(Antichain::from_elem).unwrap_or_default(),
214                    // No `FORCE NOT NULL` for subscribes
215                    non_null_assertions: vec![],
216                    // No `REFRESH` for subscribes
217                    refresh_schedule: None,
218                };
219                df_desc.export_sink(self.sink_id, sink_description);
220            }
221            SubscribeFrom::Query { expr, desc } => {
222                // TODO: Change the `expr` type to be `HirRelationExpr` and run
223                // HIR ⇒ MIR lowering and decorrelation here. This would allow
224                // us implement something like `EXPLAIN RAW PLAN FOR SUBSCRIBE.`
225                //
226                // let expr = expr.lower(&self.config)?;
227
228                // MIR ⇒ MIR optimization (local)
229                let mut transform_ctx = TransformCtx::local(
230                    &self.config.features,
231                    &self.typecheck_ctx,
232                    &mut df_meta,
233                    Some(&self.metrics),
234                );
235                let expr = optimize_mir_local(expr, &mut transform_ctx)?;
236
237                df_builder.import_view_into_dataflow(
238                    &self.view_id,
239                    &expr,
240                    &mut df_desc,
241                    &self.config.features,
242                )?;
243                df_builder.maybe_reoptimize_imported_views(&mut df_desc, &self.config)?;
244
245                // Make SinkDesc
246                let sink_description = ComputeSinkDesc {
247                    from: self.view_id,
248                    from_desc: RelationDesc::new(expr.typ(), desc.iter_names()),
249                    connection: ComputeSinkConnection::Subscribe(SubscribeSinkConnection::default()),
250                    with_snapshot: self.with_snapshot,
251                    up_to: self.up_to.map(Antichain::from_elem).unwrap_or_default(),
252                    // No `FORCE NOT NULL` for subscribes
253                    non_null_assertions: vec![],
254                    // No `REFRESH` for subscribes
255                    refresh_schedule: None,
256                };
257                df_desc.export_sink(self.sink_id, sink_description);
258            }
259        };
260
261        // Prepare expressions in the assembled dataflow.
262        let style = ExprPrepStyle::Index;
263        df_desc.visit_children(
264            |r| prep_relation_expr(r, style),
265            |s| prep_scalar_expr(s, style),
266        )?;
267
268        // Construct TransformCtx for global optimization.
269        let mut transform_ctx = TransformCtx::global(
270            &df_builder,
271            &mz_transform::EmptyStatisticsOracle, // TODO: wire proper stats
272            &self.config.features,
273            &self.typecheck_ctx,
274            &mut df_meta,
275            Some(&self.metrics),
276        );
277        // Run global optimization.
278        mz_transform::optimize_dataflow(&mut df_desc, &mut transform_ctx, false)?;
279
280        if self.config.mode == OptimizeMode::Explain {
281            // Collect the list of indexes used by the dataflow at this point.
282            trace_plan!(at: "global", &df_meta.used_indexes(&df_desc));
283        }
284
285        self.duration += time.elapsed();
286
287        // Return the (sealed) plan at the end of this optimization step.
288        Ok(GlobalMirPlan {
289            df_desc,
290            df_meta,
291            phantom: PhantomData::<Unresolved>,
292        })
293    }
294}
295
296impl GlobalMirPlan<Unresolved> {
297    /// Produces the [`GlobalMirPlan`] with [`Resolved`] timestamp.
298    ///
299    /// We need to resolve timestamps before the `GlobalMirPlan ⇒ GlobalLirPlan`
300    /// optimization stage in order to profit from possible single-time
301    /// optimizations in the `Plan::finalize_dataflow` call.
302    pub fn resolve(mut self, as_of: Antichain<Timestamp>) -> GlobalMirPlan<Resolved> {
303        // A dataflow description for a `SUBSCRIBE` statement should not have
304        // index exports.
305        soft_assert_or_log!(
306            self.df_desc.index_exports.is_empty(),
307            "unexpectedly setting until for a DataflowDescription with an index",
308        );
309
310        // Set the `as_of` timestamp for the dataflow.
311        self.df_desc.set_as_of(as_of);
312
313        // The only outputs of the dataflow are sinks, so we might be able to
314        // turn off the computation early, if they all have non-trivial
315        // `up_to`s.
316        self.df_desc.until = Antichain::from_elem(Timestamp::MIN);
317        for (_, sink) in &self.df_desc.sink_exports {
318            self.df_desc.until.join_assign(&sink.up_to);
319        }
320
321        GlobalMirPlan {
322            df_desc: self.df_desc,
323            df_meta: self.df_meta,
324            phantom: PhantomData::<Resolved>,
325        }
326    }
327}
328
329impl Optimize<GlobalMirPlan<Resolved>> for Optimizer {
330    type To = GlobalLirPlan;
331
332    fn optimize(&mut self, plan: GlobalMirPlan<Resolved>) -> Result<Self::To, OptimizerError> {
333        let time = Instant::now();
334
335        let GlobalMirPlan {
336            mut df_desc,
337            df_meta,
338            phantom: _,
339        } = plan;
340
341        // Ensure all expressions are normalized before finalizing.
342        for build in df_desc.objects_to_build.iter_mut() {
343            normalize_lets(&mut build.plan.0, &self.config.features)?
344        }
345
346        // Finalize the dataflow. This includes:
347        // - MIR ⇒ LIR lowering
348        // - LIR ⇒ LIR transforms
349        let df_desc = Plan::finalize_dataflow(df_desc, &self.config.features)?;
350
351        self.duration += time.elapsed();
352        self.metrics
353            .observe_e2e_optimization_time("subscribe", self.duration);
354
355        // Return the plan at the end of this `optimize` step.
356        Ok(GlobalLirPlan { df_desc, df_meta })
357    }
358}
359
360impl GlobalLirPlan {
361    /// Unwraps the parts of the final result of the optimization pipeline.
362    pub fn unapply(self) -> (LirDataflowDescription, DataflowMetainfo) {
363        (self.df_desc, self.df_meta)
364    }
365}