Skip to main content

mz_adapter/coord/sequencer/inner/
create_materialized_view.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
10use anyhow::anyhow;
11use differential_dataflow::lattice::Lattice;
12use maplit::btreemap;
13use maplit::btreeset;
14use mz_adapter_types::compaction::CompactionWindow;
15use mz_catalog::memory::objects::{CatalogItem, MaterializedView};
16use mz_expr::{CollectionPlan, ResultSpec};
17use mz_ore::collections::CollectionExt;
18use mz_ore::instrument;
19use mz_ore::soft_panic_or_log;
20use mz_repr::explain::{ExprHumanizerExt, TransientItem};
21use mz_repr::optimize::OptimizerFeatures;
22use mz_repr::optimize::OverrideFrom;
23use mz_repr::refresh_schedule::RefreshSchedule;
24use mz_repr::{CatalogItemId, Datum, RelationVersion, Row, VersionedRelationDesc};
25use mz_sql::ast::ExplainStage;
26use mz_sql::catalog::CatalogError;
27use mz_sql::names::ResolvedIds;
28use mz_sql::plan;
29use mz_sql::session::metadata::SessionMetadata;
30use mz_sql_parser::ast;
31use mz_sql_parser::ast::display::AstDisplay;
32use mz_storage_client::controller::CollectionDescription;
33use std::collections::BTreeMap;
34use timely::progress::Antichain;
35use tracing::Span;
36
37use crate::ReadHolds;
38use crate::command::ExecuteResponse;
39use crate::coord::sequencer::inner::return_if_err;
40use crate::coord::{
41    Coordinator, CreateMaterializedViewExplain, CreateMaterializedViewFinish,
42    CreateMaterializedViewOptimize, CreateMaterializedViewStage, ExplainContext,
43    ExplainPlanContext, Message, PlanValidity, StageResult, Staged,
44};
45use crate::error::AdapterError;
46use crate::explain::explain_dataflow;
47use crate::explain::explain_plan;
48use crate::explain::optimizer_trace::OptimizerTrace;
49use crate::optimize::dataflows::dataflow_import_id_bundle;
50use crate::optimize::{self, Optimize};
51use crate::session::Session;
52use crate::util::ResultExt;
53use crate::{AdapterNotice, CollectionIdBundle, ExecuteContext, TimestampProvider, catalog};
54
55impl Staged for CreateMaterializedViewStage {
56    type Ctx = ExecuteContext;
57
58    fn validity(&mut self) -> &mut PlanValidity {
59        match self {
60            Self::Optimize(stage) => &mut stage.validity,
61            Self::Finish(stage) => &mut stage.validity,
62            Self::Explain(stage) => &mut stage.validity,
63        }
64    }
65
66    async fn stage(
67        self,
68        coord: &mut Coordinator,
69        ctx: &mut ExecuteContext,
70    ) -> Result<StageResult<Box<Self>>, AdapterError> {
71        match self {
72            CreateMaterializedViewStage::Optimize(stage) => {
73                coord.create_materialized_view_optimize(stage).await
74            }
75            CreateMaterializedViewStage::Finish(stage) => {
76                coord.create_materialized_view_finish(ctx, stage).await
77            }
78            CreateMaterializedViewStage::Explain(stage) => {
79                coord
80                    .create_materialized_view_explain(ctx.session(), stage)
81                    .await
82            }
83        }
84    }
85
86    fn message(self, ctx: ExecuteContext, span: Span) -> Message {
87        Message::CreateMaterializedViewStageReady {
88            ctx,
89            span,
90            stage: self,
91        }
92    }
93
94    fn cancel_enabled(&self) -> bool {
95        true
96    }
97}
98
99impl Coordinator {
100    #[instrument]
101    pub(crate) async fn sequence_create_materialized_view(
102        &mut self,
103        ctx: ExecuteContext,
104        plan: plan::CreateMaterializedViewPlan,
105        resolved_ids: ResolvedIds,
106    ) {
107        let stage = return_if_err!(
108            self.create_materialized_view_validate(
109                ctx.session(),
110                plan,
111                resolved_ids,
112                ExplainContext::None
113            ),
114            ctx
115        );
116        self.sequence_staged(ctx, Span::current(), stage).await;
117    }
118
119    #[instrument]
120    pub(crate) async fn explain_create_materialized_view(
121        &mut self,
122        ctx: ExecuteContext,
123        plan::ExplainPlanPlan {
124            stage,
125            format,
126            config,
127            explainee,
128        }: plan::ExplainPlanPlan,
129    ) {
130        let plan::Explainee::Statement(stmt) = explainee else {
131            // This is currently asserted in the `sequence_explain_plan` code that
132            // calls this method.
133            unreachable!()
134        };
135        let plan::ExplaineeStatement::CreateMaterializedView { broken, plan } = stmt else {
136            // This is currently asserted in the `sequence_explain_plan` code that
137            // calls this method.
138            unreachable!()
139        };
140
141        // Create an OptimizerTrace instance to collect plans emitted when
142        // executing the optimizer pipeline.
143        let optimizer_trace = OptimizerTrace::new(stage.paths());
144
145        // Not used in the EXPLAIN path so it's OK to generate a dummy value.
146        let resolved_ids = ResolvedIds::empty();
147
148        let explain_ctx = ExplainContext::Plan(ExplainPlanContext {
149            broken,
150            config,
151            format,
152            stage,
153            replan: None,
154            desc: None,
155            optimizer_trace,
156        });
157        let stage = return_if_err!(
158            self.create_materialized_view_validate(ctx.session(), plan, resolved_ids, explain_ctx),
159            ctx
160        );
161        self.sequence_staged(ctx, Span::current(), stage).await;
162    }
163
164    #[instrument]
165    pub(crate) async fn explain_replan_materialized_view(
166        &mut self,
167        ctx: ExecuteContext,
168        plan::ExplainPlanPlan {
169            stage,
170            format,
171            config,
172            explainee,
173        }: plan::ExplainPlanPlan,
174    ) {
175        let plan::Explainee::ReplanMaterializedView(id) = explainee else {
176            unreachable!() // Asserted in `sequence_explain_plan`.
177        };
178        let CatalogItem::MaterializedView(item) = self.catalog().get_entry(&id).item() else {
179            unreachable!() // Asserted in `plan_explain_plan`.
180        };
181        let gid = item.global_id_writes();
182
183        let create_sql = item.create_sql.clone();
184        let plan_result = self
185            .catalog_mut()
186            .deserialize_plan_with_enable_for_item_parsing(&create_sql, true);
187        let (plan, resolved_ids) = return_if_err!(plan_result, ctx);
188
189        let plan::Plan::CreateMaterializedView(plan) = plan else {
190            unreachable!() // We are parsing the `create_sql` of a `MaterializedView` item.
191        };
192
193        // It is safe to assume that query optimization will always succeed, so
194        // for now we statically assume `broken = false`.
195        let broken = false;
196
197        // Create an OptimizerTrace instance to collect plans emitted when
198        // executing the optimizer pipeline.
199        let optimizer_trace = OptimizerTrace::new(stage.paths());
200
201        let explain_ctx = ExplainContext::Plan(ExplainPlanContext {
202            broken,
203            config,
204            format,
205            stage,
206            replan: Some(gid),
207            desc: None,
208            optimizer_trace,
209        });
210        let stage = return_if_err!(
211            self.create_materialized_view_validate(ctx.session(), plan, resolved_ids, explain_ctx,),
212            ctx
213        );
214        self.sequence_staged(ctx, Span::current(), stage).await;
215    }
216
217    #[instrument]
218    pub(super) fn explain_materialized_view(
219        &self,
220        ctx: &ExecuteContext,
221        plan::ExplainPlanPlan {
222            stage,
223            format,
224            config,
225            explainee,
226        }: plan::ExplainPlanPlan,
227    ) -> Result<ExecuteResponse, AdapterError> {
228        let plan::Explainee::MaterializedView(id) = explainee else {
229            unreachable!() // Asserted in `sequence_explain_plan`.
230        };
231        let CatalogItem::MaterializedView(view) = self.catalog().get_entry(&id).item() else {
232            unreachable!() // Asserted in `plan_explain_plan`.
233        };
234        let gid = view.global_id_writes();
235
236        let Some(dataflow_metainfo) = self.catalog().try_get_dataflow_metainfo(&gid) else {
237            if !id.is_system() {
238                tracing::error!(
239                    "cannot find dataflow metainformation for materialized view {id} in catalog"
240                );
241            }
242            coord_bail!(
243                "cannot find dataflow metainformation for materialized view {id} in catalog"
244            );
245        };
246
247        let target_cluster = self.catalog().get_cluster(view.cluster_id);
248
249        let features = OptimizerFeatures::from(self.catalog().system_config())
250            .override_from(&target_cluster.config.features())
251            .override_from(&config.features);
252
253        let cardinality_stats = BTreeMap::new();
254
255        let explain = match stage {
256            ExplainStage::RawPlan => explain_plan(
257                view.raw_expr.as_ref().clone(),
258                format,
259                &config,
260                &features,
261                &self.catalog().for_session(ctx.session()),
262                cardinality_stats,
263                Some(target_cluster.name.as_str()),
264            )?,
265            ExplainStage::LocalPlan => explain_plan(
266                view.optimized_expr.as_inner().clone(),
267                format,
268                &config,
269                &features,
270                &self.catalog().for_session(ctx.session()),
271                cardinality_stats,
272                Some(target_cluster.name.as_str()),
273            )?,
274            ExplainStage::GlobalPlan => {
275                let Some(plan) = self.catalog().try_get_optimized_plan(&gid).cloned() else {
276                    tracing::error!("cannot find {stage} for materialized view {id} in catalog");
277                    coord_bail!("cannot find {stage} for materialized view in catalog");
278                };
279                explain_dataflow(
280                    plan,
281                    format,
282                    &config,
283                    &features,
284                    &self.catalog().for_session(ctx.session()),
285                    cardinality_stats,
286                    Some(target_cluster.name.as_str()),
287                    dataflow_metainfo,
288                )?
289            }
290            ExplainStage::PhysicalPlan => {
291                let Some(plan) = self.catalog().try_get_physical_plan(&gid).cloned() else {
292                    tracing::error!("cannot find {stage} for materialized view {id} in catalog",);
293                    coord_bail!("cannot find {stage} for materialized view in catalog");
294                };
295                explain_dataflow(
296                    plan,
297                    format,
298                    &config,
299                    &features,
300                    &self.catalog().for_session(ctx.session()),
301                    cardinality_stats,
302                    Some(target_cluster.name.as_str()),
303                    dataflow_metainfo,
304                )?
305            }
306            _ => {
307                coord_bail!("cannot EXPLAIN {} FOR MATERIALIZED VIEW", stage);
308            }
309        };
310
311        let row = Row::pack_slice(&[Datum::from(explain.as_str())]);
312
313        Ok(Self::send_immediate_rows(row))
314    }
315
316    #[instrument]
317    fn create_materialized_view_validate(
318        &self,
319        session: &Session,
320        plan: plan::CreateMaterializedViewPlan,
321        resolved_ids: ResolvedIds,
322        // An optional context set iff the state machine is initiated from
323        // sequencing an EXPLAIN for this statement.
324        explain_ctx: ExplainContext,
325    ) -> Result<CreateMaterializedViewStage, AdapterError> {
326        let plan::CreateMaterializedViewPlan {
327            materialized_view:
328                plan::MaterializedView {
329                    expr,
330                    cluster_id,
331                    refresh_schedule,
332                    ..
333                },
334            ambiguous_columns,
335            ..
336        } = &plan;
337
338        // Validate any references in the materialized view's expression. We do
339        // this on the unoptimized plan to better reflect what the user typed.
340        // We want to reject queries that depend on log sources, for example,
341        // even if we can *technically* optimize that reference away.
342        let expr_depends_on = expr.depends_on();
343        self.catalog()
344            .validate_timeline_context(expr_depends_on.iter().copied())?;
345        self.validate_system_column_references(*ambiguous_columns, &expr_depends_on)?;
346        // Materialized views are not allowed to depend on log sources, as replicas
347        // are not producing the same definite collection for these.
348        let log_names = expr_depends_on
349            .iter()
350            .map(|gid| self.catalog.resolve_item_id(gid))
351            .flat_map(|item_id| self.catalog().introspection_dependencies(item_id))
352            .map(|item_id| self.catalog().get_entry(&item_id).name().item.clone())
353            .collect::<Vec<_>>();
354        if !log_names.is_empty() {
355            return Err(AdapterError::InvalidLogDependency {
356                object_type: "materialized view".into(),
357                log_names,
358            });
359        }
360
361        let validity =
362            PlanValidity::require_transient_revision(self.catalog().transient_revision());
363
364        // Check whether we can read all inputs at all the REFRESH AT times.
365        if let Some(refresh_schedule) = refresh_schedule {
366            if !refresh_schedule.ats.is_empty() && matches!(explain_ctx, ExplainContext::None) {
367                // Purification has acquired the earliest possible read holds if there are any
368                // REFRESH options.
369                let read_holds = self
370                    .txn_read_holds
371                    .get(session.conn_id())
372                    .expect("purification acquired read holds if there are REFRESH ATs");
373                let least_valid_read = read_holds.least_valid_read();
374                for refresh_at_ts in &refresh_schedule.ats {
375                    if !least_valid_read.less_equal(refresh_at_ts) {
376                        return Err(AdapterError::InputNotReadableAtRefreshAtTime(
377                            *refresh_at_ts,
378                            least_valid_read,
379                        ));
380                    }
381                }
382                // Also check that no new id has appeared in `sufficient_collections` (e.g. a new
383                // index), otherwise we might be missing some read holds.
384                let ids = self
385                    .index_oracle(*cluster_id)
386                    .sufficient_collections(resolved_ids.collections().copied());
387                if !ids.difference(&read_holds.id_bundle()).is_empty() {
388                    return Err(AdapterError::ChangedPlan(
389                        "the set of possible inputs changed during the creation of the \
390                         materialized view"
391                            .to_string(),
392                    ));
393                }
394            }
395        }
396
397        Ok(CreateMaterializedViewStage::Optimize(
398            CreateMaterializedViewOptimize {
399                validity,
400                plan,
401                resolved_ids,
402                explain_ctx,
403            },
404        ))
405    }
406
407    #[instrument]
408    async fn create_materialized_view_optimize(
409        &mut self,
410        CreateMaterializedViewOptimize {
411            validity,
412            plan,
413            resolved_ids,
414            explain_ctx,
415        }: CreateMaterializedViewOptimize,
416    ) -> Result<StageResult<Box<CreateMaterializedViewStage>>, AdapterError> {
417        let plan::CreateMaterializedViewPlan {
418            name,
419            materialized_view:
420                plan::MaterializedView {
421                    column_names,
422                    cluster_id,
423                    non_null_assertions,
424                    refresh_schedule,
425                    ..
426                },
427            ..
428        } = &plan;
429
430        // Collect optimizer parameters.
431        let compute_instance = self
432            .instance_snapshot(*cluster_id)
433            .expect("compute instance does not exist");
434        let (item_id, global_id) = if let ExplainContext::None = explain_ctx {
435            self.allocate_user_id().await?
436        } else {
437            self.allocate_transient_id()
438        };
439
440        let (_, view_id) = self.allocate_transient_id();
441        let debug_name = self.catalog().resolve_full_name(name, None).to_string();
442        let optimizer_config = optimize::OptimizerConfig::from(self.catalog().system_config())
443            .override_from(&self.catalog.get_cluster(*cluster_id).config.features())
444            .override_from(&explain_ctx);
445        let optimizer_features = optimizer_config.features.clone();
446        let force_non_monotonic = Default::default();
447
448        // Build an optimizer for this MATERIALIZED VIEW.
449        let mut optimizer = optimize::materialized_view::Optimizer::new(
450            self.owned_catalog().as_optimizer_catalog(),
451            compute_instance,
452            global_id,
453            view_id,
454            column_names.clone(),
455            non_null_assertions.clone(),
456            refresh_schedule.clone(),
457            debug_name,
458            optimizer_config,
459            self.optimizer_metrics(),
460            force_non_monotonic,
461        );
462
463        let span = Span::current();
464        Ok(StageResult::Handle(mz_ore::task::spawn_blocking(
465            || "optimize create materialized view",
466            move || {
467                span.in_scope(|| {
468                    let mut pipeline = || -> Result<(
469                        optimize::materialized_view::LocalMirPlan,
470                        optimize::materialized_view::GlobalMirPlan,
471                        optimize::materialized_view::GlobalLirPlan,
472                    ), AdapterError> {
473                        let _dispatch_guard = explain_ctx.dispatch_guard();
474
475                        let raw_expr = plan.materialized_view.expr.clone();
476
477                        // HIR ⇒ MIR lowering and MIR ⇒ MIR optimization (local and global)
478                        let local_mir_plan = optimizer.catch_unwind_optimize(raw_expr)?;
479                        let global_mir_plan =
480                            optimizer.catch_unwind_optimize(local_mir_plan.clone())?;
481                        // MIR ⇒ LIR lowering and LIR ⇒ LIR optimization (global)
482                        let global_lir_plan =
483                            optimizer.catch_unwind_optimize(global_mir_plan.clone())?;
484
485                        Ok((local_mir_plan, global_mir_plan, global_lir_plan))
486                    };
487
488                    let stage = match pipeline() {
489                        Ok((local_mir_plan, global_mir_plan, global_lir_plan)) => {
490                            if let ExplainContext::Plan(explain_ctx) = explain_ctx {
491                                let (_, df_meta) = global_lir_plan.unapply();
492                                CreateMaterializedViewStage::Explain(
493                                    CreateMaterializedViewExplain {
494                                        validity,
495                                        global_id,
496                                        plan,
497                                        df_meta,
498                                        explain_ctx,
499                                    },
500                                )
501                            } else {
502                                CreateMaterializedViewStage::Finish(CreateMaterializedViewFinish {
503                                    item_id,
504                                    global_id,
505                                    validity,
506                                    plan,
507                                    resolved_ids,
508                                    local_mir_plan,
509                                    global_mir_plan,
510                                    global_lir_plan,
511                                    optimizer_features,
512                                })
513                            }
514                        }
515                        // Internal optimizer errors are handled differently
516                        // depending on the caller.
517                        Err(err) => {
518                            let ExplainContext::Plan(explain_ctx) = explain_ctx else {
519                                // In `sequence_~` contexts, immediately return the error.
520                                return Err(err);
521                            };
522
523                            if explain_ctx.broken {
524                                // In `EXPLAIN BROKEN` contexts, just log the error
525                                // and move to the next stage with default
526                                // parameters.
527                                tracing::error!("error while handling EXPLAIN statement: {}", err);
528                                CreateMaterializedViewStage::Explain(
529                                    CreateMaterializedViewExplain {
530                                        global_id,
531                                        validity,
532                                        plan,
533                                        df_meta: Default::default(),
534                                        explain_ctx,
535                                    },
536                                )
537                            } else {
538                                // In regular `EXPLAIN` contexts, immediately return the error.
539                                return Err(err);
540                            }
541                        }
542                    };
543
544                    Ok(Box::new(stage))
545                })
546            },
547        )))
548    }
549
550    #[instrument]
551    async fn create_materialized_view_finish(
552        &mut self,
553        ctx: &mut ExecuteContext,
554        stage: CreateMaterializedViewFinish,
555    ) -> Result<StageResult<Box<CreateMaterializedViewStage>>, AdapterError> {
556        let CreateMaterializedViewFinish {
557            item_id,
558            global_id,
559            plan:
560                plan::CreateMaterializedViewPlan {
561                    name,
562                    materialized_view:
563                        plan::MaterializedView {
564                            mut create_sql,
565                            expr: raw_expr,
566                            dependencies,
567                            replacement_target,
568                            cluster_id,
569                            target_replica,
570                            non_null_assertions,
571                            compaction_window,
572                            refresh_schedule,
573                            ..
574                        },
575                    drop_ids,
576                    if_not_exists,
577                    ..
578                },
579            resolved_ids,
580            local_mir_plan,
581            global_mir_plan,
582            global_lir_plan,
583            optimizer_features,
584            ..
585        } = stage;
586
587        // Validate the replacement target, if one is given.
588        if let Some(target_id) = replacement_target {
589            let Some(target) = self.catalog().get_entry(&target_id).materialized_view() else {
590                return Err(AdapterError::internal(
591                    "create materialized view",
592                    "replacement target not a materialized view",
593                ));
594            };
595
596            // For now, we don't support schema evolution for materialized views.
597            let schema_diff = target.desc.latest().diff(global_lir_plan.desc());
598            if !schema_diff.is_empty() {
599                return Err(AdapterError::ReplacementSchemaMismatch(schema_diff));
600            }
601        }
602
603        // Timestamp selection
604        let id_bundle = dataflow_import_id_bundle(global_lir_plan.df_desc(), cluster_id);
605
606        let read_holds_owned;
607        let read_holds = if let Some(txn_reads) = self.txn_read_holds.get(ctx.session().conn_id()) {
608            // In some cases, for example when REFRESH is used, the preparatory
609            // stages will already have acquired ReadHolds, we can re-use those.
610
611            txn_reads
612        } else {
613            // No one has acquired holds, make sure we can determine an as_of
614            // and render our dataflow below.
615            read_holds_owned = self.acquire_read_holds(&id_bundle);
616            &read_holds_owned
617        };
618
619        let (dataflow_as_of, storage_as_of, until) =
620            self.select_timestamps(id_bundle, refresh_schedule.as_ref(), read_holds)?;
621
622        tracing::info!(
623            dataflow_as_of = ?dataflow_as_of,
624            storage_as_of = ?storage_as_of,
625            until = ?until,
626            "materialized view timestamp selection",
627        );
628
629        let initial_as_of = storage_as_of.clone();
630
631        // Update the `create_sql` with the selected `as_of`. This is how we make sure the `as_of`
632        // is persisted to the catalog and can be relied on during bootstrapping.
633        // This has to be the `storage_as_of`, because bootstrapping uses this in
634        // `bootstrap_storage_collections`.
635        if let Some(storage_as_of_ts) = storage_as_of.as_option() {
636            let stmt = mz_sql::parse::parse(&create_sql)
637                .map_err(|_| {
638                    AdapterError::internal(
639                        "create materialized view",
640                        "original SQL should roundtrip",
641                    )
642                })?
643                .into_element()
644                .ast;
645            let ast::Statement::CreateMaterializedView(mut stmt) = stmt else {
646                panic!("unexpected statement type");
647            };
648            stmt.as_of = Some(storage_as_of_ts.into());
649            create_sql = stmt.to_ast_string_stable();
650        }
651
652        let desc = VersionedRelationDesc::new(global_lir_plan.desc().clone());
653        let collections = [(RelationVersion::root(), global_id)].into_iter().collect();
654
655        let local_mir_for_cache = local_mir_plan.expr();
656
657        let ops = vec![
658            catalog::Op::DropObjects(
659                drop_ids
660                    .into_iter()
661                    .map(catalog::DropObjectInfo::Item)
662                    .collect(),
663            ),
664            catalog::Op::CreateItem {
665                id: item_id,
666                name: name.clone(),
667                item: CatalogItem::MaterializedView(MaterializedView {
668                    create_sql,
669                    raw_expr: raw_expr.into(),
670                    optimized_expr: local_mir_plan.expr().into(),
671                    desc,
672                    collections,
673                    resolved_ids,
674                    dependencies,
675                    replacement_target,
676                    cluster_id,
677                    target_replica,
678                    non_null_assertions,
679                    custom_logical_compaction_window: compaction_window,
680                    refresh_schedule: refresh_schedule.clone(),
681                    initial_as_of: Some(initial_as_of.clone()),
682                }),
683                owner_id: *ctx.session().current_role_id(),
684            },
685        ];
686
687        // Pre-allocate a vector of transient GlobalIds for each notice.
688        let notice_ids = std::iter::repeat_with(|| self.allocate_transient_id())
689            .map(|(_item_id, global_id)| global_id)
690            .take(global_lir_plan.df_meta().optimizer_notices.len())
691            .collect::<Vec<_>>();
692
693        let transact_result = self
694            .catalog_transact_with_side_effects(Some(ctx), ops, move |coord, ctx| {
695                Box::pin(async move {
696                    let output_desc = global_lir_plan.desc().clone();
697                    let (mut df_desc, df_meta) = global_lir_plan.unapply();
698
699                    // Save plan structures.
700                    coord
701                        .catalog_mut()
702                        .set_optimized_plan(global_id, global_mir_plan.df_desc().clone());
703                    coord
704                        .catalog_mut()
705                        .set_physical_plan(global_id, df_desc.clone());
706
707                    let notice_builtin_updates_fut = coord
708                        .process_dataflow_metainfo(df_meta, global_id, ctx, notice_ids)
709                        .await;
710
711                    coord.catalog().cache_expressions(
712                        global_id,
713                        Some(local_mir_for_cache),
714                        optimizer_features,
715                    );
716
717                    df_desc.set_as_of(dataflow_as_of.clone());
718                    df_desc.set_initial_as_of(initial_as_of);
719                    df_desc.until = until;
720
721                    let storage_metadata = coord.catalog.state().storage_metadata();
722
723                    let mut collection_desc =
724                        CollectionDescription::for_other(output_desc, Some(storage_as_of));
725                    let mut allow_writes = true;
726
727                    // If this MV is intended to replace another one, we need to start it in
728                    // read-only mode, targeting the shard of the replacement target.
729                    if let Some(target_id) = replacement_target {
730                        let target_gid = coord.catalog.get_entry(&target_id).latest_global_id();
731                        collection_desc.primary = Some(target_gid);
732                        allow_writes = false;
733                    }
734
735                    // Announce the creation of the materialized view source.
736                    coord
737                        .controller
738                        .storage
739                        .create_collections(
740                            storage_metadata,
741                            None,
742                            vec![(global_id, collection_desc)],
743                        )
744                        .await
745                        .unwrap_or_terminate("cannot fail to append");
746
747                    coord
748                        .initialize_storage_read_policies(
749                            btreeset![item_id],
750                            compaction_window.unwrap_or(CompactionWindow::Default),
751                        )
752                        .await;
753
754                    coord
755                        .ship_dataflow_and_notice_builtin_table_updates(
756                            df_desc,
757                            cluster_id,
758                            notice_builtin_updates_fut,
759                            target_replica,
760                        )
761                        .await;
762
763                    if allow_writes {
764                        coord.allow_writes(cluster_id, global_id);
765                    }
766                })
767            })
768            .await;
769
770        match transact_result {
771            Ok(_) => Ok(ExecuteResponse::CreatedMaterializedView),
772            Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
773                kind:
774                    mz_catalog::memory::error::ErrorKind::Sql(
775                        CatalogError::ItemAlreadyExists(_, _),
776                    ),
777            })) if if_not_exists => {
778                ctx.session()
779                    .add_notice(AdapterNotice::ObjectAlreadyExists {
780                        name: name.item,
781                        ty: "materialized view",
782                    });
783                Ok(ExecuteResponse::CreatedMaterializedView)
784            }
785            Err(err) => Err(err),
786        }
787        .map(StageResult::Response)
788    }
789
790    /// Select the initial `dataflow_as_of`, `storage_as_of`, and `until` frontiers for a
791    /// materialized view.
792    fn select_timestamps(
793        &self,
794        id_bundle: CollectionIdBundle,
795        refresh_schedule: Option<&RefreshSchedule>,
796        read_holds: &ReadHolds<mz_repr::Timestamp>,
797    ) -> Result<
798        (
799            Antichain<mz_repr::Timestamp>,
800            Antichain<mz_repr::Timestamp>,
801            Antichain<mz_repr::Timestamp>,
802        ),
803        AdapterError,
804    > {
805        assert!(
806            id_bundle.difference(&read_holds.id_bundle()).is_empty(),
807            "we must have read holds for all involved collections"
808        );
809
810        // For non-REFRESH MVs both the `dataflow_as_of` and the `storage_as_of` should be simply
811        // `least_valid_read`.
812        let least_valid_read = read_holds.least_valid_read();
813        let mut dataflow_as_of = least_valid_read.clone();
814        let mut storage_as_of = least_valid_read.clone();
815
816        // For MVs with non-trivial REFRESH schedules:
817        // 1. it's important to set the `storage_as_of` to the first refresh. This is because we'd
818        // like queries on the MV to block until the first refresh (rather than to show an empty
819        // MV).
820        // 2. We move the `dataflow_as_of` forward to the minimum of `greatest_available_read` and
821        // the first refresh time. There is no point in processing the times before
822        // `greatest_available_read`, because the first time for which results will be exposed is
823        // the first refresh time. Also note that simply moving the `dataflow_as_of` forward to the
824        // first refresh time would prevent warmup before the first refresh.
825        if let Some(refresh_schedule) = &refresh_schedule {
826            if let Some(least_valid_read_ts) = least_valid_read.as_option() {
827                if let Some(first_refresh_ts) =
828                    refresh_schedule.round_up_timestamp(*least_valid_read_ts)
829                {
830                    storage_as_of = Antichain::from_elem(first_refresh_ts);
831                    dataflow_as_of.join_assign(
832                        &self
833                            .greatest_available_read(&id_bundle)
834                            .meet(&storage_as_of),
835                    );
836                } else {
837                    let last_refresh = refresh_schedule.last_refresh().expect(
838                        "if round_up_timestamp returned None, then there should be a last refresh",
839                    );
840
841                    return Err(AdapterError::MaterializedViewWouldNeverRefresh(
842                        last_refresh,
843                        *least_valid_read_ts,
844                    ));
845                }
846            } else {
847                // The `as_of` should never be empty, because then the MV would be unreadable.
848                soft_panic_or_log!("creating a materialized view with an empty `as_of`");
849            }
850        }
851
852        // If we have a refresh schedule that has a last refresh, then set the `until` to the last refresh.
853        // (If the `try_step_forward` fails, then no need to set an `until`, because it's not possible to get any data
854        // beyond that last refresh time, because there are no times beyond that time.)
855        let until_ts = refresh_schedule
856            .and_then(|s| s.last_refresh())
857            .and_then(|r| r.try_step_forward());
858        let until = Antichain::from_iter(until_ts);
859
860        Ok((dataflow_as_of, storage_as_of, until))
861    }
862
863    #[instrument]
864    async fn create_materialized_view_explain(
865        &self,
866        session: &Session,
867        CreateMaterializedViewExplain {
868            global_id,
869            plan:
870                plan::CreateMaterializedViewPlan {
871                    name,
872                    materialized_view:
873                        plan::MaterializedView {
874                            column_names,
875                            cluster_id,
876                            ..
877                        },
878                    ..
879                },
880            df_meta,
881            explain_ctx:
882                ExplainPlanContext {
883                    config,
884                    format,
885                    stage,
886                    optimizer_trace,
887                    ..
888                },
889            ..
890        }: CreateMaterializedViewExplain,
891    ) -> Result<StageResult<Box<CreateMaterializedViewStage>>, AdapterError> {
892        let session_catalog = self.catalog().for_session(session);
893        let expr_humanizer = {
894            let full_name = self.catalog().resolve_full_name(&name, None);
895            let transient_items = btreemap! {
896                global_id => TransientItem::new(
897                    Some(full_name.into_parts()),
898                    Some(column_names.iter().map(|c| c.to_string()).collect()),
899                )
900            };
901            ExprHumanizerExt::new(transient_items, &session_catalog)
902        };
903
904        let target_cluster = self.catalog().get_cluster(cluster_id);
905
906        let features = OptimizerFeatures::from(self.catalog().system_config())
907            .override_from(&target_cluster.config.features())
908            .override_from(&config.features);
909
910        let rows = optimizer_trace
911            .into_rows(
912                format,
913                &config,
914                &features,
915                &expr_humanizer,
916                None,
917                Some(target_cluster),
918                df_meta,
919                stage,
920                plan::ExplaineeStatementKind::CreateMaterializedView,
921                None,
922            )
923            .await?;
924
925        Ok(StageResult::Response(Self::send_immediate_rows(rows)))
926    }
927
928    pub(crate) async fn explain_pushdown_materialized_view(
929        &self,
930        ctx: ExecuteContext,
931        item_id: CatalogItemId,
932    ) {
933        let CatalogItem::MaterializedView(mview) = self.catalog().get_entry(&item_id).item() else {
934            unreachable!() // Asserted in `sequence_explain_pushdown`.
935        };
936        let gid = mview.global_id_writes();
937        let mview = mview.clone();
938
939        let Some(plan) = self.catalog().try_get_physical_plan(&gid).cloned() else {
940            let msg = format!("cannot find plan for materialized view {item_id} in catalog");
941            tracing::error!("{msg}");
942            ctx.retire(Err(anyhow!("{msg}").into()));
943            return;
944        };
945
946        // We don't have any way to "duplicate" the read hold of the actual collection, which we
947        // obtain below... but the current implementation of read holds guarantees that the storage
948        // holds we obtain here will not be any greater than the hold we actually want.
949        let read_holds =
950            Some(self.acquire_read_holds(&dataflow_import_id_bundle(&plan, mview.cluster_id)));
951
952        let frontiers = self
953            .controller
954            .compute
955            .collection_frontiers(gid, Some(mview.cluster_id))
956            .expect("materialized view exists");
957
958        let as_of = frontiers.read_frontier.to_owned();
959
960        let until = mview
961            .refresh_schedule
962            .as_ref()
963            .and_then(|s| s.last_refresh())
964            .unwrap_or(mz_repr::Timestamp::MAX);
965
966        let mz_now = match as_of.as_option() {
967            Some(&as_of) => {
968                ResultSpec::value_between(Datum::MzTimestamp(as_of), Datum::MzTimestamp(until))
969            }
970            None => ResultSpec::value_all(),
971        };
972
973        self.execute_explain_pushdown_with_read_holds(
974            ctx,
975            as_of,
976            mz_now,
977            read_holds,
978            plan.source_imports
979                .into_iter()
980                .filter_map(|(id, import)| import.desc.arguments.operators.map(|mfp| (id, mfp))),
981        )
982        .await
983    }
984}