Skip to main content

mz_adapter/coord/
ddl.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! This module encapsulates all of the [`Coordinator`]'s logic for creating, dropping,
11//! and altering objects.
12
13use std::collections::BTreeMap;
14use std::pin::Pin;
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18use fail::fail_point;
19use maplit::{btreemap, btreeset};
20use mz_adapter_types::compaction::SINCE_GRANULARITY;
21use mz_adapter_types::connection::ConnectionId;
22use mz_audit_log::VersionedEvent;
23use mz_catalog::SYSTEM_CONN_ID;
24use mz_catalog::memory::objects::Sink;
25use mz_cluster_client::ReplicaId;
26use mz_controller_types::ClusterId;
27use mz_ore::cast::CastFrom;
28use mz_ore::instrument;
29use mz_ore::metrics::MetricsFutureExt;
30use mz_ore::now::to_datetime;
31use mz_ore::retry::Retry;
32use mz_ore::task;
33use mz_ore::tracing::OpenTelemetryContext;
34use mz_repr::adt::numeric::Numeric;
35use mz_repr::{CatalogItemId, GlobalId, Timestamp};
36use mz_sql::catalog::CatalogClusterReplica;
37use mz_sql::session::metadata::SessionMetadata;
38use mz_sql::session::vars::{self, DEFAULT_TIMESTAMP_INTERVAL, SystemVars, Var};
39use mz_storage_client::controller::{CollectionDescription, DataSource, ExportDescription};
40use mz_storage_types::connections::inline::IntoInlineConnection;
41use mz_storage_types::read_policy::ReadPolicy;
42use mz_storage_types::sources::SourceConnection;
43use mz_storage_types::sources::kafka::KAFKA_PROGRESS_DESC;
44use serde_json::json;
45use tracing::{Instrument, Level, event, info_span, warn};
46
47use crate::active_compute_sink::{ActiveComputeSink, ActiveComputeSinkRetireReason};
48use crate::catalog::{DropObjectInfo, Op, TransactionResult};
49use crate::coord::appends::{BuiltinTableAppendCompletion, BuiltinTableAppendNotify};
50use crate::coord::catalog_implications::parsed_state_updates::ParsedStateUpdate;
51use crate::coord::{Coordinator, DeferredDdl, Message, PendingTxn};
52use crate::session::{Session, TransactionOps};
53use crate::telemetry::{EventDetails, SegmentClientExt};
54use crate::util::ResultExt;
55use crate::{AdapterError, ExecuteContext, catalog, flags};
56
57#[derive(Debug)]
58pub struct PendingSourceStatement {
59    ctx: ExecuteContext,
60    statement: catalog::command::source_statement::SourceStatement,
61}
62
63#[derive(Debug)]
64pub struct PendingDdlCommit {
65    context: DdlCommitContext,
66    commands: Vec<catalog::command::CatalogCommand>,
67    responses: BTreeMap<usize, catalog::CommandResponse>,
68}
69
70#[derive(Debug)]
71enum DdlCommitContext {
72    Transaction(PendingTxn),
73    Statement {
74        ctx: ExecuteContext,
75        response: crate::ExecuteResponse,
76    },
77}
78
79impl PendingDdlCommit {
80    pub(super) fn conn_id(&self) -> &ConnectionId {
81        match &self.context {
82            DdlCommitContext::Transaction(txn) => txn.ctx.session().conn_id(),
83            DdlCommitContext::Statement { ctx, response: _ } => ctx.session().conn_id(),
84        }
85    }
86
87    pub(super) fn transaction(
88        txn: PendingTxn,
89        commands: Vec<catalog::command::CatalogCommand>,
90    ) -> Self {
91        Self {
92            context: DdlCommitContext::Transaction(txn),
93            commands,
94            responses: BTreeMap::new(),
95        }
96    }
97
98    pub(super) fn statement(
99        ctx: ExecuteContext,
100        response: crate::ExecuteResponse,
101        commands: Vec<catalog::command::CatalogCommand>,
102    ) -> Self {
103        Self {
104            context: DdlCommitContext::Statement { ctx, response },
105            commands,
106            responses: BTreeMap::new(),
107        }
108    }
109}
110
111impl DdlCommitContext {
112    fn context_mut(&mut self) -> &mut ExecuteContext {
113        match self {
114            Self::Transaction(txn) => &mut txn.ctx,
115            Self::Statement { ctx, .. } => ctx,
116        }
117    }
118
119    fn finish(self, result: Result<(), AdapterError>) {
120        match self {
121            Self::Transaction(mut txn) => {
122                if let Err(error) = result {
123                    txn.response = Err(error);
124                    txn.action = crate::session::EndTransactionAction::Rollback;
125                }
126                txn.finish();
127            }
128            Self::Statement { ctx, response } => ctx.retire(result.map(|()| response)),
129        }
130    }
131}
132
133/// Waits while a test configures the named failpoint with a `return` action.
134async fn catalog_preparation_test_pause(name: &'static str) {
135    let paused = || {
136        fail::fail_point!(name, |_| true);
137        false
138    };
139    // Clearing the failpoint requires coordinator and runtime progress.
140    while paused() {
141        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
142    }
143}
144
145impl Coordinator {
146    /// Sets allowed responses and checks read-only and execution-cluster restrictions.
147    fn prepare_command_execution(
148        &self,
149        ctx: &mut ExecuteContext,
150        plan: &mz_sql::plan::Plan,
151    ) -> Result<(), AdapterError> {
152        ctx.tx_mut()
153            .set_allowed(crate::ExecuteResponse::generated_from(
154                &mz_sql::plan::PlanKind::from(plan),
155            ));
156        if self.controller.read_only() && !plan.allowed_in_read_only() {
157            return Err(AdapterError::ReadOnly);
158        }
159        self.prepare_plan_execution(ctx, plan)?;
160        Ok(())
161    }
162
163    pub(super) fn sequence_catalog_result_command(
164        &self,
165        mut ctx: ExecuteContext,
166        statement: Arc<mz_sql::ast::Statement<mz_sql::ast::Raw>>,
167        params: mz_sql::plan::Params,
168    ) {
169        let prepared = {
170            let catalog = self.catalog().for_session(ctx.session());
171            catalog::command::CatalogResultCommand::prepare(
172                catalog.state(),
173                statement,
174                params,
175                ctx.session().meta(),
176            )
177        };
178        let (command, plan) = match prepared {
179            Ok(prepared) => prepared,
180            Err(error) => return ctx.retire(Err(error)),
181        };
182        if let Err(error) = self.prepare_command_execution(&mut ctx, &plan) {
183            return ctx.retire(Err(error));
184        }
185        let row = match catalog::command::CatalogResultCommand::result(&plan) {
186            Ok(row) => row,
187            Err(error) => return ctx.retire(Err(error)),
188        };
189        let command = Arc::new(command);
190        self.emit_command_notices(
191            ctx.session(),
192            &catalog::command::CatalogCommand::CatalogResult(Arc::clone(&command)),
193        );
194        ctx.session_mut().retain_catalog_result(command);
195        ctx.retire(Ok(Self::send_immediate_rows(row)));
196    }
197
198    pub(super) async fn sequence_create_connection_command(
199        &mut self,
200        mut ctx: ExecuteContext,
201        statement: Arc<mz_sql::ast::Statement<mz_sql::ast::Raw>>,
202        params: mz_sql::plan::Params,
203    ) {
204        let mut command = catalog::command::connection::ConnectionStatement::new(
205            statement,
206            params,
207            ctx.session().meta(),
208        );
209        let compiled = match command.compile_create(self.catalog().state()) {
210            Ok(compiled) => compiled,
211            Err(error) => return ctx.retire(Err(error)),
212        };
213        let plan = mz_sql::plan::Plan::CreateConnection(compiled.plan);
214        if let Err(error) = self.prepare_command_execution(&mut ctx, &plan) {
215            return ctx.retire(Err(error));
216        }
217        let id = match self.allocate_user_id().await {
218            Ok(id) => id,
219            Err(error) => return ctx.retire(Err(error)),
220        };
221        command.allocate_create(id);
222        self.sequence_ddl_commit(PendingDdlCommit::statement(
223            ctx,
224            crate::ExecuteResponse::CreatedConnection,
225            vec![catalog::command::CatalogCommand::CreateConnection(
226                Arc::new(command),
227            )],
228        ))
229        .await;
230    }
231
232    pub(super) async fn sequence_alter_connection_command(
233        &mut self,
234        mut ctx: ExecuteContext,
235        statement: Arc<mz_sql::ast::Statement<mz_sql::ast::Raw>>,
236        params: mz_sql::plan::Params,
237    ) {
238        let command = catalog::command::connection::ConnectionStatement::new(
239            statement,
240            params,
241            ctx.session().meta(),
242        );
243        let compiled = match command.compile_alter(self.catalog().state()) {
244            Ok(compiled) => compiled,
245            Err(error) => return ctx.retire(Err(error)),
246        };
247        if let Err(error) = self.prepare_command_execution(&mut ctx, &compiled.plan) {
248            return ctx.retire(Err(error));
249        }
250        self.sequence_ddl_commit(PendingDdlCommit::statement(
251            ctx,
252            crate::ExecuteResponse::AlteredObject(mz_sql::catalog::ObjectType::Connection),
253            vec![catalog::command::CatalogCommand::AlterConnection(Arc::new(
254                command,
255            ))],
256        ))
257        .await;
258    }
259
260    pub(super) async fn sequence_source_statement(
261        &mut self,
262        ctx: ExecuteContext,
263        statement: Arc<mz_sql::ast::Statement<mz_sql::ast::Raw>>,
264        params: mz_sql::plan::Params,
265    ) {
266        let statement = catalog::command::source_statement::SourceStatement::new(
267            statement,
268            params,
269            ctx.session().meta(),
270            (self.catalog().config().now)(),
271        );
272        self.sequence_source_statement_ready(PendingSourceStatement { ctx, statement }, None)
273            .await;
274    }
275
276    pub(super) async fn sequence_source_statement_ready(
277        &mut self,
278        mut pending: PendingSourceStatement,
279        mut response: Option<mz_sql::pure::SourcePreparationResponse>,
280    ) {
281        use catalog::command::source_statement::{SourceCommand, SourceResolution};
282        if self.controller.read_only() {
283            return pending.ctx.retire(Err(AdapterError::ReadOnly));
284        }
285        let compiled = loop {
286            let state = pending
287                .ctx
288                .session()
289                .transaction()
290                .catalog_state()
291                .unwrap_or_else(|| self.catalog().state());
292            let result = match response.take() {
293                Some(response) => pending.statement.finish(state, response),
294                None => pending.statement.resolve(state),
295            };
296            match result {
297                Err(error) => return pending.ctx.retire(Err(error)),
298                Ok(SourceResolution::Ready(compiled)) => break compiled,
299                Ok(SourceResolution::Allocate(keys)) => {
300                    let ids = match self.allocate_user_ids(u64::cast_from(keys.len())).await {
301                        Ok(ids) => ids,
302                        Err(error) => return pending.ctx.retire(Err(error)),
303                    };
304                    pending.statement.record_ids(keys, ids);
305                }
306                Ok(SourceResolution::Prepare(request)) => {
307                    let conn_id = pending.ctx.session().conn_id().clone();
308                    let config = self.controller.storage.config().clone();
309                    let tx = self.internal_cmd_tx.clone();
310                    let otel_ctx = OpenTelemetryContext::obtain();
311                    task::spawn(|| "ddl_statement_preparation", async move {
312                        let response = request.execute(&config).await;
313                        tracing::debug!(
314                            target: "mz_adapter::catalog_preparation",
315                            %conn_id, kind = "purification", "catalog preparation complete"
316                        );
317                        catalog_preparation_test_pause("catalog_purification_ready").await;
318                        if let Err(error) = tx.send(Message::SourceStatementReady {
319                            pending, response, otel_ctx,
320                        }) {
321                            warn!("internal_cmd_rx dropped before source preparation completed: {error:?}");
322                        }
323                    }.instrument(tracing::Span::current()));
324                    return;
325                }
326            }
327        };
328        let mut ctx = pending.ctx;
329        if let Err(error) = self.prepare_command_execution(&mut ctx, &compiled.plan) {
330            return ctx.retire(Err(error));
331        }
332        let response = match &compiled.plan {
333            mz_sql::plan::Plan::CreateSources(_) => crate::ExecuteResponse::CreatedSource,
334            mz_sql::plan::Plan::CreateTable(_) => crate::ExecuteResponse::CreatedTable,
335            mz_sql::plan::Plan::AlterSource(_) => {
336                crate::ExecuteResponse::AlteredObject(mz_sql::catalog::ObjectType::Source)
337            }
338            mz_sql::plan::Plan::AlterNoop(plan) => {
339                crate::ExecuteResponse::AlteredObject(plan.object_type)
340            }
341            _ => unreachable!("source command plan"),
342        };
343        if ctx.session().transaction().is_ddl() {
344            let ts = self.get_local_write_ts().await.timestamp;
345            let TransactionOps::DDL {
346                commands: _,
347                state,
348                snapshot,
349            } = &ctx
350                .session()
351                .transaction()
352                .inner()
353                .expect("DDL transaction")
354                .ops
355            else {
356                unreachable!("DDL transaction")
357            };
358            let staged = match self
359                .catalog()
360                .stage_source_statement(
361                    pending.statement,
362                    *compiled,
363                    (state, snapshot),
364                    self.active_conns.get(ctx.session().conn_id()),
365                    ts,
366                )
367                .await
368            {
369                Ok(staged) => staged,
370                Err(error) => return ctx.retire(Err(error)),
371            };
372            let command = catalog::command::CatalogCommand::Source(Arc::new(staged.command));
373            if let Err(error) = ctx
374                .session_mut()
375                .transaction_mut()
376                .add_ops(TransactionOps::DDL {
377                    commands: vec![command.clone()],
378                    state: staged.state,
379                    snapshot: staged.snapshot,
380                })
381            {
382                return ctx.retire(Err(error));
383            }
384            self.emit_command_notices(ctx.session(), &command);
385            ctx.retire(Ok(response));
386        } else {
387            let command = catalog::command::CatalogCommand::Source(Arc::new(
388                SourceCommand::unobserved(pending.statement, *compiled),
389            ));
390            self.sequence_ddl_commit(PendingDdlCommit::statement(ctx, response, vec![command]))
391                .await;
392        }
393    }
394
395    fn emit_command_notices(&self, session: &Session, command: &catalog::command::CatalogCommand) {
396        session.add_notices(command.notices().iter().cloned().map(Into::into));
397        if let catalog::command::CatalogCommand::CreateConnection(command) = command {
398            if let Some(name) = command.skipped_name() {
399                session.add_notice(crate::AdapterNotice::ObjectAlreadyExists {
400                    name: name.to_owned(),
401                    ty: "connection",
402                });
403            }
404        }
405        let catalog::command::CatalogCommand::Source(command) = command else {
406            return;
407        };
408        if let Some(notice) = command.skipped_notice() {
409            session.add_notice(notice);
410            return;
411        }
412        let state = session
413            .transaction()
414            .catalog_state()
415            .unwrap_or_else(|| self.catalog().state());
416        for id in command.item_ids() {
417            let Some(entry) = state.try_get_entry(&id) else {
418                continue;
419            };
420            let Some(source) = entry.source() else {
421                continue;
422            };
423            use mz_catalog::memory::objects::DataSourceDesc;
424            let cluster_id = match &source.data_source {
425                DataSourceDesc::Ingestion { desc, cluster_id }
426                | DataSourceDesc::OldSyntaxIngestion {
427                    desc, cluster_id, ..
428                } if desc.connection.prefers_single_replica() => cluster_id,
429                _ => continue,
430            };
431            let Some(cluster) = self.catalog().try_get_cluster(*cluster_id) else {
432                continue;
433            };
434            let name = state.resolve_full_name(entry.name(), None);
435            self.notify_single_replica_sources(session, cluster, Some(&name));
436        }
437    }
438
439    pub(super) async fn sequence_rename_command(
440        &mut self,
441        mut ctx: ExecuteContext,
442        statement: Arc<mz_sql::ast::Statement<mz_sql::ast::Raw>>,
443        params: mz_sql::plan::Params,
444    ) {
445        let prepared = {
446            let catalog = self.catalog().for_session(ctx.session());
447            catalog::command::RenameCommand::prepare(
448                catalog.state(),
449                statement,
450                params,
451                ctx.session().meta(),
452            )
453        };
454        let (command, plan) = match prepared {
455            Ok(prepared) => prepared,
456            Err(error) => return ctx.retire(Err(error)),
457        };
458        if let Err(error) = self.prepare_command_execution(&mut ctx, &plan) {
459            return ctx.retire(Err(error));
460        }
461        let command = Arc::new(command);
462        if !ctx.session().transaction().is_ddl() {
463            let response = crate::ExecuteResponse::AlteredObject(command.object_type());
464            self.sequence_ddl_commit(PendingDdlCommit::statement(
465                ctx,
466                response,
467                vec![catalog::command::CatalogCommand::Rename(command)],
468            ))
469            .await;
470            return;
471        }
472        let TransactionOps::DDL {
473            state, snapshot, ..
474        } = &ctx
475            .session()
476            .transaction()
477            .inner()
478            .expect("DDL transaction")
479            .ops
480        else {
481            unreachable!("standalone command handled above")
482        };
483        let state = state.clone();
484        let snapshot = snapshot.clone();
485        let ts = self.get_local_write_ts().await.timestamp;
486        let result = Box::pin(self.catalog().transact_incremental_dry_run(
487            &state,
488            vec![Op::RenameCommand(Arc::clone(&command))],
489            self.active_conns.get(ctx.session().conn_id()),
490            Some(snapshot),
491            ts,
492        ))
493        .await
494        .and_then(|(state, snapshot)| {
495            ctx.session_mut()
496                .transaction_mut()
497                .add_ops(TransactionOps::DDL {
498                    commands: vec![catalog::command::CatalogCommand::Rename(Arc::clone(
499                        &command,
500                    ))],
501                    state,
502                    snapshot,
503                })
504        });
505        match result {
506            Ok(()) => {
507                ctx.session()
508                    .add_notices(command.notices().iter().cloned().map(Into::into));
509                ctx.retire(Ok(crate::ExecuteResponse::AlteredObject(
510                    command.object_type(),
511                )));
512            }
513            Err(error) => ctx.retire(Err(error)),
514        }
515    }
516
517    /// Same as [`Self::catalog_transact_with_context`] but takes a [`Session`].
518    #[instrument(name = "coord::catalog_transact")]
519    pub(crate) async fn catalog_transact(
520        &mut self,
521        session: Option<&Session>,
522        ops: Vec<catalog::Op>,
523    ) -> Result<(), AdapterError> {
524        if session.is_some_and(|session| session.transaction().is_ddl()) {
525            return Err(AdapterError::Unsupported(
526                "raw operations in a DDL command transaction",
527            ));
528        }
529        let start = Instant::now();
530        let result = self
531            .catalog_transact_with_context(session.map(|session| session.conn_id()), None, ops)
532            .await;
533        self.metrics
534            .catalog_transact_seconds
535            .with_label_values(&["catalog_transact"])
536            .observe(start.elapsed().as_secs_f64());
537        result
538    }
539
540    /// Same as [`Self::catalog_transact_with_context`] but takes a [`Session`]
541    /// and runs builtin table updates concurrently with any side effects (e.g.
542    /// creating collections).
543    // TODO(aljoscha): Remove this method once all call-sites have been migrated
544    // to the newer catalog_transact_with_context. The latter is what allows us
545    // to apply catalog implications that we derive from catalog chanages either
546    // when initially applying the ops to the catalog _or_ when following
547    // catalog changes from another process.
548    #[instrument(name = "coord::catalog_transact_with_side_effects")]
549    pub(crate) async fn catalog_transact_with_side_effects<F>(
550        &mut self,
551        mut ctx: Option<&mut ExecuteContext>,
552        ops: Vec<catalog::Op>,
553        side_effect: F,
554    ) -> Result<(), AdapterError>
555    where
556        F: for<'a> FnOnce(
557                &'a mut Coordinator,
558                Option<&'a mut ExecuteContext>,
559            ) -> Pin<Box<dyn Future<Output = ()> + 'a>>
560            + 'static,
561    {
562        if ctx
563            .as_ref()
564            .is_some_and(|ctx| ctx.session().transaction().is_ddl())
565        {
566            return Err(AdapterError::Unsupported(
567                "raw operations in a DDL command transaction",
568            ));
569        }
570        let start = Instant::now();
571
572        // Keep catalog work out of the inline state of callers such as ordinary
573        // transaction completion and the coordinator's command dispatcher.
574        let (table_updates, catalog_updates) = Box::pin(
575            self.catalog_transact_inner(ctx.as_ref().map(|ctx| ctx.session().conn_id()), ops),
576        )
577        .await?;
578
579        // We can't run this concurrently with the explicit side effects,
580        // because both want to borrow self mutably.
581        let apply_implications_res =
582            Box::pin(self.apply_catalog_implications(ctx.as_deref_mut(), catalog_updates)).await;
583
584        // We would get into an inconsistent state if we updated the catalog but
585        // then failed to apply commands/updates to the controller. Easiest
586        // thing to do is panic and let restart/bootstrap handle it.
587        apply_implications_res.expect("cannot fail to apply catalog update implications");
588
589        // NOTE: `check_consistency` only runs with soft assertions enabled, so
590        // this phase reads about zero in production. We time it because a local
591        // rig debugging a transact stall commonly has them on, where the check is
592        // O(catalog size) and would otherwise appear as an unexplained remainder
593        // against the wrapper metric. The observation stays outside the macro,
594        // anything inside it compiles out exactly where soft assertions are off.
595        let consistency_start = Instant::now();
596
597        // Note: It's important that we keep the function call inside macro, this way we only run
598        // the consistency checks if soft assertions are enabled.
599        mz_ore::soft_assert_eq_no_log!(
600            self.check_consistency(),
601            Ok(()),
602            "coordinator inconsistency detected"
603        );
604
605        self.metrics
606            .catalog_transact_phase_seconds
607            .with_label_values(&["consistency_check"])
608            .observe(consistency_start.elapsed().as_secs_f64());
609
610        let side_effects_seconds = self
611            .metrics
612            .catalog_transact_phase_seconds
613            .with_label_values(&["side_effects"]);
614        // Distinct from `table_updates_wait` in `catalog_transact_with_context`.
615        // Here the group commit has already been running concurrently with
616        // `apply_catalog_implications` above, so this wrapper is first polled
617        // late and only records the residual wait.
618        let table_updates_wait = self
619            .metrics
620            .catalog_transact_phase_seconds
621            .with_label_values(&["table_updates_residual_wait"]);
622        let side_effects_fut = side_effect(self, ctx);
623
624        // Run our side effects concurrently with the table updates.
625        let ((), ()) = futures::future::join(
626            side_effects_fut
627                .wall_time()
628                .observe(side_effects_seconds)
629                .instrument(info_span!(
630                    "coord::catalog_transact_with_side_effects::side_effects_fut"
631                )),
632            table_updates
633                .wall_time()
634                .observe(table_updates_wait)
635                .instrument(info_span!(
636                    "coord::catalog_transact_with_side_effects::table_updates"
637                )),
638        )
639        .await;
640
641        self.metrics
642            .catalog_transact_seconds
643            .with_label_values(&["catalog_transact_with_side_effects"])
644            .observe(start.elapsed().as_secs_f64());
645
646        Ok(())
647    }
648
649    /// Same as [`Self::catalog_transact_inner`] but takes an execution context
650    /// or connection ID and runs builtin table updates concurrently with any
651    /// catalog implications that are generated as part of applying the given
652    /// `ops` (e.g. creating collections).
653    ///
654    /// This will use a connection ID if provided and otherwise fall back to
655    /// getting a connection ID from the execution context.
656    #[instrument(name = "coord::catalog_transact_with_context")]
657    pub(crate) async fn catalog_transact_with_context(
658        &mut self,
659        conn_id: Option<&ConnectionId>,
660        ctx: Option<&mut ExecuteContext>,
661        ops: Vec<catalog::Op>,
662    ) -> Result<(), AdapterError> {
663        if ctx
664            .as_ref()
665            .is_some_and(|ctx| ctx.session().transaction().is_ddl())
666        {
667            return Err(AdapterError::Unsupported(
668                "raw operations in a DDL command transaction",
669            ));
670        }
671        let start = Instant::now();
672
673        let conn_id = conn_id.or_else(|| ctx.as_ref().map(|ctx| ctx.session().conn_id()));
674
675        let (table_updates, catalog_updates) =
676            Box::pin(self.catalog_transact_inner(conn_id, ops)).await?;
677
678        self.finish_catalog_transaction(ctx, table_updates, catalog_updates)
679            .await;
680
681        self.metrics
682            .catalog_transact_seconds
683            .with_label_values(&["catalog_transact_with_context"])
684            .observe(start.elapsed().as_secs_f64());
685
686        Ok(())
687    }
688
689    pub(super) fn release_ddl_lock(&self, guard: tokio::sync::OwnedMutexGuard<()>) {
690        drop(guard);
691        if !self.serialized_ddl.is_empty() {
692            let _ = self.internal_cmd_tx.send(Message::DeferredStatementReady);
693        }
694    }
695
696    pub(super) async fn sequence_ddl_commit(&mut self, mut pending: PendingDdlCommit) {
697        // Command replay must respect the plans other DDLs hold across off-thread work.
698        // Never await this lock on the coordinator, which its owner needs to finish.
699        let guard = self
700            .active_conns
701            .get_mut(pending.conn_id())
702            .expect("connection must exist")
703            .deferred_lock
704            .take();
705        let guard = match guard {
706            Some(guard) => guard,
707            None => match self.serialized_ddl.try_lock_owned() {
708                Ok(guard) => guard,
709                Err(_) => {
710                    tracing::debug!(
711                        conn_id = %pending.conn_id(),
712                        "deferring catalog commit for DDL lock"
713                    );
714                    self.serialized_ddl.push_back(DeferredDdl::Commit(pending));
715                    return;
716                }
717            },
718        };
719        let result = loop {
720            match self
721                .catalog_transact_commands(
722                    pending.context.context_mut(),
723                    &mut pending.commands,
724                    &mut pending.responses,
725                )
726                .await
727            {
728                Ok(()) => break Ok(()),
729                Err(catalog::CommandExecutionError::Error(error)) => break Err(error),
730                Err(catalog::CommandExecutionError::Pending { index, work }) => match work {
731                    catalog::CommandWork::Allocate(keys) => {
732                        let ids = match self.allocate_user_ids(u64::cast_from(keys.len())).await {
733                            Ok(ids) => ids,
734                            Err(error) => break Err(error),
735                        };
736                        match &mut pending.commands[index] {
737                            catalog::command::CatalogCommand::Source(command) => {
738                                Arc::make_mut(command).record_ids(keys, ids);
739                            }
740                            catalog::command::CatalogCommand::Rename(_)
741                            | catalog::command::CatalogCommand::CatalogResult(_)
742                            | catalog::command::CatalogCommand::Description(_)
743                            | catalog::command::CatalogCommand::AlterConnection(_)
744                            | catalog::command::CatalogCommand::CreateConnection(_) => {
745                                unreachable!("this command does not allocate IDs");
746                            }
747                        }
748                    }
749                    catalog::CommandWork::ConnectionSecret(request) => {
750                        self.release_ddl_lock(guard);
751                        let controller = Arc::clone(&self.secrets_controller);
752                        let secrets = self.caching_secrets_reader.clone();
753                        let tx = self.internal_cmd_tx.clone();
754                        let otel_ctx = OpenTelemetryContext::obtain();
755                        task::spawn(|| "ddl_connection_secret", async move {
756                            let response = request.execute(controller.as_ref(), &secrets).await;
757                            pending.responses.insert(
758                                index, catalog::CommandResponse::ConnectionSecret(response),
759                            );
760                            if let Err(error) =
761                                tx.send(Message::DdlCommandsReady { pending, otel_ctx })
762                            {
763                                warn!("internal_cmd_rx dropped before connection secret completed: {error:?}");
764                            }
765                        }.instrument(tracing::Span::current()));
766                        return;
767                    }
768                    catalog::CommandWork::Connection(request) => {
769                        self.release_ddl_lock(guard);
770                        let conn_id = pending.context.context_mut().session().conn_id().clone();
771                        let (kind, failpoint) = match &pending.commands[index] {
772                            catalog::command::CatalogCommand::CreateConnection(_) => {
773                                ("create_connection", "catalog_create_connection_ready")
774                            }
775                            catalog::command::CatalogCommand::AlterConnection(_) => {
776                                ("alter_connection", "catalog_alter_connection_ready")
777                            }
778                            _ => unreachable!(
779                                "connection preparation belongs to a connection command"
780                            ),
781                        };
782                        let config = self.controller.storage.config().clone();
783                        let secrets = self.caching_secrets_reader.clone();
784                        let tx = self.internal_cmd_tx.clone();
785                        let otel_ctx = OpenTelemetryContext::obtain();
786                        task::spawn(|| "ddl_connection_preparation", async move {
787                            let response = request.execute(&config, &secrets).await;
788                            tracing::debug!(
789                                target: "mz_adapter::catalog_preparation",
790                                %conn_id, kind, "catalog preparation complete"
791                            );
792                            catalog_preparation_test_pause(failpoint).await;
793                            pending.responses.insert(
794                                index, catalog::CommandResponse::Connection(response),
795                            );
796                            if let Err(error) =
797                                tx.send(Message::DdlCommandsReady { pending, otel_ctx })
798                            {
799                                warn!("internal_cmd_rx dropped before connection preparation completed: {error:?}");
800                            }
801                        }.instrument(tracing::Span::current()));
802                        return;
803                    }
804                    catalog::CommandWork::Prepare(request) => {
805                        self.release_ddl_lock(guard);
806                        let conn_id = pending.context.context_mut().session().conn_id().clone();
807                        let config = self.controller.storage.config().clone();
808                        let tx = self.internal_cmd_tx.clone();
809                        let otel_ctx = OpenTelemetryContext::obtain();
810                        task::spawn(|| "ddl_command_preparation", async move {
811                            let response = request.execute(&config).await;
812                            tracing::debug!(
813                                target: "mz_adapter::catalog_preparation",
814                                %conn_id, kind = "purification", "catalog preparation complete"
815                            );
816                            catalog_preparation_test_pause("catalog_purification_ready").await;
817                            pending.responses.insert(
818                                index, catalog::CommandResponse::Source(response),
819                            );
820                            if let Err(error) =
821                                tx.send(Message::DdlCommandsReady { pending, otel_ctx })
822                            {
823                                warn!(
824                                    "internal_cmd_rx dropped before DDL preparation completed: {error:?}"
825                                );
826                            }
827                        }.instrument(tracing::Span::current()));
828                        return;
829                    }
830                },
831            }
832        };
833        self.release_ddl_lock(guard);
834        self.finish_ddl_commit(pending, result);
835    }
836
837    pub(super) fn finish_ddl_commit(
838        &self,
839        mut pending: PendingDdlCommit,
840        result: Result<(), AdapterError>,
841    ) {
842        let cleanup_ids: Vec<_> = pending
843            .commands
844            .iter()
845            .filter_map(|command| {
846                let catalog::command::CatalogCommand::CreateConnection(command) = command else {
847                    return None;
848                };
849                command
850                    .cleanup_secret_id()
851                    .filter(|id| self.catalog().state().try_get_entry(id).is_none())
852            })
853            .collect();
854        if result.is_ok() && matches!(pending.context, DdlCommitContext::Statement { .. }) {
855            for command in &pending.commands {
856                self.emit_command_notices(pending.context.context_mut().session(), command);
857            }
858        }
859        if cleanup_ids.is_empty() {
860            pending.context.finish(result);
861        } else {
862            let controller = Arc::clone(&self.secrets_controller);
863            let secrets = self.caching_secrets_reader.clone();
864            task::spawn(
865                || "ddl_connection_cleanup",
866                async move {
867                    for id in cleanup_ids {
868                        match controller.delete(id).await {
869                            Ok(()) => {
870                                secrets.invalidate(id);
871                            }
872                            Err(error) => {
873                                warn!("failed to clean up uncommitted connection secret: {error}")
874                            }
875                        }
876                    }
877                    pending.context.finish(result);
878                }
879                .instrument(tracing::Span::current()),
880            );
881        }
882    }
883
884    pub(crate) async fn catalog_transact_commands(
885        &mut self,
886        ctx: &mut ExecuteContext,
887        commands: &mut [catalog::command::CatalogCommand],
888        responses: &mut BTreeMap<usize, catalog::CommandResponse>,
889    ) -> Result<(), catalog::CommandExecutionError> {
890        if self.controller.read_only() {
891            return Err(AdapterError::ReadOnly.into());
892        }
893        let start = Instant::now();
894        let phase_seconds = self.metrics.catalog_transact_phase_seconds.clone();
895        let oracle_write_ts = self
896            .get_catalog_write_ts()
897            .wall_time()
898            .observe(phase_seconds.with_label_values(&["write_ts"]))
899            .await;
900        let conn_id = ctx.session().conn_id();
901        let Coordinator {
902            catalog,
903            active_conns,
904            controller,
905            ..
906        } = self;
907        let conn = active_conns.get(conn_id).expect("connection must exist");
908        let TransactionResult {
909            builtin_table_updates,
910            catalog_updates,
911            audit_events,
912        } = Box::pin(Arc::make_mut(catalog).transact_commands(
913            Some(&mut controller.storage_collections),
914            oracle_write_ts,
915            Some(conn),
916            commands,
917            responses,
918        ))
919        .wall_time()
920        .observe(phase_seconds.with_label_values(&["transact"]))
921        .await?;
922
923        self.track_catalog_audit_events(Some(conn_id), audit_events);
924        let stage_start = Instant::now();
925        let table_updates = self.builtin_table_update().execute(builtin_table_updates);
926        phase_seconds
927            .with_label_values(&["stage_builtin"])
928            .observe(stage_start.elapsed().as_secs_f64());
929        self.finish_catalog_transaction(Some(ctx), table_updates, catalog_updates)
930            .await;
931        self.metrics
932            .catalog_transact_seconds
933            .with_label_values(&["catalog_transact_with_context"])
934            .observe(start.elapsed().as_secs_f64());
935        Ok(())
936    }
937
938    async fn finish_catalog_transaction(
939        &mut self,
940        ctx: Option<&mut ExecuteContext>,
941        table_updates: BuiltinTableAppendNotify,
942        catalog_updates: Vec<ParsedStateUpdate>,
943    ) {
944        let table_updates_wait = self
945            .metrics
946            .catalog_transact_phase_seconds
947            .with_label_values(&["table_updates_wait"]);
948        let apply_catalog_implications_fut =
949            Box::pin(self.apply_catalog_implications(ctx, catalog_updates));
950
951        // Apply catalog implications concurrently with the table updates.
952        let (combined_apply_res, ()) = futures::future::join(
953            apply_catalog_implications_fut.instrument(info_span!(
954                "coord::catalog_transact_with_context::side_effects_fut"
955            )),
956            table_updates
957                .wall_time()
958                .observe(table_updates_wait)
959                .instrument(info_span!(
960                    "coord::catalog_transact_with_context::table_updates"
961                )),
962        )
963        .await;
964
965        // We would get into an inconsistent state if we updated the catalog but
966        // then failed to apply implications. Easiest thing to do is panic and
967        // let restart/bootstrap handle it.
968        combined_apply_res.expect("cannot fail to apply catalog implications");
969
970        // See the note in `catalog_transact_with_side_effects` on why this is
971        // timed outside the macro and reads about zero in production.
972        let consistency_start = Instant::now();
973
974        // Note: It's important that we keep the function call inside macro, this way we only run
975        // the consistency checks if soft assertions are enabled.
976        mz_ore::soft_assert_eq_no_log!(
977            self.check_consistency(),
978            Ok(()),
979            "coordinator inconsistency detected"
980        );
981
982        self.metrics
983            .catalog_transact_phase_seconds
984            .with_label_values(&["consistency_check"])
985            .observe(consistency_start.elapsed().as_secs_f64());
986    }
987
988    /// Perform a catalog transaction. [`Coordinator::ship_dataflow`] must be
989    /// called after this function successfully returns on any built
990    /// [`MirDataflowDescription`](mz_compute_types::dataflows::MirDataflowDescription).
991    #[instrument(name = "coord::catalog_transact_inner")]
992    pub(crate) async fn catalog_transact_inner(
993        &mut self,
994        conn_id: Option<&ConnectionId>,
995        mut ops: Vec<catalog::Op>,
996    ) -> Result<(BuiltinTableAppendNotify, Vec<ParsedStateUpdate>), AdapterError> {
997        if self.controller.read_only() {
998            return Err(AdapterError::ReadOnly);
999        }
1000
1001        if let Some(scoped_op) = self.scoped_overrides_create_op(&ops) {
1002            ops.push(scoped_op);
1003        }
1004
1005        event!(Level::TRACE, ops = format!("{:?}", ops));
1006
1007        let phase_seconds = self.metrics.catalog_transact_phase_seconds.clone();
1008        let phase_start = Instant::now();
1009
1010        let mut clusters_to_drop = vec![];
1011        let mut cluster_replicas_to_drop = vec![];
1012        let mut clusters_to_create = vec![];
1013        let mut cluster_replicas_to_create = vec![];
1014        let mut update_metrics_config = false;
1015        let mut update_tracing_config = false;
1016        let mut update_controller_config = false;
1017        let mut update_compute_config = false;
1018        let mut update_storage_config = false;
1019        let mut update_timestamp_oracle_config = false;
1020        let mut update_metrics_retention = false;
1021        let mut update_secrets_caching_config = false;
1022        let mut update_cluster_scheduling_config = false;
1023        let mut update_http_config = false;
1024        let mut update_advance_timelines_interval = false;
1025        let mut update_optimizer_e2e_latency_warning_threshold = false;
1026        let mut reconcile_metric_sinks = false;
1027
1028        for op in &ops {
1029            match op {
1030                catalog::Op::DropObjects {
1031                    objects: drop_object_infos,
1032                    ..
1033                } => {
1034                    for drop_object_info in drop_object_infos {
1035                        match &drop_object_info {
1036                            catalog::DropObjectInfo::Item(_) => {
1037                                // Nothing to do, these will be handled by
1038                                // applying the side effects that we return.
1039                            }
1040                            catalog::DropObjectInfo::Cluster(id) => {
1041                                clusters_to_drop.push(*id);
1042                            }
1043                            catalog::DropObjectInfo::ClusterReplica((
1044                                cluster_id,
1045                                replica_id,
1046                                _reason,
1047                            )) => {
1048                                // Drop the cluster replica itself.
1049                                cluster_replicas_to_drop.push((*cluster_id, *replica_id));
1050                            }
1051                            _ => (),
1052                        }
1053                    }
1054                }
1055                catalog::Op::ResetSystemConfiguration { name }
1056                | catalog::Op::UpdateSystemConfiguration { name, .. } => {
1057                    update_metrics_config |= self
1058                        .catalog
1059                        .state()
1060                        .system_config()
1061                        .is_metrics_config_var(name);
1062                    update_tracing_config |= vars::is_tracing_var(name);
1063                    update_controller_config |= self
1064                        .catalog
1065                        .state()
1066                        .system_config()
1067                        .is_controller_config_var(name);
1068                    update_compute_config |= self
1069                        .catalog
1070                        .state()
1071                        .system_config()
1072                        .is_compute_config_var(name);
1073                    update_storage_config |= self
1074                        .catalog
1075                        .state()
1076                        .system_config()
1077                        .is_storage_config_var(name);
1078                    update_timestamp_oracle_config |= vars::is_timestamp_oracle_config_var(name);
1079                    update_metrics_retention |= name == vars::METRICS_RETENTION.name();
1080                    update_secrets_caching_config |= vars::is_secrets_caching_var(name);
1081                    update_cluster_scheduling_config |= vars::is_cluster_scheduling_var(name);
1082                    update_http_config |= vars::is_http_config_var(name);
1083                    update_advance_timelines_interval |= name == DEFAULT_TIMESTAMP_INTERVAL.name();
1084                    update_optimizer_e2e_latency_warning_threshold |=
1085                        name == vars::OPTIMIZER_E2E_LATENCY_WARNING_THRESHOLD.name();
1086                    reconcile_metric_sinks |= name == vars::DISABLED_METRIC_SINKS.name();
1087                }
1088                catalog::Op::ResetAllSystemConfiguration => {
1089                    // Assume they all need to be updated.
1090                    // We could see if the config's have actually changed, but
1091                    // this is simpler.
1092                    update_tracing_config = true;
1093                    update_controller_config = true;
1094                    update_compute_config = true;
1095                    update_storage_config = true;
1096                    update_timestamp_oracle_config = true;
1097                    update_metrics_retention = true;
1098                    update_secrets_caching_config = true;
1099                    update_cluster_scheduling_config = true;
1100                    update_metrics_config = true;
1101                    update_http_config = true;
1102                    update_advance_timelines_interval = true;
1103                    update_optimizer_e2e_latency_warning_threshold = true;
1104                    reconcile_metric_sinks = true;
1105                }
1106                catalog::Op::CreateCluster { id, .. } => {
1107                    clusters_to_create.push(*id);
1108                }
1109                catalog::Op::CreateClusterReplica {
1110                    cluster_id,
1111                    name,
1112                    config,
1113                    ..
1114                } => {
1115                    cluster_replicas_to_create.push((
1116                        *cluster_id,
1117                        name.clone(),
1118                        config.location.num_processes(),
1119                    ));
1120                }
1121                _ => (),
1122            }
1123        }
1124
1125        // Observe before propagating, so a transaction rejected on resource
1126        // limits still accounts for the op scan it burned on the loop.
1127        let validate_res = self
1128            .catalog()
1129            .state()
1130            .validate_resource_limits(&ops, conn_id.unwrap_or(&SYSTEM_CONN_ID));
1131        phase_seconds
1132            .with_label_values(&["prep"])
1133            .observe(phase_start.elapsed().as_secs_f64());
1134        validate_res?;
1135
1136        // This will produce timestamps that are guaranteed to increase on each
1137        // call, and also never be behind the system clock. If the system clock
1138        // hasn't advanced (or has gone backward), it will increment by 1. For
1139        // the audit log, we need to balance "close (within 10s or so) to the
1140        // system clock" and "always goes up". We've chosen here to prioritize
1141        // always going up, and believe we will always be close to the system
1142        // clock because it is well configured (chrony) and so may only rarely
1143        // regress or pause for 10s.
1144        let oracle_write_ts = self
1145            .get_catalog_write_ts()
1146            .wall_time()
1147            .observe(phase_seconds.with_label_values(&["write_ts"]))
1148            .await;
1149
1150        let Coordinator {
1151            catalog,
1152            active_conns,
1153            controller,
1154            cluster_replica_statuses,
1155            ..
1156        } = self;
1157        let catalog = Arc::make_mut(catalog);
1158        let conn = conn_id.map(|id| active_conns.get(id).expect("connection must exist"));
1159
1160        // Register the session as an ephemeral owner (its uuid <-> connection
1161        // mapping) at its first temporary-item creation.
1162        if let Some(conn) = conn {
1163            let creates_temp_item = ops.iter().any(
1164                |op| matches!(op, catalog::Op::CreateItem { item, .. } if item.is_temporary()),
1165            );
1166            if creates_temp_item && !catalog.state().has_temporary_namespace(conn.conn_id()) {
1167                catalog.register_temporary_namespace(conn.conn_id(), conn.uuid());
1168            }
1169        }
1170
1171        // NOTE: This phase contains every durable `sync` and `commit` a catalog
1172        // transaction performs, which is what makes `transact` minus those two
1173        // histograms an estimate of the in-memory work. Two caveats. More than
1174        // one sync happens per transaction, so the subtraction is only valid on
1175        // rates of `_sum`, never on per-observation means. And durable
1176        // `allocate_id` (user ID pool refills, storage usage batch IDs) observes
1177        // into the same histograms from outside any catalog transaction, so the
1178        // estimate is biased low while allocation is active.
1179        let TransactionResult {
1180            builtin_table_updates,
1181            catalog_updates,
1182            audit_events,
1183        } = catalog
1184            .transact(
1185                Some(&mut controller.storage_collections),
1186                oracle_write_ts,
1187                conn,
1188                ops,
1189            )
1190            .wall_time()
1191            .observe(phase_seconds.with_label_values(&["transact"]))
1192            .await?;
1193
1194        for (cluster_id, replica_id) in &cluster_replicas_to_drop {
1195            cluster_replica_statuses.remove_cluster_replica_statuses(cluster_id, replica_id);
1196        }
1197        for cluster_id in &clusters_to_drop {
1198            cluster_replica_statuses.remove_cluster_statuses(cluster_id);
1199        }
1200        for cluster_id in clusters_to_create {
1201            cluster_replica_statuses.initialize_cluster_statuses(cluster_id);
1202        }
1203        let now = to_datetime((catalog.config().now)());
1204        for (cluster_id, replica_name, num_processes) in cluster_replicas_to_create {
1205            let replica_id = catalog
1206                .resolve_replica_in_cluster(&cluster_id, &replica_name)
1207                .expect("just created")
1208                .replica_id();
1209            cluster_replica_statuses.initialize_cluster_replica_statuses(
1210                cluster_id,
1211                replica_id,
1212                num_processes,
1213                now,
1214            );
1215        }
1216
1217        // Append our builtin table updates, then return the notify so we can run other tasks in
1218        // parallel.
1219        let stage_start = Instant::now();
1220        let builtin_update_notify = self.builtin_table_update().execute(builtin_table_updates);
1221        phase_seconds
1222            .with_label_values(&["stage_builtin"])
1223            .observe(stage_start.elapsed().as_secs_f64());
1224
1225        let finalize_start = Instant::now();
1226
1227        // No error returns are allowed after this point. Enforce this at compile time
1228        // by using this odd structure so we don't accidentally add a stray `?`.
1229        let _: () = async {
1230            if update_metrics_config {
1231                mz_metrics::update_dyncfg(&self.catalog().system_config().dyncfg_updates());
1232            }
1233            if update_controller_config {
1234                self.update_controller_config();
1235            }
1236            if update_compute_config {
1237                self.update_compute_config();
1238            }
1239            if update_storage_config {
1240                self.update_storage_config();
1241            }
1242            if update_timestamp_oracle_config {
1243                self.update_timestamp_oracle_config();
1244            }
1245            if update_metrics_retention {
1246                self.update_metrics_retention();
1247            }
1248            if update_tracing_config {
1249                self.update_tracing_config();
1250            }
1251            if update_secrets_caching_config {
1252                self.update_secrets_caching_config();
1253            }
1254            if update_cluster_scheduling_config {
1255                self.update_cluster_scheduling_config();
1256            }
1257            if update_http_config {
1258                self.update_http_config();
1259            }
1260            if update_advance_timelines_interval {
1261                let new_interval = self.catalog().system_config().default_timestamp_interval();
1262                if new_interval != self.advance_timelines_interval.period() {
1263                    self.advance_timelines_interval = tokio::time::interval(new_interval);
1264                }
1265            }
1266            if update_optimizer_e2e_latency_warning_threshold {
1267                let threshold = self
1268                    .catalog()
1269                    .system_config()
1270                    .optimizer_e2e_latency_warning_threshold();
1271                self.optimizer_metrics
1272                    .set_e2e_optimization_time_log_threshold(threshold);
1273            }
1274            if reconcile_metric_sinks {
1275                self.reconcile_metric_sinks().await;
1276            }
1277        }
1278        .instrument(info_span!("coord::catalog_transact_with::finalize"))
1279        .await;
1280
1281        self.track_catalog_audit_events(conn_id, audit_events);
1282
1283        phase_seconds
1284            .with_label_values(&["finalize"])
1285            .observe(finalize_start.elapsed().as_secs_f64());
1286
1287        Ok((builtin_update_notify, catalog_updates))
1288    }
1289
1290    fn track_catalog_audit_events(
1291        &self,
1292        conn_id: Option<&ConnectionId>,
1293        audit_events: Vec<VersionedEvent>,
1294    ) {
1295        let conn = conn_id.and_then(|id| self.active_conns.get(id));
1296        if let Some(segment_client) = &self.segment_client {
1297            for VersionedEvent::V1(event) in audit_events {
1298                let event_type = format!(
1299                    "{} {}",
1300                    event.object_type.as_title_case(),
1301                    event.event_type.as_title_case()
1302                );
1303                segment_client.environment_track(
1304                    &self.catalog().config().environment_id,
1305                    event_type,
1306                    json!({ "details": event.details.as_json() }),
1307                    EventDetails {
1308                        user_id: conn
1309                            .and_then(|c| c.user().external_metadata.as_ref())
1310                            .map(|m| m.user_id),
1311                        application_name: conn.map(|c| c.application_name()),
1312                        ..Default::default()
1313                    },
1314                );
1315            }
1316        }
1317    }
1318
1319    pub(crate) fn drop_replica(&mut self, cluster_id: ClusterId, replica_id: ReplicaId) {
1320        self.drop_introspection_subscribes(replica_id);
1321        self.drop_metric_sinks(replica_id);
1322
1323        self.controller
1324            .drop_replica(cluster_id, replica_id)
1325            .expect("dropping replica must not fail");
1326    }
1327
1328    /// A convenience method for dropping sources.
1329    pub(crate) fn drop_sources(&mut self, sources: Vec<(CatalogItemId, GlobalId)>) {
1330        for (item_id, _gid) in &sources {
1331            self.active_webhooks.remove(item_id);
1332        }
1333        let storage_metadata = self.catalog.state().storage_metadata();
1334        let source_gids = sources.into_iter().map(|(_id, gid)| gid).collect();
1335        self.controller
1336            .storage
1337            .drop_sources(storage_metadata, source_gids)
1338            .unwrap_or_terminate("cannot fail to drop sources");
1339    }
1340
1341    /// A convenience method for dropping tables.
1342    pub(crate) async fn drop_tables(&mut self, tables: Vec<(CatalogItemId, GlobalId)>) {
1343        for (item_id, _gid) in &tables {
1344            self.active_webhooks.remove(item_id);
1345        }
1346
1347        let table_gids: Vec<_> = tables.into_iter().map(|(_id, gid)| gid).collect();
1348
1349        // FIFO ordering places the forget after every staged append.
1350        let forget_ids = self
1351            .controller
1352            .storage
1353            .txns_table_ids(table_gids.clone())
1354            .unwrap_or_terminate("cannot fail to look up txns-registered tables");
1355        if !forget_ids.is_empty() {
1356            self.forget_tables_via_committer(forget_ids).await;
1357        }
1358
1359        let storage_metadata = self.catalog.state().storage_metadata();
1360        self.controller
1361            .storage
1362            .drop_tables(storage_metadata, table_gids)
1363            .unwrap_or_terminate("cannot fail to drop tables");
1364    }
1365
1366    /// Like `drop_compute_sinks`, but for a single compute sink.
1367    ///
1368    /// Returns the controller's state for the compute sink if the identified
1369    /// sink was known to the controller. It is the caller's responsibility to
1370    /// retire the returned sink. Consider using `retire_compute_sinks` instead.
1371    #[must_use]
1372    pub async fn drop_compute_sink(
1373        &mut self,
1374        sink_id: GlobalId,
1375    ) -> Option<(ActiveComputeSink, BuiltinTableAppendNotify)> {
1376        self.drop_compute_sinks([sink_id]).await.remove(&sink_id)
1377    }
1378
1379    /// Drops a batch of compute sinks.
1380    ///
1381    /// For each sink that exists, the coordinator and controller's state
1382    /// associated with the sink is removed.
1383    ///
1384    /// Returns a map from sink id to the controller's state for the sink and a notify that
1385    /// resolves once the sink's `mz_subscriptions` retraction is durable (see
1386    /// `remove_active_compute_sink`). It is the caller's responsibility to await the notify
1387    /// off the coordinator loop and then retire the returned sinks. Consider using
1388    /// `retire_compute_sinks` instead.
1389    #[must_use]
1390    pub async fn drop_compute_sinks(
1391        &mut self,
1392        sink_ids: impl IntoIterator<Item = GlobalId>,
1393    ) -> BTreeMap<GlobalId, (ActiveComputeSink, BuiltinTableAppendNotify)> {
1394        let mut by_id = BTreeMap::new();
1395        let mut by_cluster: BTreeMap<_, Vec<_>> = BTreeMap::new();
1396        for sink_id in sink_ids {
1397            let (sink, write_notify) = match self.remove_active_compute_sink(sink_id).await {
1398                None => {
1399                    // This can happen due to a race condition: an internal
1400                    // subscribe may be cleaned up via its own message while
1401                    // session disconnect cleanup is in progress. This is
1402                    // benign.
1403                    tracing::debug!(%sink_id, "drop_compute_sinks: sink already removed");
1404                    continue;
1405                }
1406                Some(entry) => entry,
1407            };
1408
1409            by_cluster
1410                .entry(sink.cluster_id())
1411                .or_default()
1412                .push(sink_id);
1413            by_id.insert(sink_id, (sink, write_notify));
1414        }
1415        for (cluster_id, ids) in by_cluster {
1416            let compute = &mut self.controller.compute;
1417            // A cluster could have been dropped, so verify it exists.
1418            if compute.instance_exists(cluster_id) {
1419                compute
1420                    .drop_collections(cluster_id, ids)
1421                    .unwrap_or_terminate("cannot fail to drop collections");
1422            }
1423        }
1424        by_id
1425    }
1426
1427    /// Retires a batch of sinks with disparate reasons for retirement.
1428    ///
1429    /// Each sink identified in `reasons` is dropped (see `drop_compute_sinks`),
1430    /// then retired with its corresponding reason. Returns a notify that resolves
1431    /// once all `mz_subscriptions` retractions are durable and the sinks are retired.
1432    pub async fn retire_compute_sinks(
1433        &mut self,
1434        mut reasons: BTreeMap<GlobalId, ActiveComputeSinkRetireReason>,
1435    ) -> BuiltinTableAppendCompletion {
1436        let sink_ids = reasons.keys().cloned();
1437        let to_retire: Vec<_> = self
1438            .drop_compute_sinks(sink_ids)
1439            .await
1440            .into_iter()
1441            .map(|(id, (sink, write_notify))| {
1442                let reason = reasons
1443                    .remove(&id)
1444                    .expect("all returned IDs are in `reasons`");
1445                (sink, write_notify, reason)
1446            })
1447            .collect();
1448
1449        if to_retire.is_empty() {
1450            return BuiltinTableAppendCompletion::completed();
1451        }
1452
1453        // Retire off the coordinator loop. We wait for each `mz_subscriptions` retraction
1454        // before telling the subscribing client that the sink is gone. The returned notify
1455        // lets statements that caused the retirement also wait before sending their response.
1456        // The wait must not happen on the coordinator loop, since that would block every
1457        // other session on the group-commit oracle round trip.
1458        let (done_tx, done_rx) = tokio::sync::oneshot::channel();
1459        task::spawn(|| "retire_compute_sinks", async move {
1460            for (sink, write_notify, reason) in to_retire {
1461                write_notify.await;
1462                sink.retire(reason);
1463            }
1464            let _ = done_tx.send(());
1465        });
1466        BuiltinTableAppendCompletion::new(Box::pin(async move {
1467            let _ = done_rx.await;
1468        }))
1469    }
1470
1471    /// Cancels all active compute sinks for the identified connection.
1472    #[mz_ore::instrument(level = "debug")]
1473    pub(crate) async fn cancel_compute_sinks_for_conn(
1474        &mut self,
1475        conn_id: &ConnectionId,
1476    ) -> BuiltinTableAppendCompletion {
1477        self.retire_compute_sinks_for_conn(conn_id, ActiveComputeSinkRetireReason::Canceled)
1478            .await
1479    }
1480
1481    /// Retires all active compute sinks for the identified connection with the
1482    /// specified reason.
1483    #[mz_ore::instrument(level = "debug")]
1484    pub(crate) async fn retire_compute_sinks_for_conn(
1485        &mut self,
1486        conn_id: &ConnectionId,
1487        reason: ActiveComputeSinkRetireReason,
1488    ) -> BuiltinTableAppendCompletion {
1489        let drop_sinks = self
1490            .active_conns
1491            .get_mut(conn_id)
1492            .expect("must exist for active session")
1493            .drop_sinks
1494            .iter()
1495            .map(|sink_id| (*sink_id, reason.clone()))
1496            .collect();
1497        self.retire_compute_sinks(drop_sinks).await
1498    }
1499
1500    pub(crate) fn drop_storage_sinks(&mut self, sink_gids: Vec<GlobalId>) {
1501        let storage_metadata = self.catalog.state().storage_metadata();
1502        self.controller
1503            .storage
1504            .drop_sinks(storage_metadata, sink_gids)
1505            .unwrap_or_terminate("cannot fail to drop sinks");
1506    }
1507
1508    pub(crate) fn drop_compute_collections(&mut self, collections: Vec<(ClusterId, GlobalId)>) {
1509        let mut by_cluster: BTreeMap<_, Vec<_>> = BTreeMap::new();
1510        for (cluster_id, gid) in collections {
1511            by_cluster.entry(cluster_id).or_default().push(gid);
1512        }
1513        for (cluster_id, gids) in by_cluster {
1514            let compute = &mut self.controller.compute;
1515            // A cluster could have been dropped, so verify it exists.
1516            if compute.instance_exists(cluster_id) {
1517                compute
1518                    .drop_collections(cluster_id, gids)
1519                    .unwrap_or_terminate("cannot fail to drop collections");
1520            }
1521        }
1522    }
1523
1524    pub(crate) fn drop_vpc_endpoints_in_background(&self, vpc_endpoints: Vec<CatalogItemId>) {
1525        // Match the create path (catalog_implications.rs) which gracefully
1526        // logs an error when cloud_resource_controller is None, rather than
1527        // panicking.
1528        let Some(cloud_resource_controller) = self.cloud_resource_controller.as_ref() else {
1529            warn!("dropping VPC endpoints without cloud_resource_controller; skipping cleanup");
1530            return;
1531        };
1532        let cloud_resource_controller = Arc::clone(cloud_resource_controller);
1533        // We don't want to block the coordinator on an external delete api
1534        // calls, so move the drop vpc_endpoint to a separate task. This does
1535        // mean that a failed drop won't bubble up to the user as an error
1536        // message. However, even if it did (and how the code previously
1537        // worked), mz has already dropped it from our catalog, and so we
1538        // wouldn't be able to retry anyway. Any orphaned vpc_endpoints will
1539        // eventually be cleaned during restart via coord bootstrap.
1540        task::spawn(
1541            || "drop_vpc_endpoints",
1542            async move {
1543                for vpc_endpoint in vpc_endpoints {
1544                    let _ = Retry::default()
1545                        .max_duration(Duration::from_secs(60))
1546                        .retry_async(|_state| async {
1547                            fail_point!("drop_vpc_endpoint", |r| {
1548                                Err(anyhow::anyhow!("Fail point error {:?}", r))
1549                            });
1550                            match cloud_resource_controller
1551                                .delete_vpc_endpoint(vpc_endpoint)
1552                                .await
1553                            {
1554                                Ok(_) => Ok(()),
1555                                Err(e) => {
1556                                    warn!("Dropping VPC Endpoints has encountered an error: {}", e);
1557                                    Err(e)
1558                                }
1559                            }
1560                        })
1561                        .await;
1562                }
1563            }
1564            .instrument(info_span!(
1565                "coord::catalog_transact_inner::drop_vpc_endpoints"
1566            )),
1567        );
1568    }
1569
1570    /// Removes all temporary items created by the specified connection, though
1571    /// not the temporary schema itself.
1572    pub(crate) async fn drop_temp_items(&mut self, conn_id: &ConnectionId) {
1573        let temp_items = self.catalog().state().get_temp_items(conn_id).collect();
1574        let all_items = self.catalog().object_dependents(&temp_items, conn_id);
1575
1576        if all_items.is_empty() {
1577            return;
1578        }
1579        let op = Op::DropObjects {
1580            objects: all_items
1581                .into_iter()
1582                .map(DropObjectInfo::manual_drop_from_object_id)
1583                .collect(),
1584            cascade: false,
1585        };
1586
1587        self.catalog_transact_with_context(Some(conn_id), None, vec![op])
1588            .await
1589            .expect("unable to drop temporary items for conn_id");
1590    }
1591
1592    fn update_cluster_scheduling_config(&self) {
1593        let config = flags::orchestrator_scheduling_config(self.catalog.system_config());
1594        self.controller
1595            .update_orchestrator_scheduling_config(config);
1596    }
1597
1598    fn update_secrets_caching_config(&self) {
1599        let config = flags::caching_config(self.catalog.system_config());
1600        self.caching_secrets_reader.set_policy(config);
1601    }
1602
1603    fn update_tracing_config(&self) {
1604        let tracing = flags::tracing_config(self.catalog().system_config());
1605        tracing.apply(&self.tracing_handle);
1606    }
1607
1608    fn update_compute_config(&mut self) {
1609        let config_params = flags::compute_config(self.catalog().system_config());
1610        self.controller.compute.update_configuration(config_params);
1611    }
1612
1613    fn update_storage_config(&mut self) {
1614        let config_params = flags::storage_config(self.catalog().system_config());
1615        self.controller.storage.update_parameters(config_params);
1616    }
1617
1618    fn update_timestamp_oracle_config(&self) {
1619        let config_params = flags::timestamp_oracle_config(self.catalog().system_config());
1620        if let Some(config) = self.timestamp_oracle_config.as_ref() {
1621            config.apply_parameters(config_params)
1622        }
1623    }
1624
1625    fn update_metrics_retention(&self) {
1626        let duration = self.catalog().system_config().metrics_retention();
1627        let policy = ReadPolicy::lag_writes_by(
1628            Timestamp::new(u64::try_from(duration.as_millis()).unwrap_or_else(|_e| {
1629                tracing::error!("Absurd metrics retention duration: {duration:?}.");
1630                u64::MAX
1631            })),
1632            SINCE_GRANULARITY,
1633        );
1634        let storage_policies = self
1635            .catalog()
1636            .entries()
1637            .filter(|entry| {
1638                entry.item().is_retained_metrics_object()
1639                    && entry.item().is_compute_object_on_cluster().is_none()
1640            })
1641            .map(|entry| (entry.id(), policy.clone()))
1642            .collect::<Vec<_>>();
1643        let compute_policies = self
1644            .catalog()
1645            .entries()
1646            .filter_map(|entry| {
1647                if let (true, Some(cluster_id)) = (
1648                    entry.item().is_retained_metrics_object(),
1649                    entry.item().is_compute_object_on_cluster(),
1650                ) {
1651                    Some((cluster_id, entry.id(), policy.clone()))
1652                } else {
1653                    None
1654                }
1655            })
1656            .collect::<Vec<_>>();
1657        self.update_storage_read_policies(storage_policies);
1658        self.update_compute_read_policies(compute_policies);
1659    }
1660
1661    fn update_controller_config(&mut self) {
1662        let sys_config = self.catalog().system_config();
1663        self.controller
1664            .update_configuration(sys_config.dyncfg_updates());
1665    }
1666
1667    fn update_http_config(&mut self) {
1668        let webhook_request_limit = self
1669            .catalog()
1670            .system_config()
1671            .webhook_concurrent_request_limit();
1672        self.webhook_concurrency_limit
1673            .set_limit(webhook_request_limit);
1674    }
1675
1676    pub(crate) async fn create_storage_export(
1677        &mut self,
1678        id: GlobalId,
1679        sink: &Sink,
1680    ) -> Result<(), AdapterError> {
1681        // Validate `sink.from` is in fact a storage collection
1682        self.controller.storage.check_exists(sink.from)?;
1683
1684        // The AsOf is used to determine at what time to snapshot reading from
1685        // the persist collection.  This is primarily relevant when we do _not_
1686        // want to include the snapshot in the sink.
1687        //
1688        // We choose the smallest as_of that is legal, according to the sinked
1689        // collection's since.
1690        let id_bundle = crate::CollectionIdBundle {
1691            storage_ids: btreeset! {sink.from},
1692            compute_ids: btreemap! {},
1693        };
1694
1695        // We're putting in place read holds, such that create_exports, below,
1696        // which calls update_read_capabilities, can successfully do so.
1697        // Otherwise, the since of dependencies might move along concurrently,
1698        // pulling the rug from under us!
1699        //
1700        // TODO: Maybe in the future, pass those holds on to storage, to hold on
1701        // to them and downgrade when possible?
1702        let read_holds = self.acquire_read_holds(&id_bundle);
1703        let as_of = read_holds.least_valid_read();
1704
1705        let storage_sink_from_entry = self.catalog().get_entry_by_global_id(&sink.from);
1706        let storage_sink_desc = mz_storage_types::sinks::StorageSinkDesc {
1707            from: sink.from,
1708            from_desc: storage_sink_from_entry
1709                .relation_desc()
1710                .expect("sinks can only be built on items with descs")
1711                .into_owned(),
1712            connection: sink
1713                .connection
1714                .clone()
1715                .into_inline_connection(self.catalog().state()),
1716            envelope: sink.envelope,
1717            as_of,
1718            with_snapshot: sink.with_snapshot,
1719            version: sink.version,
1720            from_storage_metadata: (),
1721            to_storage_metadata: (),
1722            commit_interval: sink.commit_interval,
1723        };
1724
1725        let collection_desc = CollectionDescription {
1726            // TODO(sinks): make generic once we have more than one sink type.
1727            desc: KAFKA_PROGRESS_DESC.clone(),
1728            data_source: DataSource::Sink {
1729                desc: ExportDescription {
1730                    sink: storage_sink_desc,
1731                    instance_id: sink.cluster_id,
1732                },
1733            },
1734            since: None,
1735            timeline: None,
1736            primary: None,
1737        };
1738        let collections = vec![(id, collection_desc)];
1739
1740        // Create the collections.
1741        let storage_metadata = self.catalog.state().storage_metadata();
1742        let res = self
1743            .controller
1744            .storage
1745            .create_collections(storage_metadata, None, collections)
1746            .await;
1747
1748        // Drop read holds after the export has been created, at which point
1749        // storage will have put in its own read holds.
1750        drop(read_holds);
1751
1752        Ok(res?)
1753    }
1754
1755    pub(crate) fn validate_resource_limit<F>(
1756        &self,
1757        current_amount: usize,
1758        new_instances: i64,
1759        resource_limit: F,
1760        resource_type: &str,
1761        limit_name: &str,
1762    ) -> Result<(), AdapterError>
1763    where
1764        F: Fn(&SystemVars) -> u32,
1765    {
1766        self.catalog().state().validate_resource_limit(
1767            current_amount,
1768            new_instances,
1769            resource_limit,
1770            resource_type,
1771            limit_name,
1772        )
1773    }
1774
1775    pub(crate) fn validate_resource_limit_numeric<F>(
1776        &self,
1777        current_amount: Numeric,
1778        new_amount: Numeric,
1779        resource_limit: F,
1780        resource_type: &str,
1781        limit_name: &str,
1782    ) -> Result<(), AdapterError>
1783    where
1784        F: Fn(&SystemVars) -> Numeric,
1785    {
1786        self.catalog().state().validate_resource_limit_numeric(
1787            current_amount,
1788            new_amount,
1789            resource_limit,
1790            resource_type,
1791            limit_name,
1792        )
1793    }
1794}