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, BTreeSet};
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::{CatalogItem, DataSourceDesc, Sink};
25use mz_cluster_client::ReplicaId;
26use mz_controller::clusters::ReplicaLocation;
27use mz_controller_types::ClusterId;
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_repr::adt::numeric::Numeric;
34use mz_repr::{CatalogItemId, GlobalId, Timestamp};
35use mz_sql::catalog::{CatalogClusterReplica, CatalogSchema};
36use mz_sql::names::ResolvedDatabaseSpecifier;
37use mz_sql::plan::ConnectionDetails;
38use mz_sql::session::metadata::SessionMetadata;
39use mz_sql::session::vars::{
40    self, DEFAULT_TIMESTAMP_INTERVAL, MAX_AWS_PRIVATELINK_CONNECTIONS, MAX_CLUSTERS,
41    MAX_CREDIT_CONSUMPTION_RATE, MAX_DATABASES, MAX_KAFKA_CONNECTIONS, MAX_MATERIALIZED_VIEWS,
42    MAX_MYSQL_CONNECTIONS, MAX_NETWORK_POLICIES, MAX_OBJECTS_PER_SCHEMA, MAX_POSTGRES_CONNECTIONS,
43    MAX_REPLICAS_PER_CLUSTER, MAX_ROLES, MAX_SCHEMAS_PER_DATABASE, MAX_SECRETS, MAX_SINKS,
44    MAX_SOURCES, MAX_SQL_SERVER_CONNECTIONS, MAX_TABLES, SystemVars, Var,
45};
46use mz_storage_client::controller::{CollectionDescription, DataSource, ExportDescription};
47use mz_storage_types::connections::inline::IntoInlineConnection;
48use mz_storage_types::read_policy::ReadPolicy;
49use mz_storage_types::sources::kafka::KAFKA_PROGRESS_DESC;
50use serde_json::json;
51use tracing::{Instrument, Level, event, info_span, warn};
52
53use crate::active_compute_sink::{ActiveComputeSink, ActiveComputeSinkRetireReason};
54use crate::catalog::{DropObjectInfo, Op, TransactionResult};
55use crate::coord::Coordinator;
56use crate::coord::appends::{BuiltinTableAppendCompletion, BuiltinTableAppendNotify};
57use crate::coord::catalog_implications::parsed_state_updates::ParsedStateUpdate;
58use crate::session::{Session, Transaction, TransactionOps};
59use crate::telemetry::{EventDetails, SegmentClientExt};
60use crate::util::ResultExt;
61use crate::{AdapterError, ExecuteContext, catalog, flags};
62
63impl Coordinator {
64    /// Same as [`Self::catalog_transact_with_context`] but takes a [`Session`].
65    #[instrument(name = "coord::catalog_transact")]
66    pub(crate) async fn catalog_transact(
67        &mut self,
68        session: Option<&Session>,
69        ops: Vec<catalog::Op>,
70    ) -> Result<(), AdapterError> {
71        let start = Instant::now();
72        let result = self
73            .catalog_transact_with_context(session.map(|session| session.conn_id()), None, ops)
74            .await;
75        self.metrics
76            .catalog_transact_seconds
77            .with_label_values(&["catalog_transact"])
78            .observe(start.elapsed().as_secs_f64());
79        result
80    }
81
82    /// Same as [`Self::catalog_transact_with_context`] but takes a [`Session`]
83    /// and runs builtin table updates concurrently with any side effects (e.g.
84    /// creating collections).
85    // TODO(aljoscha): Remove this method once all call-sites have been migrated
86    // to the newer catalog_transact_with_context. The latter is what allows us
87    // to apply catalog implications that we derive from catalog chanages either
88    // when initially applying the ops to the catalog _or_ when following
89    // catalog changes from another process.
90    #[instrument(name = "coord::catalog_transact_with_side_effects")]
91    pub(crate) async fn catalog_transact_with_side_effects<F>(
92        &mut self,
93        mut ctx: Option<&mut ExecuteContext>,
94        ops: Vec<catalog::Op>,
95        side_effect: F,
96    ) -> Result<(), AdapterError>
97    where
98        F: for<'a> FnOnce(
99                &'a mut Coordinator,
100                Option<&'a mut ExecuteContext>,
101            ) -> Pin<Box<dyn Future<Output = ()> + 'a>>
102            + 'static,
103    {
104        let start = Instant::now();
105
106        let (table_updates, catalog_updates) = self
107            .catalog_transact_inner(ctx.as_ref().map(|ctx| ctx.session().conn_id()), ops)
108            .await?;
109
110        // We can't run this concurrently with the explicit side effects,
111        // because both want to borrow self mutably.
112        let apply_implications_res = self
113            .apply_catalog_implications(ctx.as_deref_mut(), catalog_updates)
114            .await;
115
116        // We would get into an inconsistent state if we updated the catalog but
117        // then failed to apply commands/updates to the controller. Easiest
118        // thing to do is panic and let restart/bootstrap handle it.
119        apply_implications_res.expect("cannot fail to apply catalog update implications");
120
121        // NOTE: `check_consistency` only runs with soft assertions enabled, so
122        // this phase reads about zero in production. We time it because a local
123        // rig debugging a transact stall commonly has them on, where the check is
124        // O(catalog size) and would otherwise appear as an unexplained remainder
125        // against the wrapper metric. The observation stays outside the macro,
126        // anything inside it compiles out exactly where soft assertions are off.
127        let consistency_start = Instant::now();
128
129        // Note: It's important that we keep the function call inside macro, this way we only run
130        // the consistency checks if soft assertions are enabled.
131        mz_ore::soft_assert_eq_no_log!(
132            self.check_consistency(),
133            Ok(()),
134            "coordinator inconsistency detected"
135        );
136
137        self.metrics
138            .catalog_transact_phase_seconds
139            .with_label_values(&["consistency_check"])
140            .observe(consistency_start.elapsed().as_secs_f64());
141
142        let side_effects_seconds = self
143            .metrics
144            .catalog_transact_phase_seconds
145            .with_label_values(&["side_effects"]);
146        // Distinct from `table_updates_wait` in `catalog_transact_with_context`.
147        // Here the group commit has already been running concurrently with
148        // `apply_catalog_implications` above, so this wrapper is first polled
149        // late and only records the residual wait.
150        let table_updates_wait = self
151            .metrics
152            .catalog_transact_phase_seconds
153            .with_label_values(&["table_updates_residual_wait"]);
154        let side_effects_fut = side_effect(self, ctx);
155
156        // Run our side effects concurrently with the table updates.
157        let ((), ()) = futures::future::join(
158            side_effects_fut
159                .wall_time()
160                .observe(side_effects_seconds)
161                .instrument(info_span!(
162                    "coord::catalog_transact_with_side_effects::side_effects_fut"
163                )),
164            table_updates
165                .wall_time()
166                .observe(table_updates_wait)
167                .instrument(info_span!(
168                    "coord::catalog_transact_with_side_effects::table_updates"
169                )),
170        )
171        .await;
172
173        self.metrics
174            .catalog_transact_seconds
175            .with_label_values(&["catalog_transact_with_side_effects"])
176            .observe(start.elapsed().as_secs_f64());
177
178        Ok(())
179    }
180
181    /// Same as [`Self::catalog_transact_inner`] but takes an execution context
182    /// or connection ID and runs builtin table updates concurrently with any
183    /// catalog implications that are generated as part of applying the given
184    /// `ops` (e.g. creating collections).
185    ///
186    /// This will use a connection ID if provided and otherwise fall back to
187    /// getting a connection ID from the execution context.
188    #[instrument(name = "coord::catalog_transact_with_context")]
189    pub(crate) async fn catalog_transact_with_context(
190        &mut self,
191        conn_id: Option<&ConnectionId>,
192        ctx: Option<&mut ExecuteContext>,
193        ops: Vec<catalog::Op>,
194    ) -> Result<(), AdapterError> {
195        let start = Instant::now();
196
197        let conn_id = conn_id.or_else(|| ctx.as_ref().map(|ctx| ctx.session().conn_id()));
198
199        let (table_updates, catalog_updates) = self.catalog_transact_inner(conn_id, ops).await?;
200
201        let table_updates_wait = self
202            .metrics
203            .catalog_transact_phase_seconds
204            .with_label_values(&["table_updates_wait"]);
205        let apply_catalog_implications_fut = self.apply_catalog_implications(ctx, catalog_updates);
206
207        // Apply catalog implications concurrently with the table updates.
208        let (combined_apply_res, ()) = futures::future::join(
209            apply_catalog_implications_fut.instrument(info_span!(
210                "coord::catalog_transact_with_context::side_effects_fut"
211            )),
212            table_updates
213                .wall_time()
214                .observe(table_updates_wait)
215                .instrument(info_span!(
216                    "coord::catalog_transact_with_context::table_updates"
217                )),
218        )
219        .await;
220
221        // We would get into an inconsistent state if we updated the catalog but
222        // then failed to apply implications. Easiest thing to do is panic and
223        // let restart/bootstrap handle it.
224        combined_apply_res.expect("cannot fail to apply catalog implications");
225
226        // See the note in `catalog_transact_with_side_effects` on why this is
227        // timed outside the macro and reads about zero in production.
228        let consistency_start = Instant::now();
229
230        // Note: It's important that we keep the function call inside macro, this way we only run
231        // the consistency checks if soft assertions are enabled.
232        mz_ore::soft_assert_eq_no_log!(
233            self.check_consistency(),
234            Ok(()),
235            "coordinator inconsistency detected"
236        );
237
238        self.metrics
239            .catalog_transact_phase_seconds
240            .with_label_values(&["consistency_check"])
241            .observe(consistency_start.elapsed().as_secs_f64());
242
243        self.metrics
244            .catalog_transact_seconds
245            .with_label_values(&["catalog_transact_with_context"])
246            .observe(start.elapsed().as_secs_f64());
247
248        Ok(())
249    }
250
251    /// Executes a Catalog transaction with handling if the provided [`Session`]
252    /// is in a SQL transaction that is executing DDL.
253    #[instrument(name = "coord::catalog_transact_with_ddl_transaction")]
254    pub(crate) async fn catalog_transact_with_ddl_transaction<F>(
255        &mut self,
256        ctx: &mut ExecuteContext,
257        mut ops: Vec<catalog::Op>,
258        side_effect: F,
259    ) -> Result<(), AdapterError>
260    where
261        F: for<'a> FnOnce(
262                &'a mut Coordinator,
263                Option<&'a mut ExecuteContext>,
264            ) -> Pin<Box<dyn Future<Output = ()> + 'a>>
265            + Send
266            + Sync
267            + 'static,
268    {
269        let start = Instant::now();
270
271        let Some(Transaction {
272            ops:
273                TransactionOps::DDL {
274                    ops: txn_ops,
275                    revision: txn_revision,
276                    state: txn_state,
277                    snapshot: txn_snapshot,
278                    side_effects: _,
279                },
280            ..
281        }) = ctx.session().transaction().inner()
282        else {
283            let result = self
284                .catalog_transact_with_side_effects(Some(ctx), ops, side_effect)
285                .await;
286            self.metrics
287                .catalog_transact_seconds
288                .with_label_values(&["catalog_transact_with_ddl_transaction"])
289                .observe(start.elapsed().as_secs_f64());
290            return result;
291        };
292
293        // Make sure our Catalog hasn't changed since openning the transaction.
294        if self.catalog().transient_revision() != *txn_revision {
295            self.metrics
296                .catalog_transact_seconds
297                .with_label_values(&["catalog_transact_with_ddl_transaction"])
298                .observe(start.elapsed().as_secs_f64());
299            return Err(AdapterError::DDLTransactionRace);
300        }
301
302        // The per-statement phases of a DDL transaction carry their own labels.
303        // The work differs from a real transaction's phases, and it is billed
304        // once per statement rather than once per transaction, so pooling the two
305        // populations under one label would blur both.
306        let phase_seconds = self.metrics.catalog_transact_phase_seconds.clone();
307
308        // Clone what we need from the session before taking &mut below.
309        let clone_start = Instant::now();
310        let txn_ops_clone = txn_ops.clone();
311        let txn_state_clone = txn_state.clone();
312        // NOTE: `txn_snapshot` is a deep clone of the durable `Snapshot`, which is
313        // O(catalog size) in allocations, once per statement. `txn_state` next to
314        // it is cheap, `CatalogState` holds its large collections in `imbl` maps.
315        let prev_snapshot = txn_snapshot.clone();
316        phase_seconds
317            .with_label_values(&["ddl_txn_snapshot_clone"])
318            .observe(clone_start.elapsed().as_secs_f64());
319
320        // Validate resource limits with all accumulated + new ops (cheap O(N) counting).
321        let prep_start = Instant::now();
322        let mut combined_ops = txn_ops_clone;
323        combined_ops.extend(ops.iter().cloned());
324        let creates_scoped_object = ops.iter().any(|op| {
325            matches!(
326                op,
327                catalog::Op::CreateCluster { .. } | catalog::Op::CreateClusterReplica { .. }
328            )
329        });
330        if creates_scoped_object {
331            // Include accumulated creates when deriving contexts. A replica can
332            // be created in a later DDL statement than its still-uncommitted
333            // cluster, which is absent from the coordinator's live catalog.
334            if let Some(scoped_op) = self.scoped_overrides_create_op(&combined_ops) {
335                ops.push(scoped_op.clone());
336                combined_ops.push(scoped_op);
337            }
338        }
339        let conn_id = ctx.session().conn_id().clone();
340        let validate_res = self.validate_resource_limits(&combined_ops, &conn_id);
341        phase_seconds
342            .with_label_values(&["ddl_txn_prep"])
343            .observe(prep_start.elapsed().as_secs_f64());
344        validate_res?;
345
346        // Get oracle timestamp for audit log entries.
347        let oracle_write_ts = self
348            .get_local_write_ts()
349            .wall_time()
350            .observe(phase_seconds.with_label_values(&["ddl_txn_write_ts"]))
351            .await
352            .timestamp;
353
354        // Get ConnMeta for the session.
355        let conn = self.active_conns.get(ctx.session().conn_id());
356
357        // Incremental dry run: process only NEW ops against accumulated state.
358        // If we have a saved snapshot from a previous dry run, use it to
359        // initialize the transaction so it starts in sync with the accumulated
360        // state. Otherwise (first statement), the fresh durable transaction is
361        // already in sync with the real catalog state.
362        let (new_state, new_snapshot) = self
363            .catalog()
364            .transact_incremental_dry_run(
365                &txn_state_clone,
366                ops.clone(),
367                conn,
368                prev_snapshot,
369                oracle_write_ts,
370            )
371            .wall_time()
372            .observe(phase_seconds.with_label_values(&["ddl_txn_dry_run"]))
373            .await?;
374
375        // Accumulate ops for eventual COMMIT.
376        let result = ctx
377            .session_mut()
378            .transaction_mut()
379            .add_ops(TransactionOps::DDL {
380                ops: combined_ops,
381                state: new_state,
382                side_effects: vec![Box::new(side_effect)],
383                revision: self.catalog().transient_revision(),
384                snapshot: Some(new_snapshot),
385            });
386
387        self.metrics
388            .catalog_transact_seconds
389            .with_label_values(&["catalog_transact_with_ddl_transaction"])
390            .observe(start.elapsed().as_secs_f64());
391
392        result
393    }
394
395    /// Perform a catalog transaction. [`Coordinator::ship_dataflow`] must be
396    /// called after this function successfully returns on any built
397    /// [`DataflowDesc`](mz_compute_types::dataflows::DataflowDesc).
398    #[instrument(name = "coord::catalog_transact_inner")]
399    pub(crate) async fn catalog_transact_inner(
400        &mut self,
401        conn_id: Option<&ConnectionId>,
402        mut ops: Vec<catalog::Op>,
403    ) -> Result<(BuiltinTableAppendNotify, Vec<ParsedStateUpdate>), AdapterError> {
404        if self.controller.read_only() {
405            return Err(AdapterError::ReadOnly);
406        }
407
408        if let Some(scoped_op) = self.scoped_overrides_create_op(&ops) {
409            ops.push(scoped_op);
410        }
411
412        event!(Level::TRACE, ops = format!("{:?}", ops));
413
414        let phase_seconds = self.metrics.catalog_transact_phase_seconds.clone();
415        let phase_start = Instant::now();
416
417        let mut webhook_sources_to_restart = BTreeSet::new();
418        let mut clusters_to_drop = vec![];
419        let mut cluster_replicas_to_drop = vec![];
420        let mut clusters_to_create = vec![];
421        let mut cluster_replicas_to_create = vec![];
422        let mut update_metrics_config = false;
423        let mut update_tracing_config = false;
424        let mut update_controller_config = false;
425        let mut update_compute_config = false;
426        let mut update_storage_config = false;
427        let mut update_timestamp_oracle_config = false;
428        let mut update_metrics_retention = false;
429        let mut update_secrets_caching_config = false;
430        let mut update_cluster_scheduling_config = false;
431        let mut update_http_config = false;
432        let mut update_advance_timelines_interval = false;
433        let mut update_optimizer_e2e_latency_warning_threshold = false;
434
435        for op in &ops {
436            match op {
437                catalog::Op::DropObjects(drop_object_infos) => {
438                    for drop_object_info in drop_object_infos {
439                        match &drop_object_info {
440                            catalog::DropObjectInfo::Item(_) => {
441                                // Nothing to do, these will be handled by
442                                // applying the side effects that we return.
443                            }
444                            catalog::DropObjectInfo::Cluster(id) => {
445                                clusters_to_drop.push(*id);
446                            }
447                            catalog::DropObjectInfo::ClusterReplica((
448                                cluster_id,
449                                replica_id,
450                                _reason,
451                            )) => {
452                                // Drop the cluster replica itself.
453                                cluster_replicas_to_drop.push((*cluster_id, *replica_id));
454                            }
455                            _ => (),
456                        }
457                    }
458                }
459                catalog::Op::ResetSystemConfiguration { name }
460                | catalog::Op::UpdateSystemConfiguration { name, .. } => {
461                    update_metrics_config |= self
462                        .catalog
463                        .state()
464                        .system_config()
465                        .is_metrics_config_var(name);
466                    update_tracing_config |= vars::is_tracing_var(name);
467                    update_controller_config |= self
468                        .catalog
469                        .state()
470                        .system_config()
471                        .is_controller_config_var(name);
472                    update_compute_config |= self
473                        .catalog
474                        .state()
475                        .system_config()
476                        .is_compute_config_var(name);
477                    update_storage_config |= self
478                        .catalog
479                        .state()
480                        .system_config()
481                        .is_storage_config_var(name);
482                    update_timestamp_oracle_config |= vars::is_timestamp_oracle_config_var(name);
483                    update_metrics_retention |= name == vars::METRICS_RETENTION.name();
484                    update_secrets_caching_config |= vars::is_secrets_caching_var(name);
485                    update_cluster_scheduling_config |= vars::is_cluster_scheduling_var(name);
486                    update_http_config |= vars::is_http_config_var(name);
487                    update_advance_timelines_interval |= name == DEFAULT_TIMESTAMP_INTERVAL.name();
488                    update_optimizer_e2e_latency_warning_threshold |=
489                        name == vars::OPTIMIZER_E2E_LATENCY_WARNING_THRESHOLD.name();
490                }
491                catalog::Op::ResetAllSystemConfiguration => {
492                    // Assume they all need to be updated.
493                    // We could see if the config's have actually changed, but
494                    // this is simpler.
495                    update_tracing_config = true;
496                    update_controller_config = true;
497                    update_compute_config = true;
498                    update_storage_config = true;
499                    update_timestamp_oracle_config = true;
500                    update_metrics_retention = true;
501                    update_secrets_caching_config = true;
502                    update_cluster_scheduling_config = true;
503                    update_metrics_config = true;
504                    update_http_config = true;
505                    update_advance_timelines_interval = true;
506                    update_optimizer_e2e_latency_warning_threshold = true;
507                }
508                catalog::Op::RenameItem { id, .. } => {
509                    let item = self.catalog().get_entry(id);
510                    let is_webhook_source = item
511                        .source()
512                        .map(|s| matches!(s.data_source, DataSourceDesc::Webhook { .. }))
513                        .unwrap_or(false);
514                    if is_webhook_source {
515                        webhook_sources_to_restart.insert(*id);
516                    }
517                }
518                catalog::Op::RenameSchema {
519                    database_spec,
520                    schema_spec,
521                    ..
522                } => {
523                    let schema = self.catalog().get_schema(
524                        database_spec,
525                        schema_spec,
526                        conn_id.unwrap_or(&SYSTEM_CONN_ID),
527                    );
528                    let webhook_sources = schema.item_ids().filter(|id| {
529                        let item = self.catalog().get_entry(id);
530                        item.source()
531                            .map(|s| matches!(s.data_source, DataSourceDesc::Webhook { .. }))
532                            .unwrap_or(false)
533                    });
534                    webhook_sources_to_restart.extend(webhook_sources);
535                }
536                catalog::Op::CreateCluster { id, .. } => {
537                    clusters_to_create.push(*id);
538                }
539                catalog::Op::CreateClusterReplica {
540                    cluster_id,
541                    name,
542                    config,
543                    ..
544                } => {
545                    cluster_replicas_to_create.push((
546                        *cluster_id,
547                        name.clone(),
548                        config.location.num_processes(),
549                    ));
550                }
551                _ => (),
552            }
553        }
554
555        // Observe before propagating, so a transaction rejected on resource
556        // limits still accounts for the op scan it burned on the loop.
557        let validate_res = self.validate_resource_limits(&ops, conn_id.unwrap_or(&SYSTEM_CONN_ID));
558        phase_seconds
559            .with_label_values(&["prep"])
560            .observe(phase_start.elapsed().as_secs_f64());
561        validate_res?;
562
563        // This will produce timestamps that are guaranteed to increase on each
564        // call, and also never be behind the system clock. If the system clock
565        // hasn't advanced (or has gone backward), it will increment by 1. For
566        // the audit log, we need to balance "close (within 10s or so) to the
567        // system clock" and "always goes up". We've chosen here to prioritize
568        // always going up, and believe we will always be close to the system
569        // clock because it is well configured (chrony) and so may only rarely
570        // regress or pause for 10s.
571        let oracle_write_ts = self
572            .get_catalog_write_ts()
573            .wall_time()
574            .observe(phase_seconds.with_label_values(&["write_ts"]))
575            .await;
576
577        let Coordinator {
578            catalog,
579            active_conns,
580            controller,
581            cluster_replica_statuses,
582            ..
583        } = self;
584        let catalog = Arc::make_mut(catalog);
585        let conn = conn_id.map(|id| active_conns.get(id).expect("connection must exist"));
586
587        // Register the session as an ephemeral owner (its uuid <-> connection
588        // mapping) at its first temporary-item creation.
589        if let Some(conn) = conn {
590            let creates_temp_item = ops.iter().any(
591                |op| matches!(op, catalog::Op::CreateItem { item, .. } if item.is_temporary()),
592            );
593            if creates_temp_item && !catalog.state().has_temporary_namespace(conn.conn_id()) {
594                catalog.register_temporary_namespace(conn.conn_id(), conn.uuid());
595            }
596        }
597
598        // NOTE: This phase contains every durable `sync` and `commit` a catalog
599        // transaction performs, which is what makes `transact` minus those two
600        // histograms an estimate of the in-memory work. Two caveats. More than
601        // one sync happens per transaction, so the subtraction is only valid on
602        // rates of `_sum`, never on per-observation means. And durable
603        // `allocate_id` (user ID pool refills, storage usage batch IDs) observes
604        // into the same histograms from outside any catalog transaction, so the
605        // estimate is biased low while allocation is active.
606        let TransactionResult {
607            builtin_table_updates,
608            catalog_updates,
609            audit_events,
610        } = catalog
611            .transact(
612                Some(&mut controller.storage_collections),
613                oracle_write_ts,
614                conn,
615                ops,
616            )
617            .wall_time()
618            .observe(phase_seconds.with_label_values(&["transact"]))
619            .await?;
620
621        for (cluster_id, replica_id) in &cluster_replicas_to_drop {
622            cluster_replica_statuses.remove_cluster_replica_statuses(cluster_id, replica_id);
623        }
624        for cluster_id in &clusters_to_drop {
625            cluster_replica_statuses.remove_cluster_statuses(cluster_id);
626        }
627        for cluster_id in clusters_to_create {
628            cluster_replica_statuses.initialize_cluster_statuses(cluster_id);
629        }
630        let now = to_datetime((catalog.config().now)());
631        for (cluster_id, replica_name, num_processes) in cluster_replicas_to_create {
632            let replica_id = catalog
633                .resolve_replica_in_cluster(&cluster_id, &replica_name)
634                .expect("just created")
635                .replica_id();
636            cluster_replica_statuses.initialize_cluster_replica_statuses(
637                cluster_id,
638                replica_id,
639                num_processes,
640                now,
641            );
642        }
643
644        // Append our builtin table updates, then return the notify so we can run other tasks in
645        // parallel.
646        let stage_start = Instant::now();
647        let builtin_update_notify = self.builtin_table_update().execute(builtin_table_updates);
648        phase_seconds
649            .with_label_values(&["stage_builtin"])
650            .observe(stage_start.elapsed().as_secs_f64());
651
652        let finalize_start = Instant::now();
653
654        // No error returns are allowed after this point. Enforce this at compile time
655        // by using this odd structure so we don't accidentally add a stray `?`.
656        let _: () = async {
657            if !webhook_sources_to_restart.is_empty() {
658                self.restart_webhook_sources(webhook_sources_to_restart);
659            }
660
661            if update_metrics_config {
662                mz_metrics::update_dyncfg(&self.catalog().system_config().dyncfg_updates());
663            }
664            if update_controller_config {
665                self.update_controller_config();
666            }
667            if update_compute_config {
668                self.update_compute_config();
669            }
670            if update_storage_config {
671                self.update_storage_config();
672            }
673            if update_timestamp_oracle_config {
674                self.update_timestamp_oracle_config();
675            }
676            if update_metrics_retention {
677                self.update_metrics_retention();
678            }
679            if update_tracing_config {
680                self.update_tracing_config();
681            }
682            if update_secrets_caching_config {
683                self.update_secrets_caching_config();
684            }
685            if update_cluster_scheduling_config {
686                self.update_cluster_scheduling_config();
687            }
688            if update_http_config {
689                self.update_http_config();
690            }
691            if update_advance_timelines_interval {
692                let new_interval = self.catalog().system_config().default_timestamp_interval();
693                if new_interval != self.advance_timelines_interval.period() {
694                    self.advance_timelines_interval = tokio::time::interval(new_interval);
695                }
696            }
697            if update_optimizer_e2e_latency_warning_threshold {
698                let threshold = self
699                    .catalog()
700                    .system_config()
701                    .optimizer_e2e_latency_warning_threshold();
702                self.optimizer_metrics
703                    .set_e2e_optimization_time_log_threshold(threshold);
704            }
705        }
706        .instrument(info_span!("coord::catalog_transact_with::finalize"))
707        .await;
708
709        let conn = conn_id.and_then(|id| self.active_conns.get(id));
710        if let Some(segment_client) = &self.segment_client {
711            for VersionedEvent::V1(event) in audit_events {
712                let event_type = format!(
713                    "{} {}",
714                    event.object_type.as_title_case(),
715                    event.event_type.as_title_case()
716                );
717                segment_client.environment_track(
718                    &self.catalog().config().environment_id,
719                    event_type,
720                    json!({ "details": event.details.as_json() }),
721                    EventDetails {
722                        user_id: conn
723                            .and_then(|c| c.user().external_metadata.as_ref())
724                            .map(|m| m.user_id),
725                        application_name: conn.map(|c| c.application_name()),
726                        ..Default::default()
727                    },
728                );
729            }
730        }
731
732        phase_seconds
733            .with_label_values(&["finalize"])
734            .observe(finalize_start.elapsed().as_secs_f64());
735
736        Ok((builtin_update_notify, catalog_updates))
737    }
738
739    pub(crate) fn drop_replica(&mut self, cluster_id: ClusterId, replica_id: ReplicaId) {
740        self.drop_introspection_subscribes(replica_id);
741        self.drop_metric_sinks(replica_id);
742
743        self.controller
744            .drop_replica(cluster_id, replica_id)
745            .expect("dropping replica must not fail");
746    }
747
748    /// A convenience method for dropping sources.
749    pub(crate) fn drop_sources(&mut self, sources: Vec<(CatalogItemId, GlobalId)>) {
750        for (item_id, _gid) in &sources {
751            self.active_webhooks.remove(item_id);
752        }
753        let storage_metadata = self.catalog.state().storage_metadata();
754        let source_gids = sources.into_iter().map(|(_id, gid)| gid).collect();
755        self.controller
756            .storage
757            .drop_sources(storage_metadata, source_gids)
758            .unwrap_or_terminate("cannot fail to drop sources");
759    }
760
761    /// A convenience method for dropping tables.
762    pub(crate) async fn drop_tables(&mut self, tables: Vec<(CatalogItemId, GlobalId)>) {
763        for (item_id, _gid) in &tables {
764            self.active_webhooks.remove(item_id);
765        }
766
767        let table_gids: Vec<_> = tables.into_iter().map(|(_id, gid)| gid).collect();
768
769        // FIFO ordering places the forget after every staged append.
770        let forget_ids = self
771            .controller
772            .storage
773            .txns_table_ids(table_gids.clone())
774            .unwrap_or_terminate("cannot fail to look up txns-registered tables");
775        if !forget_ids.is_empty() {
776            self.forget_tables_via_committer(forget_ids).await;
777        }
778
779        let storage_metadata = self.catalog.state().storage_metadata();
780        self.controller
781            .storage
782            .drop_tables(storage_metadata, table_gids)
783            .unwrap_or_terminate("cannot fail to drop tables");
784    }
785
786    fn restart_webhook_sources(&mut self, sources: impl IntoIterator<Item = CatalogItemId>) {
787        for id in sources {
788            self.active_webhooks.remove(&id);
789        }
790    }
791
792    /// Like `drop_compute_sinks`, but for a single compute sink.
793    ///
794    /// Returns the controller's state for the compute sink if the identified
795    /// sink was known to the controller. It is the caller's responsibility to
796    /// retire the returned sink. Consider using `retire_compute_sinks` instead.
797    #[must_use]
798    pub async fn drop_compute_sink(
799        &mut self,
800        sink_id: GlobalId,
801    ) -> Option<(ActiveComputeSink, BuiltinTableAppendNotify)> {
802        self.drop_compute_sinks([sink_id]).await.remove(&sink_id)
803    }
804
805    /// Drops a batch of compute sinks.
806    ///
807    /// For each sink that exists, the coordinator and controller's state
808    /// associated with the sink is removed.
809    ///
810    /// Returns a map from sink id to the controller's state for the sink and a notify that
811    /// resolves once the sink's `mz_subscriptions` retraction is durable (see
812    /// `remove_active_compute_sink`). It is the caller's responsibility to await the notify
813    /// off the coordinator loop and then retire the returned sinks. Consider using
814    /// `retire_compute_sinks` instead.
815    #[must_use]
816    pub async fn drop_compute_sinks(
817        &mut self,
818        sink_ids: impl IntoIterator<Item = GlobalId>,
819    ) -> BTreeMap<GlobalId, (ActiveComputeSink, BuiltinTableAppendNotify)> {
820        let mut by_id = BTreeMap::new();
821        let mut by_cluster: BTreeMap<_, Vec<_>> = BTreeMap::new();
822        for sink_id in sink_ids {
823            let (sink, write_notify) = match self.remove_active_compute_sink(sink_id).await {
824                None => {
825                    // This can happen due to a race condition: an internal
826                    // subscribe may be cleaned up via its own message while
827                    // session disconnect cleanup is in progress. This is
828                    // benign.
829                    tracing::debug!(%sink_id, "drop_compute_sinks: sink already removed");
830                    continue;
831                }
832                Some(entry) => entry,
833            };
834
835            by_cluster
836                .entry(sink.cluster_id())
837                .or_default()
838                .push(sink_id);
839            by_id.insert(sink_id, (sink, write_notify));
840        }
841        for (cluster_id, ids) in by_cluster {
842            let compute = &mut self.controller.compute;
843            // A cluster could have been dropped, so verify it exists.
844            if compute.instance_exists(cluster_id) {
845                compute
846                    .drop_collections(cluster_id, ids)
847                    .unwrap_or_terminate("cannot fail to drop collections");
848            }
849        }
850        by_id
851    }
852
853    /// Retires a batch of sinks with disparate reasons for retirement.
854    ///
855    /// Each sink identified in `reasons` is dropped (see `drop_compute_sinks`),
856    /// then retired with its corresponding reason. Returns a notify that resolves
857    /// once all `mz_subscriptions` retractions are durable and the sinks are retired.
858    pub async fn retire_compute_sinks(
859        &mut self,
860        mut reasons: BTreeMap<GlobalId, ActiveComputeSinkRetireReason>,
861    ) -> BuiltinTableAppendCompletion {
862        let sink_ids = reasons.keys().cloned();
863        let to_retire: Vec<_> = self
864            .drop_compute_sinks(sink_ids)
865            .await
866            .into_iter()
867            .map(|(id, (sink, write_notify))| {
868                let reason = reasons
869                    .remove(&id)
870                    .expect("all returned IDs are in `reasons`");
871                (sink, write_notify, reason)
872            })
873            .collect();
874
875        // Retire off the coordinator loop. We wait for each `mz_subscriptions` retraction
876        // before telling the subscribing client that the sink is gone. The returned notify
877        // lets statements that caused the retirement also wait before sending their response.
878        // The wait must not happen on the coordinator loop, since that would block every
879        // other session on the group-commit oracle round trip.
880        let (done_tx, done_rx) = tokio::sync::oneshot::channel();
881        task::spawn(|| "retire_compute_sinks", async move {
882            for (sink, write_notify, reason) in to_retire {
883                write_notify.await;
884                sink.retire(reason);
885            }
886            let _ = done_tx.send(());
887        });
888        BuiltinTableAppendCompletion::new(Box::pin(async move {
889            let _ = done_rx.await;
890        }))
891    }
892
893    /// Cancels all active compute sinks for the identified connection.
894    #[mz_ore::instrument(level = "debug")]
895    pub(crate) async fn cancel_compute_sinks_for_conn(
896        &mut self,
897        conn_id: &ConnectionId,
898    ) -> BuiltinTableAppendCompletion {
899        self.retire_compute_sinks_for_conn(conn_id, ActiveComputeSinkRetireReason::Canceled)
900            .await
901    }
902
903    /// Retires all active compute sinks for the identified connection with the
904    /// specified reason.
905    #[mz_ore::instrument(level = "debug")]
906    pub(crate) async fn retire_compute_sinks_for_conn(
907        &mut self,
908        conn_id: &ConnectionId,
909        reason: ActiveComputeSinkRetireReason,
910    ) -> BuiltinTableAppendCompletion {
911        let drop_sinks = self
912            .active_conns
913            .get_mut(conn_id)
914            .expect("must exist for active session")
915            .drop_sinks
916            .iter()
917            .map(|sink_id| (*sink_id, reason.clone()))
918            .collect();
919        self.retire_compute_sinks(drop_sinks).await
920    }
921
922    pub(crate) fn drop_storage_sinks(&mut self, sink_gids: Vec<GlobalId>) {
923        let storage_metadata = self.catalog.state().storage_metadata();
924        self.controller
925            .storage
926            .drop_sinks(storage_metadata, sink_gids)
927            .unwrap_or_terminate("cannot fail to drop sinks");
928    }
929
930    pub(crate) fn drop_compute_collections(&mut self, collections: Vec<(ClusterId, GlobalId)>) {
931        let mut by_cluster: BTreeMap<_, Vec<_>> = BTreeMap::new();
932        for (cluster_id, gid) in collections {
933            by_cluster.entry(cluster_id).or_default().push(gid);
934        }
935        for (cluster_id, gids) in by_cluster {
936            let compute = &mut self.controller.compute;
937            // A cluster could have been dropped, so verify it exists.
938            if compute.instance_exists(cluster_id) {
939                compute
940                    .drop_collections(cluster_id, gids)
941                    .unwrap_or_terminate("cannot fail to drop collections");
942            }
943        }
944    }
945
946    pub(crate) fn drop_vpc_endpoints_in_background(&self, vpc_endpoints: Vec<CatalogItemId>) {
947        // Match the create path (catalog_implications.rs) which gracefully
948        // logs an error when cloud_resource_controller is None, rather than
949        // panicking.
950        let Some(cloud_resource_controller) = self.cloud_resource_controller.as_ref() else {
951            warn!("dropping VPC endpoints without cloud_resource_controller; skipping cleanup");
952            return;
953        };
954        let cloud_resource_controller = Arc::clone(cloud_resource_controller);
955        // We don't want to block the coordinator on an external delete api
956        // calls, so move the drop vpc_endpoint to a separate task. This does
957        // mean that a failed drop won't bubble up to the user as an error
958        // message. However, even if it did (and how the code previously
959        // worked), mz has already dropped it from our catalog, and so we
960        // wouldn't be able to retry anyway. Any orphaned vpc_endpoints will
961        // eventually be cleaned during restart via coord bootstrap.
962        task::spawn(
963            || "drop_vpc_endpoints",
964            async move {
965                for vpc_endpoint in vpc_endpoints {
966                    let _ = Retry::default()
967                        .max_duration(Duration::from_secs(60))
968                        .retry_async(|_state| async {
969                            fail_point!("drop_vpc_endpoint", |r| {
970                                Err(anyhow::anyhow!("Fail point error {:?}", r))
971                            });
972                            match cloud_resource_controller
973                                .delete_vpc_endpoint(vpc_endpoint)
974                                .await
975                            {
976                                Ok(_) => Ok(()),
977                                Err(e) => {
978                                    warn!("Dropping VPC Endpoints has encountered an error: {}", e);
979                                    Err(e)
980                                }
981                            }
982                        })
983                        .await;
984                }
985            }
986            .instrument(info_span!(
987                "coord::catalog_transact_inner::drop_vpc_endpoints"
988            )),
989        );
990    }
991
992    /// Removes all temporary items created by the specified connection, though
993    /// not the temporary schema itself.
994    pub(crate) async fn drop_temp_items(&mut self, conn_id: &ConnectionId) {
995        let temp_items = self.catalog().state().get_temp_items(conn_id).collect();
996        let all_items = self.catalog().object_dependents(&temp_items, conn_id);
997
998        if all_items.is_empty() {
999            return;
1000        }
1001        let op = Op::DropObjects(
1002            all_items
1003                .into_iter()
1004                .map(DropObjectInfo::manual_drop_from_object_id)
1005                .collect(),
1006        );
1007
1008        self.catalog_transact_with_context(Some(conn_id), None, vec![op])
1009            .await
1010            .expect("unable to drop temporary items for conn_id");
1011    }
1012
1013    fn update_cluster_scheduling_config(&self) {
1014        let config = flags::orchestrator_scheduling_config(self.catalog.system_config());
1015        self.controller
1016            .update_orchestrator_scheduling_config(config);
1017    }
1018
1019    fn update_secrets_caching_config(&self) {
1020        let config = flags::caching_config(self.catalog.system_config());
1021        self.caching_secrets_reader.set_policy(config);
1022    }
1023
1024    fn update_tracing_config(&self) {
1025        let tracing = flags::tracing_config(self.catalog().system_config());
1026        tracing.apply(&self.tracing_handle);
1027    }
1028
1029    fn update_compute_config(&mut self) {
1030        let config_params = flags::compute_config(self.catalog().system_config());
1031        self.controller.compute.update_configuration(config_params);
1032    }
1033
1034    fn update_storage_config(&mut self) {
1035        let config_params = flags::storage_config(self.catalog().system_config());
1036        self.controller.storage.update_parameters(config_params);
1037    }
1038
1039    fn update_timestamp_oracle_config(&self) {
1040        let config_params = flags::timestamp_oracle_config(self.catalog().system_config());
1041        if let Some(config) = self.timestamp_oracle_config.as_ref() {
1042            config.apply_parameters(config_params)
1043        }
1044    }
1045
1046    fn update_metrics_retention(&self) {
1047        let duration = self.catalog().system_config().metrics_retention();
1048        let policy = ReadPolicy::lag_writes_by(
1049            Timestamp::new(u64::try_from(duration.as_millis()).unwrap_or_else(|_e| {
1050                tracing::error!("Absurd metrics retention duration: {duration:?}.");
1051                u64::MAX
1052            })),
1053            SINCE_GRANULARITY,
1054        );
1055        let storage_policies = self
1056            .catalog()
1057            .entries()
1058            .filter(|entry| {
1059                entry.item().is_retained_metrics_object()
1060                    && entry.item().is_compute_object_on_cluster().is_none()
1061            })
1062            .map(|entry| (entry.id(), policy.clone()))
1063            .collect::<Vec<_>>();
1064        let compute_policies = self
1065            .catalog()
1066            .entries()
1067            .filter_map(|entry| {
1068                if let (true, Some(cluster_id)) = (
1069                    entry.item().is_retained_metrics_object(),
1070                    entry.item().is_compute_object_on_cluster(),
1071                ) {
1072                    Some((cluster_id, entry.id(), policy.clone()))
1073                } else {
1074                    None
1075                }
1076            })
1077            .collect::<Vec<_>>();
1078        self.update_storage_read_policies(storage_policies);
1079        self.update_compute_read_policies(compute_policies);
1080    }
1081
1082    fn update_controller_config(&mut self) {
1083        let sys_config = self.catalog().system_config();
1084        self.controller
1085            .update_configuration(sys_config.dyncfg_updates());
1086    }
1087
1088    fn update_http_config(&mut self) {
1089        let webhook_request_limit = self
1090            .catalog()
1091            .system_config()
1092            .webhook_concurrent_request_limit();
1093        self.webhook_concurrency_limit
1094            .set_limit(webhook_request_limit);
1095    }
1096
1097    pub(crate) async fn create_storage_export(
1098        &mut self,
1099        id: GlobalId,
1100        sink: &Sink,
1101    ) -> Result<(), AdapterError> {
1102        // Validate `sink.from` is in fact a storage collection
1103        self.controller.storage.check_exists(sink.from)?;
1104
1105        // The AsOf is used to determine at what time to snapshot reading from
1106        // the persist collection.  This is primarily relevant when we do _not_
1107        // want to include the snapshot in the sink.
1108        //
1109        // We choose the smallest as_of that is legal, according to the sinked
1110        // collection's since.
1111        let id_bundle = crate::CollectionIdBundle {
1112            storage_ids: btreeset! {sink.from},
1113            compute_ids: btreemap! {},
1114        };
1115
1116        // We're putting in place read holds, such that create_exports, below,
1117        // which calls update_read_capabilities, can successfully do so.
1118        // Otherwise, the since of dependencies might move along concurrently,
1119        // pulling the rug from under us!
1120        //
1121        // TODO: Maybe in the future, pass those holds on to storage, to hold on
1122        // to them and downgrade when possible?
1123        let read_holds = self.acquire_read_holds(&id_bundle);
1124        let as_of = read_holds.least_valid_read();
1125
1126        let storage_sink_from_entry = self.catalog().get_entry_by_global_id(&sink.from);
1127        let storage_sink_desc = mz_storage_types::sinks::StorageSinkDesc {
1128            from: sink.from,
1129            from_desc: storage_sink_from_entry
1130                .relation_desc()
1131                .expect("sinks can only be built on items with descs")
1132                .into_owned(),
1133            connection: sink
1134                .connection
1135                .clone()
1136                .into_inline_connection(self.catalog().state()),
1137            envelope: sink.envelope,
1138            as_of,
1139            with_snapshot: sink.with_snapshot,
1140            version: sink.version,
1141            from_storage_metadata: (),
1142            to_storage_metadata: (),
1143            commit_interval: sink.commit_interval,
1144        };
1145
1146        let collection_desc = CollectionDescription {
1147            // TODO(sinks): make generic once we have more than one sink type.
1148            desc: KAFKA_PROGRESS_DESC.clone(),
1149            data_source: DataSource::Sink {
1150                desc: ExportDescription {
1151                    sink: storage_sink_desc,
1152                    instance_id: sink.cluster_id,
1153                },
1154            },
1155            since: None,
1156            timeline: None,
1157            primary: None,
1158        };
1159        let collections = vec![(id, collection_desc)];
1160
1161        // Create the collections.
1162        let storage_metadata = self.catalog.state().storage_metadata();
1163        let res = self
1164            .controller
1165            .storage
1166            .create_collections(storage_metadata, None, collections)
1167            .await;
1168
1169        // Drop read holds after the export has been created, at which point
1170        // storage will have put in its own read holds.
1171        drop(read_holds);
1172
1173        Ok(res?)
1174    }
1175
1176    /// Validate all resource limits in a catalog transaction and return an error if that limit is
1177    /// exceeded.
1178    fn validate_resource_limits(
1179        &self,
1180        ops: &Vec<catalog::Op>,
1181        conn_id: &ConnectionId,
1182    ) -> Result<(), AdapterError> {
1183        let mut new_kafka_connections = 0;
1184        let mut new_postgres_connections = 0;
1185        let mut new_mysql_connections = 0;
1186        let mut new_sql_server_connections = 0;
1187        let mut new_aws_privatelink_connections = 0;
1188        let mut new_tables = 0;
1189        let mut new_sources = 0;
1190        let mut new_sinks = 0;
1191        let mut new_materialized_views = 0;
1192        let mut new_clusters = 0;
1193        let mut new_replicas_per_cluster = BTreeMap::new();
1194        let mut new_credit_consumption_rate = Numeric::zero();
1195        let mut new_databases = 0;
1196        let mut new_schemas_per_database = BTreeMap::new();
1197        let mut new_objects_per_schema = BTreeMap::new();
1198        let mut new_secrets = 0;
1199        let mut new_roles = 0;
1200        let mut new_network_policies = 0;
1201        for op in ops {
1202            match op {
1203                Op::CreateDatabase { .. } => {
1204                    new_databases += 1;
1205                }
1206                Op::CreateSchema { database_id, .. } => {
1207                    if let ResolvedDatabaseSpecifier::Id(database_id) = database_id {
1208                        *new_schemas_per_database.entry(database_id).or_insert(0) += 1;
1209                    }
1210                }
1211                Op::CreateRole { .. } => {
1212                    new_roles += 1;
1213                }
1214                Op::CreateNetworkPolicy { .. } => {
1215                    new_network_policies += 1;
1216                }
1217                Op::CreateCluster { .. } => {
1218                    // TODO(benesch): having deprecated linked clusters, remove
1219                    // the `max_sources` and `max_sinks` limit, and set a higher
1220                    // max cluster limit?
1221                    new_clusters += 1;
1222                }
1223                Op::CreateClusterReplica {
1224                    cluster_id, config, ..
1225                } => {
1226                    if cluster_id.is_user() {
1227                        *new_replicas_per_cluster.entry(*cluster_id).or_insert(0) += 1;
1228                        if let ReplicaLocation::Managed(location) = &config.location {
1229                            new_credit_consumption_rate += self.replica_credits_per_hour(location);
1230                        }
1231                    }
1232                }
1233                Op::CreateItem { name, item, .. } => {
1234                    *new_objects_per_schema
1235                        .entry((
1236                            name.qualifiers.database_spec.clone(),
1237                            name.qualifiers.schema_spec.clone(),
1238                        ))
1239                        .or_insert(0) += 1;
1240                    match item {
1241                        CatalogItem::Connection(connection) => match connection.details {
1242                            ConnectionDetails::Kafka(_) => new_kafka_connections += 1,
1243                            ConnectionDetails::Postgres(_) => new_postgres_connections += 1,
1244                            ConnectionDetails::MySql(_) => new_mysql_connections += 1,
1245                            ConnectionDetails::SqlServer(_) => new_sql_server_connections += 1,
1246                            ConnectionDetails::AwsPrivatelink(_) => {
1247                                new_aws_privatelink_connections += 1
1248                            }
1249                            ConnectionDetails::Csr(_)
1250                            | ConnectionDetails::GlueSchemaRegistry(_)
1251                            | ConnectionDetails::Ssh { .. }
1252                            | ConnectionDetails::Aws(_)
1253                            | ConnectionDetails::Gcp(_)
1254                            | ConnectionDetails::IcebergCatalog(_) => {}
1255                        },
1256                        CatalogItem::Table(_) => {
1257                            new_tables += 1;
1258                        }
1259                        CatalogItem::Source(source) => {
1260                            new_sources += source.user_controllable_persist_shard_count()
1261                        }
1262                        CatalogItem::Sink(_) => new_sinks += 1,
1263                        CatalogItem::MaterializedView(_) => {
1264                            new_materialized_views += 1;
1265                        }
1266                        CatalogItem::Secret(_) => {
1267                            new_secrets += 1;
1268                        }
1269                        CatalogItem::Log(_)
1270                        | CatalogItem::View(_)
1271                        | CatalogItem::Index(_)
1272                        | CatalogItem::Type(_)
1273                        | CatalogItem::Func(_)
1274                        | CatalogItem::MetricSink(_) => {}
1275                    }
1276                }
1277                Op::DropObjects(drop_object_infos) => {
1278                    for drop_object_info in drop_object_infos {
1279                        match drop_object_info {
1280                            DropObjectInfo::Cluster(_) => {
1281                                new_clusters -= 1;
1282                            }
1283                            DropObjectInfo::ClusterReplica((cluster_id, replica_id, _reason)) => {
1284                                if cluster_id.is_user() {
1285                                    *new_replicas_per_cluster.entry(*cluster_id).or_insert(0) -= 1;
1286                                    let cluster = self
1287                                        .catalog()
1288                                        .get_cluster_replica(*cluster_id, *replica_id);
1289                                    if let ReplicaLocation::Managed(location) =
1290                                        &cluster.config.location
1291                                    {
1292                                        new_credit_consumption_rate -=
1293                                            self.replica_credits_per_hour(location);
1294                                    }
1295                                }
1296                            }
1297                            DropObjectInfo::Database(_) => {
1298                                new_databases -= 1;
1299                            }
1300                            DropObjectInfo::Schema((database_spec, _)) => {
1301                                if let ResolvedDatabaseSpecifier::Id(database_id) = database_spec {
1302                                    *new_schemas_per_database.entry(database_id).or_insert(0) -= 1;
1303                                }
1304                            }
1305                            DropObjectInfo::Role(_) => {
1306                                new_roles -= 1;
1307                            }
1308                            DropObjectInfo::NetworkPolicy(_) => {
1309                                new_network_policies -= 1;
1310                            }
1311                            DropObjectInfo::Item(id) => {
1312                                let entry = self.catalog().get_entry(id);
1313                                *new_objects_per_schema
1314                                    .entry((
1315                                        entry.name().qualifiers.database_spec.clone(),
1316                                        entry.name().qualifiers.schema_spec.clone(),
1317                                    ))
1318                                    .or_insert(0) -= 1;
1319                                match entry.item() {
1320                                    CatalogItem::Connection(connection) => match connection.details
1321                                    {
1322                                        ConnectionDetails::AwsPrivatelink(_) => {
1323                                            new_aws_privatelink_connections -= 1;
1324                                        }
1325                                        _ => (),
1326                                    },
1327                                    CatalogItem::Table(_) => {
1328                                        new_tables -= 1;
1329                                    }
1330                                    CatalogItem::Source(source) => {
1331                                        new_sources -=
1332                                            source.user_controllable_persist_shard_count()
1333                                    }
1334                                    CatalogItem::Sink(_) => new_sinks -= 1,
1335                                    CatalogItem::MaterializedView(_) => {
1336                                        new_materialized_views -= 1;
1337                                    }
1338                                    CatalogItem::Secret(_) => {
1339                                        new_secrets -= 1;
1340                                    }
1341                                    CatalogItem::Log(_)
1342                                    | CatalogItem::View(_)
1343                                    | CatalogItem::Index(_)
1344                                    | CatalogItem::Type(_)
1345                                    | CatalogItem::Func(_)
1346                                    | CatalogItem::MetricSink(_) => {}
1347                                }
1348                            }
1349                        }
1350                    }
1351                }
1352                Op::UpdateItem {
1353                    name: _,
1354                    id,
1355                    to_item,
1356                } => match to_item {
1357                    CatalogItem::Source(source) => {
1358                        let current_source = self
1359                            .catalog()
1360                            .get_entry(id)
1361                            .source()
1362                            .expect("source update is for source item");
1363
1364                        new_sources += source.user_controllable_persist_shard_count()
1365                            - current_source.user_controllable_persist_shard_count();
1366                    }
1367                    CatalogItem::Connection(_)
1368                    | CatalogItem::Table(_)
1369                    | CatalogItem::Sink(_)
1370                    | CatalogItem::MaterializedView(_)
1371                    | CatalogItem::Secret(_)
1372                    | CatalogItem::Log(_)
1373                    | CatalogItem::View(_)
1374                    | CatalogItem::Index(_)
1375                    | CatalogItem::Type(_)
1376                    | CatalogItem::Func(_)
1377                    | CatalogItem::MetricSink(_) => {}
1378                },
1379                Op::AlterRole { .. }
1380                | Op::AlterRetainHistory { .. }
1381                | Op::AlterSourceTimestampInterval { .. }
1382                | Op::AlterNetworkPolicy { .. }
1383                | Op::AlterAddColumn { .. }
1384                | Op::AlterMaterializedViewApplyReplacement { .. }
1385                | Op::UpdatePrivilege { .. }
1386                | Op::UpdateDefaultPrivilege { .. }
1387                | Op::GrantRole { .. }
1388                | Op::RenameCluster { .. }
1389                | Op::RenameClusterReplica { .. }
1390                | Op::RenameItem { .. }
1391                | Op::RenameSchema { .. }
1392                | Op::UpdateOwner { .. }
1393                | Op::RevokeRole { .. }
1394                | Op::UpdateClusterConfig { .. }
1395                | Op::UpdateSourceReferences { .. }
1396                | Op::UpdateSystemConfiguration { .. }
1397                | Op::ResetSystemConfiguration { .. }
1398                | Op::ResetAllSystemConfiguration { .. }
1399                | Op::UpdateScopedSystemParameters { .. }
1400                | Op::Comment { .. }
1401                | Op::CheckClusterState { .. }
1402                | Op::InjectAuditEvents { .. } => {}
1403            }
1404        }
1405
1406        let mut current_aws_privatelink_connections = 0;
1407        let mut current_postgres_connections = 0;
1408        let mut current_mysql_connections = 0;
1409        let mut current_sql_server_connections = 0;
1410        let mut current_kafka_connections = 0;
1411        for c in self.catalog().user_connections() {
1412            let connection = c
1413                .connection()
1414                .expect("`user_connections()` only returns connection objects");
1415
1416            match connection.details {
1417                ConnectionDetails::AwsPrivatelink(_) => current_aws_privatelink_connections += 1,
1418                ConnectionDetails::Postgres(_) => current_postgres_connections += 1,
1419                ConnectionDetails::MySql(_) => current_mysql_connections += 1,
1420                ConnectionDetails::SqlServer(_) => current_sql_server_connections += 1,
1421                ConnectionDetails::Kafka(_) => current_kafka_connections += 1,
1422                ConnectionDetails::Csr(_)
1423                | ConnectionDetails::GlueSchemaRegistry(_)
1424                | ConnectionDetails::Ssh { .. }
1425                | ConnectionDetails::Aws(_)
1426                | ConnectionDetails::Gcp(_)
1427                | ConnectionDetails::IcebergCatalog(_) => {}
1428            }
1429        }
1430        self.validate_resource_limit(
1431            current_kafka_connections,
1432            new_kafka_connections,
1433            SystemVars::max_kafka_connections,
1434            "Kafka Connection",
1435            MAX_KAFKA_CONNECTIONS.name(),
1436        )?;
1437        self.validate_resource_limit(
1438            current_postgres_connections,
1439            new_postgres_connections,
1440            SystemVars::max_postgres_connections,
1441            "PostgreSQL Connection",
1442            MAX_POSTGRES_CONNECTIONS.name(),
1443        )?;
1444        self.validate_resource_limit(
1445            current_mysql_connections,
1446            new_mysql_connections,
1447            SystemVars::max_mysql_connections,
1448            "MySQL Connection",
1449            MAX_MYSQL_CONNECTIONS.name(),
1450        )?;
1451        self.validate_resource_limit(
1452            current_sql_server_connections,
1453            new_sql_server_connections,
1454            SystemVars::max_sql_server_connections,
1455            "SQL Server Connection",
1456            MAX_SQL_SERVER_CONNECTIONS.name(),
1457        )?;
1458        self.validate_resource_limit(
1459            current_aws_privatelink_connections,
1460            new_aws_privatelink_connections,
1461            SystemVars::max_aws_privatelink_connections,
1462            "AWS PrivateLink Connection",
1463            MAX_AWS_PRIVATELINK_CONNECTIONS.name(),
1464        )?;
1465        self.validate_resource_limit(
1466            self.catalog().user_tables().count(),
1467            new_tables,
1468            SystemVars::max_tables,
1469            "table",
1470            MAX_TABLES.name(),
1471        )?;
1472
1473        let current_sources: usize = self
1474            .catalog()
1475            .user_sources()
1476            .filter_map(|source| source.source())
1477            .map(|source| source.user_controllable_persist_shard_count())
1478            .sum::<i64>()
1479            .try_into()
1480            .expect("non-negative sum of sources");
1481
1482        self.validate_resource_limit(
1483            current_sources,
1484            new_sources,
1485            SystemVars::max_sources,
1486            "source",
1487            MAX_SOURCES.name(),
1488        )?;
1489        self.validate_resource_limit(
1490            self.catalog().user_sinks().count(),
1491            new_sinks,
1492            SystemVars::max_sinks,
1493            "sink",
1494            MAX_SINKS.name(),
1495        )?;
1496        self.validate_resource_limit(
1497            self.catalog().user_materialized_views().count(),
1498            new_materialized_views,
1499            SystemVars::max_materialized_views,
1500            "materialized view",
1501            MAX_MATERIALIZED_VIEWS.name(),
1502        )?;
1503        self.validate_resource_limit(
1504            // Linked compute clusters don't count against the limit, since
1505            // we have a separate sources and sinks limit.
1506            //
1507            // TODO(benesch): remove the `max_sources` and `max_sinks` limit,
1508            // and set a higher max cluster limit?
1509            self.catalog().user_clusters().count(),
1510            new_clusters,
1511            SystemVars::max_clusters,
1512            "cluster",
1513            MAX_CLUSTERS.name(),
1514        )?;
1515        for (cluster_id, new_replicas) in new_replicas_per_cluster {
1516            // It's possible that the cluster hasn't been created yet.
1517            let current_amount = self
1518                .catalog()
1519                .try_get_cluster(cluster_id)
1520                .map(|instance| instance.user_replicas().count())
1521                .unwrap_or(0);
1522            self.validate_resource_limit(
1523                current_amount,
1524                new_replicas,
1525                SystemVars::max_replicas_per_cluster,
1526                "cluster replica",
1527                MAX_REPLICAS_PER_CLUSTER.name(),
1528            )?;
1529        }
1530        self.validate_resource_limit_numeric(
1531            self.current_credit_consumption_rate(None),
1532            new_credit_consumption_rate,
1533            |system_vars| {
1534                self.license_key
1535                    .max_credit_consumption_rate()
1536                    .map_or_else(|| system_vars.max_credit_consumption_rate(), Numeric::from)
1537            },
1538            "cluster replica",
1539            MAX_CREDIT_CONSUMPTION_RATE.name(),
1540        )?;
1541        self.validate_resource_limit(
1542            self.catalog().databases().count(),
1543            new_databases,
1544            SystemVars::max_databases,
1545            "database",
1546            MAX_DATABASES.name(),
1547        )?;
1548        for (database_id, new_schemas) in new_schemas_per_database {
1549            self.validate_resource_limit(
1550                self.catalog().get_database(database_id).schemas_by_id.len(),
1551                new_schemas,
1552                SystemVars::max_schemas_per_database,
1553                "schema",
1554                MAX_SCHEMAS_PER_DATABASE.name(),
1555            )?;
1556        }
1557        for ((database_spec, schema_spec), new_objects) in new_objects_per_schema {
1558            // For temporary schemas that don't exist yet (lazy creation),
1559            // treat them as having 0 items.
1560            let current_items = self
1561                .catalog()
1562                .try_get_schema(&database_spec, &schema_spec, conn_id)
1563                .map(|schema| schema.items.len())
1564                .unwrap_or(0);
1565            self.validate_resource_limit(
1566                current_items,
1567                new_objects,
1568                SystemVars::max_objects_per_schema,
1569                "object",
1570                MAX_OBJECTS_PER_SCHEMA.name(),
1571            )?;
1572        }
1573        self.validate_resource_limit(
1574            self.catalog().user_secrets().count(),
1575            new_secrets,
1576            SystemVars::max_secrets,
1577            "secret",
1578            MAX_SECRETS.name(),
1579        )?;
1580        self.validate_resource_limit(
1581            self.catalog().user_roles().count(),
1582            new_roles,
1583            SystemVars::max_roles,
1584            "role",
1585            MAX_ROLES.name(),
1586        )?;
1587        self.validate_resource_limit(
1588            self.catalog().user_network_policies().count(),
1589            new_network_policies,
1590            SystemVars::max_network_policies,
1591            "network_policy",
1592            MAX_NETWORK_POLICIES.name(),
1593        )?;
1594        Ok(())
1595    }
1596
1597    /// Validate a specific type of resource limit and return an error if that limit is exceeded.
1598    pub(crate) fn validate_resource_limit<F>(
1599        &self,
1600        current_amount: usize,
1601        new_instances: i64,
1602        resource_limit: F,
1603        resource_type: &str,
1604        limit_name: &str,
1605    ) -> Result<(), AdapterError>
1606    where
1607        F: Fn(&SystemVars) -> u32,
1608    {
1609        if new_instances <= 0 {
1610            return Ok(());
1611        }
1612
1613        let limit: i64 = resource_limit(self.catalog().system_config()).into();
1614        let current_amount: Option<i64> = current_amount.try_into().ok();
1615        let desired =
1616            current_amount.and_then(|current_amount| current_amount.checked_add(new_instances));
1617
1618        let exceeds_limit = if let Some(desired) = desired {
1619            desired > limit
1620        } else {
1621            true
1622        };
1623
1624        let desired = desired
1625            .map(|desired| desired.to_string())
1626            .unwrap_or_else(|| format!("more than {}", i64::MAX));
1627        let current = current_amount
1628            .map(|current| current.to_string())
1629            .unwrap_or_else(|| format!("more than {}", i64::MAX));
1630        if exceeds_limit {
1631            Err(AdapterError::ResourceExhaustion {
1632                resource_type: resource_type.to_string(),
1633                limit_name: limit_name.to_string(),
1634                desired,
1635                limit: limit.to_string(),
1636                current,
1637            })
1638        } else {
1639            Ok(())
1640        }
1641    }
1642
1643    /// Validate a specific type of float resource limit and return an error if that limit is exceeded.
1644    ///
1645    /// This is very similar to [`Self::validate_resource_limit`] but for numerics.
1646    pub(crate) fn validate_resource_limit_numeric<F>(
1647        &self,
1648        current_amount: Numeric,
1649        new_amount: Numeric,
1650        resource_limit: F,
1651        resource_type: &str,
1652        limit_name: &str,
1653    ) -> Result<(), AdapterError>
1654    where
1655        F: Fn(&SystemVars) -> Numeric,
1656    {
1657        if new_amount <= Numeric::zero() {
1658            return Ok(());
1659        }
1660
1661        let limit = resource_limit(self.catalog().system_config());
1662        // Floats will overflow to infinity instead of panicking, which has the correct comparison
1663        // semantics.
1664        // NaN should be impossible here since both values are positive.
1665        let desired = current_amount + new_amount;
1666        if desired > limit {
1667            Err(AdapterError::ResourceExhaustion {
1668                resource_type: resource_type.to_string(),
1669                limit_name: limit_name.to_string(),
1670                desired: desired.to_string(),
1671                limit: limit.to_string(),
1672                current: current_amount.to_string(),
1673            })
1674        } else {
1675            Ok(())
1676        }
1677    }
1678}