Skip to main content

mz_adapter/coord/
catalog_implications.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//! Logic related to deriving and applying implications from [catalog
11//! changes](ParsedStateUpdate).
12//!
13//! The flow from "raw" catalog changes to [CatalogImplication] works like this:
14//!
15//! StateUpdateKind -> ParsedStateUpdate -> CatalogImplication
16//!
17//! [ParsedStateUpdate] adds context to a "raw" catalog change
18//! ([StateUpdateKind](mz_catalog::memory::objects::StateUpdateKind)). It
19//! includes an in-memory representation of the updated object, which can in
20//! theory be derived from the raw change but only when we have access to all
21//! the other raw changes or to an in-memory Catalog, which represents a
22//! "rollup" of all the raw changes.
23//!
24//! [CatalogImplication] is both the state machine that we use for absorbing
25//! multiple state updates for the same object and the final command that has to
26//! be applied to in-memory state and or the controller(s) after absorbing all
27//! the state updates in a given batch of updates.
28
29use std::collections::{BTreeMap, BTreeSet};
30use std::sync::Arc;
31use std::time::{Duration, Instant};
32
33use fail::fail_point;
34use itertools::Itertools;
35use mz_adapter_types::compaction::CompactionWindow;
36use mz_catalog::memory::objects::{
37    CatalogItem, Cluster, ClusterReplica, Connection, DataSourceDesc, Index, MaterializedView,
38    MetricSink, Secret, Sink, Source, StateDiff, Table, TableDataSource, View,
39};
40use mz_cloud_resources::VpcEndpointConfig;
41use mz_compute_client::logging::LogVariant;
42use mz_controller::clusters::{ClusterRole, ReplicaConfig};
43use mz_controller_types::{ClusterId, ReplicaId};
44use mz_ore::collections::CollectionExt;
45use mz_ore::error::ErrorExt;
46use mz_ore::future::InTask;
47use mz_ore::instrument;
48use mz_ore::retry::Retry;
49use mz_ore::task;
50use mz_repr::{CatalogItemId, GlobalId, RelationVersion, RelationVersionSelector};
51use mz_sql::plan::ConnectionDetails;
52use mz_storage_client::controller::{CollectionDescription, DataSource};
53use mz_storage_types::connections::PostgresConnection;
54use mz_storage_types::connections::inline::{InlinedConnection, IntoInlineConnection};
55use mz_storage_types::sinks::StorageSinkConnection;
56use mz_storage_types::sources::{
57    GenericSourceConnection, SourceDesc, SourceExport, SourceExportDataConfig,
58};
59use tracing::{Instrument, info_span, warn};
60
61use crate::active_compute_sink::ActiveComputeSinkRetireReason;
62use crate::coord::Coordinator;
63use crate::coord::catalog_implications::parsed_state_updates::{
64    ParsedStateUpdate, ParsedStateUpdateKind,
65};
66use crate::coord::peek::DroppedDependency;
67use crate::coord::timeline::TimelineState;
68use crate::statement_logging::StatementLoggingId;
69use crate::{AdapterError, CollectionIdBundle, ExecuteContext, ResultExt};
70
71pub mod parsed_state_updates;
72
73impl Coordinator {
74    /// Applies implications from the given bucket of [ParsedStateUpdate] to our
75    /// in-memory state and our controllers. This also applies transitive
76    /// implications, for example, peeks and subscribes will be cancelled when
77    /// referenced objects are dropped.
78    ///
79    /// This _requires_ that the given updates are consolidated. There must be
80    /// at most one addition and/or one retraction for a given item, as
81    /// identified by that items ID type.
82    #[instrument(level = "debug")]
83    pub async fn apply_catalog_implications(
84        &mut self,
85        ctx: Option<&mut ExecuteContext>,
86        catalog_updates: Vec<ParsedStateUpdate>,
87    ) -> Result<(), AdapterError> {
88        let start = Instant::now();
89
90        for id in webhook_sources_to_restart(&catalog_updates) {
91            self.active_webhooks.remove(&id);
92        }
93
94        let mut catalog_implications: BTreeMap<CatalogItemId, CatalogImplication> = BTreeMap::new();
95        let mut cluster_commands: BTreeMap<ClusterId, CatalogImplication> = BTreeMap::new();
96        let mut cluster_replica_commands: BTreeMap<(ClusterId, ReplicaId), CatalogImplication> =
97            BTreeMap::new();
98        // Introspection source index additions, collected separately and
99        // merged into the AddCluster handler. Not routed through the
100        // absorb machinery since they are simple additions that don't
101        // need Altered support.
102        let mut introspection_source_indexes: BTreeMap<ClusterId, BTreeMap<LogVariant, GlobalId>> =
103            BTreeMap::new();
104        // Whether any replica-scoped system-parameter override changed in this
105        // batch. The push re-pushes the complete per-replica dyncfg layer, so we
106        // only track that a change happened, not the individual rows.
107        let mut replica_scoped_config_changed = false;
108        // Whether any environment-wide system-parameter changed in this batch.
109        // We re-run all `SystemVars` callbacks against the committed values, so
110        // we only track that a change happened, not the individual vars.
111        let mut system_config_changed = false;
112
113        // Whether to wake the cluster controller once the implications below are
114        // applied. Decided from the committed diff, see the method.
115        let should_reconcile_now = Self::should_reconcile_now(&catalog_updates);
116
117        for update in catalog_updates {
118            tracing::trace!(?update, "got parsed state update");
119            match &update.kind {
120                ParsedStateUpdateKind::Item {
121                    durable_item,
122                    parsed_item: _,
123                    connection: _,
124                    parsed_full_name: _,
125                } => {
126                    let entry = catalog_implications
127                        .entry(durable_item.id.clone())
128                        .or_insert_with(|| CatalogImplication::None);
129                    entry.absorb(update);
130                }
131                ParsedStateUpdateKind::Cluster {
132                    durable_cluster,
133                    parsed_cluster: _,
134                } => {
135                    let entry = cluster_commands
136                        .entry(durable_cluster.id)
137                        .or_insert_with(|| CatalogImplication::None);
138                    entry.absorb(update.clone());
139                }
140                ParsedStateUpdateKind::ClusterReplica {
141                    durable_cluster_replica,
142                    parsed_cluster_replica: _,
143                } => {
144                    let entry = cluster_replica_commands
145                        .entry((
146                            durable_cluster_replica.cluster_id,
147                            durable_cluster_replica.replica_id,
148                        ))
149                        .or_insert_with(|| CatalogImplication::None);
150                    entry.absorb(update.clone());
151                }
152                ParsedStateUpdateKind::IntrospectionSourceIndex {
153                    cluster_id,
154                    log,
155                    index_id,
156                } => {
157                    if update.diff == StateDiff::Addition {
158                        introspection_source_indexes
159                            .entry(*cluster_id)
160                            .or_default()
161                            .insert(log.clone(), *index_id);
162                    }
163                    // Retractions don't need handling: introspection
164                    // source indexes are dropped with their cluster.
165                }
166                ParsedStateUpdateKind::ReplicaSystemConfiguration { durable: _ } => {
167                    // Additions and retractions both re-derive the full
168                    // per-replica layer from the working copy, so the diff sign
169                    // does not matter here.
170                    replica_scoped_config_changed = true;
171                }
172                ParsedStateUpdateKind::SystemConfiguration { durable: _ } => {
173                    // Additions and retractions both re-run the callbacks
174                    // against the committed values, so the diff sign does not
175                    // matter here.
176                    system_config_changed = true;
177                }
178            }
179        }
180
181        self.apply_catalog_implications_inner(
182            ctx,
183            catalog_implications.into_iter().collect_vec(),
184            cluster_commands.into_iter().collect_vec(),
185            cluster_replica_commands.into_iter().collect_vec(),
186            introspection_source_indexes,
187            replica_scoped_config_changed,
188            system_config_changed,
189        )
190        .await?;
191
192        if should_reconcile_now {
193            // Wake the controller to reconcile immediately rather than waiting
194            // out its tick interval. A missed or spurious wake is harmless: the
195            // periodic tick is the backstop, and an extra wake costs one no-op
196            // reconcile.
197            self.reconcile_now.notify_one();
198        }
199
200        self.metrics
201            .apply_catalog_implications_seconds
202            .observe(start.elapsed().as_secs_f64());
203
204        Ok(())
205    }
206
207    /// Whether a batch of committed catalog updates should wake the cluster
208    /// controller. True when any cluster or cluster-replica durable state
209    /// changed, the only catalog changes the controller reconciles against.
210    ///
211    /// We key the wake off the committed diff rather than the input ops so it
212    /// fires the same way whether this node applied the change or is following
213    /// another writer's diff. NOTE: environment-wide system-config changes (the
214    /// controller's gate and tick interval) do parse into
215    /// `ParsedStateUpdateKind::SystemConfiguration`, but we deliberately do not
216    /// match on them here, so they do not wake the controller. The controller
217    /// re-reads both each tick, so a config change is picked up on the next tick
218    /// without a wake.
219    fn should_reconcile_now(updates: &[ParsedStateUpdate]) -> bool {
220        updates.iter().any(|update| {
221            matches!(
222                update.kind,
223                ParsedStateUpdateKind::Cluster { .. }
224                    | ParsedStateUpdateKind::ClusterReplica { .. }
225            )
226        })
227    }
228
229    #[instrument(level = "debug")]
230    async fn apply_catalog_implications_inner(
231        &mut self,
232        ctx: Option<&mut ExecuteContext>,
233        implications: Vec<(CatalogItemId, CatalogImplication)>,
234        cluster_commands: Vec<(ClusterId, CatalogImplication)>,
235        cluster_replica_commands: Vec<((ClusterId, ReplicaId), CatalogImplication)>,
236        mut introspection_source_indexes: BTreeMap<ClusterId, BTreeMap<LogVariant, GlobalId>>,
237        replica_scoped_config_changed: bool,
238        system_config_changed: bool,
239    ) -> Result<(), AdapterError> {
240        // Re-run the `SystemVars` callbacks against the committed values.
241        // Deriving this from the committed diff, rather than the input ops, is
242        // what makes it also fire on a follower `environmentd` that only
243        // replays the catalog changes. The callbacks are order-independent
244        // idempotent reads, so we fire them once, up front.
245        if system_config_changed {
246            self.catalog().system_config().notify_all_callbacks();
247        }
248
249        let mut tables_to_drop = BTreeSet::new();
250        let mut sources_to_drop = vec![];
251        let mut replication_slots_to_drop: Vec<(PostgresConnection, String)> = vec![];
252        let mut storage_sink_gids_to_drop = vec![];
253        let mut indexes_to_drop = vec![];
254        let mut compute_sinks_to_drop = vec![];
255        let mut view_gids_to_drop = vec![];
256        let mut secrets_to_drop = vec![];
257        let mut vpc_endpoints_to_drop = vec![];
258        let mut clusters_to_drop = vec![];
259        let mut cluster_replicas_to_drop = vec![];
260        let mut cluster_replicas_to_create = vec![];
261        let mut active_compute_sinks_to_drop = BTreeMap::new();
262        let mut copies_to_drop = vec![];
263
264        // Maps for storing names of dropped objects for error messages.
265        let mut dropped_item_names: BTreeMap<GlobalId, String> = BTreeMap::new();
266        let mut dropped_cluster_names: BTreeMap<ClusterId, String> = BTreeMap::new();
267
268        // Separate collections for tables (which need write timestamps) and
269        // sources (which don't).
270        let mut table_collections_to_create = BTreeMap::new();
271        let mut source_collections_to_create = BTreeMap::new();
272        let mut storage_policies_to_initialize = BTreeMap::new();
273        let mut execution_timestamps_to_set = BTreeSet::new();
274        let mut vpc_endpoints_to_create: Vec<(CatalogItemId, VpcEndpointConfig)> = vec![];
275
276        // Sources that shouldn't be dropped, even if we saw a `Dropped` event.
277        // Used for correct handling of ALTER MV.
278        let mut source_gids_to_keep = BTreeSet::new();
279
280        // Collections for batching connection-related alterations.
281        let mut source_connections_to_alter: BTreeMap<
282            GlobalId,
283            GenericSourceConnection<InlinedConnection>,
284        > = BTreeMap::new();
285        let mut sink_connections_to_alter: BTreeMap<GlobalId, StorageSinkConnection> =
286            BTreeMap::new();
287        let mut source_export_data_configs_to_alter: BTreeMap<GlobalId, SourceExportDataConfig> =
288            BTreeMap::new();
289        let mut source_descs_to_alter: BTreeMap<GlobalId, SourceDesc> = BTreeMap::new();
290
291        // We're incrementally migrating the code that manipulates the
292        // controller from closures in the sequencer. For some types of catalog
293        // changes we haven't done this migration yet, so there you will see
294        // just a log message. Over the next couple of PRs all of these will go
295        // away.
296
297        for (catalog_id, implication) in implications {
298            tracing::trace!(?implication, "have to apply catalog implication");
299
300            match implication {
301                CatalogImplication::Table(CatalogImplicationKind::Added(table)) => {
302                    self.handle_create_table(
303                        &ctx,
304                        &mut table_collections_to_create,
305                        &mut storage_policies_to_initialize,
306                        &mut execution_timestamps_to_set,
307                        catalog_id,
308                        table.clone(),
309                    )
310                    .await?
311                }
312                CatalogImplication::Table(CatalogImplicationKind::Altered {
313                    prev: prev_table,
314                    new: new_table,
315                }) => {
316                    self.handle_alter_table(catalog_id, prev_table, new_table)
317                        .await?
318                }
319
320                CatalogImplication::Table(CatalogImplicationKind::Dropped(table, full_name)) => {
321                    let global_ids = table.global_ids();
322                    for global_id in global_ids {
323                        tables_to_drop.insert((catalog_id, global_id));
324                        dropped_item_names.insert(global_id, full_name.clone());
325                    }
326                }
327                CatalogImplication::Source(CatalogImplicationKind::Added((
328                    source,
329                    _connection,
330                ))) => {
331                    // Get the compaction windows for all sources with this
332                    // catalog_id This replicates the logic from
333                    // sequence_create_source where it collects all item_ids and
334                    // gets their compaction windows
335                    let compaction_windows = self
336                        .catalog()
337                        .state()
338                        .source_compaction_windows(vec![catalog_id]);
339
340                    self.handle_create_source(
341                        &mut source_collections_to_create,
342                        &mut storage_policies_to_initialize,
343                        catalog_id,
344                        source,
345                        compaction_windows,
346                    )
347                    .await?
348                }
349                CatalogImplication::Source(CatalogImplicationKind::Altered {
350                    prev: (prev_source, _prev_connection),
351                    new: (new_source, new_connection),
352                }) => {
353                    if prev_source.custom_logical_compaction_window
354                        != new_source.custom_logical_compaction_window
355                    {
356                        let new_window = new_source
357                            .custom_logical_compaction_window
358                            .unwrap_or(CompactionWindow::Default);
359                        self.update_storage_read_policies(vec![(catalog_id, new_window.into())]);
360                    }
361                    match (&prev_source.data_source, &new_source.data_source) {
362                        (
363                            DataSourceDesc::Ingestion {
364                                desc: prev_desc, ..
365                            }
366                            | DataSourceDesc::OldSyntaxIngestion {
367                                desc: prev_desc, ..
368                            },
369                            DataSourceDesc::Ingestion { desc: new_desc, .. }
370                            | DataSourceDesc::OldSyntaxIngestion { desc: new_desc, .. },
371                        ) => {
372                            if prev_desc != new_desc {
373                                let inlined_connection = new_connection
374                                    .expect("ingestion source should have inlined connection");
375                                let inlined_desc = SourceDesc {
376                                    connection: inlined_connection,
377                                    timestamp_interval: new_desc.timestamp_interval,
378                                };
379                                source_descs_to_alter.insert(new_source.global_id, inlined_desc);
380                            }
381                        }
382                        _ => {}
383                    }
384                }
385                CatalogImplication::Source(CatalogImplicationKind::Dropped(
386                    (source, connection),
387                    full_name,
388                )) => {
389                    let global_id = source.global_id();
390                    sources_to_drop.push((catalog_id, global_id));
391                    dropped_item_names.insert(global_id, full_name);
392
393                    if let DataSourceDesc::Ingestion { desc, .. }
394                    | DataSourceDesc::OldSyntaxIngestion { desc, .. } = &source.data_source
395                    {
396                        match &desc.connection {
397                            GenericSourceConnection::Postgres(_referenced_conn) => {
398                                let inline_conn = connection.expect("missing inlined connection");
399
400                                let pg_conn = match inline_conn {
401                                    GenericSourceConnection::Postgres(pg_conn) => pg_conn,
402                                    other => {
403                                        panic!("expected postgres connection, got: {:?}", other)
404                                    }
405                                };
406                                let pending_drop = (
407                                    pg_conn.connection.clone(),
408                                    pg_conn.publication_details.slot.clone(),
409                                );
410                                replication_slots_to_drop.push(pending_drop);
411                            }
412                            _ => {}
413                        }
414                    }
415                }
416                CatalogImplication::Sink(CatalogImplicationKind::Added(sink)) => {
417                    tracing::debug!(?sink, "not handling AddSink in here yet");
418                }
419                CatalogImplication::Sink(CatalogImplicationKind::Altered {
420                    prev: prev_sink,
421                    new: new_sink,
422                }) => {
423                    tracing::debug!(?prev_sink, ?new_sink, "not handling AlterSink in here yet");
424                }
425                CatalogImplication::Sink(CatalogImplicationKind::Dropped(sink, full_name)) => {
426                    storage_sink_gids_to_drop.push(sink.global_id());
427                    dropped_item_names.insert(sink.global_id(), full_name);
428                }
429                CatalogImplication::Index(CatalogImplicationKind::Added(index)) => {
430                    tracing::debug!(?index, "not handling AddIndex in here yet");
431                }
432                CatalogImplication::Index(CatalogImplicationKind::Altered {
433                    prev: prev_index,
434                    new: new_index,
435                }) => {
436                    if prev_index.custom_logical_compaction_window
437                        != new_index.custom_logical_compaction_window
438                    {
439                        let new_window = new_index
440                            .custom_logical_compaction_window
441                            .unwrap_or(CompactionWindow::Default);
442                        self.update_compute_read_policy(
443                            new_index.cluster_id,
444                            catalog_id,
445                            new_window.into(),
446                        );
447                    }
448                }
449                CatalogImplication::Index(CatalogImplicationKind::Dropped(index, full_name)) => {
450                    indexes_to_drop.push((index.cluster_id, index.global_id()));
451                    dropped_item_names.insert(index.global_id(), full_name);
452                }
453                CatalogImplication::MetricSink(CatalogImplicationKind::Added(_metric_sink)) => {
454                    // Nothing to do, mirroring `Index`: shipping the dataflow at create time is
455                    // the sequencer's job (`create_metric_sink_finish`), and re-rendering it after
456                    // a restart happens during bootstrap (`bootstrap_dataflow_plans`).
457                }
458                CatalogImplication::MetricSink(CatalogImplicationKind::Altered { .. }) => {
459                    // Nothing to do: owner, privilege, and rename changes are catalog-only.
460                }
461                CatalogImplication::MetricSink(CatalogImplicationKind::Dropped(
462                    metric_sink,
463                    full_name,
464                )) => {
465                    // A metric sink is a non-readable leaf compute dataflow, like an MV's write
466                    // side, so it drops through the same path as other compute sinks.
467                    compute_sinks_to_drop.push((metric_sink.cluster_id, metric_sink.global_id));
468                    dropped_item_names.insert(metric_sink.global_id, full_name);
469                }
470                CatalogImplication::MaterializedView(CatalogImplicationKind::Added(mv)) => {
471                    tracing::debug!(?mv, "not handling AddMaterializedView in here yet");
472                }
473                CatalogImplication::MaterializedView(CatalogImplicationKind::Altered {
474                    prev: prev_mv,
475                    new: new_mv,
476                }) => {
477                    // We get here for three reasons:
478                    //  1. Name changes, like those caused by ALTER SCHEMA.
479                    //  2. Replacement application.
480                    //  3. Compaction window changes (ALTER ... SET (RETAIN HISTORY ...)).
481                    //
482                    // 1. Name changes: We don't have to do anything here.
483                    //
484                    // 2. Replacement application: This is tricky: It changes the `CatalogItemId` of
485                    // the target to that of the replacement and simultaneously drops the replacement.
486                    // Which means when we get here `prev_mv` is the replacement that should be
487                    // dropped, and `new_mv` is the target that already exists but under a different
488                    // ID (which will receive a `Dropped` event separately). We can sniff out this
489                    // case by checking for version differences.
490                    //
491                    // 3. Compaction window changes: We handle this in an `else if`, because if there
492                    // is also a replacement application, then the replacement's storage collections
493                    // already have the correct read policies from when they were created, so we
494                    // don't need to update them here.
495                    if prev_mv.collections != new_mv.collections {
496                        // Sanity check: The replacement's last (and only) version must be the same
497                        // as the new target's last version.
498                        assert_eq!(
499                            prev_mv.global_id_writes(),
500                            new_mv.global_id_writes(),
501                            "unexpected MV Altered implication: prev={prev_mv:?}, new={new_mv:?}",
502                        );
503
504                        let gid = new_mv.global_id_writes();
505                        self.allow_writes(new_mv.cluster_id, gid);
506
507                        // There will be a separate `Dropped` implication for the old definition of
508                        // the target MV. That will drop the old compute collection, as we desire,
509                        // but we need to prevent it from dropping the old storage collection as
510                        // well, since that might still be depended on.
511                        source_gids_to_keep.extend(new_mv.global_ids());
512                    } else if prev_mv.custom_logical_compaction_window
513                        != new_mv.custom_logical_compaction_window
514                    {
515                        let new_window = new_mv
516                            .custom_logical_compaction_window
517                            .unwrap_or(CompactionWindow::Default);
518                        self.update_storage_read_policies(vec![(catalog_id, new_window.into())]);
519                    }
520                }
521                CatalogImplication::MaterializedView(CatalogImplicationKind::Dropped(
522                    mv,
523                    full_name,
524                )) => {
525                    compute_sinks_to_drop.push((mv.cluster_id, mv.global_id_writes()));
526                    for gid in mv.global_ids() {
527                        sources_to_drop.push((catalog_id, gid));
528                        dropped_item_names.insert(gid, full_name.clone());
529                    }
530                }
531                CatalogImplication::View(CatalogImplicationKind::Added(_view)) => {
532                    // No action needed: views are catalog-only objects with no
533                    // storage collections or dataflows to create.
534                }
535                CatalogImplication::View(CatalogImplicationKind::Altered {
536                    prev: _prev_view,
537                    new: _new_view,
538                }) => {
539                    // No action needed: view alterations (e.g. renames) are
540                    // catalog-only and require no controller changes.
541                }
542                CatalogImplication::View(CatalogImplicationKind::Dropped(view, full_name)) => {
543                    view_gids_to_drop.push(view.global_id());
544                    dropped_item_names.insert(view.global_id(), full_name);
545                }
546                CatalogImplication::Secret(CatalogImplicationKind::Added(_secret)) => {
547                    // No action needed: the secret payload is stored in
548                    // secrets_controller.ensure() BEFORE the catalog transaction.
549                    // By the time we see this update, the secret is already stored.
550                }
551                CatalogImplication::Secret(CatalogImplicationKind::Altered {
552                    prev: _prev_secret,
553                    new: _new_secret,
554                }) => {
555                    // No action needed: altering a secret updates the payload via
556                    // secrets_controller.ensure() without a catalog transaction.
557                }
558                CatalogImplication::Secret(CatalogImplicationKind::Dropped(
559                    _secret,
560                    _full_name,
561                )) => {
562                    secrets_to_drop.push(catalog_id);
563                }
564                CatalogImplication::Connection(CatalogImplicationKind::Added(connection)) => {
565                    match &connection.details {
566                        // SSH connections: key pair is stored in secrets_controller
567                        // BEFORE the catalog transaction, so no action needed here.
568                        ConnectionDetails::Ssh { .. } => {}
569                        // AWS PrivateLink connections: create the VPC endpoint
570                        ConnectionDetails::AwsPrivatelink(privatelink) => {
571                            let spec = VpcEndpointConfig {
572                                aws_service_name: privatelink.service_name.to_owned(),
573                                availability_zone_ids: privatelink.availability_zones.to_owned(),
574                            };
575                            vpc_endpoints_to_create.push((catalog_id, spec));
576                        }
577                        // Other connection types don't require post-transaction actions
578                        _ => {}
579                    }
580                }
581                CatalogImplication::Connection(CatalogImplicationKind::Altered {
582                    prev: _prev_connection,
583                    new: new_connection,
584                }) => {
585                    self.handle_alter_connection(
586                        catalog_id,
587                        new_connection,
588                        &mut vpc_endpoints_to_create,
589                        &mut source_connections_to_alter,
590                        &mut sink_connections_to_alter,
591                        &mut source_export_data_configs_to_alter,
592                    );
593                }
594                CatalogImplication::Connection(CatalogImplicationKind::Dropped(
595                    connection,
596                    _full_name,
597                )) => {
598                    match &connection.details {
599                        // SSH connections have an associated secret that should be dropped
600                        ConnectionDetails::Ssh { .. } => {
601                            secrets_to_drop.push(catalog_id);
602                        }
603                        // AWS PrivateLink connections have an associated
604                        // VpcEndpoint K8S resource that should be dropped
605                        ConnectionDetails::AwsPrivatelink(_) => {
606                            vpc_endpoints_to_drop.push(catalog_id);
607                        }
608                        _ => (),
609                    }
610                }
611                CatalogImplication::None => {
612                    // Nothing to do for None commands
613                }
614                CatalogImplication::Cluster(_) | CatalogImplication::ClusterReplica(_) => {
615                    unreachable!("clusters and cluster replicas are handled below")
616                }
617                CatalogImplication::Table(CatalogImplicationKind::None)
618                | CatalogImplication::Source(CatalogImplicationKind::None)
619                | CatalogImplication::Sink(CatalogImplicationKind::None)
620                | CatalogImplication::Index(CatalogImplicationKind::None)
621                | CatalogImplication::MetricSink(CatalogImplicationKind::None)
622                | CatalogImplication::MaterializedView(CatalogImplicationKind::None)
623                | CatalogImplication::View(CatalogImplicationKind::None)
624                | CatalogImplication::Secret(CatalogImplicationKind::None)
625                | CatalogImplication::Connection(CatalogImplicationKind::None) => {
626                    unreachable!("will never leave None in place");
627                }
628            }
629        }
630
631        for (cluster_id, command) in cluster_commands {
632            tracing::trace!(?command, "have cluster command to apply!");
633
634            match command {
635                CatalogImplication::Cluster(CatalogImplicationKind::Added(cluster)) => {
636                    // The Cluster's log_indexes is empty at parse time
637                    // because IntrospectionSourceIndex updates are applied
638                    // after the Cluster update. Use the separately collected
639                    // introspection_source_indexes instead.
640                    let arranged_logs = introspection_source_indexes
641                        .remove(&cluster_id)
642                        .unwrap_or_default();
643                    let introspection_source_ids: Vec<_> =
644                        arranged_logs.values().copied().collect();
645
646                    self.controller
647                        .create_cluster(
648                            cluster_id,
649                            mz_controller::clusters::ClusterConfig {
650                                arranged_logs,
651                                workload_class: cluster.config.workload_class.clone(),
652                            },
653                        )
654                        .expect("creating cluster must not fail");
655
656                    if !introspection_source_ids.is_empty() {
657                        self.initialize_compute_read_policies(
658                            introspection_source_ids,
659                            cluster_id,
660                            CompactionWindow::Default,
661                        )
662                        .await;
663                    }
664                }
665                CatalogImplication::Cluster(CatalogImplicationKind::Altered {
666                    prev: prev_cluster,
667                    new: new_cluster,
668                }) => {
669                    // Replica adds/drops/renames from config changes arrive as
670                    // separate AddClusterReplica/DroppedClusterReplica/
671                    // AlterClusterReplica events, so the only cluster-level
672                    // side effect here is updating the workload class on the
673                    // controller when it changes.
674                    if prev_cluster.config.workload_class != new_cluster.config.workload_class {
675                        self.controller.update_cluster_workload_class(
676                            cluster_id,
677                            new_cluster.config.workload_class.clone(),
678                        );
679                    }
680                }
681                CatalogImplication::Cluster(CatalogImplicationKind::Dropped(
682                    cluster,
683                    _full_name,
684                )) => {
685                    clusters_to_drop.push(cluster_id);
686                    dropped_cluster_names.insert(cluster_id, cluster.name);
687                }
688                CatalogImplication::Cluster(CatalogImplicationKind::None) => {
689                    unreachable!("will never leave None in place");
690                }
691                command => {
692                    unreachable!(
693                        "we only handle cluster commands in this map, got: {:?}",
694                        command
695                    );
696                }
697            }
698        }
699
700        // Apply replica-scoped overrides after clusters are created (so their
701        // compute instances exist) but before replicas are created below. The
702        // override layer must be set before `create_replica`, so the new
703        // replica's first configuration replays with its override, and so the
704        // configuration the controller freezes into the replica's process at
705        // provisioning time resolves against it. The push reads the catalog
706        // working copy, which already reflects this transaction's scoped-config
707        // changes.
708        if replica_scoped_config_changed {
709            self.push_replica_dyncfg_overrides();
710        }
711
712        for ((cluster_id, replica_id), command) in cluster_replica_commands {
713            tracing::trace!(?command, "have cluster replica command to apply!");
714
715            match command {
716                CatalogImplication::ClusterReplica(CatalogImplicationKind::Added(replica)) => {
717                    // Read the cluster name and role from the current catalog
718                    // state. This is correct as long as implications are
719                    // processed right after each catalog transaction. For a
720                    // more future-proof approach that tracks cluster info
721                    // locally across transactions, see the last commit of
722                    // https://github.com/ggevay/materialize/tree/implications-cluster-name-tracking
723                    // which removes that logic.
724                    let cluster = self.catalog().get_cluster(cluster_id);
725                    let cluster_name = cluster.name.clone();
726                    let cluster_role = cluster.role();
727                    cluster_replicas_to_create.push((
728                        cluster_id,
729                        replica_id,
730                        cluster_role,
731                        cluster_name,
732                        replica.name.clone(),
733                        replica.config.clone(),
734                    ));
735                }
736                CatalogImplication::ClusterReplica(CatalogImplicationKind::Altered {
737                    prev: _prev_replica,
738                    new: _new_replica,
739                }) => {
740                    // No action needed: cluster replica alterations (e.g.
741                    // renames, owner changes, pending flag changes) are
742                    // catalog-only and require no controller changes.
743                }
744                CatalogImplication::ClusterReplica(CatalogImplicationKind::Dropped(
745                    _replica,
746                    _full_name,
747                )) => {
748                    cluster_replicas_to_drop.push((cluster_id, replica_id));
749                }
750                CatalogImplication::ClusterReplica(CatalogImplicationKind::None) => {
751                    unreachable!("will never leave None in place");
752                }
753                command => {
754                    unreachable!(
755                        "we only handle cluster replica commands in this map, got: {:?}",
756                        command
757                    );
758                }
759            }
760        }
761
762        let clusters_with_replica_creates = cluster_replicas_to_create
763            .iter()
764            .map(|(cluster_id, ..)| *cluster_id)
765            .collect();
766        let (replacement_drops, deferred_drops) = partition_cluster_replica_drops(
767            &clusters_with_replica_creates,
768            cluster_replicas_to_drop,
769        );
770        cluster_replicas_to_drop = deferred_drops;
771
772        // A same-cluster mixed drop/create batch replaces the replica set, as a
773        // forced cut-over does. Catalog resource accounting charges its net, so
774        // controller side effects must preserve the same contract. Queue the
775        // old replicas' drops before creates. If orchestration needs time to
776        // release a physical quota, a later ensure can retry without blocking
777        // the drop behind it.
778        if !replacement_drops.is_empty() {
779            fail::fail_point!("after_catalog_drop_replica");
780            for (cluster_id, replica_id) in replacement_drops {
781                self.drop_replica(cluster_id, replica_id);
782            }
783        }
784        for (cluster_id, replica_id, role, cluster_name, replica_name, config) in
785            cluster_replicas_to_create
786        {
787            self.handle_create_cluster_replica(
788                cluster_id,
789                replica_id,
790                role,
791                cluster_name,
792                replica_name,
793                config,
794            )
795            .await;
796        }
797
798        if !source_collections_to_create.is_empty() {
799            self.create_source_collections(source_collections_to_create)
800                .await?;
801        }
802
803        // Have to create sources first and then tables, because tables within
804        // one transaction can depend on sources.
805        if !table_collections_to_create.is_empty() {
806            self.create_table_collections(table_collections_to_create, execution_timestamps_to_set)
807                .await?;
808        }
809        // It is _very_ important that we only initialize read policies after we
810        // have created all the sources/collections. Some of the sources created
811        // in this collection might have dependencies on other sources, so the
812        // controller must get a chance to install read holds before we set a
813        // policy that might make the since advance.
814        self.initialize_storage_collections(storage_policies_to_initialize)
815            .await?;
816
817        // Create VPC endpoints for AWS PrivateLink connections
818        if !vpc_endpoints_to_create.is_empty() {
819            if let Some(cloud_resource_controller) = self.cloud_resource_controller.as_ref() {
820                for (connection_id, spec) in vpc_endpoints_to_create {
821                    if let Err(err) = cloud_resource_controller
822                        .ensure_vpc_endpoint(connection_id, spec)
823                        .await
824                    {
825                        tracing::error!(?err, "failed to ensure vpc endpoint!");
826                    }
827                }
828            } else {
829                tracing::error!(
830                    "AWS PrivateLink connections unsupported without cloud_resource_controller"
831                );
832            }
833        }
834
835        // Apply batched connection alterations to dependent sources/sinks/tables.
836        if !source_connections_to_alter.is_empty() {
837            self.controller
838                .storage
839                .alter_ingestion_connections(source_connections_to_alter)
840                .await
841                .unwrap_or_terminate("cannot fail to alter ingestion connections");
842        }
843
844        if !sink_connections_to_alter.is_empty() {
845            self.controller
846                .storage
847                .alter_export_connections(sink_connections_to_alter)
848                .await
849                .unwrap_or_terminate("altering export connections after txn must succeed");
850        }
851
852        if !source_export_data_configs_to_alter.is_empty() {
853            self.controller
854                .storage
855                .alter_ingestion_export_data_configs(source_export_data_configs_to_alter)
856                .await
857                .unwrap_or_terminate("altering source export data configs after txn must succeed");
858        }
859
860        if !source_descs_to_alter.is_empty() {
861            self.controller
862                .storage
863                .alter_ingestion_source_desc(source_descs_to_alter)
864                .await
865                .unwrap_or_terminate("cannot fail to alter ingestion source desc");
866        }
867
868        // Apply source drop overwrites.
869        sources_to_drop.retain(|(_, gid)| !source_gids_to_keep.contains(gid));
870
871        let readable_collections_to_drop: BTreeSet<_> = sources_to_drop
872            .iter()
873            .map(|(_, gid)| *gid)
874            .chain(tables_to_drop.iter().map(|(_, gid)| *gid))
875            .chain(indexes_to_drop.iter().map(|(_, gid)| *gid))
876            .chain(view_gids_to_drop.iter().copied())
877            .collect();
878
879        // Clean up any active compute sinks like subscribes or copy to-s that
880        // rely on dropped relations or clusters.
881        for (sink_id, sink) in &self.active_compute_sinks {
882            let cluster_id = sink.cluster_id();
883            if let Some(id) = sink
884                .depends_on()
885                .iter()
886                .find(|id| readable_collections_to_drop.contains(id))
887            {
888                let name = dropped_item_names
889                    .get(id)
890                    .cloned()
891                    .expect("missing relation name");
892                active_compute_sinks_to_drop.insert(
893                    *sink_id,
894                    ActiveComputeSinkRetireReason::DependencyDropped(DroppedDependency::Relation {
895                        name,
896                    }),
897                );
898            } else if clusters_to_drop.contains(&cluster_id) {
899                let name = dropped_cluster_names
900                    .get(&cluster_id)
901                    .cloned()
902                    .expect("missing cluster name");
903                active_compute_sinks_to_drop.insert(
904                    *sink_id,
905                    ActiveComputeSinkRetireReason::DependencyDropped(DroppedDependency::Cluster {
906                        name,
907                    }),
908                );
909            }
910        }
911
912        // Clean up any pending peeks that rely on dropped relations or clusters.
913        // NOTE: `dropped_item_names` also names collections that stay readable,
914        // such as the old version of a materialized view after a replacement.
915        let dropped_readable_names: BTreeMap<_, _> = dropped_item_names
916            .iter()
917            .filter(|(gid, _)| readable_collections_to_drop.contains(gid))
918            .map(|(gid, name)| (*gid, name.clone()))
919            .collect();
920        self.peek_registry
921            .invalidate(&dropped_readable_names, &dropped_cluster_names);
922        // Clean up any pending `COPY` statements that rely on dropped relations or clusters.
923        for (conn_id, pending_copy) in &self.active_copies {
924            let dropping_table = tables_to_drop
925                .iter()
926                .any(|(item_id, _gid)| pending_copy.table_id == *item_id);
927            let dropping_cluster = clusters_to_drop.contains(&pending_copy.cluster_id);
928
929            if dropping_table || dropping_cluster {
930                copies_to_drop.push(conn_id.clone());
931            }
932        }
933
934        let storage_gids_to_drop: BTreeSet<_> = sources_to_drop
935            .iter()
936            .map(|(_id, gid)| gid)
937            .chain(storage_sink_gids_to_drop.iter())
938            .chain(tables_to_drop.iter().map(|(_id, gid)| gid))
939            .copied()
940            .collect();
941        let compute_gids_to_drop: Vec<_> = indexes_to_drop
942            .iter()
943            .chain(compute_sinks_to_drop.iter())
944            .copied()
945            .collect();
946
947        // Gather resources that we have to remove from timeline state and
948        // pre-check if any Timelines become empty, when we drop the specified
949        // storage and compute resources.
950        //
951        // Note: We only apply these changes below.
952        let mut timeline_id_bundles = BTreeMap::new();
953
954        for (timeline, TimelineState { read_holds, .. }) in &self.global_timelines {
955            let mut id_bundle = CollectionIdBundle::default();
956
957            for storage_id in read_holds.storage_ids() {
958                if storage_gids_to_drop.contains(&storage_id) {
959                    id_bundle.storage_ids.insert(storage_id);
960                }
961            }
962
963            for (instance_id, id) in read_holds.compute_ids() {
964                if compute_gids_to_drop.contains(&(instance_id, id))
965                    || clusters_to_drop.contains(&instance_id)
966                {
967                    id_bundle
968                        .compute_ids
969                        .entry(instance_id)
970                        .or_default()
971                        .insert(id);
972                }
973            }
974
975            timeline_id_bundles.insert(timeline.clone(), id_bundle);
976        }
977
978        let mut timeline_associations = BTreeMap::new();
979        for (timeline, id_bundle) in timeline_id_bundles.into_iter() {
980            let TimelineState { read_holds, .. } = self
981                .global_timelines
982                .get(&timeline)
983                .expect("all timelines have a timestamp oracle");
984
985            let empty = read_holds.id_bundle().difference(&id_bundle).is_empty();
986            timeline_associations.insert(timeline, (empty, id_bundle));
987        }
988
989        // No error returns are allowed after this point. Enforce this at compile time
990        // by using this odd structure so we don't accidentally add a stray `?`.
991        let _: () = async {
992            if !timeline_associations.is_empty() {
993                for (timeline, (should_be_empty, id_bundle)) in timeline_associations {
994                    let became_empty =
995                        self.remove_resources_associated_with_timeline(timeline, id_bundle);
996                    assert_eq!(should_be_empty, became_empty, "emptiness did not match!");
997                }
998            }
999
1000            // Note that we drop tables before sources since there can be a weak
1001            // dependency on sources from tables in the storage controller that
1002            // will result in error logging that we'd prefer to avoid. This
1003            // isn't an actual dependency issue but we'd like to keep that error
1004            // logging around to indicate when an actual dependency error might
1005            // occur.
1006            if !tables_to_drop.is_empty() {
1007                self.drop_tables(tables_to_drop.into_iter().collect_vec())
1008                    .await;
1009            }
1010
1011            if !sources_to_drop.is_empty() {
1012                self.drop_sources(sources_to_drop);
1013            }
1014
1015            if !storage_sink_gids_to_drop.is_empty() {
1016                self.drop_storage_sinks(storage_sink_gids_to_drop);
1017            }
1018
1019            if !active_compute_sinks_to_drop.is_empty() {
1020                let retire_notify = self
1021                    .retire_compute_sinks(active_compute_sinks_to_drop)
1022                    .await;
1023                if let Some(ctx) = ctx {
1024                    ctx.delay_response_until(retire_notify);
1025                }
1026            }
1027
1028            if !copies_to_drop.is_empty() {
1029                for conn_id in copies_to_drop {
1030                    self.cancel_pending_copy(&conn_id);
1031                }
1032            }
1033
1034            if !compute_gids_to_drop.is_empty() {
1035                self.drop_compute_collections(compute_gids_to_drop);
1036            }
1037
1038            if !vpc_endpoints_to_drop.is_empty() {
1039                self.drop_vpc_endpoints_in_background(vpc_endpoints_to_drop)
1040            }
1041
1042            let clusters_losing_replicas: BTreeSet<_> = cluster_replicas_to_drop
1043                .iter()
1044                .map(|(cluster_id, _)| *cluster_id)
1045                .collect();
1046            if !cluster_replicas_to_drop.is_empty() {
1047                fail::fail_point!("after_catalog_drop_replica");
1048
1049                for (cluster_id, replica_id) in cluster_replicas_to_drop {
1050                    self.drop_replica(cluster_id, replica_id);
1051                }
1052            }
1053            if !clusters_to_drop.is_empty() {
1054                for cluster_id in &clusters_to_drop {
1055                    self.controller.drop_cluster(*cluster_id);
1056                }
1057            }
1058            // A dropped cluster, or one left without replicas, cannot serve
1059            // peeks, so its peek series are stale. They come back on the first
1060            // peek once a cluster has a replica again.
1061            for cluster_id in clusters_losing_replicas.into_iter().chain(clusters_to_drop) {
1062                let has_replicas = self
1063                    .catalog()
1064                    .try_get_cluster(cluster_id)
1065                    .is_some_and(|cluster| cluster.replicas().next().is_some());
1066                if !has_replicas {
1067                    self.metrics.by_cluster.remove_cluster(cluster_id);
1068                }
1069            }
1070
1071            // We don't want to block the main coordinator thread on cleaning
1072            // up external resources (PostgreSQL replication slots and secrets),
1073            // so we perform that cleanup in a background task.
1074            //
1075            // TODO(14551): This is inherently best effort. An ill-timed crash
1076            // means we'll never clean these resources up. Safer cleanup for non-Materialize resources.
1077            // See <https://github.com/MaterializeInc/materialize/issues/14551>
1078            task::spawn(|| "drop_replication_slots_and_secrets", {
1079                let ssh_tunnel_manager = self.connection_context().ssh_tunnel_manager.clone();
1080                let caching_secrets_reader = self.caching_secrets_reader.clone();
1081                let secrets_controller = Arc::clone(&self.secrets_controller);
1082                let secrets_reader = Arc::clone(self.secrets_reader());
1083                let storage_config = self.controller.storage.config().clone();
1084
1085                async move {
1086                    for (connection, replication_slot_name) in replication_slots_to_drop {
1087                        tracing::info!(?replication_slot_name, "dropping replication slot");
1088
1089                        // Try to drop the replication slots, but give up after
1090                        // a while. The PostgreSQL server may no longer be
1091                        // healthy. Users often drop PostgreSQL sources
1092                        // *because* the PostgreSQL server has been
1093                        // decomissioned.
1094                        let result: Result<(), anyhow::Error> = Retry::default()
1095                            .max_duration(Duration::from_secs(60))
1096                            .retry_async(|_state| async {
1097                                let config = connection
1098                                    .config(&secrets_reader, &storage_config, InTask::No)
1099                                    .await
1100                                    .map_err(|e| {
1101                                        anyhow::anyhow!(
1102                                            "error creating Postgres client for \
1103                                            dropping acquired slots: {}",
1104                                            e.display_with_causes()
1105                                        )
1106                                    })?;
1107
1108                                mz_postgres_util::drop_replication_slots(
1109                                    &ssh_tunnel_manager,
1110                                    config.clone(),
1111                                    &[(&replication_slot_name, true)],
1112                                )
1113                                .await?;
1114
1115                                Ok(())
1116                            })
1117                            .await;
1118
1119                        if let Err(err) = result {
1120                            tracing::warn!(
1121                                ?replication_slot_name,
1122                                ?err,
1123                                "failed to drop replication slot"
1124                            );
1125                        }
1126                    }
1127
1128                    // Drop secrets *after* dropping the replication slots,
1129                    // because dropping replication slots may rely on those
1130                    // secrets still being present.
1131                    //
1132                    // It's okay if we crash before processing the secret drops,
1133                    // as we look for and remove any orphaned secrets during
1134                    // startup.
1135                    fail_point!("drop_secrets");
1136                    for secret in secrets_to_drop {
1137                        if let Err(e) = secrets_controller.delete(secret).await {
1138                            warn!("Dropping secrets has encountered an error: {}", e);
1139                        } else {
1140                            caching_secrets_reader.invalidate(secret);
1141                        }
1142                    }
1143                }
1144            });
1145        }
1146        .instrument(info_span!(
1147            "coord::apply_catalog_implications_inner::finalize"
1148        ))
1149        .await;
1150
1151        Ok(())
1152    }
1153
1154    #[instrument(level = "debug")]
1155    async fn create_table_collections(
1156        &mut self,
1157        table_collections_to_create: BTreeMap<GlobalId, CollectionDescription>,
1158        execution_timestamps_to_set: BTreeSet<StatementLoggingId>,
1159    ) -> Result<(), AdapterError> {
1160        // Storage filters table catalog items that are not managed by txn-wal.
1161        let table_ids: Vec<GlobalId> = table_collections_to_create.keys().copied().collect();
1162        let collections = table_collections_to_create.into_iter().collect_vec();
1163
1164        // Confirm leadership after allocating the collections' initial timestamp.
1165        let write_ts = self.get_local_write_ts().await;
1166        let register_ts = write_ts.timestamp;
1167        self.catalog
1168            .advance_upper(write_ts.advance_to)
1169            .await
1170            .unwrap_or_terminate("unable to advance catalog upper");
1171
1172        {
1173            let storage_metadata = self.catalog.state().storage_metadata();
1174            self.controller
1175                .storage
1176                .create_collections(storage_metadata, Some(register_ts), collections)
1177                .await
1178                .unwrap_or_terminate("cannot fail to create collections");
1179        }
1180
1181        // Registration can choose a later timestamp than the collections' initial since. Reads
1182        // remain above the applied registration timestamp.
1183        let registrations = self
1184            .controller
1185            .storage
1186            .table_registrations(table_ids)
1187            .unwrap_or_terminate("cannot fail to look up table registrations");
1188        let table_ts = if registrations.is_empty() {
1189            // Without txn-wal registration, this timestamp still makes the collections readable.
1190            self.apply_local_write(register_ts).await;
1191            register_ts
1192        } else {
1193            self.register_tables_via_committer(registrations).await
1194        };
1195
1196        for id in execution_timestamps_to_set {
1197            self.set_statement_execution_timestamp(id, table_ts);
1198        }
1199
1200        Ok(())
1201    }
1202
1203    #[instrument(level = "debug")]
1204    async fn create_source_collections(
1205        &mut self,
1206        source_collections_to_create: BTreeMap<GlobalId, CollectionDescription>,
1207    ) -> Result<(), AdapterError> {
1208        let storage_metadata = self.catalog.state().storage_metadata();
1209
1210        self.controller
1211            .storage
1212            .create_collections(
1213                storage_metadata,
1214                None, // Sources don't need a write timestamp
1215                source_collections_to_create.into_iter().collect_vec(),
1216            )
1217            .await
1218            .unwrap_or_terminate("cannot fail to create collections");
1219
1220        Ok(())
1221    }
1222
1223    #[instrument(level = "debug")]
1224    async fn initialize_storage_collections(
1225        &mut self,
1226        storage_policies_to_initialize: BTreeMap<CompactionWindow, BTreeSet<GlobalId>>,
1227    ) -> Result<(), AdapterError> {
1228        for (compaction_window, global_ids) in storage_policies_to_initialize {
1229            self.initialize_read_policies(
1230                &CollectionIdBundle {
1231                    storage_ids: global_ids,
1232                    compute_ids: BTreeMap::new(),
1233                },
1234                compaction_window,
1235            )
1236            .await;
1237        }
1238
1239        Ok(())
1240    }
1241
1242    #[instrument(level = "debug")]
1243    async fn handle_create_table(
1244        &self,
1245        ctx: &Option<&mut ExecuteContext>,
1246        storage_collections_to_create: &mut BTreeMap<GlobalId, CollectionDescription>,
1247        storage_policies_to_initialize: &mut BTreeMap<CompactionWindow, BTreeSet<GlobalId>>,
1248        execution_timestamps_to_set: &mut BTreeSet<StatementLoggingId>,
1249        table_id: CatalogItemId,
1250        table: Table,
1251    ) -> Result<(), AdapterError> {
1252        // The table data_source determines whether this table will be written to
1253        // by environmentd (e.g. with INSERT INTO statements) or by the storage layer
1254        // (e.g. a source-fed table).
1255        match &table.data_source {
1256            TableDataSource::TableWrites { defaults: _ } => {
1257                let versions: BTreeMap<_, _> = table
1258                    .collection_descs()
1259                    .map(|(gid, version, desc)| (version, (gid, desc)))
1260                    .collect();
1261                let collection_descs = versions.iter().map(|(_version, (gid, desc))| {
1262                    let collection_desc = CollectionDescription::for_table(desc.clone());
1263
1264                    (*gid, collection_desc)
1265                });
1266
1267                let compaction_window = table
1268                    .custom_logical_compaction_window
1269                    .unwrap_or(CompactionWindow::Default);
1270                let ids_to_initialize = storage_policies_to_initialize
1271                    .entry(compaction_window)
1272                    .or_default();
1273
1274                for (gid, collection_desc) in collection_descs {
1275                    storage_collections_to_create.insert(gid, collection_desc);
1276                    ids_to_initialize.insert(gid);
1277                }
1278
1279                if let Some(id) = ctx.as_ref().and_then(|ctx| ctx.extra().contents()) {
1280                    execution_timestamps_to_set.insert(id);
1281                }
1282            }
1283            TableDataSource::DataSource {
1284                desc: data_source_desc,
1285                timeline,
1286            } => {
1287                match data_source_desc {
1288                    DataSourceDesc::IngestionExport {
1289                        ingestion_id,
1290                        external_reference: _,
1291                        details,
1292                        data_config,
1293                    } => {
1294                        let global_ingestion_id =
1295                            self.catalog().get_entry(ingestion_id).latest_global_id();
1296
1297                        let collection_desc = CollectionDescription {
1298                            desc: table.desc.latest(),
1299                            data_source: DataSource::IngestionExport {
1300                                ingestion_id: global_ingestion_id,
1301                                details: details.clone(),
1302                                data_config: data_config
1303                                    .clone()
1304                                    .into_inline_connection(self.catalog.state()),
1305                            },
1306                            since: None,
1307                            timeline: Some(timeline.clone()),
1308                            primary: None,
1309                        };
1310
1311                        let global_id = table
1312                            .global_ids()
1313                            .expect_element(|| "subsources cannot have multiple versions");
1314
1315                        storage_collections_to_create.insert(global_id, collection_desc);
1316
1317                        let read_policies = self
1318                            .catalog()
1319                            .state()
1320                            .source_compaction_windows(vec![table_id]);
1321                        for (compaction_window, catalog_ids) in read_policies {
1322                            let compaction_ids = storage_policies_to_initialize
1323                                .entry(compaction_window)
1324                                .or_default();
1325
1326                            let gids = catalog_ids
1327                                .into_iter()
1328                                .map(|item_id| self.catalog().get_entry(&item_id).global_ids())
1329                                .flatten();
1330                            compaction_ids.extend(gids);
1331                        }
1332                    }
1333                    DataSourceDesc::Webhook {
1334                        validate_using: _,
1335                        body_format: _,
1336                        headers: _,
1337                        cluster_id: _,
1338                    } => {
1339                        // Create the underlying collection with the latest schema from the Table.
1340                        assert_eq!(
1341                            table.desc.latest_version(),
1342                            RelationVersion::root(),
1343                            "found webhook with more than 1 relation version, {:?}",
1344                            table.desc
1345                        );
1346                        let desc = table.desc.latest();
1347
1348                        let collection_desc = CollectionDescription {
1349                            desc,
1350                            data_source: DataSource::Webhook,
1351                            since: None,
1352                            timeline: Some(timeline.clone()),
1353                            primary: None,
1354                        };
1355
1356                        let global_id = table
1357                            .global_ids()
1358                            .expect_element(|| "webhooks cannot have multiple versions");
1359
1360                        storage_collections_to_create.insert(global_id, collection_desc);
1361
1362                        let read_policies = self
1363                            .catalog()
1364                            .state()
1365                            .source_compaction_windows(vec![table_id]);
1366
1367                        for (compaction_window, catalog_ids) in read_policies {
1368                            let compaction_ids = storage_policies_to_initialize
1369                                .entry(compaction_window)
1370                                .or_default();
1371
1372                            let gids = catalog_ids
1373                                .into_iter()
1374                                .map(|item_id| self.catalog().get_entry(&item_id).global_ids())
1375                                .flatten();
1376                            compaction_ids.extend(gids);
1377                        }
1378                    }
1379                    _ => unreachable!("CREATE TABLE data source got {:?}", data_source_desc),
1380                }
1381            }
1382        }
1383
1384        Ok(())
1385    }
1386
1387    #[instrument(level = "debug")]
1388    async fn handle_alter_table(
1389        &mut self,
1390        catalog_id: CatalogItemId,
1391        prev_table: Table,
1392        new_table: Table,
1393    ) -> Result<(), AdapterError> {
1394        let existing_gid = prev_table.global_id_writes();
1395        let new_gid = new_table.global_id_writes();
1396
1397        if existing_gid == new_gid {
1398            // It's not an ALTER TABLE ADD COLUMN, because we still have the
1399            // same GlobalId. It might be a compaction window change.
1400            if prev_table.custom_logical_compaction_window
1401                != new_table.custom_logical_compaction_window
1402            {
1403                let new_window = new_table
1404                    .custom_logical_compaction_window
1405                    .unwrap_or(CompactionWindow::Default);
1406                self.update_storage_read_policies(vec![(catalog_id, new_window.into())]);
1407            }
1408            return Ok(());
1409        }
1410
1411        // Acquire a read hold on the original table for the duration of
1412        // the alter to prevent the since of the original table from
1413        // getting advanced, while the ALTER is running.
1414        let existing_table = crate::CollectionIdBundle {
1415            storage_ids: BTreeSet::from([existing_gid]),
1416            compute_ids: BTreeMap::new(),
1417        };
1418        let existing_table_read_hold = self.acquire_read_holds(&existing_table);
1419
1420        let expected_version = prev_table.desc.latest_version();
1421        let new_version = new_table.desc.latest_version();
1422        let new_desc = new_table
1423            .desc
1424            .at_version(RelationVersionSelector::Specific(new_version));
1425
1426        // Confirm leadership before mutating controller state.
1427        let write_ts = self.get_local_write_ts().await;
1428        self.catalog
1429            .advance_upper(write_ts.advance_to)
1430            .await
1431            .unwrap_or_terminate("unable to advance catalog upper");
1432
1433        self.controller
1434            .storage
1435            .alter_table_desc(existing_gid, new_gid, new_desc, expected_version)
1436            .await
1437            .unwrap_or_terminate("failed to alter desc of table");
1438
1439        // FIFO registration follows all staged writes to the old collection.
1440        let registrations = self
1441            .controller
1442            .storage
1443            .table_registrations(vec![new_gid])
1444            .unwrap_or_terminate("cannot fail to look up table registrations");
1445        self.register_tables_via_committer(registrations).await;
1446
1447        // Initialize the ReadPolicy which ensures we have the correct read holds.
1448        let compaction_window = new_table
1449            .custom_logical_compaction_window
1450            .unwrap_or(CompactionWindow::Default);
1451        self.initialize_read_policies(
1452            &crate::CollectionIdBundle {
1453                storage_ids: BTreeSet::from([new_gid]),
1454                compute_ids: BTreeMap::new(),
1455            },
1456            compaction_window,
1457        )
1458        .await;
1459
1460        // Alter is complete! We can drop our read hold.
1461        drop(existing_table_read_hold);
1462
1463        Ok(())
1464    }
1465
1466    #[instrument(level = "debug")]
1467    async fn handle_create_source(
1468        &self,
1469        storage_collections_to_create: &mut BTreeMap<GlobalId, CollectionDescription>,
1470        storage_policies_to_initialize: &mut BTreeMap<CompactionWindow, BTreeSet<GlobalId>>,
1471        item_id: CatalogItemId,
1472        source: Source,
1473        compaction_windows: BTreeMap<CompactionWindow, BTreeSet<CatalogItemId>>,
1474    ) -> Result<(), AdapterError> {
1475        let data_source = match source.data_source {
1476            DataSourceDesc::Ingestion { desc, cluster_id } => {
1477                let desc = desc.into_inline_connection(self.catalog().state());
1478                let item_global_id = self.catalog().get_entry(&item_id).latest_global_id();
1479
1480                let ingestion = mz_storage_types::sources::IngestionDescription::new(
1481                    desc,
1482                    cluster_id,
1483                    item_global_id,
1484                );
1485
1486                DataSource::Ingestion(ingestion)
1487            }
1488            DataSourceDesc::OldSyntaxIngestion {
1489                desc,
1490                progress_subsource,
1491                data_config,
1492                details,
1493                cluster_id,
1494            } => {
1495                let desc = desc.into_inline_connection(self.catalog().state());
1496                let data_config = data_config.into_inline_connection(self.catalog().state());
1497
1498                // TODO(parkmycar): We should probably check the type here, but I'm not
1499                // sure if this will always be a Source or a Table.
1500                let progress_subsource = self
1501                    .catalog()
1502                    .get_entry(&progress_subsource)
1503                    .latest_global_id();
1504
1505                let mut ingestion = mz_storage_types::sources::IngestionDescription::new(
1506                    desc,
1507                    cluster_id,
1508                    progress_subsource,
1509                );
1510
1511                let legacy_export = SourceExport {
1512                    storage_metadata: (),
1513                    data_config,
1514                    details,
1515                };
1516
1517                ingestion
1518                    .source_exports
1519                    .insert(source.global_id, legacy_export);
1520
1521                DataSource::Ingestion(ingestion)
1522            }
1523            DataSourceDesc::IngestionExport {
1524                ingestion_id,
1525                external_reference: _,
1526                details,
1527                data_config,
1528            } => {
1529                // TODO(parkmycar): We should probably check the type here, but I'm not sure if
1530                // this will always be a Source or a Table.
1531                let ingestion_id = self.catalog().get_entry(&ingestion_id).latest_global_id();
1532
1533                DataSource::IngestionExport {
1534                    ingestion_id,
1535                    details,
1536                    data_config: data_config.into_inline_connection(self.catalog().state()),
1537                }
1538            }
1539            DataSourceDesc::Progress => DataSource::Progress,
1540            DataSourceDesc::Webhook { .. } => DataSource::Webhook,
1541            DataSourceDesc::Introspection(_) | DataSourceDesc::Catalog => {
1542                unreachable!("cannot create sources with internal data sources")
1543            }
1544        };
1545
1546        storage_collections_to_create.insert(
1547            source.global_id,
1548            CollectionDescription {
1549                desc: source.desc.clone(),
1550                data_source,
1551                timeline: Some(source.timeline),
1552                since: None,
1553                primary: None,
1554            },
1555        );
1556
1557        // Initialize read policies for the source
1558        for (compaction_window, catalog_ids) in compaction_windows {
1559            let compaction_ids = storage_policies_to_initialize
1560                .entry(compaction_window)
1561                .or_default();
1562
1563            let gids = catalog_ids
1564                .into_iter()
1565                .map(|item_id| self.catalog().get_entry(&item_id).global_ids())
1566                .flatten();
1567            compaction_ids.extend(gids);
1568        }
1569
1570        Ok(())
1571    }
1572
1573    /// Handles altering a connection by collecting all the dependent sources,
1574    /// sinks, and tables that need their connection updated.
1575    ///
1576    /// This mirrors the logic from `sequence_alter_connection_stage_finish` but
1577    /// collects the changes into batched collections for application after all
1578    /// implications are processed.
1579    #[instrument(level = "debug")]
1580    fn handle_alter_connection(
1581        &self,
1582        connection_id: CatalogItemId,
1583        connection: Connection,
1584        vpc_endpoints_to_create: &mut Vec<(CatalogItemId, VpcEndpointConfig)>,
1585        source_connections_to_alter: &mut BTreeMap<
1586            GlobalId,
1587            GenericSourceConnection<InlinedConnection>,
1588        >,
1589        sink_connections_to_alter: &mut BTreeMap<GlobalId, StorageSinkConnection>,
1590        source_export_data_configs_to_alter: &mut BTreeMap<GlobalId, SourceExportDataConfig>,
1591    ) {
1592        use std::collections::VecDeque;
1593
1594        // Handle AWS PrivateLink connections by queueing VPC endpoint creation.
1595        if let ConnectionDetails::AwsPrivatelink(ref privatelink) = connection.details {
1596            let spec = VpcEndpointConfig {
1597                aws_service_name: privatelink.service_name.to_owned(),
1598                availability_zone_ids: privatelink.availability_zones.to_owned(),
1599            };
1600            vpc_endpoints_to_create.push((connection_id, spec));
1601        }
1602
1603        // Walk the dependency graph to find all sources, sinks, and tables
1604        // that depend on this connection (directly or transitively through
1605        // other connections).
1606        let mut connections_to_process = VecDeque::new();
1607        connections_to_process.push_front(connection_id.clone());
1608
1609        while let Some(id) = connections_to_process.pop_front() {
1610            for dependent_id in self.catalog().get_entry(&id).used_by() {
1611                let dependent_entry = self.catalog().get_entry(dependent_id);
1612                match dependent_entry.item() {
1613                    CatalogItem::Connection(_) => {
1614                        // Connections can depend on other connections (e.g., a
1615                        // Kafka connection using an SSH tunnel connection).
1616                        // Process these transitively.
1617                        connections_to_process.push_back(*dependent_id);
1618                    }
1619                    CatalogItem::Source(source) => {
1620                        let desc = match &dependent_entry
1621                            .source()
1622                            .expect("known to be source")
1623                            .data_source
1624                        {
1625                            DataSourceDesc::Ingestion { desc, .. }
1626                            | DataSourceDesc::OldSyntaxIngestion { desc, .. } => {
1627                                desc.clone().into_inline_connection(self.catalog().state())
1628                            }
1629                            DataSourceDesc::IngestionExport { .. }
1630                            | DataSourceDesc::Introspection(_)
1631                            | DataSourceDesc::Progress
1632                            | DataSourceDesc::Webhook { .. }
1633                            | DataSourceDesc::Catalog => {
1634                                // Only ingestions reference connections directly.
1635                                continue;
1636                            }
1637                        };
1638
1639                        source_connections_to_alter.insert(source.global_id, desc.connection);
1640                    }
1641                    CatalogItem::Sink(sink) => {
1642                        let export = dependent_entry.sink().expect("known to be sink");
1643                        sink_connections_to_alter.insert(
1644                            sink.global_id,
1645                            export
1646                                .connection
1647                                .clone()
1648                                .into_inline_connection(self.catalog().state()),
1649                        );
1650                    }
1651                    CatalogItem::Table(table) => {
1652                        // This is a source-fed table that references a schema
1653                        // registry connection as part of its encoding/data
1654                        // config.
1655                        if let Some((_, _, _, export_data_config)) =
1656                            dependent_entry.source_export_details()
1657                        {
1658                            let data_config = export_data_config.clone();
1659                            source_export_data_configs_to_alter.insert(
1660                                table.global_id_writes(),
1661                                data_config.into_inline_connection(self.catalog().state()),
1662                            );
1663                        }
1664                    }
1665                    CatalogItem::Log(_)
1666                    | CatalogItem::View(_)
1667                    | CatalogItem::MaterializedView(_)
1668                    | CatalogItem::Index(_)
1669                    | CatalogItem::Type(_)
1670                    | CatalogItem::Func(_)
1671                    | CatalogItem::Secret(_)
1672                    | CatalogItem::MetricSink(_) => {
1673                        // Other item types don't have connection dependencies
1674                        // that need updating.
1675                    }
1676                }
1677            }
1678        }
1679    }
1680
1681    async fn handle_create_cluster_replica(
1682        &mut self,
1683        cluster_id: ClusterId,
1684        replica_id: ReplicaId,
1685        role: ClusterRole,
1686        cluster_name: String,
1687        replica_name: String,
1688        replica_config: ReplicaConfig,
1689    ) {
1690        let enable_worker_core_affinity =
1691            self.catalog().system_config().enable_worker_core_affinity();
1692
1693        // This replica's scoped (replica-local) overrides were pushed into the
1694        // controller's per-replica layer before this loop, by the
1695        // replica-scoped-configuration implication, so the replica's first
1696        // configuration replays with them. Render-frozen flags make a later push
1697        // too late, which is why the push precedes `create_replica`.
1698
1699        self.controller
1700            .create_replica(
1701                cluster_id,
1702                replica_id,
1703                cluster_name,
1704                replica_name,
1705                role,
1706                replica_config,
1707                enable_worker_core_affinity,
1708            )
1709            .expect("creating replicas must not fail");
1710
1711        self.install_introspection_subscribes(cluster_id, replica_id)
1712            .await;
1713        self.install_metric_sinks(cluster_id, replica_id).await;
1714    }
1715}
1716
1717/// A state machine for building catalog implications from catalog updates.
1718///
1719/// Once all [ParsedStateUpdate] of a timestamp are ingested this is a command
1720/// that has to potentially be applied to in-memory state and/or the
1721/// controller(s).
1722#[derive(Debug, Clone)]
1723enum CatalogImplication {
1724    None,
1725    Table(CatalogImplicationKind<Table>),
1726    Source(CatalogImplicationKind<(Source, Option<GenericSourceConnection>)>),
1727    Sink(CatalogImplicationKind<Sink>),
1728    Index(CatalogImplicationKind<Index>),
1729    MetricSink(CatalogImplicationKind<MetricSink>),
1730    MaterializedView(CatalogImplicationKind<MaterializedView>),
1731    View(CatalogImplicationKind<View>),
1732    Secret(CatalogImplicationKind<Secret>),
1733    Connection(CatalogImplicationKind<Connection>),
1734    Cluster(CatalogImplicationKind<Cluster>),
1735    ClusterReplica(CatalogImplicationKind<ClusterReplica>),
1736}
1737
1738#[derive(Debug, Clone)]
1739enum CatalogImplicationKind<T> {
1740    /// No operations seen yet.
1741    None,
1742    /// Item was added.
1743    Added(T),
1744    /// Item was dropped (with its name retained for error messages).
1745    Dropped(T, String),
1746    /// Item is being altered from one state to another.
1747    Altered { prev: T, new: T },
1748}
1749
1750impl<T: Clone> CatalogImplicationKind<T> {
1751    /// Apply a state transition based on a diff. Returns an error message if
1752    /// the transition is invalid.
1753    fn transition(&mut self, item: T, name: Option<String>, diff: StateDiff) -> Result<(), String> {
1754        use CatalogImplicationKind::*;
1755        use StateDiff::*;
1756
1757        let new_state = match (&*self, diff) {
1758            // Initial state transitions
1759            (None, Addition) => Added(item),
1760            (None, Retraction) => Dropped(item, name.unwrap_or_else(|| "<unknown>".to_string())),
1761
1762            // From Added state
1763            (Added(existing), Retraction) => {
1764                // Add -> Drop means the item is being altered
1765                Altered {
1766                    prev: item,
1767                    new: existing.clone(),
1768                }
1769            }
1770            (Added(_), Addition) => {
1771                return Err("Cannot add an already added object".to_string());
1772            }
1773
1774            // From Dropped state
1775            (Dropped(existing, _), Addition) => {
1776                // Drop -> Add means the item is being altered
1777                Altered {
1778                    prev: existing.clone(),
1779                    new: item,
1780                }
1781            }
1782            (Dropped(_, _), Retraction) => {
1783                return Err("Cannot drop an already dropped object".to_string());
1784            }
1785
1786            // From Altered state
1787            (Altered { .. }, _) => {
1788                return Err(format!(
1789                    "Cannot apply {:?} to an object in Altered state",
1790                    diff
1791                ));
1792            }
1793        };
1794
1795        *self = new_state;
1796        Ok(())
1797    }
1798}
1799
1800/// Macro to generate absorb methods for each item type.
1801macro_rules! impl_absorb_method {
1802    (
1803        $method_name:ident,
1804        $variant:ident,
1805        $item_type:ty
1806    ) => {
1807        fn $method_name(
1808            &mut self,
1809            item: $item_type,
1810            parsed_full_name: Option<String>,
1811            diff: StateDiff,
1812        ) {
1813            let state = match self {
1814                CatalogImplication::$variant(state) => state,
1815                CatalogImplication::None => {
1816                    *self = CatalogImplication::$variant(CatalogImplicationKind::None);
1817                    match self {
1818                        CatalogImplication::$variant(state) => state,
1819                        _ => unreachable!(),
1820                    }
1821                }
1822                _ => {
1823                    panic!(
1824                        "Unexpected command type for {:?}: {} {:?}",
1825                        self,
1826                        stringify!($variant),
1827                        diff,
1828                    );
1829                }
1830            };
1831
1832            if let Err(e) = state.transition(item, parsed_full_name, diff) {
1833                panic!(
1834                    "Invalid state transition for {}: {}",
1835                    stringify!($variant),
1836                    e
1837                );
1838            }
1839        }
1840    };
1841}
1842
1843impl CatalogImplication {
1844    /// Absorbs the given catalog update into this [CatalogImplication], causing
1845    /// a state transition or error.
1846    fn absorb(&mut self, catalog_update: ParsedStateUpdate) {
1847        match catalog_update.kind {
1848            ParsedStateUpdateKind::Item {
1849                durable_item: _,
1850                parsed_item,
1851                connection,
1852                parsed_full_name,
1853            } => match parsed_item {
1854                CatalogItem::Table(table) => self.absorb_table(
1855                    table,
1856                    Some(parsed_full_name.to_string()),
1857                    catalog_update.diff,
1858                ),
1859                CatalogItem::Source(source) => {
1860                    self.absorb_source(
1861                        (source, connection),
1862                        Some(parsed_full_name.to_string()),
1863                        catalog_update.diff,
1864                    );
1865                }
1866                CatalogItem::Sink(sink) => {
1867                    self.absorb_sink(
1868                        sink,
1869                        Some(parsed_full_name.to_string()),
1870                        catalog_update.diff,
1871                    );
1872                }
1873                CatalogItem::Index(index) => {
1874                    self.absorb_index(
1875                        index,
1876                        Some(parsed_full_name.to_string()),
1877                        catalog_update.diff,
1878                    );
1879                }
1880                CatalogItem::MaterializedView(mv) => {
1881                    self.absorb_materialized_view(
1882                        mv,
1883                        Some(parsed_full_name.to_string()),
1884                        catalog_update.diff,
1885                    );
1886                }
1887                CatalogItem::View(view) => {
1888                    self.absorb_view(
1889                        view,
1890                        Some(parsed_full_name.to_string()),
1891                        catalog_update.diff,
1892                    );
1893                }
1894
1895                CatalogItem::Secret(secret) => {
1896                    self.absorb_secret(secret, None, catalog_update.diff);
1897                }
1898                CatalogItem::Connection(connection) => {
1899                    self.absorb_connection(connection, None, catalog_update.diff);
1900                }
1901                CatalogItem::MetricSink(metric_sink) => {
1902                    self.absorb_metric_sink(
1903                        metric_sink,
1904                        Some(parsed_full_name.to_string()),
1905                        catalog_update.diff,
1906                    );
1907                }
1908                CatalogItem::Log(_) => {}
1909                CatalogItem::Type(_) => {}
1910                CatalogItem::Func(_) => {}
1911            },
1912            ParsedStateUpdateKind::Cluster {
1913                durable_cluster: _,
1914                parsed_cluster,
1915            } => {
1916                let name = parsed_cluster.name.clone();
1917                self.absorb_cluster(parsed_cluster, Some(name), catalog_update.diff);
1918            }
1919            ParsedStateUpdateKind::ClusterReplica {
1920                durable_cluster_replica: _,
1921                parsed_cluster_replica,
1922            } => {
1923                let name = parsed_cluster_replica.name.clone();
1924                self.absorb_cluster_replica(
1925                    parsed_cluster_replica,
1926                    Some(name),
1927                    catalog_update.diff,
1928                );
1929            }
1930            ParsedStateUpdateKind::IntrospectionSourceIndex { .. } => {
1931                // IntrospectionSourceIndex updates are collected
1932                // separately in apply_catalog_implications and not
1933                // routed through absorb.
1934                unreachable!("IntrospectionSourceIndex should not be passed to absorb");
1935            }
1936            ParsedStateUpdateKind::ReplicaSystemConfiguration { .. } => {
1937                // ReplicaSystemConfiguration updates are collected separately in
1938                // apply_catalog_implications and not routed through absorb.
1939                unreachable!("ReplicaSystemConfiguration should not be passed to absorb");
1940            }
1941            ParsedStateUpdateKind::SystemConfiguration { .. } => {
1942                // SystemConfiguration updates are collected separately in
1943                // apply_catalog_implications and not routed through absorb.
1944                unreachable!("SystemConfiguration should not be passed to absorb");
1945            }
1946        }
1947    }
1948
1949    impl_absorb_method!(absorb_table, Table, Table);
1950    impl_absorb_method!(
1951        absorb_source,
1952        Source,
1953        (Source, Option<GenericSourceConnection>)
1954    );
1955    impl_absorb_method!(absorb_sink, Sink, Sink);
1956    impl_absorb_method!(absorb_index, Index, Index);
1957    impl_absorb_method!(absorb_metric_sink, MetricSink, MetricSink);
1958    impl_absorb_method!(absorb_materialized_view, MaterializedView, MaterializedView);
1959    impl_absorb_method!(absorb_view, View, View);
1960
1961    impl_absorb_method!(absorb_secret, Secret, Secret);
1962    impl_absorb_method!(absorb_connection, Connection, Connection);
1963
1964    impl_absorb_method!(absorb_cluster, Cluster, Cluster);
1965    impl_absorb_method!(absorb_cluster_replica, ClusterReplica, ClusterReplica);
1966}
1967
1968/// Webhooks whose endpoint names changed in a consolidated committed diff.
1969fn webhook_sources_to_restart(updates: &[ParsedStateUpdate]) -> BTreeSet<CatalogItemId> {
1970    let mut names = BTreeMap::new();
1971    for update in updates {
1972        let ParsedStateUpdateKind::Item {
1973            durable_item,
1974            parsed_item,
1975            parsed_full_name,
1976            ..
1977        } = &update.kind
1978        else {
1979            continue;
1980        };
1981        let is_webhook = matches!(
1982            parsed_item,
1983            CatalogItem::Source(Source {
1984                data_source: DataSourceDesc::Webhook { .. },
1985                ..
1986            }) | CatalogItem::Table(Table {
1987                data_source: TableDataSource::DataSource {
1988                    desc: DataSourceDesc::Webhook { .. },
1989                    ..
1990                },
1991                ..
1992            })
1993        );
1994        if is_webhook {
1995            names
1996                .entry(durable_item.id)
1997                .or_insert(CatalogImplicationKind::None)
1998                .transition(parsed_full_name, None, update.diff)
1999                .expect("webhook updates must be consolidated");
2000        }
2001    }
2002
2003    // Schema renames rewrite their items too. Their parsed full names capture
2004    // the schema name on each side of the committed change.
2005    names
2006        .into_iter()
2007        .filter_map(|(id, change)| match change {
2008            CatalogImplicationKind::Altered { prev, new } if prev != new => Some(id),
2009            _ => None,
2010        })
2011        .collect()
2012}
2013
2014fn partition_cluster_replica_drops(
2015    clusters_with_creates: &BTreeSet<ClusterId>,
2016    drops: Vec<(ClusterId, ReplicaId)>,
2017) -> (Vec<(ClusterId, ReplicaId)>, Vec<(ClusterId, ReplicaId)>) {
2018    drops
2019        .into_iter()
2020        .partition(|(cluster_id, _)| clusters_with_creates.contains(cluster_id))
2021}
2022
2023#[cfg(test)]
2024mod tests {
2025    use super::*;
2026    use mz_repr::{GlobalId, RelationDesc, RelationVersion, VersionedRelationDesc};
2027    use mz_sql::names::{FullItemName, RawDatabaseSpecifier, ResolvedIds};
2028    use std::collections::BTreeMap;
2029
2030    fn create_test_table(name: &str) -> Table {
2031        Table {
2032            desc: VersionedRelationDesc::new(
2033                RelationDesc::builder()
2034                    .with_column(name, mz_repr::SqlScalarType::String.nullable(false))
2035                    .finish(),
2036            ),
2037            create_sql: None,
2038            collections: BTreeMap::from([(RelationVersion::root(), GlobalId::System(1))]),
2039            conn_id: None,
2040            resolved_ids: ResolvedIds::empty(),
2041            custom_logical_compaction_window: None,
2042            is_retained_metrics_object: false,
2043            data_source: TableDataSource::TableWrites { defaults: vec![] },
2044        }
2045    }
2046
2047    fn webhook_update(
2048        id: u64,
2049        [database, schema, item]: [&str; 3],
2050        diff: StateDiff,
2051        as_table: bool,
2052    ) -> ParsedStateUpdate {
2053        let full_name = FullItemName {
2054            database: RawDatabaseSpecifier::Name(database.to_string()),
2055            schema: schema.to_string(),
2056            item: item.to_string(),
2057        };
2058        let data_source = DataSourceDesc::Webhook {
2059            validate_using: None,
2060            body_format: mz_sql::plan::WebhookBodyFormat::Text,
2061            headers: mz_sql::plan::WebhookHeaders::default(),
2062            cluster_id: ClusterId::user(1).expect("valid id"),
2063        };
2064        let mut table = create_test_table("body");
2065        let parsed_item = if as_table {
2066            table.data_source = TableDataSource::DataSource {
2067                desc: data_source,
2068                timeline: mz_storage_types::sources::Timeline::EpochMilliseconds,
2069            };
2070            CatalogItem::Table(table)
2071        } else {
2072            CatalogItem::Source(Source {
2073                create_sql: None,
2074                global_id: GlobalId::User(id),
2075                data_source,
2076                desc: table.desc.latest(),
2077                timeline: mz_storage_types::sources::Timeline::EpochMilliseconds,
2078                resolved_ids: ResolvedIds::empty(),
2079                custom_logical_compaction_window: None,
2080                is_retained_metrics_object: false,
2081            })
2082        };
2083        ParsedStateUpdate {
2084            kind: ParsedStateUpdateKind::Item {
2085                durable_item: mz_catalog::durable::objects::Item {
2086                    id: CatalogItemId::User(id),
2087                    oid: 1,
2088                    global_id: GlobalId::User(id),
2089                    schema_id: mz_sql::names::SchemaId::User(1),
2090                    name: full_name.item.clone(),
2091                    create_sql: format!("CREATE SOURCE {full_name} FROM WEBHOOK BODY FORMAT TEXT"),
2092                    owner_id: mz_repr::role_id::RoleId::User(1),
2093                    privileges: vec![],
2094                    extra_versions: BTreeMap::new(),
2095                    ephemeral_owner_session: None,
2096                },
2097                parsed_item,
2098                connection: None,
2099                parsed_full_name: full_name,
2100            },
2101            ts: mz_repr::Timestamp::MIN,
2102            diff,
2103        }
2104    }
2105
2106    #[mz_ore::test]
2107    fn webhook_item_and_schema_renames_invalidate_both_representations() {
2108        for as_table in [false, true] {
2109            for new_name in [["db", "schema", "renamed"], ["db", "renamed", "hook"]] {
2110                let before =
2111                    webhook_update(1, ["db", "schema", "hook"], StateDiff::Retraction, as_table);
2112                let after = webhook_update(1, new_name, StateDiff::Addition, as_table);
2113                for updates in [
2114                    vec![before.clone(), after.clone()],
2115                    vec![after.clone(), before.clone()],
2116                ] {
2117                    assert_eq!(
2118                        webhook_sources_to_restart(&updates),
2119                        BTreeSet::from([CatalogItemId::User(1)])
2120                    );
2121                }
2122            }
2123        }
2124    }
2125
2126    #[mz_ore::test]
2127    fn webhook_invalidation_preserves_dotted_name_components() {
2128        for as_table in [false, true] {
2129            let before = webhook_update(1, ["db", "a", "b.c"], StateDiff::Retraction, as_table);
2130            let after = webhook_update(1, ["db", "a.b", "c"], StateDiff::Addition, as_table);
2131            let full_name = |update: &ParsedStateUpdate| {
2132                let ParsedStateUpdateKind::Item {
2133                    parsed_full_name, ..
2134                } = &update.kind
2135                else {
2136                    unreachable!();
2137                };
2138                parsed_full_name.to_string()
2139            };
2140            assert_eq!(full_name(&before), full_name(&after));
2141            for updates in [
2142                vec![before.clone(), after.clone()],
2143                vec![after.clone(), before.clone()],
2144            ] {
2145                assert_eq!(
2146                    webhook_sources_to_restart(&updates),
2147                    BTreeSet::from([CatalogItemId::User(1)])
2148                );
2149            }
2150            let unchanged = webhook_update(1, ["db", "a", "b.c"], StateDiff::Addition, as_table);
2151            assert!(webhook_sources_to_restart(&[before, unchanged]).is_empty());
2152        }
2153    }
2154
2155    #[mz_ore::test]
2156    fn webhook_invalidation_uses_net_names_not_intermediate_operations() {
2157        for as_table in [false, true] {
2158            let before =
2159                webhook_update(1, ["db", "schema", "hook"], StateDiff::Retraction, as_table);
2160            let after = webhook_update(1, ["db", "schema", "hook"], StateDiff::Addition, as_table);
2161            // An unchanged endpoint, including a rename away and back, needs no restart.
2162            assert!(webhook_sources_to_restart(&[before.clone(), after.clone()]).is_empty());
2163            // Create-then-rename has only a final addition. Drops use drop cleanup.
2164            assert!(webhook_sources_to_restart(&[after]).is_empty());
2165            assert!(webhook_sources_to_restart(&[before]).is_empty());
2166        }
2167
2168        let mut before = webhook_update(1, ["db", "schema", "old"], StateDiff::Retraction, true);
2169        let mut after = webhook_update(1, ["db", "schema", "new"], StateDiff::Addition, true);
2170        for update in [&mut before, &mut after] {
2171            let ParsedStateUpdateKind::Item { parsed_item, .. } = &mut update.kind else {
2172                unreachable!();
2173            };
2174            *parsed_item = CatalogItem::Table(create_test_table("body"));
2175        }
2176        assert!(webhook_sources_to_restart(&[before, after]).is_empty());
2177    }
2178
2179    #[mz_ore::test]
2180    fn webhook_atomic_name_swap_invalidates_each_item() {
2181        let updates = [
2182            webhook_update(1, ["db", "schema", "a"], StateDiff::Retraction, true),
2183            webhook_update(2, ["db", "schema", "b"], StateDiff::Retraction, true),
2184            webhook_update(2, ["db", "schema", "a"], StateDiff::Addition, true),
2185            webhook_update(1, ["db", "schema", "b"], StateDiff::Addition, true),
2186        ];
2187        assert_eq!(
2188            webhook_sources_to_restart(&updates),
2189            BTreeSet::from([CatalogItemId::User(1), CatalogItemId::User(2)])
2190        );
2191    }
2192
2193    #[mz_ore::test]
2194    fn mixed_replica_drops_are_applied_before_creates() {
2195        let c1 = ClusterId::user(1).expect("valid id");
2196        let c2 = ClusterId::user(2).expect("valid id");
2197        let r1 = ReplicaId::User(1);
2198        let r2 = ReplicaId::User(2);
2199        let creates = BTreeSet::from([c1]);
2200
2201        let (before_creates, deferred) =
2202            partition_cluster_replica_drops(&creates, vec![(c1, r1), (c2, r2)]);
2203
2204        assert_eq!(before_creates, vec![(c1, r1)]);
2205        assert_eq!(deferred, vec![(c2, r2)]);
2206    }
2207
2208    #[mz_ore::test]
2209    fn test_item_state_transitions() {
2210        // Test None -> Added
2211        let mut state = CatalogImplicationKind::None;
2212        assert!(
2213            state
2214                .transition("item1".to_string(), None, StateDiff::Addition)
2215                .is_ok()
2216        );
2217        assert!(matches!(state, CatalogImplicationKind::Added(_)));
2218
2219        // Test Added -> Altered (via retraction)
2220        let mut state = CatalogImplicationKind::Added("new_item".to_string());
2221        assert!(
2222            state
2223                .transition("old_item".to_string(), None, StateDiff::Retraction)
2224                .is_ok()
2225        );
2226        match &state {
2227            CatalogImplicationKind::Altered { prev, new } => {
2228                // The retracted item is the OLD state
2229                assert_eq!(prev, "old_item");
2230                // The existing Added item is the NEW state
2231                assert_eq!(new, "new_item");
2232            }
2233            _ => panic!("Expected Altered state"),
2234        }
2235
2236        // Test None -> Dropped
2237        let mut state = CatalogImplicationKind::None;
2238        assert!(
2239            state
2240                .transition(
2241                    "item1".to_string(),
2242                    Some("test_name".to_string()),
2243                    StateDiff::Retraction
2244                )
2245                .is_ok()
2246        );
2247        assert!(matches!(state, CatalogImplicationKind::Dropped(_, _)));
2248
2249        // Test Dropped -> Altered (via addition)
2250        let mut state = CatalogImplicationKind::Dropped("old_item".to_string(), "name".to_string());
2251        assert!(
2252            state
2253                .transition("new_item".to_string(), None, StateDiff::Addition)
2254                .is_ok()
2255        );
2256        match &state {
2257            CatalogImplicationKind::Altered { prev, new } => {
2258                // The existing Dropped item is the OLD state
2259                assert_eq!(prev, "old_item");
2260                // The added item is the NEW state
2261                assert_eq!(new, "new_item");
2262            }
2263            _ => panic!("Expected Altered state"),
2264        }
2265
2266        // Test invalid transitions
2267        let mut state = CatalogImplicationKind::Added("item".to_string());
2268        assert!(
2269            state
2270                .transition("item2".to_string(), None, StateDiff::Addition)
2271                .is_err()
2272        );
2273
2274        let mut state = CatalogImplicationKind::Dropped("item".to_string(), "name".to_string());
2275        assert!(
2276            state
2277                .transition("item2".to_string(), None, StateDiff::Retraction)
2278                .is_err()
2279        );
2280    }
2281
2282    #[mz_ore::test]
2283    fn test_table_absorb_state_machine() {
2284        let table1 = create_test_table("table1");
2285        let table2 = create_test_table("table2");
2286
2287        // Test None -> AddTable
2288        let mut cmd = CatalogImplication::None;
2289        cmd.absorb_table(
2290            table1.clone(),
2291            Some("schema.table1".to_string()),
2292            StateDiff::Addition,
2293        );
2294        // Check that we have an Added state
2295        match &cmd {
2296            CatalogImplication::Table(state) => match state {
2297                CatalogImplicationKind::Added(t) => {
2298                    assert_eq!(t.desc.latest().arity(), table1.desc.latest().arity())
2299                }
2300                _ => panic!("Expected Added state"),
2301            },
2302            _ => panic!("Expected Table command"),
2303        }
2304
2305        // Test AddTable -> AlterTable (via retraction)
2306        // This tests the bug fix: when we have AddTable(table1) and receive Retraction(table2),
2307        // table2 is the old state being removed, table1 is the new state
2308        cmd.absorb_table(
2309            table2.clone(),
2310            Some("schema.table2".to_string()),
2311            StateDiff::Retraction,
2312        );
2313        match &cmd {
2314            CatalogImplication::Table(state) => match state {
2315                CatalogImplicationKind::Altered { prev, new } => {
2316                    // Verify the fix: prev should be the retracted table, new should be the added table
2317                    assert_eq!(prev.desc.latest().arity(), table2.desc.latest().arity());
2318                    assert_eq!(new.desc.latest().arity(), table1.desc.latest().arity());
2319                }
2320                _ => panic!("Expected Altered state"),
2321            },
2322            _ => panic!("Expected Table command"),
2323        }
2324
2325        // Test None -> DropTable
2326        let mut cmd = CatalogImplication::None;
2327        cmd.absorb_table(
2328            table1.clone(),
2329            Some("schema.table1".to_string()),
2330            StateDiff::Retraction,
2331        );
2332        match &cmd {
2333            CatalogImplication::Table(state) => match state {
2334                CatalogImplicationKind::Dropped(t, name) => {
2335                    assert_eq!(t.desc.latest().arity(), table1.desc.latest().arity());
2336                    assert_eq!(name, "schema.table1");
2337                }
2338                _ => panic!("Expected Dropped state"),
2339            },
2340            _ => panic!("Expected Table command"),
2341        }
2342
2343        // Test DropTable -> AlterTable (via addition)
2344        cmd.absorb_table(
2345            table2.clone(),
2346            Some("schema.table2".to_string()),
2347            StateDiff::Addition,
2348        );
2349        match &cmd {
2350            CatalogImplication::Table(state) => match state {
2351                CatalogImplicationKind::Altered { prev, new } => {
2352                    // prev should be the dropped table, new should be the added table
2353                    assert_eq!(prev.desc.latest().arity(), table1.desc.latest().arity());
2354                    assert_eq!(new.desc.latest().arity(), table2.desc.latest().arity());
2355                }
2356                _ => panic!("Expected Altered state"),
2357            },
2358            _ => panic!("Expected Table command"),
2359        }
2360    }
2361
2362    #[mz_ore::test]
2363    #[should_panic(expected = "Cannot add an already added object")]
2364    fn test_invalid_double_add() {
2365        let table = create_test_table("table");
2366        let mut cmd = CatalogImplication::None;
2367
2368        // First addition
2369        cmd.absorb_table(
2370            table.clone(),
2371            Some("schema.table".to_string()),
2372            StateDiff::Addition,
2373        );
2374
2375        // Second addition should panic
2376        cmd.absorb_table(
2377            table.clone(),
2378            Some("schema.table".to_string()),
2379            StateDiff::Addition,
2380        );
2381    }
2382
2383    #[mz_ore::test]
2384    #[should_panic(expected = "Cannot drop an already dropped object")]
2385    fn test_invalid_double_drop() {
2386        let table = create_test_table("table");
2387        let mut cmd = CatalogImplication::None;
2388
2389        // First drop
2390        cmd.absorb_table(
2391            table.clone(),
2392            Some("schema.table".to_string()),
2393            StateDiff::Retraction,
2394        );
2395
2396        // Second drop should panic
2397        cmd.absorb_table(
2398            table.clone(),
2399            Some("schema.table".to_string()),
2400            StateDiff::Retraction,
2401        );
2402    }
2403}