Skip to main content

mz_adapter/coord/sequencer/
inner.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 std::borrow::Cow;
11use std::collections::{BTreeMap, BTreeSet, VecDeque};
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14use std::{future, iter};
15
16use futures::Future;
17use futures::future::BoxFuture;
18use maplit::btreemap;
19use mz_adapter_types::compaction::CompactionWindow;
20use mz_adapter_types::connection::ConnectionId;
21use mz_adapter_types::dyncfgs::{ENABLE_EXPRESSION_CACHE, ENABLE_PASSWORD_AUTH};
22use mz_catalog::memory::error::ErrorKind;
23use mz_catalog::memory::objects::{
24    CatalogEntry, CatalogItem, DataSourceDesc, Index, Sink, Source, Table, TableDataSource, Type,
25};
26use mz_compute_types::ComputeInstanceId;
27use mz_compute_types::dataflows::LirDataflowDescription;
28use mz_compute_types::plan::scalar::LirScalarExpr;
29use mz_expr::{MfpPlan, ResultSpec};
30use mz_ore::collections::{CollectionExt, HashSet};
31use mz_ore::task::{self, JoinHandle, spawn};
32use mz_ore::tracing::OpenTelemetryContext;
33use mz_ore::{instrument, soft_panic_or_log};
34use mz_repr::adt::jsonb::Jsonb;
35use mz_repr::adt::mz_acl_item::{MzAclItem, PrivilegeMap};
36use mz_repr::explain::{ExprHumanizer, ExprHumanizerExt, TransientItem};
37use mz_repr::role_id::RoleId;
38use mz_repr::{CatalogItemId, Datum, Diff, GlobalId, RelationDesc, Row, Timestamp};
39use mz_sql::ast::{CreateSinkOption, CreateSinkOptionName};
40use mz_sql::catalog::{
41    CatalogCluster, CatalogClusterReplica, CatalogDatabase, CatalogError,
42    CatalogItem as SqlCatalogItem, CatalogRole, CatalogSchema, CatalogTypeDetails,
43    ErrorMessageObjectDescription, ObjectType, RoleAttributesRaw, RoleVars, SessionCatalog,
44};
45use mz_sql::names::{
46    ObjectId, QualifiedItemName, ResolvedDatabaseSpecifier, ResolvedIds, ResolvedItemName,
47    SchemaSpecifier, SystemObjectId,
48};
49use mz_sql::plan::{AlterMaterializedViewApplyReplacementPlan, NetworkPolicyRule};
50use mz_storage_types::sinks::StorageSinkDesc;
51// Import `plan` module, but only import select elements to avoid merge conflicts on use statements.
52use mz_sql::plan::{
53    AlterConnectionAction, AlterConnectionPlan, ExplainSinkSchemaPlan, Explainee,
54    ExplaineeStatement, PlannedAlterRoleOption, PlannedRoleVariable, SideEffectingFunc,
55    UpdatePrivilege, VariableValue,
56};
57use mz_sql::session::metadata::SessionMetadata;
58use mz_sql::session::user::UserKind;
59use mz_sql::session::vars::{
60    self, IsolationLevel, MAX_CONCURRENT_OCC_WRITES, NETWORK_POLICY, OwnedVarInput, SCHEMA_ALIAS,
61    TRANSACTION_ISOLATION_VAR_NAME, Var, VarError, VarInput,
62};
63use mz_sql::{plan, rbac};
64use mz_sql_parser::ast::display::AstDisplay;
65use mz_sql_parser::ast::{Statement, TransactionMode, WithOptionValue};
66use mz_storage_client::controller::ExportDescription;
67use mz_storage_types::connections::inline::IntoInlineConnection;
68use mz_storage_types::controller::StorageError;
69use mz_storage_types::sources::SourceConnection;
70use mz_transform::dataflow::DataflowMetainfo;
71use mz_transform::notice::{OptimizerNotice, RawOptimizerNotice};
72use smallvec::SmallVec;
73use timely::progress::Antichain;
74use tokio::sync::watch;
75use tracing::{Instrument, Span, info, warn};
76
77use crate::active_compute_sink::ActiveComputeSink;
78use crate::catalog::{
79    self, Catalog, CatalogState, ConnCatalog, DropObjectInfo, UpdatePrivilegeVariant,
80};
81use crate::command::ExecuteResponse;
82use crate::coord::appends::{BuiltinTableAppendNotify, PendingWriteTxn, UserWriteResponder};
83use crate::coord::sequencer::emit_optimizer_notices;
84use crate::coord::{
85    AlterMaterializedViewReadyContext, AlterSinkReadyContext, Coordinator, DeferredDdl,
86    ExecuteContext, Message, NetworkPolicyError, PendingReadTxn, PendingTxn, PendingTxnResponse,
87    PlanValidity, StageResult, Staged, StagedContext, WatchSetResponse,
88    validate_ip_with_policy_rules,
89};
90use crate::error::AdapterError;
91use crate::notice::{AdapterNotice, DroppedInUseIndex, InFlightIndexReaders};
92use crate::session::{
93    EndTransactionAction, RequireLinearization, Session, TransactionOps, TransactionStatus, WriteOp,
94};
95use crate::util::{ResultExt, viewable_variables};
96use crate::{CollectionIdBundle, ReadHolds};
97
98/// A future that resolves to a real-time recency timestamp.
99type RtrTimestampFuture = BoxFuture<'static, Result<Timestamp, StorageError>>;
100
101mod cluster;
102mod copy_from;
103mod create_index;
104mod create_materialized_view;
105mod create_metric_sink;
106mod create_view;
107mod explain_timestamp;
108mod secret;
109mod subscribe;
110
111/// Attempts to evaluate an expression. If an error is returned then the error is sent
112/// to the client and the function is exited.
113macro_rules! return_if_err {
114    ($expr:expr, $ctx:expr) => {
115        match $expr {
116            Ok(v) => v,
117            Err(e) => return $ctx.retire(Err(e.into())),
118        }
119    };
120}
121
122pub(super) use return_if_err;
123
124struct DropOps {
125    ops: Vec<catalog::Op>,
126    dropped_active_db: bool,
127    dropped_active_cluster: bool,
128}
129
130/// The outcome of [`Coordinator::check_index_dependents`].
131struct IndexDropNotices {
132    /// Indexes dropped while durable readers survive. Non-empty only when
133    /// `enable_drop_in_use_index` let the drop through.
134    orphaned: Vec<DroppedInUseIndex>,
135    /// Indexes still read by one-shot dataflows, which never block a drop.
136    in_flight: Vec<InFlightIndexReaders>,
137}
138
139// A bundle of values returned from create_source_inner
140struct CreateSourceInner {
141    ops: Vec<catalog::Op>,
142    sources: Vec<(CatalogItemId, QualifiedItemName, Source)>,
143    if_not_exists_ids: BTreeMap<CatalogItemId, QualifiedItemName>,
144}
145
146impl Coordinator {
147    /// Sequences a [Staged] plan.
148    ///
149    /// This is designed for plans that execute both on and off the coordinator
150    /// thread. Stages can either produce another stage to execute or a final
151    /// response. Maintains the connection-scoped cancel watch in
152    /// `connection_cancel_watches` while a stage is cancelable.
153    pub(crate) async fn sequence_staged<S>(
154        &mut self,
155        mut ctx: S::Ctx,
156        parent_span: Span,
157        mut stage: S,
158    ) where
159        S: Staged + 'static,
160        S::Ctx: Send + 'static,
161    {
162        return_if_err!(stage.validity().check(self.catalog()), ctx);
163        loop {
164            let mut cancel_enabled = stage.cancel_enabled();
165            if let Some(session) = ctx.session() {
166                if cancel_enabled {
167                    // Channel to await cancellation. Insert a new channel, but check if the previous one
168                    // was already canceled.
169                    if let Some((_prev_tx, prev_rx)) = self
170                        .connection_cancel_watches
171                        .insert(session.conn_id().clone(), watch::channel(false))
172                    {
173                        let was_canceled = *prev_rx.borrow();
174                        if was_canceled {
175                            ctx.retire(Err(AdapterError::Canceled));
176                            return;
177                        }
178                    }
179                } else {
180                    // If no cancel allowed, remove it so handle_spawn doesn't observe any previous value
181                    // when cancel_enabled may have been true on an earlier stage.
182                    self.connection_cancel_watches.remove(session.conn_id());
183                }
184            } else {
185                cancel_enabled = false
186            };
187            // Stage implementations can contain large optimizer and DDL futures.
188            // Keep that state out of the generic plan dispatcher's allocation.
189            let next = Box::pin(stage.stage(self, &mut ctx).instrument(parent_span.clone())).await;
190            let res = return_if_err!(next, ctx);
191            stage = match res {
192                StageResult::Handle(handle) => {
193                    let internal_cmd_tx = self.internal_cmd_tx.clone();
194                    self.handle_spawn(ctx, handle, cancel_enabled, move |ctx, next| {
195                        let _ = internal_cmd_tx.send(next.message(ctx, parent_span));
196                    });
197                    return;
198                }
199                StageResult::HandleRetire(handle) => {
200                    self.handle_spawn(ctx, handle, cancel_enabled, move |ctx, resp| {
201                        ctx.retire(Ok(resp));
202                    });
203                    return;
204                }
205                StageResult::Response(resp) => {
206                    ctx.retire(Ok(resp));
207                    return;
208                }
209                StageResult::Immediate(stage) => *stage,
210            }
211        }
212    }
213
214    /// Waits for either the spawned stage work to complete or cancellation to
215    /// be signaled through the connection-scoped cancel watch.
216    fn handle_spawn<C, T, F>(
217        &self,
218        ctx: C,
219        handle: JoinHandle<Result<T, AdapterError>>,
220        cancel_enabled: bool,
221        f: F,
222    ) where
223        C: StagedContext + Send + 'static,
224        T: Send + 'static,
225        F: FnOnce(C, T) + Send + 'static,
226    {
227        let rx: BoxFuture<()> = if let Some((_tx, rx)) = ctx
228            .session()
229            .and_then(|session| self.connection_cancel_watches.get(session.conn_id()))
230        {
231            let mut rx = rx.clone();
232            Box::pin(async move {
233                // Wait for true or dropped sender.
234                let _ = rx.wait_for(|v| *v).await;
235                ()
236            })
237        } else {
238            Box::pin(future::pending())
239        };
240        spawn(|| "sequence_staged", async move {
241            tokio::select! {
242                res = handle => {
243                    let next = return_if_err!(res, ctx);
244                    f(ctx, next);
245                }
246                _ = rx, if cancel_enabled => {
247                    ctx.retire(Err(AdapterError::Canceled));
248                }
249            }
250        });
251    }
252
253    async fn create_source_inner(
254        &self,
255        session: &Session,
256        plans: Vec<plan::CreateSourcePlanBundle>,
257    ) -> Result<CreateSourceInner, AdapterError> {
258        let mut ops = vec![];
259        let mut sources = vec![];
260
261        let if_not_exists_ids = plans
262            .iter()
263            .filter_map(
264                |plan::CreateSourcePlanBundle {
265                     item_id,
266                     global_id: _,
267                     plan,
268                     resolved_ids: _,
269                     available_source_references: _,
270                 }| {
271                    if plan.if_not_exists {
272                        Some((*item_id, plan.name.clone()))
273                    } else {
274                        None
275                    }
276                },
277            )
278            .collect::<BTreeMap<_, _>>();
279
280        for plan::CreateSourcePlanBundle {
281            item_id,
282            global_id,
283            mut plan,
284            resolved_ids,
285            available_source_references,
286        } in plans
287        {
288            let name = plan.name.clone();
289
290            // Attempt to reduce the `CHECK` expression, we timeout if this takes too long.
291            if let mz_sql::plan::DataSourceDesc::Webhook {
292                validate_using: Some(validate),
293                ..
294            } = &mut plan.source.data_source
295            {
296                if let Err(reason) = validate.reduce_expression().await {
297                    self.metrics
298                        .webhook_validation_reduce_failures
299                        .with_label_values(&[reason])
300                        .inc();
301                    return Err(AdapterError::Internal(format!(
302                        "failed to reduce check expression, {reason}"
303                    )));
304                }
305            }
306
307            // If this source contained a set of available source references, update the
308            // source references catalog table.
309            let mut reference_ops = vec![];
310            if let Some(references) = &available_source_references {
311                reference_ops.push(catalog::Op::UpdateSourceReferences {
312                    source_id: item_id,
313                    references: references.clone().into(),
314                });
315            }
316
317            let source = Source::new(plan, global_id, resolved_ids, None, false);
318            ops.push(catalog::Op::CreateItem {
319                id: item_id,
320                name: name.clone(),
321                item: CatalogItem::Source(source.clone()),
322                owner_id: *session.current_role_id(),
323            });
324            sources.push((item_id, name, source));
325            // These operations must be executed after the source is added to the catalog.
326            ops.extend(reference_ops);
327        }
328
329        Ok(CreateSourceInner {
330            ops,
331            sources,
332            if_not_exists_ids,
333        })
334    }
335
336    #[instrument]
337    pub(super) async fn sequence_create_source(
338        &mut self,
339        ctx: &mut ExecuteContext,
340        plans: Vec<plan::CreateSourcePlanBundle>,
341    ) -> Result<ExecuteResponse, AdapterError> {
342        let CreateSourceInner {
343            ops,
344            sources,
345            if_not_exists_ids,
346        } = self.create_source_inner(ctx.session(), plans).await?;
347
348        let transact_result = self
349            .catalog_transact_with_context(None, Some(ctx), ops)
350            .await;
351
352        // Check if any sources are webhook sources and report them as created.
353        for (item_id, _name, source) in &sources {
354            if matches!(source.data_source, DataSourceDesc::Webhook { .. }) {
355                if let Some(url) = self.catalog().state().try_get_webhook_url(item_id) {
356                    ctx.session()
357                        .add_notice(AdapterNotice::WebhookSourceCreated { url });
358                }
359            }
360        }
361
362        match transact_result {
363            Ok(()) => {
364                // Speculative names belong to the transaction's catalog. Their
365                // schema or cluster can disappear before commit validation.
366                for (_item_id, name, source) in &sources {
367                    let cluster_id = match &source.data_source {
368                        DataSourceDesc::Ingestion { desc, cluster_id }
369                        | DataSourceDesc::OldSyntaxIngestion {
370                            desc, cluster_id, ..
371                        } if desc.connection.prefers_single_replica() => cluster_id,
372                        _ => continue,
373                    };
374                    let Some(cluster) = self.catalog().try_get_cluster(*cluster_id) else {
375                        continue;
376                    };
377                    let state = ctx
378                        .session()
379                        .transaction()
380                        .catalog_state()
381                        .unwrap_or_else(|| self.catalog().state());
382                    let name = state.resolve_full_name(name, None);
383                    self.notify_single_replica_sources(ctx.session(), cluster, Some(&name));
384                }
385                Ok(ExecuteResponse::CreatedSource)
386            }
387            Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
388                kind: ErrorKind::Sql(CatalogError::ItemAlreadyExists(id, _)),
389            })) if if_not_exists_ids.contains_key(&id) => {
390                ctx.session()
391                    .add_notice(AdapterNotice::ObjectAlreadyExists {
392                        name: if_not_exists_ids[&id].item.clone(),
393                        ty: "source",
394                    });
395                Ok(ExecuteResponse::CreatedSource)
396            }
397            Err(err) => Err(err),
398        }
399    }
400
401    /// Applies the secret-content guards of every connection that uses
402    /// `secret_id` against proposed new `contents` for that secret. Must be
403    /// called whenever a secret's contents change, before the new value is
404    /// persisted.
405    pub(super) fn check_secret_content_guards_of_dependents(
406        &self,
407        secret_id: CatalogItemId,
408        contents: &str,
409    ) -> Result<(), AdapterError> {
410        for dependent_id in self.catalog().get_entry(&secret_id).used_by() {
411            if let CatalogItem::Connection(conn) = self.catalog().get_entry(dependent_id).item() {
412                for (guarded_id, guard) in conn.details.secret_content_guards() {
413                    if guarded_id == secret_id {
414                        guard(contents)?;
415                    }
416                }
417            }
418        }
419        Ok(())
420    }
421
422    #[instrument]
423    pub(super) async fn sequence_create_database(
424        &mut self,
425        session: &Session,
426        plan: plan::CreateDatabasePlan,
427    ) -> Result<ExecuteResponse, AdapterError> {
428        let ops = vec![catalog::Op::CreateDatabase {
429            name: plan.name.clone(),
430            owner_id: *session.current_role_id(),
431        }];
432        match self.catalog_transact(Some(session), ops).await {
433            Ok(_) => Ok(ExecuteResponse::CreatedDatabase),
434            Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
435                kind: ErrorKind::Sql(CatalogError::DatabaseAlreadyExists(_)),
436            })) if plan.if_not_exists => {
437                session.add_notice(AdapterNotice::DatabaseAlreadyExists { name: plan.name });
438                Ok(ExecuteResponse::CreatedDatabase)
439            }
440            Err(err) => Err(err),
441        }
442    }
443
444    #[instrument]
445    pub(super) async fn sequence_create_schema(
446        &mut self,
447        session: &Session,
448        plan: plan::CreateSchemaPlan,
449    ) -> Result<ExecuteResponse, AdapterError> {
450        let op = catalog::Op::CreateSchema {
451            database_id: plan.database_spec,
452            schema_name: plan.schema_name.clone(),
453            owner_id: *session.current_role_id(),
454        };
455        match self.catalog_transact(Some(session), vec![op]).await {
456            Ok(_) => Ok(ExecuteResponse::CreatedSchema),
457            Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
458                kind: ErrorKind::Sql(CatalogError::SchemaAlreadyExists(_)),
459            })) if plan.if_not_exists => {
460                session.add_notice(AdapterNotice::SchemaAlreadyExists {
461                    name: plan.schema_name,
462                });
463                Ok(ExecuteResponse::CreatedSchema)
464            }
465            Err(err) => Err(err),
466        }
467    }
468
469    /// Validates the role attributes for a `CREATE ROLE` statement.
470    fn validate_role_attributes(&self, attributes: &RoleAttributesRaw) -> Result<(), AdapterError> {
471        if !ENABLE_PASSWORD_AUTH.get(self.catalog().system_config().dyncfgs()) {
472            if attributes.superuser.is_some() || attributes.password.is_some() {
473                return Err(AdapterError::UnavailableFeature {
474                    feature: "SUPERUSER and PASSWORD attributes".to_string(),
475                    docs: Some("https://materialize.com/docs/sql/create-role/#details".to_string()),
476                });
477            }
478        }
479        Ok(())
480    }
481
482    #[instrument]
483    pub(super) async fn sequence_create_role(
484        &mut self,
485        conn_id: Option<&ConnectionId>,
486        plan::CreateRolePlan { name, attributes }: plan::CreateRolePlan,
487    ) -> Result<ExecuteResponse, AdapterError> {
488        self.validate_role_attributes(&attributes.clone())?;
489        let op = catalog::Op::CreateRole { name, attributes };
490        self.catalog_transact_with_context(conn_id, None, vec![op])
491            .await
492            .map(|_| ExecuteResponse::CreatedRole)
493    }
494
495    #[instrument]
496    pub(super) async fn sequence_create_query_policy(
497        &mut self,
498        session: &Session,
499        plan::CreateQueryPolicyPlan { name, mode, rules }: plan::CreateQueryPolicyPlan,
500    ) -> Result<ExecuteResponse, AdapterError> {
501        let op = catalog::Op::CreateQueryPolicy {
502            name,
503            mode,
504            rules,
505            owner_id: *session.current_role_id(),
506        };
507        self.catalog_transact_with_context(Some(session.conn_id()), None, vec![op])
508            .await
509            .map(|_| ExecuteResponse::CreatedQueryPolicy)
510    }
511
512    #[instrument]
513    pub(super) async fn sequence_alter_query_policy(
514        &mut self,
515        session: &Session,
516        plan::AlterQueryPolicyPlan {
517            id,
518            name: _,
519            mode,
520            rules,
521        }: plan::AlterQueryPolicyPlan,
522    ) -> Result<ExecuteResponse, AdapterError> {
523        let op = catalog::Op::AlterQueryPolicy { id, mode, rules };
524        self.catalog_transact_with_context(Some(session.conn_id()), None, vec![op])
525            .await
526            .map(|_| ExecuteResponse::AlteredObject(ObjectType::QueryPolicy))
527    }
528
529    #[instrument]
530    pub(super) async fn sequence_create_network_policy(
531        &mut self,
532        session: &Session,
533        plan::CreateNetworkPolicyPlan { name, rules }: plan::CreateNetworkPolicyPlan,
534    ) -> Result<ExecuteResponse, AdapterError> {
535        let op = catalog::Op::CreateNetworkPolicy {
536            rules,
537            name,
538            owner_id: *session.current_role_id(),
539        };
540        self.catalog_transact_with_context(Some(session.conn_id()), None, vec![op])
541            .await
542            .map(|_| ExecuteResponse::CreatedNetworkPolicy)
543    }
544
545    #[instrument]
546    pub(super) async fn sequence_alter_network_policy(
547        &mut self,
548        session: &Session,
549        plan::AlterNetworkPolicyPlan { id, name, rules }: plan::AlterNetworkPolicyPlan,
550    ) -> Result<ExecuteResponse, AdapterError> {
551        // TODO(network_policy): Consider role based network policies here.
552        let current_network_policy_name =
553            self.catalog().system_config().default_network_policy_name();
554        // Check if the way we're alerting the policy is still valid for the current connection.
555        if current_network_policy_name == name {
556            self.validate_alter_network_policy(session, &rules)?;
557        }
558
559        let op = catalog::Op::AlterNetworkPolicy {
560            id,
561            rules,
562            name,
563            owner_id: *session.current_role_id(),
564        };
565        self.catalog_transact_with_context(Some(session.conn_id()), None, vec![op])
566            .await
567            .map(|_| ExecuteResponse::AlteredObject(ObjectType::NetworkPolicy))
568    }
569
570    #[instrument]
571    pub(super) async fn sequence_create_table(
572        &mut self,
573        ctx: &mut ExecuteContext,
574        plan: plan::CreateTablePlan,
575        resolved_ids: ResolvedIds,
576    ) -> Result<ExecuteResponse, AdapterError> {
577        let plan::CreateTablePlan {
578            name,
579            table,
580            if_not_exists,
581        } = plan;
582
583        let (table_id, global_id) = self.allocate_user_id().await?;
584        let table = Table::from_plan(
585            table,
586            global_id,
587            ctx.session().conn_id().clone(),
588            resolved_ids,
589        );
590        let is_webhook = matches!(
591            &table.data_source,
592            TableDataSource::DataSource {
593                desc: DataSourceDesc::Webhook { .. },
594                ..
595            }
596        );
597        let ops = vec![catalog::Op::CreateItem {
598            id: table_id,
599            name: name.clone(),
600            item: CatalogItem::Table(table.clone()),
601            owner_id: *ctx.session().current_role_id(),
602        }];
603
604        let catalog_result = self
605            .catalog_transact_with_context(None, Some(ctx), ops)
606            .await;
607
608        if is_webhook {
609            // try_get_webhook_url will make up a URL for things that are not
610            // webhooks, so we guard against that here.
611            if let Some(url) = self.catalog().state().try_get_webhook_url(&table_id) {
612                ctx.session()
613                    .add_notice(AdapterNotice::WebhookSourceCreated { url })
614            }
615        }
616
617        match catalog_result {
618            Ok(()) => Ok(ExecuteResponse::CreatedTable),
619            Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
620                kind: ErrorKind::Sql(CatalogError::ItemAlreadyExists(_, _)),
621            })) if if_not_exists => {
622                ctx.session_mut()
623                    .add_notice(AdapterNotice::ObjectAlreadyExists {
624                        name: name.item,
625                        ty: "table",
626                    });
627                Ok(ExecuteResponse::CreatedTable)
628            }
629            Err(err) => Err(err),
630        }
631    }
632
633    #[instrument]
634    pub(super) async fn sequence_create_sink(
635        &mut self,
636        ctx: ExecuteContext,
637        plan: plan::CreateSinkPlan,
638        resolved_ids: ResolvedIds,
639    ) {
640        let plan::CreateSinkPlan {
641            name,
642            sink,
643            with_snapshot,
644            if_not_exists,
645            in_cluster,
646        } = plan;
647
648        // First try to allocate an ID and an OID. If either fails, we're done.
649        let (item_id, global_id) = return_if_err!(self.allocate_user_id().await, ctx);
650
651        let catalog_sink = Sink {
652            create_sql: sink.create_sql,
653            global_id,
654            from: sink.from,
655            connection: sink.connection,
656            envelope: sink.envelope,
657            version: sink.version,
658            with_snapshot,
659            resolved_ids,
660            cluster_id: in_cluster,
661            commit_interval: sink.commit_interval,
662        };
663
664        let ops = vec![catalog::Op::CreateItem {
665            id: item_id,
666            name: name.clone(),
667            item: CatalogItem::Sink(catalog_sink.clone()),
668            owner_id: *ctx.session().current_role_id(),
669        }];
670
671        let result = self.catalog_transact(Some(ctx.session()), ops).await;
672
673        match result {
674            Ok(()) => {}
675            Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
676                kind: ErrorKind::Sql(CatalogError::ItemAlreadyExists(_, _)),
677            })) if if_not_exists => {
678                ctx.session()
679                    .add_notice(AdapterNotice::ObjectAlreadyExists {
680                        name: name.item,
681                        ty: "sink",
682                    });
683                ctx.retire(Ok(ExecuteResponse::CreatedSink));
684                return;
685            }
686            Err(e) => {
687                ctx.retire(Err(e));
688                return;
689            }
690        };
691
692        self.create_storage_export(global_id, &catalog_sink)
693            .await
694            .unwrap_or_terminate("cannot fail to create exports");
695
696        self.initialize_storage_read_policies([item_id].into(), CompactionWindow::Default)
697            .await;
698
699        ctx.retire(Ok(ExecuteResponse::CreatedSink))
700    }
701
702    /// Validates that a view definition does not contain any expressions that may lead to
703    /// ambiguous column references to system tables. For example `NATURAL JOIN` or `SELECT *`.
704    ///
705    /// We prevent these expressions so that we can add columns to system tables without
706    /// changing the definition of the view.
707    ///
708    /// Here is a bit of a hand wavy proof as to why we only need to check the
709    /// immediate view definition for system objects and ambiguous column
710    /// references, and not the entire dependency tree:
711    ///
712    ///   - A view with no object references cannot have any ambiguous column
713    ///   references to a system object, because it has no system objects.
714    ///   - A view with a direct reference to a system object and a * or
715    ///   NATURAL JOIN will be rejected due to ambiguous column references.
716    ///   - A view with system objects but no * or NATURAL JOINs cannot have
717    ///   any ambiguous column references to a system object, because all column
718    ///   references are explicitly named.
719    ///   - A view with * or NATURAL JOINs, that doesn't directly reference a
720    ///   system object cannot have any ambiguous column references to a system
721    ///   object, because there are no system objects in the top level view and
722    ///   all sub-views are guaranteed to have no ambiguous column references to
723    ///   system objects.
724    pub(super) fn validate_system_column_references(
725        &self,
726        uses_ambiguous_columns: bool,
727        depends_on: &BTreeSet<GlobalId>,
728    ) -> Result<(), AdapterError> {
729        if uses_ambiguous_columns
730            && depends_on
731                .iter()
732                .any(|id| id.is_system() && self.catalog().get_entry_by_global_id(id).is_relation())
733        {
734            Err(AdapterError::AmbiguousSystemColumnReference)
735        } else {
736            Ok(())
737        }
738    }
739
740    #[instrument]
741    pub(super) async fn sequence_create_type(
742        &mut self,
743        session: &Session,
744        plan: plan::CreateTypePlan,
745        resolved_ids: ResolvedIds,
746    ) -> Result<ExecuteResponse, AdapterError> {
747        let (item_id, global_id) = self.allocate_user_id().await?;
748        // Validate the type definition (e.g., composite columns) before storing.
749        plan.typ
750            .inner
751            .desc(&self.catalog().for_session(session))
752            .map_err(AdapterError::from)?;
753        let typ = Type {
754            create_sql: Some(plan.typ.create_sql),
755            global_id,
756            details: CatalogTypeDetails {
757                array_id: None,
758                typ: plan.typ.inner,
759                pg_metadata: None,
760            },
761            resolved_ids,
762        };
763        let op = catalog::Op::CreateItem {
764            id: item_id,
765            name: plan.name,
766            item: CatalogItem::Type(typ),
767            owner_id: *session.current_role_id(),
768        };
769        match self.catalog_transact(Some(session), vec![op]).await {
770            Ok(()) => Ok(ExecuteResponse::CreatedType),
771            Err(err) => Err(err),
772        }
773    }
774
775    #[instrument]
776    pub(super) async fn sequence_comment_on(
777        &mut self,
778        session: &Session,
779        plan: plan::CommentPlan,
780    ) -> Result<ExecuteResponse, AdapterError> {
781        let op = catalog::Op::Comment {
782            object_id: plan.object_id,
783            sub_component: plan.sub_component,
784            comment: plan.comment,
785        };
786        self.catalog_transact(Some(session), vec![op]).await?;
787        Ok(ExecuteResponse::Comment)
788    }
789
790    #[instrument]
791    pub(super) async fn sequence_drop_objects(
792        &mut self,
793        ctx: &mut ExecuteContext,
794        plan::DropObjectsPlan {
795            cascade,
796            drop_ids,
797            object_type,
798            referenced_ids,
799        }: plan::DropObjectsPlan,
800    ) -> Result<ExecuteResponse, AdapterError> {
801        let IndexDropNotices {
802            orphaned,
803            in_flight,
804        } = self.check_index_dependents(ctx.session(), &drop_ids)?;
805
806        let referenced_ids_hashset = referenced_ids.iter().collect::<HashSet<_>>();
807        let mut objects = Vec::new();
808        for obj_id in &drop_ids {
809            if !referenced_ids_hashset.contains(obj_id) {
810                let object_info = ErrorMessageObjectDescription::from_id(
811                    obj_id,
812                    &self.catalog().for_session(ctx.session()),
813                )
814                .to_string();
815                objects.push(object_info);
816            }
817        }
818
819        if !objects.is_empty() {
820            ctx.session()
821                .add_notice(AdapterNotice::CascadeDroppedObject { objects });
822        }
823
824        // Collect GlobalIds for expression cache invalidation.
825        let expr_cache_invalidate_ids: BTreeSet<_> = drop_ids
826            .iter()
827            .filter_map(|id| match id {
828                ObjectId::Item(item_id) => Some(self.catalog().get_entry(item_id).global_ids()),
829                _ => None,
830            })
831            .flatten()
832            .collect();
833
834        let DropOps {
835            ops,
836            dropped_active_db,
837            dropped_active_cluster,
838        } = self.sequence_drop_common(ctx.session(), drop_ids, cascade)?;
839
840        self.catalog_transact_with_context(None, Some(ctx), ops)
841            .await?;
842
843        // Invalidate expression cache entries for dropped objects.
844        if !expr_cache_invalidate_ids.is_empty() {
845            let _fut = self.catalog().update_expression_cache(
846                Default::default(),
847                Default::default(),
848                expr_cache_invalidate_ids,
849            );
850        }
851
852        fail::fail_point!("after_sequencer_drop_replica");
853
854        if dropped_active_db {
855            ctx.session()
856                .add_notice(AdapterNotice::DroppedActiveDatabase {
857                    name: ctx.session().vars().database().to_string(),
858                });
859        }
860        if dropped_active_cluster {
861            ctx.session()
862                .add_notice(AdapterNotice::DroppedActiveCluster {
863                    name: ctx.session().vars().cluster().to_string(),
864                });
865        }
866        self.emit_index_drop_notices(ctx.session(), orphaned, in_flight);
867        Ok(ExecuteResponse::DroppedObject(object_type))
868    }
869
870    fn validate_dropped_role_ownership(
871        &self,
872        session: &Session,
873        dropped_roles: &BTreeMap<RoleId, &str>,
874    ) -> Result<(), AdapterError> {
875        fn privilege_check(
876            privileges: &PrivilegeMap,
877            dropped_roles: &BTreeMap<RoleId, &str>,
878            dependent_objects: &mut BTreeMap<String, Vec<String>>,
879            object_id: &SystemObjectId,
880            catalog: &ConnCatalog,
881        ) {
882            for privilege in privileges.all_values() {
883                if let Some(role_name) = dropped_roles.get(&privilege.grantee) {
884                    let grantor_name = catalog.get_role(&privilege.grantor).name();
885                    let object_description =
886                        ErrorMessageObjectDescription::from_sys_id(object_id, catalog);
887                    dependent_objects
888                        .entry(role_name.to_string())
889                        .or_default()
890                        .push(format!(
891                            "privileges on {object_description} granted by {grantor_name}",
892                        ));
893                }
894                if let Some(role_name) = dropped_roles.get(&privilege.grantor) {
895                    let grantee_name = catalog.get_role(&privilege.grantee).name();
896                    let object_description =
897                        ErrorMessageObjectDescription::from_sys_id(object_id, catalog);
898                    dependent_objects
899                        .entry(role_name.to_string())
900                        .or_default()
901                        .push(format!(
902                            "privileges granted on {object_description} to {grantee_name}"
903                        ));
904                }
905            }
906        }
907
908        let catalog = self.catalog().for_session(session);
909        let mut dependent_objects: BTreeMap<_, Vec<_>> = BTreeMap::new();
910        for entry in self.catalog.entries() {
911            let id = SystemObjectId::Object(entry.id().into());
912            if let Some(role_name) = dropped_roles.get(entry.owner_id()) {
913                let object_description = ErrorMessageObjectDescription::from_sys_id(&id, &catalog);
914                dependent_objects
915                    .entry(role_name.to_string())
916                    .or_default()
917                    .push(format!("owner of {object_description}"));
918            }
919            privilege_check(
920                entry.privileges(),
921                dropped_roles,
922                &mut dependent_objects,
923                &id,
924                &catalog,
925            );
926        }
927        for database in self.catalog.databases() {
928            let database_id = SystemObjectId::Object(database.id().into());
929            if let Some(role_name) = dropped_roles.get(&database.owner_id) {
930                let object_description =
931                    ErrorMessageObjectDescription::from_sys_id(&database_id, &catalog);
932                dependent_objects
933                    .entry(role_name.to_string())
934                    .or_default()
935                    .push(format!("owner of {object_description}"));
936            }
937            privilege_check(
938                &database.privileges,
939                dropped_roles,
940                &mut dependent_objects,
941                &database_id,
942                &catalog,
943            );
944            for schema in database.schemas_by_id.values() {
945                let schema_id = SystemObjectId::Object(
946                    (ResolvedDatabaseSpecifier::Id(database.id()), *schema.id()).into(),
947                );
948                if let Some(role_name) = dropped_roles.get(&schema.owner_id) {
949                    let object_description =
950                        ErrorMessageObjectDescription::from_sys_id(&schema_id, &catalog);
951                    dependent_objects
952                        .entry(role_name.to_string())
953                        .or_default()
954                        .push(format!("owner of {object_description}"));
955                }
956                privilege_check(
957                    &schema.privileges,
958                    dropped_roles,
959                    &mut dependent_objects,
960                    &schema_id,
961                    &catalog,
962                );
963            }
964        }
965        for cluster in self.catalog.clusters() {
966            let cluster_id = SystemObjectId::Object(cluster.id().into());
967            if let Some(role_name) = dropped_roles.get(&cluster.owner_id) {
968                let object_description =
969                    ErrorMessageObjectDescription::from_sys_id(&cluster_id, &catalog);
970                dependent_objects
971                    .entry(role_name.to_string())
972                    .or_default()
973                    .push(format!("owner of {object_description}"));
974            }
975            privilege_check(
976                &cluster.privileges,
977                dropped_roles,
978                &mut dependent_objects,
979                &cluster_id,
980                &catalog,
981            );
982            for replica in cluster.replicas() {
983                if let Some(role_name) = dropped_roles.get(&replica.owner_id) {
984                    let replica_id =
985                        SystemObjectId::Object((replica.cluster_id(), replica.replica_id()).into());
986                    let object_description =
987                        ErrorMessageObjectDescription::from_sys_id(&replica_id, &catalog);
988                    dependent_objects
989                        .entry(role_name.to_string())
990                        .or_default()
991                        .push(format!("owner of {object_description}"));
992                }
993            }
994        }
995        for policy in catalog.get_query_policies() {
996            let id = SystemObjectId::Object(ObjectId::QueryPolicy(policy.id()));
997            if let Some(role_name) = dropped_roles.get(&policy.owner_id()) {
998                let object_description = ErrorMessageObjectDescription::from_sys_id(&id, &catalog);
999                dependent_objects
1000                    .entry(role_name.to_string())
1001                    .or_default()
1002                    .push(format!("owner of {object_description}"));
1003            }
1004            privilege_check(
1005                policy.privileges(),
1006                dropped_roles,
1007                &mut dependent_objects,
1008                &id,
1009                &catalog,
1010            );
1011        }
1012        privilege_check(
1013            self.catalog().system_privileges(),
1014            dropped_roles,
1015            &mut dependent_objects,
1016            &SystemObjectId::System,
1017            &catalog,
1018        );
1019        for (default_privilege_object, default_privilege_acl_items) in
1020            self.catalog.default_privileges()
1021        {
1022            if let Some(role_name) = dropped_roles.get(&default_privilege_object.role_id) {
1023                dependent_objects
1024                    .entry(role_name.to_string())
1025                    .or_default()
1026                    .push(format!(
1027                        "default privileges on {}S created by {}",
1028                        default_privilege_object.object_type, role_name
1029                    ));
1030            }
1031            for default_privilege_acl_item in default_privilege_acl_items {
1032                if let Some(role_name) = dropped_roles.get(&default_privilege_acl_item.grantee) {
1033                    dependent_objects
1034                        .entry(role_name.to_string())
1035                        .or_default()
1036                        .push(format!(
1037                            "default privileges on {}S granted to {}",
1038                            default_privilege_object.object_type, role_name
1039                        ));
1040                }
1041            }
1042        }
1043
1044        if !dependent_objects.is_empty() {
1045            Err(AdapterError::DependentObject(dependent_objects))
1046        } else {
1047            Ok(())
1048        }
1049    }
1050
1051    #[instrument]
1052    pub(super) async fn sequence_drop_owned(
1053        &mut self,
1054        session: &Session,
1055        plan: plan::DropOwnedPlan,
1056    ) -> Result<ExecuteResponse, AdapterError> {
1057        for role_id in &plan.role_ids {
1058            self.catalog().ensure_not_reserved_role(role_id)?;
1059        }
1060
1061        let mut privilege_revokes = plan.privilege_revokes;
1062
1063        // Make sure this stays in sync with the beginning of `rbac::check_plan`.
1064        let session_catalog = self.catalog().for_session(session);
1065        if rbac::is_rbac_enabled_for_session(session_catalog.system_vars(), session)
1066            && !session.is_superuser()
1067        {
1068            // Obtain all roles that the current session is a member of.
1069            let role_membership =
1070                session_catalog.collect_role_membership(session.current_role_id());
1071            let invalid_revokes: BTreeSet<_> = privilege_revokes
1072                .extract_if(.., |(_, privilege)| {
1073                    !role_membership.contains(&privilege.grantor)
1074                })
1075                .map(|(object_id, _)| object_id)
1076                .collect();
1077            for invalid_revoke in invalid_revokes {
1078                let object_description =
1079                    ErrorMessageObjectDescription::from_sys_id(&invalid_revoke, &session_catalog);
1080                session.add_notice(AdapterNotice::CannotRevoke { object_description });
1081            }
1082        }
1083
1084        // Group revokes by target so each object is rewritten once, not once per privilege.
1085        let mut privilege_revokes_by_target: BTreeMap<SystemObjectId, Vec<MzAclItem>> =
1086            BTreeMap::new();
1087        for (object_id, privilege) in privilege_revokes {
1088            privilege_revokes_by_target
1089                .entry(object_id)
1090                .or_default()
1091                .push(privilege);
1092        }
1093        let privilege_revoke_ops =
1094            privilege_revokes_by_target
1095                .into_iter()
1096                .map(|(target_id, privileges)| catalog::Op::UpdatePrivilege {
1097                    target_id,
1098                    privileges,
1099                    variant: UpdatePrivilegeVariant::Revoke,
1100                });
1101        let default_privilege_revoke_ops = plan.default_privilege_revokes.into_iter().map(
1102            |(privilege_object, privilege_acl_item)| catalog::Op::UpdateDefaultPrivilege {
1103                privilege_object,
1104                privilege_acl_item,
1105                variant: UpdatePrivilegeVariant::Revoke,
1106            },
1107        );
1108        let IndexDropNotices {
1109            orphaned,
1110            in_flight,
1111        } = self.check_index_dependents(session, &plan.drop_ids)?;
1112        let DropOps {
1113            ops: drop_ops,
1114            dropped_active_db,
1115            dropped_active_cluster,
1116        } = self.sequence_drop_common(session, plan.drop_ids, plan.cascade)?;
1117
1118        let ops = privilege_revoke_ops
1119            .chain(default_privilege_revoke_ops)
1120            .chain(drop_ops.into_iter())
1121            .collect();
1122
1123        self.catalog_transact(Some(session), ops).await?;
1124
1125        if dropped_active_db {
1126            session.add_notice(AdapterNotice::DroppedActiveDatabase {
1127                name: session.vars().database().to_string(),
1128            });
1129        }
1130        if dropped_active_cluster {
1131            session.add_notice(AdapterNotice::DroppedActiveCluster {
1132                name: session.vars().cluster().to_string(),
1133            });
1134        }
1135        self.emit_index_drop_notices(session, orphaned, in_flight);
1136        Ok(ExecuteResponse::DroppedOwned)
1137    }
1138
1139    /// Refuses to drop indexes that a surviving materialized view, index, or metric sink reads
1140    /// from, naming every blocked index in one error.
1141    ///
1142    /// A reader survives unless it is itself in `drop_ids`. With `enable_drop_in_use_index`
1143    /// set, the drop proceeds instead and the orphaned indexes are reported for a warning.
1144    ///
1145    /// One-shot dataflows (`SUBSCRIBE`, `COPY TO`, slow-path `SELECT`, and system dataflows
1146    /// such as curated metric sinks) never block a drop. They finish on their own or are
1147    /// reinstalled, and are reported only for a notice.
1148    ///
1149    /// TODO: once pinned LIR makes a dataflow's index imports a durable property, record them
1150    /// as catalog dependencies so the planner can do this with its regular dependency walk.
1151    ///
1152    /// NOTE: The check is sound only because `DROP` is serialized DDL (`must_serialize_ddl`)
1153    /// and callers do not await between it and the catalog commit. Otherwise a concurrent
1154    /// `CREATE MATERIALIZED VIEW` could start reading the index in between.
1155    fn check_index_dependents(
1156        &self,
1157        session: &Session,
1158        drop_ids: &[ObjectId],
1159    ) -> Result<IndexDropNotices, AdapterError> {
1160        let humanizer = self.catalog().for_session(session);
1161        let drop_in_use_allowed = self.catalog().system_config().enable_drop_in_use_index();
1162        let humanize_index = |index: &Index, item_id: &CatalogItemId| {
1163            humanizer
1164                .humanize_id(index.global_id())
1165                .unwrap_or_else(|| item_id.to_string())
1166        };
1167
1168        let drop_set: BTreeSet<ObjectId> = drop_ids.iter().cloned().collect();
1169        let mut orphaned = Vec::new();
1170        let mut blocked = Vec::new();
1171        let mut transient_by_index = Vec::new();
1172        for id in drop_ids {
1173            let ObjectId::Item(item_id) = id else {
1174                continue;
1175            };
1176            let Some(index) = self.catalog().get_entry(item_id).index() else {
1177                continue;
1178            };
1179            let (durable, transient) = self.index_readers(index, &drop_set);
1180            if !transient.is_empty() {
1181                transient_by_index.push((index, item_id, transient));
1182            }
1183            if durable.is_empty() {
1184                continue;
1185            }
1186            if !drop_in_use_allowed {
1187                let dependents = durable
1188                    .into_iter()
1189                    .map(|dependent_id| {
1190                        let entry = self.catalog().get_entry(&dependent_id);
1191                        (
1192                            entry.item_type().to_string(),
1193                            humanizer.minimal_qualification(entry.name()).to_string(),
1194                        )
1195                    })
1196                    .collect();
1197                // Minimal qualification, like the planner's RESTRICT error.
1198                let index_name = humanizer
1199                    .minimal_qualification(self.catalog().get_entry(item_id).name())
1200                    .to_string();
1201                blocked.push((index_name, dependents));
1202                continue;
1203            }
1204            let dependant_objects = durable
1205                .into_iter()
1206                .filter_map(|dependent_id| {
1207                    let entry = self.catalog().get_entry(&dependent_id);
1208                    humanizer.humanize_id(entry.latest_global_id())
1209                })
1210                .collect();
1211            orphaned.push(DroppedInUseIndex {
1212                index_name: humanize_index(index, item_id),
1213                dependant_objects,
1214            });
1215        }
1216
1217        if !blocked.is_empty() {
1218            return Err(AdapterError::IndexInUse { blocked });
1219        }
1220
1221        let mut in_flight = Vec::new();
1222        for (index, item_id, transient) in transient_by_index {
1223            let mut readers = InFlightIndexReaders {
1224                index_name: humanize_index(index, item_id),
1225                ..Default::default()
1226            };
1227            for gid in transient {
1228                match self.active_compute_sinks.get(&gid) {
1229                    Some(ActiveComputeSink::Subscribe(_)) => readers.subscribes += 1,
1230                    Some(ActiveComputeSink::CopyTo(_)) => readers.copy_tos += 1,
1231                    None if self.introspection_subscribes.contains_key(&gid)
1232                        || self.is_metric_sink(gid) =>
1233                    {
1234                        readers.system += 1
1235                    }
1236                    // Slow-path peeks are the remaining owners of transient compute
1237                    // collections that import user indexes.
1238                    None => readers.selects += 1,
1239                }
1240            }
1241            in_flight.push(readers);
1242        }
1243
1244        Ok(IndexDropNotices {
1245            orphaned,
1246            in_flight,
1247        })
1248    }
1249
1250    /// Compute collections that read from `index`, split into catalog items not in `drop_set`
1251    /// and transient (one-shot) dataflows.
1252    fn index_readers(
1253        &self,
1254        index: &Index,
1255        drop_set: &BTreeSet<ObjectId>,
1256    ) -> (Vec<CatalogItemId>, Vec<GlobalId>) {
1257        let mut durable = Vec::new();
1258        let mut transient = Vec::new();
1259        let readers = self
1260            .controller
1261            .compute
1262            .collection_reverse_dependencies(index.cluster_id, index.global_id())
1263            .ok()
1264            .into_iter()
1265            .flatten();
1266        for gid in readers {
1267            if gid.is_transient() {
1268                transient.push(gid);
1269                continue;
1270            }
1271            // A collection whose item is gone from the catalog is already being torn down.
1272            let Some(entry) = self.catalog().try_get_entry_by_global_id(&gid) else {
1273                continue;
1274            };
1275            if !drop_set.contains(&ObjectId::Item(entry.id())) {
1276                durable.push(entry.id());
1277            }
1278        }
1279        (durable, transient)
1280    }
1281
1282    /// Reports the outcome of [`Coordinator::check_index_dependents`] to the session.
1283    ///
1284    /// An orphaned index is loud on purpose: it only happens under `enable_drop_in_use_index`,
1285    /// and every occurrence should be visible to us as well as to the user.
1286    fn emit_index_drop_notices(
1287        &self,
1288        session: &Session,
1289        orphaned: Vec<DroppedInUseIndex>,
1290        in_flight: Vec<InFlightIndexReaders>,
1291    ) {
1292        for orphaned in orphaned {
1293            tracing::error!(
1294                index = %orphaned.index_name,
1295                dependents = ?orphaned.dependant_objects,
1296                "dropped an index that other dataflows read from because enable_drop_in_use_index is set"
1297            );
1298            self.metrics
1299                .optimization_notices
1300                .with_label_values(&["DroppedInUseIndex"])
1301                .inc();
1302            session.add_notice(AdapterNotice::DroppedInUseIndex(orphaned));
1303        }
1304        session.add_notices(
1305            in_flight
1306                .into_iter()
1307                .map(AdapterNotice::DroppedIndexReadByInFlightStatements),
1308        );
1309    }
1310
1311    fn sequence_drop_common(
1312        &self,
1313        session: &Session,
1314        ids: Vec<ObjectId>,
1315        cascade: bool,
1316    ) -> Result<DropOps, AdapterError> {
1317        let mut dropped_active_db = false;
1318        let mut dropped_active_cluster = false;
1319        let mut dropped_roles = BTreeMap::new();
1320        let mut dropped_databases = BTreeSet::new();
1321        let mut dropped_schemas = BTreeSet::new();
1322        // Dropping either the group role or the member role of a role membership will trigger a
1323        // revoke role. We use a Set for the revokes to avoid trying to attempt to revoke the same
1324        // role membership twice.
1325        let mut role_revokes = BTreeSet::new();
1326        // Dropping a database or a schema will revoke all default roles associated with that
1327        // database or schema.
1328        let mut default_privilege_revokes = BTreeSet::new();
1329
1330        // Clusters we're dropping
1331        let mut clusters_to_drop = BTreeSet::new();
1332
1333        for id in &ids {
1334            match id {
1335                ObjectId::Database(id) => {
1336                    let name = self.catalog().get_database(id).name();
1337                    if name == session.vars().database() {
1338                        dropped_active_db = true;
1339                    }
1340                    dropped_databases.insert(id);
1341                }
1342                ObjectId::Schema((_, spec)) => {
1343                    if let SchemaSpecifier::Id(id) = spec {
1344                        dropped_schemas.insert(id);
1345                    }
1346                }
1347                ObjectId::Cluster(id) => {
1348                    clusters_to_drop.insert(*id);
1349                    if let Some(active_id) = self
1350                        .catalog()
1351                        .active_cluster(session)
1352                        .ok()
1353                        .map(|cluster| cluster.id())
1354                    {
1355                        if id == &active_id {
1356                            dropped_active_cluster = true;
1357                        }
1358                    }
1359                }
1360                ObjectId::Role(id) => {
1361                    let role = self.catalog().get_role(id);
1362                    let name = role.name();
1363                    dropped_roles.insert(*id, name);
1364                    // We must revoke all role memberships that the dropped roles belongs to.
1365                    for (group_id, grantor_id) in &role.membership.map {
1366                        role_revokes.insert((*group_id, *id, *grantor_id));
1367                    }
1368                }
1369                _ => {}
1370            }
1371        }
1372
1373        for id in &ids {
1374            match id {
1375                // Validate that `ClusterReplica` drops do not drop replicas of managed clusters,
1376                // unless they are internal replicas, which exist outside the scope
1377                // of managed clusters.
1378                ObjectId::ClusterReplica((cluster_id, replica_id)) => {
1379                    if !clusters_to_drop.contains(cluster_id) {
1380                        let cluster = self.catalog.get_cluster(*cluster_id);
1381                        if cluster.is_managed() {
1382                            let replica =
1383                                cluster.replica(*replica_id).expect("Catalog out of sync");
1384                            if !replica.config.location.internal() {
1385                                coord_bail!("cannot drop replica of managed cluster");
1386                            }
1387                        }
1388                    }
1389                }
1390                _ => {}
1391            }
1392        }
1393
1394        for role_id in dropped_roles.keys() {
1395            self.catalog().ensure_not_reserved_role(role_id)?;
1396        }
1397        self.validate_dropped_role_ownership(session, &dropped_roles)?;
1398        // If any role is a member of a dropped role, then we must revoke that membership.
1399        let dropped_role_ids: BTreeSet<_> = dropped_roles.keys().collect();
1400        for role in self.catalog().user_roles() {
1401            for dropped_role_id in
1402                dropped_role_ids.intersection(&role.membership.map.keys().collect())
1403            {
1404                role_revokes.insert((
1405                    **dropped_role_id,
1406                    role.id(),
1407                    *role
1408                        .membership
1409                        .map
1410                        .get(*dropped_role_id)
1411                        .expect("included in keys above"),
1412                ));
1413            }
1414        }
1415
1416        for (default_privilege_object, default_privilege_acls) in
1417            self.catalog().default_privileges()
1418        {
1419            if matches!(
1420                &default_privilege_object.database_id,
1421                Some(database_id) if dropped_databases.contains(database_id),
1422            ) || matches!(
1423                &default_privilege_object.schema_id,
1424                Some(schema_id) if dropped_schemas.contains(schema_id),
1425            ) {
1426                for default_privilege_acl in default_privilege_acls {
1427                    default_privilege_revokes.insert((
1428                        default_privilege_object.clone(),
1429                        default_privilege_acl.clone(),
1430                    ));
1431                }
1432            }
1433        }
1434
1435        let ops = role_revokes
1436            .into_iter()
1437            .map(|(role_id, member_id, grantor_id)| catalog::Op::RevokeRole {
1438                role_id,
1439                member_id,
1440                grantor_id,
1441            })
1442            .chain(default_privilege_revokes.into_iter().map(
1443                |(privilege_object, privilege_acl_item)| catalog::Op::UpdateDefaultPrivilege {
1444                    privilege_object,
1445                    privilege_acl_item,
1446                    variant: UpdatePrivilegeVariant::Revoke,
1447                },
1448            ))
1449            .chain(iter::once(catalog::Op::DropObjects {
1450                objects: ids
1451                    .into_iter()
1452                    .map(DropObjectInfo::manual_drop_from_object_id)
1453                    .collect(),
1454                cascade,
1455            }))
1456            .collect();
1457
1458        Ok(DropOps {
1459            ops,
1460            dropped_active_db,
1461            dropped_active_cluster,
1462        })
1463    }
1464
1465    pub(super) fn sequence_explain_schema(
1466        &self,
1467        ExplainSinkSchemaPlan { json_schema, .. }: ExplainSinkSchemaPlan,
1468    ) -> Result<ExecuteResponse, AdapterError> {
1469        let value: serde_json::Value = serde_json::from_str(&json_schema).map_err(|error| {
1470            AdapterError::Explain(mz_repr::explain::ExplainError::SerdeJsonError(error))
1471        })?;
1472        let json = mz_repr::explain::json::json_string(&value);
1473        let row = Row::pack_slice(&[Datum::String(&json)]);
1474        Ok(Self::send_immediate_rows(row))
1475    }
1476
1477    pub(super) fn sequence_show_all_variables(
1478        &self,
1479        session: &Session,
1480    ) -> Result<ExecuteResponse, AdapterError> {
1481        let mut rows = viewable_variables(self.catalog().state(), session)
1482            .map(|v| (v.name(), v.value(), v.description()))
1483            .collect::<Vec<_>>();
1484        rows.sort_by_cached_key(|(name, _, _)| name.to_lowercase());
1485
1486        // TODO(parkmycar): Pack all of these into a single RowCollection.
1487        let rows: Vec<_> = rows
1488            .into_iter()
1489            .map(|(name, val, desc)| {
1490                Row::pack_slice(&[
1491                    Datum::String(name),
1492                    Datum::String(&val),
1493                    Datum::String(desc),
1494                ])
1495            })
1496            .collect();
1497        Ok(Self::send_immediate_rows(rows))
1498    }
1499
1500    pub(super) fn sequence_show_variable(
1501        &self,
1502        session: &Session,
1503        plan: plan::ShowVariablePlan,
1504    ) -> Result<ExecuteResponse, AdapterError> {
1505        if &plan.name == SCHEMA_ALIAS {
1506            let schemas = self.catalog.resolve_search_path(session);
1507            let schema = schemas.first();
1508            return match schema {
1509                Some((database_spec, schema_spec)) => {
1510                    let schema_name = &self
1511                        .catalog
1512                        .get_schema(database_spec, schema_spec, session.conn_id())
1513                        .name()
1514                        .schema;
1515                    let row = Row::pack_slice(&[Datum::String(schema_name)]);
1516                    Ok(Self::send_immediate_rows(row))
1517                }
1518                None => {
1519                    if session.vars().current_object_missing_warnings() {
1520                        session.add_notice(AdapterNotice::NoResolvableSearchPathSchema {
1521                            search_path: session
1522                                .vars()
1523                                .search_path()
1524                                .into_iter()
1525                                .map(|schema| schema.to_string())
1526                                .collect(),
1527                        });
1528                    }
1529                    Ok(Self::send_immediate_rows(Row::pack_slice(&[Datum::Null])))
1530                }
1531            };
1532        }
1533
1534        let variable = session
1535            .vars()
1536            .get(self.catalog().system_config(), &plan.name)
1537            .or_else(|_| self.catalog().system_config().get(&plan.name))?;
1538
1539        // In lieu of plumbing the user to all system config functions, just check that the var is
1540        // visible.
1541        variable.visible(session.user(), self.catalog().system_config())?;
1542
1543        let row = Row::pack_slice(&[Datum::String(&variable.value())]);
1544        if variable.name() == vars::DATABASE.name()
1545            && matches!(
1546                self.catalog().resolve_database(&variable.value()),
1547                Err(CatalogError::UnknownDatabase(_))
1548            )
1549            && session.vars().current_object_missing_warnings()
1550        {
1551            let name = variable.value();
1552            session.add_notice(AdapterNotice::DatabaseDoesNotExist { name });
1553        } else if variable.name() == vars::CLUSTER.name()
1554            && matches!(
1555                self.catalog().resolve_cluster(&variable.value()),
1556                Err(CatalogError::UnknownCluster(_))
1557            )
1558            && session.vars().current_object_missing_warnings()
1559        {
1560            let name = variable.value();
1561            session.add_notice(AdapterNotice::ClusterDoesNotExist { name });
1562        }
1563        Ok(Self::send_immediate_rows(row))
1564    }
1565
1566    #[instrument]
1567    pub(super) async fn sequence_inspect_shard(
1568        &self,
1569        session: &Session,
1570        plan: plan::InspectShardPlan,
1571    ) -> Result<ExecuteResponse, AdapterError> {
1572        // TODO: Not thrilled about this rbac special case here, but probably
1573        // sufficient for now.
1574        if !session.user().is_internal() {
1575            return Err(AdapterError::Unauthorized(
1576                rbac::UnauthorizedError::MzSystem {
1577                    action: "inspect".into(),
1578                },
1579            ));
1580        }
1581        let state = self
1582            .controller
1583            .storage
1584            .inspect_persist_state(plan.id)
1585            .await?;
1586        let jsonb = Jsonb::from_serde_json(state)?;
1587        Ok(Self::send_immediate_rows(jsonb.into_row()))
1588    }
1589
1590    #[instrument]
1591    pub(super) fn sequence_set_variable(
1592        &self,
1593        session: &mut Session,
1594        plan: plan::SetVariablePlan,
1595    ) -> Result<ExecuteResponse, AdapterError> {
1596        let (name, local) = (plan.name, plan.local);
1597        if &name == TRANSACTION_ISOLATION_VAR_NAME {
1598            self.validate_set_isolation_level(session)?;
1599        }
1600        if &name == vars::CLUSTER.name() {
1601            self.validate_set_cluster(session)?;
1602        }
1603
1604        let vars = session.vars_mut();
1605        let values = match plan.value {
1606            plan::VariableValue::Default => None,
1607            plan::VariableValue::Values(values) => Some(values),
1608        };
1609
1610        match values {
1611            Some(values) => {
1612                vars.set(
1613                    self.catalog().system_config(),
1614                    &name,
1615                    VarInput::SqlSet(&values),
1616                    local,
1617                )?;
1618
1619                let vars = session.vars();
1620
1621                // Emit a warning when deprecated variables are used.
1622                // TODO(database-issues#8069) remove this after sufficient time has passed
1623                if name == vars::OLD_AUTO_ROUTE_CATALOG_QUERIES {
1624                    session.add_notice(AdapterNotice::AutoRouteIntrospectionQueriesUsage);
1625                } else if name == vars::CLUSTER.name()
1626                    && values[0] == vars::OLD_CATALOG_SERVER_CLUSTER
1627                {
1628                    session.add_notice(AdapterNotice::IntrospectionClusterUsage);
1629                }
1630
1631                // Database or cluster value does not correspond to a catalog item.
1632                if name.as_str() == vars::DATABASE.name()
1633                    && matches!(
1634                        self.catalog().resolve_database(vars.database()),
1635                        Err(CatalogError::UnknownDatabase(_))
1636                    )
1637                    && session.vars().current_object_missing_warnings()
1638                {
1639                    let name = vars.database().to_string();
1640                    session.add_notice(AdapterNotice::DatabaseDoesNotExist { name });
1641                } else if name.as_str() == vars::CLUSTER.name()
1642                    && matches!(
1643                        self.catalog().resolve_cluster(vars.cluster()),
1644                        Err(CatalogError::UnknownCluster(_))
1645                    )
1646                    && session.vars().current_object_missing_warnings()
1647                {
1648                    let name = vars.cluster().to_string();
1649                    session.add_notice(AdapterNotice::ClusterDoesNotExist { name });
1650                } else if name.as_str() == TRANSACTION_ISOLATION_VAR_NAME {
1651                    let v = values.into_first().to_lowercase();
1652                    if v == IsolationLevel::ReadUncommitted.as_variant_str()
1653                        || v == IsolationLevel::ReadCommitted.as_variant_str()
1654                        || v == IsolationLevel::RepeatableRead.as_variant_str()
1655                    {
1656                        session.add_notice(AdapterNotice::UnimplementedIsolationLevel {
1657                            isolation_level: v,
1658                        });
1659                    } else if v == IsolationLevel::StrongSessionSerializable.as_variant_str() {
1660                        session.add_notice(AdapterNotice::StrongSessionSerializable);
1661                    }
1662                }
1663
1664                // Reject incompatible combinations of bounded staleness and
1665                // `real_time_recency` after the variable has been applied. Either
1666                // SET name can introduce the conflict, so check both.
1667                if (name.as_str() == TRANSACTION_ISOLATION_VAR_NAME
1668                    || name.as_str() == vars::REAL_TIME_RECENCY.name())
1669                    && session
1670                        .vars()
1671                        .transaction_isolation()
1672                        .is_bounded_staleness()
1673                    && session.vars().real_time_recency()
1674                {
1675                    return Err(AdapterError::BoundedStalenessRealTimeRecencyConflict);
1676                }
1677            }
1678            None => vars.reset(self.catalog().system_config(), &name, local)?,
1679        }
1680
1681        Ok(ExecuteResponse::SetVariable { name, reset: false })
1682    }
1683
1684    pub(super) fn sequence_reset_variable(
1685        &self,
1686        session: &mut Session,
1687        plan: plan::ResetVariablePlan,
1688    ) -> Result<ExecuteResponse, AdapterError> {
1689        let name = plan.name;
1690        if &name == TRANSACTION_ISOLATION_VAR_NAME {
1691            self.validate_set_isolation_level(session)?;
1692        }
1693        if &name == vars::CLUSTER.name() {
1694            self.validate_set_cluster(session)?;
1695        }
1696        session
1697            .vars_mut()
1698            .reset(self.catalog().system_config(), &name, false)?;
1699        Ok(ExecuteResponse::SetVariable { name, reset: true })
1700    }
1701
1702    pub(super) fn sequence_set_transaction(
1703        &self,
1704        session: &mut Session,
1705        plan: plan::SetTransactionPlan,
1706    ) -> Result<ExecuteResponse, AdapterError> {
1707        // TODO(jkosh44) Only supports isolation levels for now.
1708        for mode in plan.modes {
1709            match mode {
1710                TransactionMode::AccessMode(_) => {
1711                    return Err(AdapterError::Unsupported("SET TRANSACTION <access-mode>"));
1712                }
1713                TransactionMode::IsolationLevel(isolation_level) => {
1714                    self.validate_set_isolation_level(session)?;
1715
1716                    session.vars_mut().set(
1717                        self.catalog().system_config(),
1718                        TRANSACTION_ISOLATION_VAR_NAME,
1719                        VarInput::Flat(&isolation_level.to_ast_string_stable()),
1720                        plan.local,
1721                    )?
1722                }
1723            }
1724        }
1725        Ok(ExecuteResponse::SetVariable {
1726            name: TRANSACTION_ISOLATION_VAR_NAME.to_string(),
1727            reset: false,
1728        })
1729    }
1730
1731    fn validate_set_isolation_level(&self, session: &Session) -> Result<(), AdapterError> {
1732        if session.transaction().contains_ops() {
1733            Err(AdapterError::InvalidSetIsolationLevel)
1734        } else {
1735            Ok(())
1736        }
1737    }
1738
1739    fn validate_set_cluster(&self, session: &Session) -> Result<(), AdapterError> {
1740        if session.transaction().contains_ops() {
1741            Err(AdapterError::InvalidSetCluster)
1742        } else {
1743            Ok(())
1744        }
1745    }
1746
1747    #[instrument(level = "debug")]
1748    pub(super) async fn sequence_end_transaction(
1749        &mut self,
1750        mut ctx: ExecuteContext,
1751        mut action: EndTransactionAction,
1752    ) {
1753        // If the transaction has failed, we can only rollback.
1754        if let (EndTransactionAction::Commit, TransactionStatus::Failed(_)) =
1755            (&action, ctx.session().transaction())
1756        {
1757            action = EndTransactionAction::Rollback;
1758        }
1759        let response = match action {
1760            EndTransactionAction::Commit => Ok(PendingTxnResponse::Committed {
1761                params: BTreeMap::new(),
1762            }),
1763            EndTransactionAction::Rollback => Ok(PendingTxnResponse::Rolledback {
1764                params: BTreeMap::new(),
1765            }),
1766        };
1767
1768        let result = self.sequence_end_transaction_inner(&mut ctx, action).await;
1769
1770        let (response, action) = match result {
1771            Ok(Some(TransactionOps::DDL { commands, .. })) => {
1772                self.sequence_ddl_commit(crate::coord::ddl::PendingDdlCommit::transaction(
1773                    PendingTxn {
1774                        ctx,
1775                        response,
1776                        action,
1777                    },
1778                    commands,
1779                ))
1780                .await;
1781                return;
1782            }
1783            Ok(Some(TransactionOps::Writes(writes))) if writes.is_empty() => (response, action),
1784            Ok(Some(TransactionOps::Writes(writes))) => {
1785                let mut collected_writes: BTreeMap<CatalogItemId, SmallVec<_>> = BTreeMap::new();
1786                for WriteOp { id, rows } in writes {
1787                    let total_rows = collected_writes.entry(id).or_default();
1788                    total_rows.push(rows);
1789                }
1790
1791                self.submit_write(PendingWriteTxn::User {
1792                    span: Span::current(),
1793                    writes: collected_writes,
1794                    responder: UserWriteResponder::Session(PendingTxn {
1795                        ctx,
1796                        response,
1797                        action,
1798                    }),
1799                });
1800                return;
1801            }
1802            Ok(Some(TransactionOps::Peeks {
1803                determination,
1804                requires_linearization: RequireLinearization::Required,
1805                ..
1806            })) if ctx.session().vars().transaction_isolation()
1807                == &IsolationLevel::StrictSerializable =>
1808            {
1809                let conn_id = ctx.session().conn_id().clone();
1810                let pending_read_txn = PendingReadTxn {
1811                    txn: PendingTxn {
1812                        ctx,
1813                        response,
1814                        action,
1815                    },
1816                    timestamp_context: determination.timestamp_context,
1817                    created: Instant::now(),
1818                    num_requeues: 0,
1819                    otel_ctx: OpenTelemetryContext::obtain(),
1820                };
1821                if let Some(pending_read_txn) = pending_read_txn.try_finish_read(&self.metrics) {
1822                    self.strict_serializable_reads_tx
1823                        .send((conn_id, pending_read_txn))
1824                        .expect("sending to strict_serializable_reads_tx cannot fail");
1825                }
1826                return;
1827            }
1828            Ok(Some(TransactionOps::Peeks {
1829                determination,
1830                requires_linearization: RequireLinearization::Required,
1831                ..
1832            })) if ctx.session().vars().transaction_isolation()
1833                == &IsolationLevel::StrongSessionSerializable =>
1834            {
1835                if let Some((timeline, ts)) = determination.timestamp_context.timeline_timestamp() {
1836                    ctx.session_mut()
1837                        .ensure_timestamp_oracle(timeline.clone())
1838                        .apply_write(*ts);
1839                }
1840                (response, action)
1841            }
1842            Ok(Some(TransactionOps::SingleStatement { stmt, params })) => {
1843                self.internal_cmd_tx
1844                    .send(Message::ExecuteSingleStatementTransaction {
1845                        ctx,
1846                        otel_ctx: OpenTelemetryContext::obtain(),
1847                        stmt,
1848                        params,
1849                    })
1850                    .expect("must send");
1851                return;
1852            }
1853            Ok(_) => (response, action),
1854            Err(err) => (Err(err), EndTransactionAction::Rollback),
1855        };
1856        let changed = ctx.session_mut().vars_mut().end_transaction(action);
1857        // Append any parameters that changed to the response.
1858        let response = response.map(|mut r| {
1859            r.extend_params(changed);
1860            ExecuteResponse::from(r)
1861        });
1862
1863        ctx.retire(response);
1864    }
1865
1866    #[instrument(level = "debug")]
1867    async fn sequence_end_transaction_inner(
1868        &mut self,
1869        ctx: &mut ExecuteContext,
1870        action: EndTransactionAction,
1871    ) -> Result<Option<TransactionOps>, AdapterError> {
1872        let (txn, retire_notify) = self.clear_transaction(ctx.session_mut()).await;
1873        ctx.delay_response_until(retire_notify);
1874
1875        if let EndTransactionAction::Commit = action {
1876            if let Some(mut ops) = txn.into_ops() {
1877                match &mut ops {
1878                    TransactionOps::Writes(writes) => {
1879                        for WriteOp { id, .. } in &mut writes.iter() {
1880                            // Re-verify this id exists.
1881                            let _ = self.catalog().try_get_entry(id).ok_or_else(|| {
1882                                AdapterError::Catalog(mz_catalog::memory::error::Error {
1883                                    kind: ErrorKind::Sql(CatalogError::UnknownItem(id.to_string())),
1884                                })
1885                            })?;
1886                        }
1887
1888                        // `rows` can be empty if, say, a DELETE's WHERE clause had 0 results.
1889                        writes.retain(|WriteOp { rows, .. }| !rows.is_empty());
1890                    }
1891                    _ => (),
1892                }
1893                return Ok(Some(ops));
1894            }
1895        }
1896
1897        Ok(None)
1898    }
1899
1900    /// Execute a side-effecting function for the frontend peek path.
1901    ///
1902    /// RBAC is checked by the caller via `rbac::check_plan` before sending
1903    /// `Command::ExecuteSideEffectingFunc`. The caller must hold the target
1904    /// connection's `ConnectionId` handle from its RBAC check until this command
1905    /// completes, so that the connection found in `active_conns` here (if any) is
1906    /// the same one the check was performed against.
1907    pub(crate) async fn execute_side_effecting_func(
1908        &mut self,
1909        plan: SideEffectingFunc,
1910        conn_id: ConnectionId,
1911    ) -> Result<ExecuteResponse, AdapterError> {
1912        match plan {
1913            SideEffectingFunc::PgCancelBackend { connection_id } => {
1914                let Some(connection_id) = connection_id else {
1915                    // The argument was `NULL`, so, like in PostgreSQL, the
1916                    // function returns `NULL`.
1917                    return Ok(Self::send_immediate_rows(Row::pack_slice(&[Datum::Null])));
1918                };
1919
1920                if conn_id.unhandled() == connection_id {
1921                    // As a special case, if we're canceling ourselves, we return
1922                    // a canceled response to the client issuing the query,
1923                    // and so we need to do no further processing of the cancel.
1924                    return Err(AdapterError::Canceled);
1925                }
1926
1927                // The caller verified role membership via rbac::check_plan and
1928                // still holds the target's `ConnectionId` handle, so this entry
1929                // (if present) is the same connection the check was performed
1930                // against.
1931                if let Some((id_handle, _conn_meta)) =
1932                    self.active_conns.get_key_value(&connection_id)
1933                {
1934                    self.handle_privileged_cancel(id_handle.clone()).await;
1935                    Ok(Self::send_immediate_rows(Row::pack_slice(&[Datum::True])))
1936                } else {
1937                    // Connection not found, return false.
1938                    Ok(Self::send_immediate_rows(Row::pack_slice(&[Datum::False])))
1939                }
1940            }
1941        }
1942    }
1943
1944    /// Determines a real-time recency timestamp, for `Command::DetermineRealTimeRecentTimestamp`.
1945    pub(crate) async fn determine_real_time_recent_timestamp(
1946        &self,
1947        source_ids: impl Iterator<Item = GlobalId>,
1948        real_time_recency_timeout: Duration,
1949    ) -> Result<Option<RtrTimestampFuture>, AdapterError> {
1950        let item_ids = source_ids
1951            .map(|gid| {
1952                self.catalog
1953                    .try_resolve_item_id(&gid)
1954                    .ok_or_else(|| AdapterError::RtrDropFailure(gid.to_string()))
1955            })
1956            .collect::<Result<Vec<_>, _>>()?;
1957
1958        // Find all dependencies transitively because we need to ensure that
1959        // RTR queries determine the timestamp from the sources' (i.e.
1960        // storage objects that ingest data from external systems) remap
1961        // data. We "cheat" a little bit and filter out any IDs that aren't
1962        // user objects because we know they are not a RTR source.
1963        let mut to_visit = VecDeque::from_iter(item_ids.into_iter().filter(CatalogItemId::is_user));
1964        // If none of the sources are user objects, we don't need to provide
1965        // a RTR timestamp.
1966        if to_visit.is_empty() {
1967            return Ok(None);
1968        }
1969
1970        let mut timestamp_objects = BTreeSet::new();
1971
1972        while let Some(id) = to_visit.pop_front() {
1973            timestamp_objects.insert(id);
1974            to_visit.extend(
1975                self.catalog()
1976                    .get_entry(&id)
1977                    .uses()
1978                    .into_iter()
1979                    .filter(|id| !timestamp_objects.contains(id) && id.is_user()),
1980            );
1981        }
1982        let timestamp_objects = timestamp_objects
1983            .into_iter()
1984            .flat_map(|item_id| self.catalog().get_entry(&item_id).global_ids())
1985            .collect();
1986
1987        let r = self
1988            .controller
1989            .determine_real_time_recent_timestamp(timestamp_objects, real_time_recency_timeout)
1990            .await?;
1991
1992        Ok(Some(r))
1993    }
1994
1995    pub(crate) async fn await_real_time_recent_timestamp<F>(
1996        catalog: Arc<Catalog>,
1997        fut: F,
1998    ) -> Result<Timestamp, AdapterError>
1999    where
2000        F: Future<Output = Result<Timestamp, StorageError>>,
2001    {
2002        fut.await
2003            .map_err(|error| Self::real_time_recent_timestamp_error(&catalog, error))
2004    }
2005
2006    fn real_time_recent_timestamp_error(catalog: &Catalog, error: StorageError) -> AdapterError {
2007        let rtr_name = |id: &GlobalId| {
2008            catalog
2009                .try_get_entry_by_global_id(id)
2010                .map(|e| e.name().item.clone())
2011                .unwrap_or_else(|| id.to_string())
2012        };
2013
2014        match error {
2015            StorageError::RtrTimeout(id) => AdapterError::RtrTimeout(rtr_name(&id)),
2016            StorageError::RtrDropFailure(id) => AdapterError::RtrDropFailure(rtr_name(&id)),
2017            error => error.into(),
2018        }
2019    }
2020
2021    #[instrument]
2022    pub(super) async fn sequence_explain_plan(
2023        &mut self,
2024        ctx: ExecuteContext,
2025        plan: plan::ExplainPlanPlan,
2026    ) {
2027        match &plan.explainee {
2028            plan::Explainee::Statement(stmt) => match stmt {
2029                plan::ExplaineeStatement::CreateView { .. } => {
2030                    self.explain_create_view(ctx, plan).await;
2031                }
2032                plan::ExplaineeStatement::CreateMaterializedView { .. } => {
2033                    self.explain_create_materialized_view(ctx, plan).await;
2034                }
2035                plan::ExplaineeStatement::CreateIndex { .. } => {
2036                    self.explain_create_index(ctx, plan).await;
2037                }
2038                stmt @ (plan::ExplaineeStatement::Select { .. }
2039                | plan::ExplaineeStatement::Subscribe { .. }) => {
2040                    let msg = format!(
2041                        "EXPLAIN of a {} reached the coordinator despite frontend routing",
2042                        plan::ExplaineeStatementKind::from(stmt)
2043                    );
2044                    soft_panic_or_log!("{msg}");
2045                    ctx.retire(Err(AdapterError::Internal(msg)));
2046                }
2047            },
2048            plan::Explainee::View(_) => {
2049                let result = self.explain_view(&ctx, plan);
2050                ctx.retire(result);
2051            }
2052            plan::Explainee::MaterializedView(_) => {
2053                let result = self.explain_materialized_view(&ctx, plan);
2054                ctx.retire(result);
2055            }
2056            plan::Explainee::Index(_) => {
2057                let result = self.explain_index(&ctx, plan);
2058                ctx.retire(result);
2059            }
2060            plan::Explainee::ReplanView(_) => {
2061                self.explain_replan_view(ctx, plan).await;
2062            }
2063            plan::Explainee::ReplanMaterializedView(_) => {
2064                self.explain_replan_materialized_view(ctx, plan).await;
2065            }
2066            plan::Explainee::ReplanIndex(_) => {
2067                self.explain_replan_index(ctx, plan).await;
2068            }
2069        };
2070    }
2071
2072    pub(super) async fn sequence_explain_pushdown(
2073        &self,
2074        ctx: ExecuteContext,
2075        plan: plan::ExplainPushdownPlan,
2076    ) {
2077        match plan.explainee {
2078            Explainee::Statement(ExplaineeStatement::Select { broken: false, .. }) => {
2079                let msg = "EXPLAIN FILTER PUSHDOWN of a SELECT reached the coordinator despite \
2080                           frontend routing";
2081                soft_panic_or_log!("{msg}");
2082                ctx.retire(Err(AdapterError::Internal(msg.into())));
2083            }
2084            Explainee::MaterializedView(item_id) => {
2085                self.explain_pushdown_materialized_view(ctx, item_id).await;
2086            }
2087            _ => {
2088                ctx.retire(Err(AdapterError::Unsupported(
2089                    "EXPLAIN FILTER PUSHDOWN queries for this explainee type",
2090                )));
2091            }
2092        };
2093    }
2094
2095    /// Executes an EXPLAIN FILTER PUSHDOWN, with read holds passed in.
2096    async fn execute_explain_pushdown_with_read_holds(
2097        &self,
2098        ctx: ExecuteContext,
2099        as_of: Antichain<Timestamp>,
2100        mz_now: ResultSpec<'static>,
2101        read_holds: Option<ReadHolds>,
2102        imports: impl IntoIterator<Item = (GlobalId, MfpPlan<LirScalarExpr>)> + 'static,
2103    ) {
2104        let fut = self
2105            .explain_pushdown_future(ctx.session(), as_of, mz_now, imports)
2106            .await;
2107        task::spawn(|| "render explain pushdown", async move {
2108            // Transfer the necessary read holds over to the background task
2109            let _read_holds = read_holds;
2110            let res = fut.await;
2111            ctx.retire(res);
2112        });
2113    }
2114
2115    /// Returns a future that will execute EXPLAIN FILTER PUSHDOWN.
2116    async fn explain_pushdown_future<I: IntoIterator<Item = (GlobalId, MfpPlan<LirScalarExpr>)>>(
2117        &self,
2118        session: &Session,
2119        as_of: Antichain<Timestamp>,
2120        mz_now: ResultSpec<'static>,
2121        imports: I,
2122    ) -> impl Future<Output = Result<ExecuteResponse, AdapterError>> + use<I> {
2123        // Get the needed Coordinator stuff and call the freestanding, shared helper.
2124        super::explain_pushdown_future_inner(
2125            session,
2126            &self.catalog,
2127            &self.controller.storage_collections,
2128            as_of,
2129            mz_now,
2130            imports,
2131        )
2132        .await
2133    }
2134
2135    #[instrument]
2136    pub(super) async fn sequence_alter_retain_history(
2137        &mut self,
2138        ctx: &mut ExecuteContext,
2139        plan: plan::AlterRetainHistoryPlan,
2140    ) -> Result<ExecuteResponse, AdapterError> {
2141        let ops = vec![catalog::Op::AlterRetainHistory {
2142            id: plan.id,
2143            value: plan.value,
2144            window: plan.window,
2145        }];
2146        self.catalog_transact_with_context(None, Some(ctx), ops)
2147            .await?;
2148        Ok(ExecuteResponse::AlteredObject(plan.object_type))
2149    }
2150
2151    #[instrument]
2152    pub(super) async fn sequence_alter_source_timestamp_interval(
2153        &mut self,
2154        ctx: &mut ExecuteContext,
2155        plan: plan::AlterSourceTimestampIntervalPlan,
2156    ) -> Result<ExecuteResponse, AdapterError> {
2157        let ops = vec![catalog::Op::AlterSourceTimestampInterval {
2158            id: plan.id,
2159            value: plan.value,
2160            interval: plan.interval,
2161        }];
2162        self.catalog_transact_with_context(None, Some(ctx), ops)
2163            .await?;
2164        Ok(ExecuteResponse::AlteredObject(ObjectType::Source))
2165    }
2166
2167    #[instrument]
2168    pub(super) async fn sequence_alter_role(
2169        &mut self,
2170        session: &Session,
2171        plan::AlterRolePlan { id, name, option }: plan::AlterRolePlan,
2172    ) -> Result<ExecuteResponse, AdapterError> {
2173        let catalog = self.catalog().for_session(session);
2174        let role = catalog.get_role(&id);
2175
2176        // We'll send these notices to the user, if the operation is successful.
2177        let mut notices = vec![];
2178
2179        // Get the attributes and variables from the role, as they currently are.
2180        let mut attributes: RoleAttributesRaw = role.attributes().clone().into();
2181        let mut vars = role.vars().clone();
2182
2183        // Whether to set the password to NULL. This is a special case since the existing
2184        // password is not stored in the role attributes.
2185        let mut nopassword = false;
2186
2187        // Apply our updates.
2188        match option {
2189            PlannedAlterRoleOption::Attributes(attrs) => {
2190                self.validate_role_attributes(&attrs.clone().into())?;
2191
2192                if let Some(inherit) = attrs.inherit {
2193                    attributes.inherit = inherit;
2194                }
2195
2196                if let Some(password) = attrs.password {
2197                    attributes.password = Some(password);
2198                    attributes.scram_iterations =
2199                        Some(self.catalog().system_config().scram_iterations())
2200                }
2201
2202                if let Some(superuser) = attrs.superuser {
2203                    attributes.superuser = Some(superuser);
2204                }
2205
2206                if let Some(login) = attrs.login {
2207                    attributes.login = Some(login);
2208                }
2209
2210                if attrs.nopassword.unwrap_or(false) {
2211                    nopassword = true;
2212                }
2213
2214                if let Some(notice) = self.should_emit_rbac_notice(session) {
2215                    notices.push(notice);
2216                }
2217            }
2218            PlannedAlterRoleOption::Variable(variable) => {
2219                // Get the variable to make sure it's valid and visible.
2220                let session_var = session.vars().inspect(variable.name())?;
2221                // Return early if it's not visible.
2222                session_var.visible(session.user(), catalog.system_vars())?;
2223
2224                // Emit a warning when deprecated variables are used.
2225                // TODO(database-issues#8069) remove this after sufficient time has passed
2226                if variable.name() == vars::OLD_AUTO_ROUTE_CATALOG_QUERIES {
2227                    notices.push(AdapterNotice::AutoRouteIntrospectionQueriesUsage);
2228                } else if let PlannedRoleVariable::Set {
2229                    name,
2230                    value: VariableValue::Values(vals),
2231                } = &variable
2232                {
2233                    if name == vars::CLUSTER.name() && vals[0] == vars::OLD_CATALOG_SERVER_CLUSTER {
2234                        notices.push(AdapterNotice::IntrospectionClusterUsage);
2235                    }
2236                }
2237
2238                let var_name = match variable {
2239                    PlannedRoleVariable::Set { name, value } => {
2240                        // Update our persisted set.
2241                        match &value {
2242                            VariableValue::Default => {
2243                                vars.remove(&name);
2244                            }
2245                            VariableValue::Values(vals) => {
2246                                let var = match &vals[..] {
2247                                    [val] => OwnedVarInput::Flat(val.clone()),
2248                                    vals => OwnedVarInput::SqlSet(vals.to_vec()),
2249                                };
2250                                // Make sure the input is valid.
2251                                session_var.check(var.borrow())?;
2252
2253                                vars.insert(name.clone(), var);
2254                            }
2255                        };
2256                        name
2257                    }
2258                    PlannedRoleVariable::Reset { name } => {
2259                        // Remove it from our persisted values.
2260                        vars.remove(&name);
2261                        name
2262                    }
2263                };
2264
2265                // Emit a notice that they need to reconnect to see the change take effect.
2266                notices.push(AdapterNotice::VarDefaultUpdated {
2267                    role: Some(name.clone()),
2268                    var_name: Some(var_name),
2269                });
2270            }
2271        }
2272
2273        let op = catalog::Op::AlterRole {
2274            id,
2275            name,
2276            attributes,
2277            nopassword,
2278            vars: RoleVars { map: vars },
2279        };
2280        let response = self
2281            .catalog_transact(Some(session), vec![op])
2282            .await
2283            .map(|_| ExecuteResponse::AlteredRole)?;
2284
2285        // Send all of our queued notices.
2286        session.add_notices(notices);
2287
2288        Ok(response)
2289    }
2290
2291    #[instrument]
2292    pub(super) async fn sequence_alter_sink_prepare(
2293        &mut self,
2294        ctx: ExecuteContext,
2295        plan: plan::AlterSinkPlan,
2296    ) {
2297        // Put a read hold on the new relation
2298        let id_bundle = crate::CollectionIdBundle {
2299            storage_ids: BTreeSet::from_iter([plan.sink.from]),
2300            compute_ids: BTreeMap::new(),
2301        };
2302        let read_hold = self.acquire_read_holds(&id_bundle);
2303
2304        let Some(read_ts) = read_hold.least_valid_read().into_option() else {
2305            ctx.retire(Err(AdapterError::UnreadableSinkCollection));
2306            return;
2307        };
2308
2309        let otel_ctx = OpenTelemetryContext::obtain();
2310        let from_item_id = self.catalog().resolve_item_id(&plan.sink.from);
2311
2312        let plan_validity = PlanValidity::new(
2313            self.catalog(),
2314            BTreeSet::from_iter([plan.item_id, from_item_id]),
2315            Some(plan.in_cluster),
2316            None,
2317            ctx.session().role_metadata().clone(),
2318        );
2319
2320        info!(
2321            "preparing alter sink for {}: frontiers={:?} export={:?}",
2322            plan.global_id,
2323            self.controller
2324                .storage_collections
2325                .collections_frontiers(vec![plan.global_id, plan.sink.from]),
2326            self.controller.storage.export(plan.global_id)
2327        );
2328
2329        // Now we must wait for the sink to make enough progress such that there is overlap between
2330        // the new `from` collection's read hold and the sink's write frontier.
2331        //
2332        // TODO(database-issues#9820): If the sink is dropped while we are waiting for progress,
2333        // the watch set never completes and neither does the `ALTER SINK` command.
2334        self.install_storage_watch_set(
2335            ctx.session().conn_id().clone(),
2336            BTreeSet::from_iter([plan.global_id]),
2337            read_ts,
2338            WatchSetResponse::AlterSinkReady(AlterSinkReadyContext {
2339                ctx: Some(ctx),
2340                otel_ctx,
2341                plan,
2342                plan_validity,
2343                read_hold,
2344            }),
2345        ).expect("plan validity verified above; we are on the coordinator main task, so they couldn't have gone away since then");
2346    }
2347
2348    #[instrument]
2349    pub async fn sequence_alter_sink_finish(&mut self, mut ctx: AlterSinkReadyContext) {
2350        ctx.otel_ctx.attach_as_parent();
2351
2352        let plan::AlterSinkPlan {
2353            item_id,
2354            global_id,
2355            sink: sink_plan,
2356            with_snapshot,
2357            in_cluster,
2358            set_options,
2359            reset_options,
2360        } = ctx.plan.clone();
2361
2362        // We avoid taking the DDL lock for `ALTER SINK` commands, see
2363        // `Coordinator::must_serialize_ddl`. We therefore must assume that the world has
2364        // arbitrarily changed since we performed planning, and we must re-assert that it still
2365        // matches our requirements.
2366        //
2367        // The `PlanValidity` check ensures that both the sink and the new source relation still
2368        // exist. Apart from that we have to ensure that nobody else altered the sink in the mean
2369        // time, which we do by comparing the catalog sink version to the one in the plan.
2370        match ctx.plan_validity.check(self.catalog()) {
2371            Ok(()) => {}
2372            Err(err) => {
2373                ctx.retire(Err(err));
2374                return;
2375            }
2376        }
2377
2378        let entry = self.catalog().get_entry(&item_id);
2379        let CatalogItem::Sink(old_sink) = entry.item() else {
2380            panic!("invalid item kind for `AlterSinkPlan`");
2381        };
2382
2383        if sink_plan.version != old_sink.version + 1 {
2384            ctx.retire(Err(AdapterError::ChangedPlan(
2385                "sink was altered concurrently".into(),
2386            )));
2387            return;
2388        }
2389
2390        info!(
2391            "finishing alter sink for {global_id}: frontiers={:?} export={:?}",
2392            self.controller
2393                .storage_collections
2394                .collections_frontiers(vec![global_id, sink_plan.from]),
2395            self.controller.storage.export(global_id),
2396        );
2397
2398        // Assert that we can recover the updates that happened at the timestamps of the write
2399        // frontier. This must be true in this call.
2400        let write_frontier = &self
2401            .controller
2402            .storage
2403            .export(global_id)
2404            .expect("sink known to exist")
2405            .write_frontier;
2406        let as_of = ctx.read_hold.least_valid_read();
2407        assert!(
2408            write_frontier.iter().all(|t| as_of.less_than(t)),
2409            "{:?} should be strictly less than {:?}",
2410            &*as_of,
2411            &**write_frontier
2412        );
2413
2414        // Parse the `create_sql` so we can update it to the new sink definition.
2415        //
2416        // Note that we need to use the `create_sql` from the catalog here, not the one from the
2417        // sink plan. Even though we ensure that the sink version didn't change since planning, the
2418        // names in the `create_sql` may have changed, for example due to a schema swap.
2419        let create_sql = &old_sink.create_sql;
2420        let parsed = mz_sql::parse::parse(create_sql).expect("valid create_sql");
2421        let Statement::CreateSink(mut stmt) = parsed.into_element().ast else {
2422            unreachable!("invalid statement kind for sink");
2423        };
2424
2425        // Update the sink version.
2426        plan::apply_sink_option_edits(
2427            &mut stmt.with_options,
2428            &[CreateSinkOption {
2429                name: CreateSinkOptionName::Version,
2430                value: Some(WithOptionValue::Value(mz_sql::ast::Value::Number(
2431                    sink_plan.version.to_string(),
2432                ))),
2433            }],
2434            &[],
2435        );
2436
2437        let conn_catalog = self.catalog().for_system_session();
2438        let (mut stmt, resolved_ids) =
2439            mz_sql::names::resolve(&conn_catalog, stmt).expect("resolvable create_sql");
2440
2441        // Re-apply the option edits requested by the `ALTER SINK`.
2442        plan::apply_sink_option_edits(&mut stmt.with_options, &set_options, &reset_options);
2443
2444        // Update the `from` relation.
2445        let from_entry = self.catalog().get_entry_by_global_id(&sink_plan.from);
2446        let full_name = self.catalog().resolve_full_name(from_entry.name(), None);
2447        stmt.from = ResolvedItemName::Item {
2448            id: from_entry.id(),
2449            qualifiers: from_entry.name.qualifiers.clone(),
2450            full_name,
2451            print_id: true,
2452            version: from_entry.version,
2453        };
2454
2455        // `resolved_ids` was derived from the old `create_sql`, so it still
2456        // references the old input. `create_sql` and `from` above already
2457        // point at the new input, so sync the dependency set to match.
2458        // Otherwise the in-memory catalog disagrees with `create_sql` until
2459        // the next reload, and the temporary-dependency check in
2460        // `Op::UpdateItem` (which reads `uses()`) would not see the new input.
2461        let mut resolved_ids = resolved_ids;
2462        resolved_ids.remove_item(&self.catalog().resolve_item_id(&old_sink.from));
2463        resolved_ids.add_item(from_entry.id());
2464
2465        let new_sink = Sink {
2466            create_sql: stmt.to_ast_string_stable(),
2467            global_id,
2468            from: sink_plan.from,
2469            connection: sink_plan.connection.clone(),
2470            envelope: sink_plan.envelope,
2471            version: sink_plan.version,
2472            with_snapshot,
2473            resolved_ids,
2474            cluster_id: in_cluster,
2475            commit_interval: sink_plan.commit_interval,
2476        };
2477
2478        let ops = vec![catalog::Op::UpdateItem {
2479            id: item_id,
2480            name: entry.name().clone(),
2481            to_item: CatalogItem::Sink(new_sink),
2482        }];
2483
2484        match self
2485            .catalog_transact(Some(ctx.ctx().session_mut()), ops)
2486            .await
2487        {
2488            Ok(()) => {}
2489            Err(err) => {
2490                ctx.retire(Err(err));
2491                return;
2492            }
2493        }
2494
2495        let storage_sink_desc = StorageSinkDesc {
2496            from: sink_plan.from,
2497            from_desc: from_entry
2498                .relation_desc()
2499                .expect("sinks can only be built on items with descs")
2500                .into_owned(),
2501            connection: sink_plan
2502                .connection
2503                .clone()
2504                .into_inline_connection(self.catalog().state()),
2505            envelope: sink_plan.envelope,
2506            as_of,
2507            with_snapshot,
2508            version: sink_plan.version,
2509            from_storage_metadata: (),
2510            to_storage_metadata: (),
2511            commit_interval: sink_plan.commit_interval,
2512        };
2513
2514        self.controller
2515            .storage
2516            .alter_export(
2517                global_id,
2518                ExportDescription {
2519                    sink: storage_sink_desc,
2520                    instance_id: in_cluster,
2521                },
2522            )
2523            .await
2524            .unwrap_or_terminate("cannot fail to alter source desc");
2525
2526        ctx.retire(Ok(ExecuteResponse::AlteredObject(ObjectType::Sink)));
2527    }
2528
2529    #[instrument]
2530    pub(super) async fn sequence_alter_connection(
2531        &mut self,
2532        ctx: ExecuteContext,
2533        AlterConnectionPlan { id, action }: AlterConnectionPlan,
2534    ) {
2535        match action {
2536            AlterConnectionAction::RotateKeys => {
2537                self.sequence_rotate_keys(ctx, id).await;
2538            }
2539            AlterConnectionAction::AlterOptions { .. } => {
2540                let msg = "ALTER CONNECTION options must execute as a catalog command";
2541                soft_panic_or_log!("{msg}");
2542                ctx.retire(Err(AdapterError::Internal(msg.into())));
2543            }
2544        }
2545    }
2546
2547    #[instrument]
2548    pub(super) async fn sequence_alter_system_set(
2549        &mut self,
2550        session: &Session,
2551        plan::AlterSystemSetPlan { name, value }: plan::AlterSystemSetPlan,
2552    ) -> Result<ExecuteResponse, AdapterError> {
2553        self.is_user_allowed_to_alter_system(session, Some(&name))?;
2554        // We want to ensure that the network policy we're switching too actually exists.
2555        if NETWORK_POLICY.name.to_string().to_lowercase() == name.clone().to_lowercase() {
2556            self.validate_alter_system_network_policy(session, &value)?;
2557        }
2558
2559        let op = match value {
2560            plan::VariableValue::Values(values) => catalog::Op::UpdateSystemConfiguration {
2561                name: name.clone(),
2562                value: OwnedVarInput::SqlSet(values),
2563            },
2564            plan::VariableValue::Default => {
2565                catalog::Op::ResetSystemConfiguration { name: name.clone() }
2566            }
2567        };
2568        self.catalog_transact(Some(session), vec![op]).await?;
2569
2570        Self::notice_if_startup_only(session, &name);
2571        if vars::is_session_default(&name) {
2572            session.add_notice(AdapterNotice::VarDefaultUpdated {
2573                role: None,
2574                var_name: Some(name),
2575            });
2576        }
2577        Ok(ExecuteResponse::AlteredSystemConfiguration)
2578    }
2579
2580    #[instrument]
2581    pub(super) async fn sequence_alter_system_reset(
2582        &mut self,
2583        session: &Session,
2584        plan::AlterSystemResetPlan { name }: plan::AlterSystemResetPlan,
2585    ) -> Result<ExecuteResponse, AdapterError> {
2586        self.is_user_allowed_to_alter_system(session, Some(&name))?;
2587        let op = catalog::Op::ResetSystemConfiguration { name: name.clone() };
2588        self.catalog_transact(Some(session), vec![op]).await?;
2589        Self::notice_if_startup_only(session, &name);
2590        if vars::is_session_default(&name) {
2591            session.add_notice(AdapterNotice::VarDefaultUpdated {
2592                role: None,
2593                var_name: Some(name),
2594            });
2595        }
2596        Ok(ExecuteResponse::AlteredSystemConfiguration)
2597    }
2598
2599    #[instrument]
2600    pub(super) async fn sequence_alter_system_reset_all(
2601        &mut self,
2602        session: &Session,
2603        _: plan::AlterSystemResetAllPlan,
2604    ) -> Result<ExecuteResponse, AdapterError> {
2605        self.is_user_allowed_to_alter_system(session, None)?;
2606        // Which parameters `RESET ALL` changes has to be read before the
2607        // transaction applies it, afterwards they all read as their default.
2608        let startup_only_changed = self.startup_only_vars_changed_by_reset_all();
2609        let session_default_changed = {
2610            let config = self.catalog().system_config();
2611            let defaults = config.defaults();
2612            config
2613                .iter()
2614                .chain(config.iter_session())
2615                .filter(|v| vars::is_session_default(v.name()))
2616                .any(|v| defaults.get(v.name()).is_some_and(|d| d != &v.value()))
2617        };
2618        let op = catalog::Op::ResetAllSystemConfiguration;
2619        self.catalog_transact(Some(session), vec![op]).await?;
2620        for name in startup_only_changed {
2621            session.add_notice(AdapterNotice::StartupOnlyVarUpdated {
2622                var_name: name.to_string(),
2623            });
2624        }
2625        if session_default_changed {
2626            session.add_notice(AdapterNotice::VarDefaultUpdated {
2627                role: None,
2628                var_name: None,
2629            });
2630        }
2631        Ok(ExecuteResponse::AlteredSystemConfiguration)
2632    }
2633
2634    /// System parameters whose value `environmentd` samples once at startup.
2635    ///
2636    /// `max_concurrent_occ_writes` sizes the OCC semaphore at boot.
2637    /// `enable_expression_cache` decides whether catalog open builds the cache,
2638    /// which has already happened by the time a session can ask.
2639    ///
2640    /// `ALTER SYSTEM` on one of these is allowed to go through. The catalog
2641    /// value is what the next process start reads, and the running process
2642    /// cannot observe it.
2643    fn startup_only_vars() -> [&'static str; 2] {
2644        [
2645            MAX_CONCURRENT_OCC_WRITES.name(),
2646            ENABLE_EXPRESSION_CACHE.name(),
2647        ]
2648    }
2649
2650    /// Warns that `name` is only read at startup, so the running process keeps
2651    /// the value it sampled at boot.
2652    fn notice_if_startup_only(session: &Session, name: &str) {
2653        if Self::startup_only_vars()
2654            .iter()
2655            .any(|n| n.eq_ignore_ascii_case(name))
2656        {
2657            session.add_notice(AdapterNotice::StartupOnlyVarUpdated {
2658                var_name: name.to_string(),
2659            });
2660        }
2661    }
2662
2663    /// The startup-only parameters whose value `ALTER SYSTEM RESET ALL` would
2664    /// change. Parameters already at their effective default are untouched, so
2665    /// they are not reported.
2666    fn startup_only_vars_changed_by_reset_all(&self) -> Vec<&'static str> {
2667        // Value-based, unlike `notice_if_startup_only`, which warns whenever an
2668        // operator names one of these parameters. `RESET ALL` names every
2669        // parameter, so only a value that actually moves is worth a warning.
2670        let config = self.catalog().system_config();
2671        let defaults = config.defaults();
2672        Self::startup_only_vars()
2673            .into_iter()
2674            .filter(|name| {
2675                // These names are all registered system vars, a lookup failure
2676                // would mean the definitions and this list have drifted apart.
2677                let current = config
2678                    .get(name)
2679                    .expect("startup-only parameter is a registered system var")
2680                    .value();
2681                defaults
2682                    .get(*name)
2683                    .is_some_and(|default| default != &current)
2684            })
2685            .collect()
2686    }
2687
2688    // TODO(jkosh44) Move this into rbac.rs once RBAC is always on.
2689    fn is_user_allowed_to_alter_system(
2690        &self,
2691        session: &Session,
2692        var_name: Option<&str>,
2693    ) -> Result<(), AdapterError> {
2694        match (session.user().kind(), var_name) {
2695            // Only internal superusers can reset all system variables.
2696            (UserKind::Superuser, None) if session.user().is_internal() => Ok(()),
2697            // Whether or not a variable can be modified depends if we're an internal superuser.
2698            (UserKind::Superuser, Some(name))
2699                if session.user().is_internal()
2700                    || self.catalog().system_config().user_modifiable(name) =>
2701            {
2702                // In lieu of plumbing the user to all system config functions, just check that
2703                // the var is visible.
2704                let var = self.catalog().system_config().get(name)?;
2705                var.visible(session.user(), self.catalog().system_config())?;
2706                Ok(())
2707            }
2708            // If we're not a superuser, but the variable is user modifiable, indicate they can use
2709            // session variables.
2710            (UserKind::Regular, Some(name))
2711                if self.catalog().system_config().user_modifiable(name) =>
2712            {
2713                Err(AdapterError::Unauthorized(
2714                    rbac::UnauthorizedError::Superuser {
2715                        action: format!("toggle the '{name}' system configuration parameter"),
2716                    },
2717                ))
2718            }
2719            _ => Err(AdapterError::Unauthorized(
2720                rbac::UnauthorizedError::MzSystem {
2721                    action: "alter system".into(),
2722                },
2723            )),
2724        }
2725    }
2726
2727    fn validate_alter_system_network_policy(
2728        &self,
2729        session: &Session,
2730        policy_value: &plan::VariableValue,
2731    ) -> Result<(), AdapterError> {
2732        let policy_name = match &policy_value {
2733            // Make sure the compiled in default still exists.
2734            plan::VariableValue::Default => Some(NETWORK_POLICY.default_value().format()),
2735            plan::VariableValue::Values(values) if values.len() == 1 => {
2736                values.iter().next().cloned()
2737            }
2738            plan::VariableValue::Values(values) => {
2739                tracing::warn!(?values, "can't set multiple network policies at once");
2740                None
2741            }
2742        };
2743        let maybe_network_policy = policy_name
2744            .as_ref()
2745            .and_then(|name| self.catalog.get_network_policy_by_name(name));
2746        let Some(network_policy) = maybe_network_policy else {
2747            return Err(AdapterError::PlanError(plan::PlanError::VarError(
2748                VarError::InvalidParameterValue {
2749                    name: NETWORK_POLICY.name(),
2750                    invalid_values: vec![policy_name.unwrap_or_else(|| "<none>".to_string())],
2751                    reason: "no network policy with such name exists".to_string(),
2752                },
2753            )));
2754        };
2755        self.validate_alter_network_policy(session, &network_policy.rules)
2756    }
2757
2758    /// Validates that a set of [`NetworkPolicyRule`]s is valid for the current [`Session`].
2759    ///
2760    /// This helps prevent users from modifying network policies in a way that would lock out their
2761    /// current connection.
2762    fn validate_alter_network_policy(
2763        &self,
2764        session: &Session,
2765        policy_rules: &Vec<NetworkPolicyRule>,
2766    ) -> Result<(), AdapterError> {
2767        // If the user is not an internal user attempt to protect them from
2768        // blocking themselves.
2769        if session.user().is_internal() {
2770            return Ok(());
2771        }
2772        if let Some(ip) = session.meta().client_ip() {
2773            validate_ip_with_policy_rules(ip, policy_rules)
2774                .map_err(|_| AdapterError::PlanError(plan::PlanError::NetworkPolicyLockoutError))?;
2775        } else {
2776            // Sessions without IPs are only temporarily constructed for default values
2777            // they should not be permitted here.
2778            return Err(AdapterError::NetworkPolicyDenied(
2779                NetworkPolicyError::MissingIp,
2780            ));
2781        }
2782        Ok(())
2783    }
2784
2785    #[instrument]
2786    pub(super) async fn sequence_grant_privileges(
2787        &mut self,
2788        session: &Session,
2789        plan::GrantPrivilegesPlan {
2790            update_privileges,
2791            grantees,
2792        }: plan::GrantPrivilegesPlan,
2793    ) -> Result<ExecuteResponse, AdapterError> {
2794        self.sequence_update_privileges(
2795            session,
2796            update_privileges,
2797            grantees,
2798            UpdatePrivilegeVariant::Grant,
2799        )
2800        .await
2801    }
2802
2803    #[instrument]
2804    pub(super) async fn sequence_revoke_privileges(
2805        &mut self,
2806        session: &Session,
2807        plan::RevokePrivilegesPlan {
2808            update_privileges,
2809            revokees,
2810        }: plan::RevokePrivilegesPlan,
2811    ) -> Result<ExecuteResponse, AdapterError> {
2812        self.sequence_update_privileges(
2813            session,
2814            update_privileges,
2815            revokees,
2816            UpdatePrivilegeVariant::Revoke,
2817        )
2818        .await
2819    }
2820
2821    #[instrument]
2822    async fn sequence_update_privileges(
2823        &mut self,
2824        session: &Session,
2825        update_privileges: Vec<UpdatePrivilege>,
2826        grantees: Vec<RoleId>,
2827        variant: UpdatePrivilegeVariant,
2828    ) -> Result<ExecuteResponse, AdapterError> {
2829        let mut ops = Vec::with_capacity(update_privileges.len());
2830        let mut warnings = Vec::new();
2831        let catalog = self.catalog().for_session(session);
2832
2833        for UpdatePrivilege {
2834            acl_mode,
2835            target_id,
2836            grantor,
2837            acl_from_all,
2838        } in update_privileges
2839        {
2840            let actual_object_type = catalog.get_system_object_type(&target_id);
2841            // For all relations we allow all applicable table privileges, but send a warning if the
2842            // privilege isn't actually applicable to the object type. We skip the warning when the
2843            // user used the `ALL [PRIVILEGES]` shorthand: the user did not explicitly name a
2844            // non-applicable privilege, and via PostgreSQL-compatible `ON TABLE <view>` syntax
2845            // `ALL` deliberately expands to the full table set.
2846            if actual_object_type.is_relation() && !acl_from_all {
2847                let applicable_privileges = rbac::all_object_privileges(actual_object_type);
2848                let non_applicable_privileges = acl_mode.difference(applicable_privileges);
2849                if !non_applicable_privileges.is_empty() {
2850                    let object_description =
2851                        ErrorMessageObjectDescription::from_sys_id(&target_id, &catalog);
2852                    warnings.push(AdapterNotice::NonApplicablePrivilegeTypes {
2853                        non_applicable_privileges,
2854                        object_description,
2855                    })
2856                }
2857            }
2858
2859            if let SystemObjectId::Object(object_id) = &target_id {
2860                self.catalog()
2861                    .ensure_not_reserved_object(object_id, session.conn_id())?;
2862            }
2863
2864            let privileges = self
2865                .catalog()
2866                .get_privileges(&target_id, session.conn_id())
2867                // Should be unreachable since the parser will refuse to parse grant/revoke
2868                // statements on objects without privileges.
2869                .ok_or(AdapterError::Unsupported(
2870                    "GRANTs/REVOKEs on an object type with no privileges",
2871                ))?;
2872
2873            // Collect every grantee's change to this target into one op, so a bulk grant/revoke
2874            // touching one object is a single durable write rather than one per grantee.
2875            let mut target_privileges = Vec::with_capacity(grantees.len());
2876            for grantee in &grantees {
2877                self.catalog().ensure_not_system_role(grantee)?;
2878                self.catalog().ensure_not_predefined_role(grantee)?;
2879                let existing_privilege = privileges
2880                    .get_acl_item(grantee, &grantor)
2881                    .map(Cow::Borrowed)
2882                    .unwrap_or_else(|| Cow::Owned(MzAclItem::empty(*grantee, grantor)));
2883
2884                // Skip grantees for which the grant/revoke would be a no-op.
2885                let changes = match variant {
2886                    UpdatePrivilegeVariant::Grant => {
2887                        !existing_privilege.acl_mode.contains(acl_mode)
2888                    }
2889                    UpdatePrivilegeVariant::Revoke => !existing_privilege
2890                        .acl_mode
2891                        .intersection(acl_mode)
2892                        .is_empty(),
2893                };
2894                if changes {
2895                    target_privileges.push(MzAclItem {
2896                        grantee: *grantee,
2897                        grantor,
2898                        acl_mode,
2899                    });
2900                }
2901            }
2902            if !target_privileges.is_empty() {
2903                ops.push(catalog::Op::UpdatePrivilege {
2904                    target_id: target_id.clone(),
2905                    privileges: target_privileges,
2906                    variant,
2907                });
2908            }
2909        }
2910
2911        if ops.is_empty() {
2912            session.add_notices(warnings);
2913            return Ok(variant.into());
2914        }
2915
2916        let res = self
2917            .catalog_transact(Some(session), ops)
2918            .await
2919            .map(|_| match variant {
2920                UpdatePrivilegeVariant::Grant => ExecuteResponse::GrantedPrivilege,
2921                UpdatePrivilegeVariant::Revoke => ExecuteResponse::RevokedPrivilege,
2922            });
2923        if res.is_ok() {
2924            session.add_notices(warnings);
2925        }
2926        res
2927    }
2928
2929    #[instrument]
2930    pub(super) async fn sequence_alter_default_privileges(
2931        &mut self,
2932        session: &Session,
2933        plan::AlterDefaultPrivilegesPlan {
2934            privilege_objects,
2935            privilege_acl_items,
2936            is_grant,
2937        }: plan::AlterDefaultPrivilegesPlan,
2938    ) -> Result<ExecuteResponse, AdapterError> {
2939        let mut ops = Vec::with_capacity(privilege_objects.len() * privilege_acl_items.len());
2940        let variant = if is_grant {
2941            UpdatePrivilegeVariant::Grant
2942        } else {
2943            UpdatePrivilegeVariant::Revoke
2944        };
2945        for privilege_object in &privilege_objects {
2946            self.catalog()
2947                .ensure_not_system_role(&privilege_object.role_id)?;
2948            self.catalog()
2949                .ensure_not_predefined_role(&privilege_object.role_id)?;
2950            if let Some(database_id) = privilege_object.database_id {
2951                self.catalog()
2952                    .ensure_not_reserved_object(&database_id.into(), session.conn_id())?;
2953            }
2954            if let Some(schema_id) = privilege_object.schema_id {
2955                let database_spec: ResolvedDatabaseSpecifier = privilege_object.database_id.into();
2956                let schema_spec: SchemaSpecifier = schema_id.into();
2957
2958                self.catalog().ensure_not_reserved_object(
2959                    &(database_spec, schema_spec).into(),
2960                    session.conn_id(),
2961                )?;
2962            }
2963            for privilege_acl_item in &privilege_acl_items {
2964                self.catalog()
2965                    .ensure_not_system_role(&privilege_acl_item.grantee)?;
2966                self.catalog()
2967                    .ensure_not_predefined_role(&privilege_acl_item.grantee)?;
2968                ops.push(catalog::Op::UpdateDefaultPrivilege {
2969                    privilege_object: privilege_object.clone(),
2970                    privilege_acl_item: privilege_acl_item.clone(),
2971                    variant,
2972                })
2973            }
2974        }
2975
2976        self.catalog_transact(Some(session), ops).await?;
2977        Ok(ExecuteResponse::AlteredDefaultPrivileges)
2978    }
2979
2980    #[instrument]
2981    pub(super) async fn sequence_grant_role(
2982        &mut self,
2983        session: &Session,
2984        plan::GrantRolePlan {
2985            role_ids,
2986            member_ids,
2987            grantor_id,
2988        }: plan::GrantRolePlan,
2989    ) -> Result<ExecuteResponse, AdapterError> {
2990        let catalog = self.catalog();
2991        let mut ops = Vec::with_capacity(role_ids.len() * member_ids.len());
2992        for role_id in role_ids {
2993            for member_id in &member_ids {
2994                let member_membership: BTreeSet<_> =
2995                    catalog.get_role(member_id).membership().keys().collect();
2996                if member_membership.contains(&role_id) {
2997                    let role_name = catalog.get_role(&role_id).name().to_string();
2998                    let member_name = catalog.get_role(member_id).name().to_string();
2999                    // We need this check so we don't accidentally return a success on a reserved role.
3000                    catalog.ensure_not_reserved_role(member_id)?;
3001                    catalog.ensure_grantable_role(&role_id)?;
3002                    session.add_notice(AdapterNotice::RoleMembershipAlreadyExists {
3003                        role_name,
3004                        member_name,
3005                    });
3006                } else {
3007                    ops.push(catalog::Op::GrantRole {
3008                        role_id,
3009                        member_id: *member_id,
3010                        grantor_id,
3011                    });
3012                }
3013            }
3014        }
3015
3016        if ops.is_empty() {
3017            return Ok(ExecuteResponse::GrantedRole);
3018        }
3019
3020        self.catalog_transact(Some(session), ops)
3021            .await
3022            .map(|_| ExecuteResponse::GrantedRole)
3023    }
3024
3025    #[instrument]
3026    pub(super) async fn sequence_revoke_role(
3027        &mut self,
3028        session: &Session,
3029        plan::RevokeRolePlan {
3030            role_ids,
3031            member_ids,
3032            grantor_id,
3033        }: plan::RevokeRolePlan,
3034    ) -> Result<ExecuteResponse, AdapterError> {
3035        let catalog = self.catalog();
3036        let mut ops = Vec::with_capacity(role_ids.len() * member_ids.len());
3037        for role_id in role_ids {
3038            for member_id in &member_ids {
3039                let member_membership: BTreeSet<_> =
3040                    catalog.get_role(member_id).membership().keys().collect();
3041                if !member_membership.contains(&role_id) {
3042                    let role_name = catalog.get_role(&role_id).name().to_string();
3043                    let member_name = catalog.get_role(member_id).name().to_string();
3044                    // We need this check so we don't accidentally return a success on a reserved role.
3045                    catalog.ensure_not_reserved_role(member_id)?;
3046                    catalog.ensure_grantable_role(&role_id)?;
3047                    session.add_notice(AdapterNotice::RoleMembershipDoesNotExists {
3048                        role_name,
3049                        member_name,
3050                    });
3051                } else {
3052                    ops.push(catalog::Op::RevokeRole {
3053                        role_id,
3054                        member_id: *member_id,
3055                        grantor_id,
3056                    });
3057                }
3058            }
3059        }
3060
3061        if ops.is_empty() {
3062            return Ok(ExecuteResponse::RevokedRole);
3063        }
3064
3065        self.catalog_transact(Some(session), ops)
3066            .await
3067            .map(|_| ExecuteResponse::RevokedRole)
3068    }
3069
3070    #[instrument]
3071    pub(super) async fn sequence_alter_owner(
3072        &mut self,
3073        session: &Session,
3074        plan::AlterOwnerPlan {
3075            id,
3076            object_type,
3077            new_owner,
3078        }: plan::AlterOwnerPlan,
3079    ) -> Result<ExecuteResponse, AdapterError> {
3080        let mut ops = vec![catalog::Op::UpdateOwner {
3081            id: id.clone(),
3082            new_owner,
3083        }];
3084
3085        match &id {
3086            ObjectId::Item(global_id) => {
3087                let entry = self.catalog().get_entry(global_id);
3088
3089                // Cannot directly change the owner of an index.
3090                if entry.is_index() {
3091                    let name = self
3092                        .catalog()
3093                        .resolve_full_name(entry.name(), Some(session.conn_id()))
3094                        .to_string();
3095                    session.add_notice(AdapterNotice::AlterIndexOwner { name });
3096                    return Ok(ExecuteResponse::AlteredObject(object_type));
3097                }
3098
3099                // Alter owner cascades down to dependent indexes.
3100                let dependent_index_ops = entry
3101                    .used_by()
3102                    .into_iter()
3103                    .filter(|id| self.catalog().get_entry(id).is_index())
3104                    .map(|id| catalog::Op::UpdateOwner {
3105                        id: ObjectId::Item(*id),
3106                        new_owner,
3107                    });
3108                ops.extend(dependent_index_ops);
3109
3110                // Alter owner cascades down to progress collections.
3111                let dependent_subsources =
3112                    entry
3113                        .progress_id()
3114                        .into_iter()
3115                        .map(|item_id| catalog::Op::UpdateOwner {
3116                            id: ObjectId::Item(item_id),
3117                            new_owner,
3118                        });
3119                ops.extend(dependent_subsources);
3120            }
3121            ObjectId::Cluster(cluster_id) => {
3122                let cluster = self.catalog().get_cluster(*cluster_id);
3123                // Alter owner cascades down to cluster replicas.
3124                let managed_cluster_replica_ops =
3125                    cluster.replicas().map(|replica| catalog::Op::UpdateOwner {
3126                        id: ObjectId::ClusterReplica((cluster.id(), replica.replica_id())),
3127                        new_owner,
3128                    });
3129                ops.extend(managed_cluster_replica_ops);
3130            }
3131            _ => {}
3132        }
3133
3134        self.catalog_transact(Some(session), ops)
3135            .await
3136            .map(|_| ExecuteResponse::AlteredObject(object_type))
3137    }
3138
3139    #[instrument]
3140    pub(super) async fn sequence_reassign_owned(
3141        &mut self,
3142        session: &Session,
3143        plan::ReassignOwnedPlan {
3144            old_roles,
3145            new_role,
3146            reassign_ids,
3147        }: plan::ReassignOwnedPlan,
3148    ) -> Result<ExecuteResponse, AdapterError> {
3149        for role_id in old_roles.iter().chain(iter::once(&new_role)) {
3150            self.catalog().ensure_not_reserved_role(role_id)?;
3151        }
3152
3153        let ops = reassign_ids
3154            .into_iter()
3155            .map(|id| catalog::Op::UpdateOwner {
3156                id,
3157                new_owner: new_role,
3158            })
3159            .collect();
3160
3161        self.catalog_transact(Some(session), ops)
3162            .await
3163            .map(|_| ExecuteResponse::ReassignOwned)
3164    }
3165
3166    #[instrument]
3167    pub(crate) async fn handle_deferred_statement(&mut self) {
3168        // It is possible Message::DeferredStatementReady was sent but then a session cancellation
3169        // was processed, removing the single element from deferred_statements, so it is expected
3170        // that this is sometimes empty.
3171        let Some(deferred) = self.serialized_ddl.pop_front() else {
3172            return;
3173        };
3174        match deferred {
3175            DeferredDdl::Statement { ctx, stmt, params } => {
3176                self.handle_execute_inner(stmt, params, ctx).await;
3177            }
3178            DeferredDdl::Commit(pending) => {
3179                Box::pin(self.sequence_ddl_commit(pending)).await;
3180            }
3181        }
3182    }
3183
3184    #[instrument]
3185    // TODO(parkmycar): Remove this once we have an actual implementation.
3186    #[allow(clippy::unused_async)]
3187    pub(super) async fn sequence_alter_table(
3188        &mut self,
3189        ctx: &mut ExecuteContext,
3190        plan: plan::AlterTablePlan,
3191    ) -> Result<ExecuteResponse, AdapterError> {
3192        let plan::AlterTablePlan {
3193            relation_id,
3194            column_name,
3195            column_type,
3196            raw_sql_type,
3197        } = plan;
3198
3199        // TODO(alter_table): Support allocating GlobalIds without a CatalogItemId.
3200        let (_, new_global_id) = self.allocate_user_id().await?;
3201        let ops = vec![catalog::Op::AlterAddColumn {
3202            id: relation_id,
3203            new_global_id,
3204            name: column_name,
3205            typ: column_type,
3206            sql: raw_sql_type,
3207        }];
3208
3209        self.catalog_transact_with_context(None, Some(ctx), ops)
3210            .await?;
3211
3212        Ok(ExecuteResponse::AlteredObject(ObjectType::Table))
3213    }
3214
3215    /// Prepares to apply a replacement materialized view.
3216    #[instrument]
3217    pub(super) async fn sequence_alter_materialized_view_apply_replacement_prepare(
3218        &mut self,
3219        ctx: ExecuteContext,
3220        plan: AlterMaterializedViewApplyReplacementPlan,
3221    ) {
3222        // To ensure there is no time gap in the output, we can only apply a replacement if the
3223        // target's write frontier has caught up to the replacement dataflow's write frontier. This
3224        // might not be the case initially, so we have to wait. To this end, we install a watch set
3225        // waiting for the target MV's write frontier to advance sufficiently.
3226        //
3227        // Note that the replacement's dataflow is not performing any writes, so it can only be
3228        // ahead of the target initially due to as-of selection. Once the target has caught up, the
3229        // replacement's write frontier is always <= the target's.
3230
3231        let AlterMaterializedViewApplyReplacementPlan { id, replacement_id } = plan.clone();
3232
3233        let plan_validity = PlanValidity::new(
3234            self.catalog(),
3235            BTreeSet::from_iter([id, replacement_id]),
3236            None,
3237            None,
3238            ctx.session().role_metadata().clone(),
3239        );
3240
3241        let target = self.catalog.get_entry(&id);
3242        let target_gid = target.latest_global_id();
3243
3244        let replacement = self.catalog.get_entry(&replacement_id);
3245        let replacement_gid = replacement.latest_global_id();
3246
3247        let target_upper = self
3248            .controller
3249            .storage_collections
3250            .collection_frontiers(target_gid)
3251            .expect("target MV exists")
3252            .write_frontier;
3253        let replacement_upper = self
3254            .controller
3255            .compute
3256            .collection_frontiers(replacement_gid, replacement.cluster_id())
3257            .expect("replacement MV exists")
3258            .write_frontier;
3259
3260        info!(
3261            %id, %replacement_id, ?target_upper, ?replacement_upper,
3262            "preparing materialized view replacement application",
3263        );
3264
3265        // Once the target's write frontier is empty, its contents are final for all times and the
3266        // replacement could never write to it. The replacement's write frontier then becomes
3267        // empty too, but the frontiers are reported independently, so either one can be observed
3268        // first.
3269        //
3270        // NOTE: `_finish` checks the target again, but checking it here is needed too. If only
3271        // compute has seen the seal so far, the watch set below never resolves: installing it
3272        // reads the storage frontier, and compute doesn't report the target's frontier again.
3273        let replacement_upper_ts = match replacement_upper.into_option() {
3274            Some(ts) if !self.materialized_view_sealed(target) => ts,
3275            _ => {
3276                ctx.retire(Err(AdapterError::ReplaceMaterializedViewSealed {
3277                    name: target.name().item.clone(),
3278                }));
3279                return;
3280            }
3281        };
3282
3283        // A watch set resolves when the watched objects' frontier becomes _greater_ than the
3284        // specified timestamp. Since we only need to wait until the target frontier is >= the
3285        // replacement's frontier, we can step back the timestamp.
3286        let replacement_upper_ts = replacement_upper_ts.step_back().unwrap_or(Timestamp::MIN);
3287
3288        // TODO(database-issues#9820): If the target MV is dropped while we are waiting for
3289        // progress, the watch set never completes and neither does the `ALTER MATERIALIZED VIEW`
3290        // command.
3291        self.install_storage_watch_set(
3292            ctx.session().conn_id().clone(),
3293            BTreeSet::from_iter([target_gid]),
3294            replacement_upper_ts,
3295            WatchSetResponse::AlterMaterializedViewReady(AlterMaterializedViewReadyContext {
3296                ctx: Some(ctx),
3297                otel_ctx: OpenTelemetryContext::obtain(),
3298                plan,
3299                plan_validity,
3300            }),
3301        )
3302        .expect("target collection exists");
3303    }
3304
3305    /// Finishes applying a replacement materialized view after the frontier wait completed.
3306    #[instrument]
3307    pub async fn sequence_alter_materialized_view_apply_replacement_finish(
3308        &mut self,
3309        mut ctx: AlterMaterializedViewReadyContext,
3310    ) {
3311        ctx.otel_ctx.attach_as_parent();
3312
3313        let AlterMaterializedViewApplyReplacementPlan { id, replacement_id } = ctx.plan;
3314
3315        // We avoid taking the DDL lock for `ALTER MATERIALIZED VIEW ... APPLY REPLACEMENT`
3316        // commands, see `Coordinator::must_serialize_ddl`. We therefore must assume that the
3317        // world has arbitrarily changed since we performed planning, and we must re-assert
3318        // that it still matches our requirements.
3319        if let Err(err) = ctx.plan_validity.check(self.catalog()) {
3320            ctx.retire(Err(err));
3321            return;
3322        }
3323
3324        // The target can also seal while we wait, which resolves the watch set as well. The
3325        // compute controller records a frontier before reporting it, so this check sees that seal.
3326        //
3327        // NOTE: The target can still seal after this check, until its old dataflow is dropped.
3328        // The replacement then never writes.
3329        let target = self.catalog().get_entry(&id);
3330        if self.materialized_view_sealed(target) {
3331            let name = target.name().item.clone();
3332            ctx.retire(Err(AdapterError::ReplaceMaterializedViewSealed { name }));
3333            return;
3334        }
3335
3336        info!(
3337            %id, %replacement_id,
3338            "finishing materialized view replacement application",
3339        );
3340
3341        // Applying a replacement changes the target's definition while it
3342        // keeps its GlobalIds, so the cached expressions under those ids are
3343        // stale. Entries record the item's version and `ExpressionCache::open`
3344        // drops them on the next boot; invalidating here only reclaims them
3345        // eagerly.
3346        let invalidate_ids = self.catalog().get_entry(&id).global_ids().collect();
3347        self.catalog()
3348            .update_expression_cache(Vec::new(), Vec::new(), invalidate_ids)
3349            .await;
3350
3351        let ops = vec![catalog::Op::AlterMaterializedViewApplyReplacement { id, replacement_id }];
3352        match self
3353            .catalog_transact(Some(ctx.ctx().session_mut()), ops)
3354            .await
3355        {
3356            Ok(()) => ctx.retire(Ok(ExecuteResponse::AlteredObject(
3357                ObjectType::MaterializedView,
3358            ))),
3359            Err(err) => ctx.retire(Err(err)),
3360        }
3361    }
3362
3363    /// Reports whether the write frontier of the materialized view `entry` is known to be empty.
3364    ///
3365    /// The compute controller and storage collections learn about the frontier independently,
3366    /// so either one can see it first.
3367    fn materialized_view_sealed(&self, entry: &CatalogEntry) -> bool {
3368        let gid = entry.latest_global_id();
3369        let compute_upper = self
3370            .controller
3371            .compute
3372            .collection_frontiers(gid, entry.cluster_id())
3373            .expect("materialized view exists")
3374            .write_frontier;
3375        let storage_upper = self
3376            .controller
3377            .storage_collections
3378            .collection_frontiers(gid)
3379            .expect("materialized view exists")
3380            .write_frontier;
3381        compute_upper.is_empty() || storage_upper.is_empty()
3382    }
3383}
3384
3385impl Coordinator {
3386    /// Emit the raw optimizer notices in `notices` to the user's session, if
3387    /// any.
3388    ///
3389    /// This intentionally consumes `RawOptimizerNotice`s (not pre-rendered
3390    /// ones) because the user-facing rendering goes through the user's
3391    /// session-aware humanizer, which produces e.g. schema-qualified names
3392    /// relative to the user's current database/schema.
3393    pub(crate) fn emit_raw_optimizer_notices_to_user(
3394        &self,
3395        ctx: &ExecuteContext,
3396        notices: &[RawOptimizerNotice],
3397    ) {
3398        emit_optimizer_notices(&*self.catalog, ctx.session(), notices);
3399    }
3400
3401    /// Renders `raw_df_meta`'s optimizer notices against a humanizer that resolves the
3402    /// about-to-be-created item's own `global_id` to `name`, rather than to the bare transient id
3403    /// a system-session humanizer would produce. `source_desc` supplies the column names the
3404    /// notices humanize against, and is the desc of the relation the new item reads.
3405    ///
3406    /// Callers render before the catalog transaction that creates the item, so the persisted
3407    /// notice text can already refer to the item by its intended name. The raw notices stay with
3408    /// the caller: they go to the user session only once the transaction succeeds, so a failed
3409    /// transaction does not tell the user about an item that was never created.
3410    fn render_create_item_notices(
3411        &self,
3412        name: &QualifiedItemName,
3413        global_id: GlobalId,
3414        source_desc: &RelationDesc,
3415        raw_df_meta: &DataflowMetainfo,
3416    ) -> DataflowMetainfo<Arc<OptimizerNotice>> {
3417        let notice_ids = std::iter::repeat_with(|| self.allocate_transient_id())
3418            .map(|(_item_id, notice_id)| notice_id)
3419            .take(raw_df_meta.optimizer_notices.len())
3420            .collect::<Vec<_>>();
3421
3422        let system_catalog = self.catalog().for_system_session();
3423        let full_name = self.catalog().resolve_full_name(name, None);
3424        let transient_items = btreemap! {
3425            global_id => TransientItem::new(
3426                Some(full_name.into_parts()),
3427                Some(source_desc.iter_names().map(|c| c.to_string()).collect()),
3428            )
3429        };
3430        let humanizer = ExprHumanizerExt::new(transient_items, &system_catalog);
3431        CatalogState::render_notices_core(
3432            &humanizer,
3433            (self.catalog().config().now)(),
3434            raw_df_meta,
3435            notice_ids,
3436            Some(global_id),
3437        )
3438    }
3439
3440    /// Sets `df_desc`'s as-of from a read hold on `id_bundle`, ships the dataflow, and drops the
3441    /// hold once compute has taken its own (compute puts in its own read holds during
3442    /// `create_dataflow`, so it is safe to release this one right after shipping).
3443    ///
3444    /// The read hold across shipping keeps the since of `id_bundle` from advancing underneath the
3445    /// as-of just picked.
3446    async fn ship_new_dataflow(
3447        &mut self,
3448        id_bundle: &CollectionIdBundle,
3449        mut df_desc: LirDataflowDescription,
3450        instance: ComputeInstanceId,
3451        notice_builtin_updates_fut: Option<BuiltinTableAppendNotify>,
3452    ) {
3453        let read_holds = self.acquire_read_holds(id_bundle);
3454        let since = read_holds.least_valid_read();
3455        df_desc.set_as_of(since);
3456
3457        self.ship_dataflow_and_notice_builtin_table_updates(
3458            df_desc,
3459            instance,
3460            notice_builtin_updates_fut,
3461            None,
3462        )
3463        .await;
3464
3465        drop(read_holds);
3466    }
3467
3468    /// Persist already-rendered optimizer notices for a newly created
3469    /// non-transient dataflow.
3470    ///
3471    /// This:
3472    /// - packs builtin-table updates for `mz_optimizer_notices` (if enabled),
3473    /// - stores the rendered metainfo on the catalog object via
3474    ///   `set_dataflow_metainfo`,
3475    /// - and returns a future that resolves once the builtin-table append
3476    ///   has been observed, or `None` if nothing was appended.
3477    fn persist_dataflow_metainfo(
3478        &mut self,
3479        df_meta: DataflowMetainfo<Arc<OptimizerNotice>>,
3480        export_id: GlobalId,
3481    ) -> Option<BuiltinTableAppendNotify> {
3482        // Attend to optimization notice builtin tables and save the metainfo in the catalog's
3483        // in-memory state.
3484        if self.catalog().state().system_config().enable_mz_notices()
3485            && !df_meta.optimizer_notices.is_empty()
3486        {
3487            let mut builtin_table_updates = Vec::with_capacity(df_meta.optimizer_notices.len());
3488            self.catalog().state().pack_optimizer_notices(
3489                &mut builtin_table_updates,
3490                df_meta.optimizer_notices.iter(),
3491                Diff::ONE,
3492            );
3493
3494            // Save the metainfo.
3495            self.catalog_mut().set_dataflow_metainfo(export_id, df_meta);
3496
3497            Some(self.builtin_table_update().execute(builtin_table_updates))
3498        } else {
3499            // Save the metainfo.
3500            self.catalog_mut().set_dataflow_metainfo(export_id, df_meta);
3501
3502            None
3503        }
3504    }
3505}