Skip to main content

mz_adapter/catalog/
apply.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 applying updates from a [`mz_catalog::durable::DurableCatalogState`] to a
11//! [`CatalogState`].
12
13use std::collections::{BTreeMap, BTreeSet, VecDeque};
14use std::fmt::Debug;
15use std::iter;
16use std::str::FromStr;
17use std::sync::Arc;
18
19use differential_dataflow::consolidation::consolidate_updates;
20use futures::future;
21use itertools::{Either, Itertools};
22use mz_adapter_types::connection::ConnectionId;
23use mz_catalog::SYSTEM_CONN_ID;
24use mz_catalog::builtin::{
25    BUILTIN_LOG_LOOKUP, BUILTIN_LOOKUP, Builtin, BuiltinLog, BuiltinTable, BuiltinView,
26};
27use mz_catalog::durable::objects::{
28    ClusterKey, DatabaseKey, DurableType, ItemKey, NetworkPolicyKey, QueryPolicyKey, RoleAuthKey,
29    RoleKey, SchemaKey,
30};
31use mz_catalog::durable::{CatalogError, SystemObjectMapping};
32use mz_catalog::memory::error::{Error, ErrorKind};
33use mz_catalog::memory::objects::{
34    CatalogEntry, CatalogItem, Cluster, ClusterReplica, Database, Func, Index, Log, NetworkPolicy,
35    QueryPolicy, Role, RoleAuth, Schema, Source, StateDiff, StateUpdate, StateUpdateKind, Table,
36    TableDataSource, Type, UpdateFrom,
37};
38use mz_compute_types::config::ComputeReplicaConfig;
39use mz_compute_types::dataflows::DataflowDescription;
40use mz_controller::clusters::{ReplicaConfig, ReplicaLogging};
41use mz_controller_types::ClusterId;
42use mz_expr::MirScalarExpr;
43use mz_ore::collections::CollectionExt;
44use mz_ore::tracing::OpenTelemetryContext;
45use mz_ore::{
46    instrument, soft_assert_eq_or_log, soft_assert_no_log, soft_assert_or_log, soft_panic_or_log,
47};
48use mz_pgrepr::oid::INVALID_OID;
49use mz_repr::adt::mz_acl_item::{MzAclItem, PrivilegeMap};
50use mz_repr::role_id::RoleId;
51use mz_repr::{CatalogItemId, Diff, GlobalId, RelationVersion, Timestamp, VersionedRelationDesc};
52use mz_sql::catalog::CatalogError as SqlCatalogError;
53use mz_sql::catalog::{CatalogItem as SqlCatalogItem, CatalogItemType, CatalogSchema, CatalogType};
54use mz_sql::names::{
55    FullItemName, ItemQualifiers, QualifiedItemName, RawDatabaseSpecifier,
56    ResolvedDatabaseSpecifier, ResolvedIds, SchemaSpecifier,
57};
58use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
59use mz_sql::session::vars::{VarError, VarInput};
60use mz_sql::{plan, rbac};
61use mz_sql_parser::ast::Expr;
62use mz_storage_types::sources::Timeline;
63use mz_transform::dataflow::DataflowMetainfo;
64use mz_transform::notice::OptimizerNotice;
65use tracing::{info_span, warn};
66
67use crate::AdapterError;
68use crate::catalog::state::LocalExpressionCache;
69use crate::catalog::{BuiltinTableUpdate, CatalogState};
70use crate::coord::catalog_implications::parsed_state_updates::{self, ParsedStateUpdate};
71use crate::util::{index_sql, sort_topological};
72
73/// Maintains the state of retractions while applying catalog state updates for a single timestamp.
74/// [`CatalogState`] maintains denormalized state for certain catalog objects. Updating an object
75/// results in applying a retraction for that object followed by applying an addition for that
76/// object. When applying those additions it can be extremely expensive to re-build that
77/// denormalized state from scratch. To avoid that issue we stash the denormalized state from
78/// retractions, so it can be used during additions.
79///
80/// Not all objects maintain denormalized state, so we only stash the retractions for the subset of
81/// objects that maintain denormalized state.
82// TODO(jkosh44) It might be simpler or more future proof to include all object types here, even if
83// the update step is a no-op for certain types.
84#[derive(Debug, Clone, Default)]
85struct InProgressRetractions {
86    roles: BTreeMap<RoleKey, Role>,
87    role_auths: BTreeMap<RoleAuthKey, RoleAuth>,
88    databases: BTreeMap<DatabaseKey, Database>,
89    schemas: BTreeMap<SchemaKey, Schema>,
90    clusters: BTreeMap<ClusterKey, Cluster>,
91    network_policies: BTreeMap<NetworkPolicyKey, NetworkPolicy>,
92    query_policies: BTreeMap<QueryPolicyKey, QueryPolicy>,
93    items: BTreeMap<ItemKey, CatalogEntry>,
94    introspection_source_indexes: BTreeMap<CatalogItemId, CatalogEntry>,
95    system_object_mappings: BTreeMap<CatalogItemId, CatalogEntry>,
96}
97
98impl CatalogState {
99    /// Update in-memory catalog state from a list of updates made to the durable catalog state.
100    ///
101    /// Returns builtin table updates corresponding to the changes to catalog state.
102    #[must_use]
103    #[instrument]
104    pub(crate) async fn apply_updates(
105        &mut self,
106        updates: Vec<StateUpdate>,
107        local_expression_cache: &mut LocalExpressionCache,
108    ) -> (
109        Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
110        Vec<ParsedStateUpdate>,
111    ) {
112        let mut builtin_table_updates = Vec::with_capacity(updates.len());
113        let mut catalog_updates = Vec::with_capacity(updates.len());
114
115        // First, consolidate updates. The code that applies parsed state
116        // updates _requires_ that the given updates are consolidated. There
117        // must be at most one addition and/or one retraction for a given item,
118        // as identified by that items ID type.
119        let updates = Self::consolidate_updates(updates);
120
121        // Apply updates in groups, according to their timestamps.
122        let mut groups: Vec<Vec<_>> = Vec::new();
123        for (_, updates) in &updates.into_iter().chunk_by(|update| update.ts) {
124            // Bring the updates into the pseudo-topological order that we need
125            // for updating our in-memory state and generating builtin table
126            // updates.
127            let updates = sort_updates(updates.collect());
128            groups.push(updates);
129        }
130
131        for updates in groups {
132            let mut apply_state = ApplyState::Updates(Vec::new());
133            let mut retractions = InProgressRetractions::default();
134
135            for update in updates {
136                let (next_apply_state, (builtin_table_update, catalog_update)) = apply_state
137                    .step(
138                        ApplyState::new(update),
139                        self,
140                        &mut retractions,
141                        local_expression_cache,
142                    )
143                    .await;
144                apply_state = next_apply_state;
145                builtin_table_updates.extend(builtin_table_update);
146                catalog_updates.extend(catalog_update);
147            }
148
149            // Apply remaining state.
150            let (builtin_table_update, catalog_update) = apply_state
151                .apply(self, &mut retractions, local_expression_cache)
152                .await;
153            builtin_table_updates.extend(builtin_table_update);
154            catalog_updates.extend(catalog_update);
155
156            // Clean up plans and optimizer notices for items that
157            // were retracted but not replaced (i.e., truly dropped).
158            let dropped_entries: Vec<CatalogEntry> = retractions.items.into_values().collect();
159            if !dropped_entries.is_empty() {
160                let dropped_notices = self.drop_optimizer_notices(dropped_entries);
161                if self.system_config().enable_mz_notices() {
162                    self.pack_optimizer_notice_updates(
163                        &mut builtin_table_updates,
164                        dropped_notices.iter(),
165                        Diff::MINUS_ONE,
166                    );
167                }
168            }
169        }
170
171        (builtin_table_updates, catalog_updates)
172    }
173
174    /// It can happen that the sequencing logic creates "fluctuating" updates
175    /// for a given catalog ID. For example, when doing a `DROP OWNED BY ...`,
176    /// for a table, there will be a retraction of the original table state,
177    /// then an addition for the same table but stripped of some of the roles
178    /// and access things, and then a retraction for that intermediate table
179    /// state. By consolidating, the intermediate state addition/retraction will
180    /// cancel out and we'll only see the retraction for the original state.
181    fn consolidate_updates(updates: Vec<StateUpdate>) -> Vec<StateUpdate> {
182        let mut updates: Vec<(StateUpdateKind, Timestamp, mz_repr::Diff)> = updates
183            .into_iter()
184            .map(|update| (update.kind, update.ts, update.diff.into()))
185            .collect_vec();
186
187        consolidate_updates(&mut updates);
188
189        updates
190            .into_iter()
191            .map(|(kind, ts, diff)| StateUpdate {
192                kind,
193                ts,
194                diff: diff
195                    .try_into()
196                    .expect("catalog state cannot have diff other than -1 or 1"),
197            })
198            .collect_vec()
199    }
200
201    #[instrument(level = "debug")]
202    fn apply_updates_inner(
203        &mut self,
204        updates: Vec<StateUpdate>,
205        retractions: &mut InProgressRetractions,
206        local_expression_cache: &mut LocalExpressionCache,
207    ) -> Result<
208        (
209            Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
210            Vec<ParsedStateUpdate>,
211        ),
212        CatalogError,
213    > {
214        soft_assert_no_log!(
215            updates.iter().map(|update| update.ts).all_equal(),
216            "all timestamps should be equal: {updates:?}"
217        );
218
219        let mut update_system_config = false;
220
221        let mut builtin_table_updates = Vec::with_capacity(updates.len());
222        let mut catalog_updates = Vec::new();
223
224        for state_update in updates {
225            // Do not apply temporary item updates from other processes, since
226            // temporary items are scoped per session, which must be in the
227            // same process.
228            if self.is_nonlocal_ephemeral_item_update(&state_update) {
229                tracing::debug!(
230                    ?state_update,
231                    "skipping ephemeral item update for non-local session"
232                );
233                continue;
234            }
235
236            if matches!(state_update.kind, StateUpdateKind::SystemConfiguration(_)) {
237                update_system_config = true;
238            }
239
240            match state_update.diff {
241                StateDiff::Retraction => {
242                    // We want the parsed catalog updates to match the state of
243                    // the catalog _before_ applying a retraction. So that we can
244                    // still have useful in-memory state to work with.
245                    if let Some(update) =
246                        parsed_state_updates::parse_state_update(self, state_update.clone())
247                    {
248                        catalog_updates.push(update);
249                    }
250
251                    // We want the builtin table retraction to match the state of the catalog
252                    // before applying the update.
253                    builtin_table_updates.extend(self.generate_builtin_table_update(
254                        state_update.kind.clone(),
255                        state_update.diff,
256                    ));
257                    self.apply_update(
258                        state_update.kind,
259                        state_update.diff,
260                        retractions,
261                        local_expression_cache,
262                    )?;
263                }
264                StateDiff::Addition => {
265                    self.apply_update(
266                        state_update.kind.clone(),
267                        state_update.diff,
268                        retractions,
269                        local_expression_cache,
270                    )?;
271                    // We want the builtin table addition to match the state of
272                    // the catalog after applying the update. So that we already
273                    // have useful in-memory state to work with.
274                    builtin_table_updates.extend(self.generate_builtin_table_update(
275                        state_update.kind.clone(),
276                        state_update.diff,
277                    ));
278
279                    // We want the parsed catalog updates to match the state of
280                    // the catalog _after_ applying an addition.
281                    if let Some(update) =
282                        parsed_state_updates::parse_state_update(self, state_update.clone())
283                    {
284                        catalog_updates.push(update);
285                    }
286                }
287            }
288        }
289
290        if update_system_config {
291            self.system_configuration.sync_dyncfgs();
292        }
293
294        Ok((builtin_table_updates, catalog_updates))
295    }
296
297    #[instrument(level = "debug")]
298    fn apply_update(
299        &mut self,
300        kind: StateUpdateKind,
301        diff: StateDiff,
302        retractions: &mut InProgressRetractions,
303        local_expression_cache: &mut LocalExpressionCache,
304    ) -> Result<(), CatalogError> {
305        match kind {
306            StateUpdateKind::Role(role) => {
307                self.apply_role_update(role, diff, retractions);
308            }
309            StateUpdateKind::RoleAuth(role_auth) => {
310                self.apply_role_auth_update(role_auth, diff, retractions);
311            }
312            StateUpdateKind::Database(database) => {
313                self.apply_database_update(database, diff, retractions);
314            }
315            StateUpdateKind::Schema(schema) => {
316                self.apply_schema_update(schema, diff, retractions);
317            }
318            StateUpdateKind::DefaultPrivilege(default_privilege) => {
319                self.apply_default_privilege_update(default_privilege, diff, retractions);
320            }
321            StateUpdateKind::SystemPrivilege(system_privilege) => {
322                self.apply_system_privilege_update(system_privilege, diff, retractions);
323            }
324            StateUpdateKind::SystemConfiguration(system_configuration) => {
325                self.apply_system_configuration_update(system_configuration, diff, retractions);
326            }
327            StateUpdateKind::ClusterSystemConfiguration(cfg) => {
328                Self::apply_scoped_system_configuration_update(
329                    &mut self.scoped_system_parameters.cluster,
330                    cfg.cluster_id,
331                    cfg.name,
332                    cfg.value,
333                    diff,
334                );
335            }
336            StateUpdateKind::ReplicaSystemConfiguration(cfg) => {
337                Self::apply_scoped_system_configuration_update(
338                    &mut self.scoped_system_parameters.replica,
339                    cfg.replica_id,
340                    cfg.name,
341                    cfg.value,
342                    diff,
343                );
344            }
345            StateUpdateKind::Cluster(cluster) => {
346                self.apply_cluster_update(cluster, diff, retractions);
347            }
348            StateUpdateKind::NetworkPolicy(network_policy) => {
349                self.apply_network_policy_update(network_policy, diff, retractions);
350            }
351            StateUpdateKind::ClusterReplicaSize(size) => {
352                self.apply_cluster_replica_size_update(size, diff);
353            }
354            StateUpdateKind::QueryPolicy(policy) => {
355                apply_inverted_lookup(
356                    &mut self.query_policies_by_name,
357                    &policy.name,
358                    policy.id,
359                    diff,
360                );
361                apply_with_update(
362                    &mut self.query_policies_by_id,
363                    policy,
364                    |policy| policy.id,
365                    diff,
366                    &mut retractions.query_policies,
367                );
368            }
369            StateUpdateKind::IntrospectionSourceIndex(introspection_source_index) => {
370                self.apply_introspection_source_index_update(
371                    introspection_source_index,
372                    diff,
373                    retractions,
374                );
375            }
376            StateUpdateKind::ClusterReplica(cluster_replica) => {
377                self.apply_cluster_replica_update(cluster_replica, diff, retractions);
378            }
379            StateUpdateKind::SystemObjectMapping(system_object_mapping) => {
380                self.apply_system_object_mapping_update(
381                    system_object_mapping,
382                    diff,
383                    retractions,
384                    local_expression_cache,
385                );
386            }
387            StateUpdateKind::Item(item) => {
388                self.apply_item_update(item, diff, retractions, local_expression_cache)?;
389            }
390            StateUpdateKind::Comment(comment) => {
391                self.apply_comment_update(comment, diff, retractions);
392            }
393            StateUpdateKind::SourceReferences(source_reference) => {
394                self.apply_source_references_update(source_reference, diff, retractions);
395            }
396            StateUpdateKind::AuditLog(_audit_log) => {
397                // Audit logs are not stored in-memory.
398            }
399            StateUpdateKind::StorageCollectionMetadata(storage_collection_metadata) => {
400                self.apply_storage_collection_metadata_update(
401                    storage_collection_metadata,
402                    diff,
403                    retractions,
404                );
405            }
406            StateUpdateKind::UnfinalizedShard(unfinalized_shard) => {
407                self.apply_unfinalized_shard_update(unfinalized_shard, diff, retractions);
408            }
409        }
410
411        Ok(())
412    }
413
414    #[instrument(level = "debug")]
415    fn apply_role_auth_update(
416        &mut self,
417        role_auth: mz_catalog::durable::RoleAuth,
418        diff: StateDiff,
419        retractions: &mut InProgressRetractions,
420    ) {
421        apply_with_update(
422            &mut self.role_auth_by_id,
423            role_auth,
424            |role_auth| role_auth.role_id,
425            diff,
426            &mut retractions.role_auths,
427        );
428    }
429
430    #[instrument(level = "debug")]
431    fn apply_role_update(
432        &mut self,
433        role: mz_catalog::durable::Role,
434        diff: StateDiff,
435        retractions: &mut InProgressRetractions,
436    ) {
437        apply_inverted_lookup(&mut self.roles_by_name, &role.name, role.id, diff);
438        apply_with_update(
439            &mut self.roles_by_id,
440            role,
441            |role| role.id,
442            diff,
443            &mut retractions.roles,
444        );
445    }
446
447    #[instrument(level = "debug")]
448    fn apply_database_update(
449        &mut self,
450        database: mz_catalog::durable::Database,
451        diff: StateDiff,
452        retractions: &mut InProgressRetractions,
453    ) {
454        apply_inverted_lookup(
455            &mut self.database_by_name,
456            &database.name,
457            database.id,
458            diff,
459        );
460        apply_with_update(
461            &mut self.database_by_id,
462            database,
463            |database| database.id,
464            diff,
465            &mut retractions.databases,
466        );
467    }
468
469    #[instrument(level = "debug")]
470    fn apply_schema_update(
471        &mut self,
472        schema: mz_catalog::durable::Schema,
473        diff: StateDiff,
474        retractions: &mut InProgressRetractions,
475    ) {
476        match &schema.database_id {
477            Some(database_id) => {
478                let db = self
479                    .database_by_id
480                    .get_mut(database_id)
481                    .expect("catalog out of sync");
482                apply_inverted_lookup(&mut db.schemas_by_name, &schema.name, schema.id, diff);
483                apply_with_update(
484                    &mut db.schemas_by_id,
485                    schema,
486                    |schema| schema.id,
487                    diff,
488                    &mut retractions.schemas,
489                );
490            }
491            None => {
492                apply_inverted_lookup(
493                    &mut self.ambient_schemas_by_name,
494                    &schema.name,
495                    schema.id,
496                    diff,
497                );
498                apply_with_update(
499                    &mut self.ambient_schemas_by_id,
500                    schema,
501                    |schema| schema.id,
502                    diff,
503                    &mut retractions.schemas,
504                );
505            }
506        }
507    }
508
509    #[instrument(level = "debug")]
510    fn apply_default_privilege_update(
511        &mut self,
512        default_privilege: mz_catalog::durable::DefaultPrivilege,
513        diff: StateDiff,
514        _retractions: &mut InProgressRetractions,
515    ) {
516        match diff {
517            StateDiff::Addition => Arc::make_mut(&mut self.default_privileges)
518                .grant(default_privilege.object, default_privilege.acl_item),
519            StateDiff::Retraction => Arc::make_mut(&mut self.default_privileges)
520                .revoke(&default_privilege.object, &default_privilege.acl_item),
521        }
522    }
523
524    #[instrument(level = "debug")]
525    fn apply_system_privilege_update(
526        &mut self,
527        system_privilege: MzAclItem,
528        diff: StateDiff,
529        _retractions: &mut InProgressRetractions,
530    ) {
531        match diff {
532            StateDiff::Addition => {
533                Arc::make_mut(&mut self.system_privileges).grant(system_privilege)
534            }
535            StateDiff::Retraction => {
536                Arc::make_mut(&mut self.system_privileges).revoke(&system_privilege)
537            }
538        }
539    }
540
541    #[instrument(level = "debug")]
542    fn apply_system_configuration_update(
543        &mut self,
544        system_configuration: mz_catalog::durable::SystemConfiguration,
545        diff: StateDiff,
546        _retractions: &mut InProgressRetractions,
547    ) {
548        let res = match diff {
549            StateDiff::Addition => self.insert_system_configuration(
550                &system_configuration.name,
551                VarInput::Flat(&system_configuration.value),
552            ),
553            StateDiff::Retraction => self.remove_system_configuration(&system_configuration.name),
554        };
555        match res {
556            Ok(_) => (),
557            // When system variables are deleted, nothing deletes them from the underlying
558            // durable catalog, which isn't great. Still, we need to be able to ignore
559            // unknown variables.
560            Err(Error {
561                kind: ErrorKind::VarError(VarError::UnknownParameter(name)),
562            }) => {
563                warn!(%name, "unknown system parameter from catalog storage");
564            }
565            Err(e) => panic!("unable to update system variable: {e:?}"),
566        }
567    }
568
569    /// Applies a durable update to one of the in-memory scoped-parameter working
570    /// copies (`scoped_system_parameters.{cluster,replica}`), keyed by object
571    /// id. Mirrors the durable `{cluster,replica}_system_configurations`
572    /// collections; the cluster copy is consumed at plan time via
573    /// [`CatalogState::cluster_scoped_optimizer_overrides`], the replica copy at
574    /// the compute controller's per-replica dyncfg push.
575    ///
576    /// Retraction is conditional on the value matching, so a value change
577    /// (retraction of the old value + addition of the new) is correct regardless
578    /// of the order the two updates are applied in. See the scoped feature flags
579    /// design.
580    ///
581    /// [`CatalogState::cluster_scoped_optimizer_overrides`]: crate::catalog::CatalogState::cluster_scoped_optimizer_overrides
582    fn apply_scoped_system_configuration_update<Id: Ord>(
583        map: &mut BTreeMap<Id, BTreeMap<String, String>>,
584        id: Id,
585        name: String,
586        value: String,
587        diff: StateDiff,
588    ) {
589        match diff {
590            StateDiff::Addition => {
591                map.entry(id).or_default().insert(name, value);
592            }
593            StateDiff::Retraction => {
594                if let Some(values) = map.get_mut(&id) {
595                    if values.get(&name) == Some(&value) {
596                        values.remove(&name);
597                        if values.is_empty() {
598                            map.remove(&id);
599                        }
600                    }
601                }
602            }
603        }
604    }
605
606    #[instrument(level = "debug")]
607    fn apply_cluster_update(
608        &mut self,
609        cluster: mz_catalog::durable::Cluster,
610        diff: StateDiff,
611        retractions: &mut InProgressRetractions,
612    ) {
613        // Soft signal for a managed cluster whose replica size isn't in
614        // the in-memory size map. The `mz_clusters` MV LEFT JOINs the size
615        // table and resolves `disk` to false when the size is missing, so
616        // this case no longer crashes a managed cluster with RF=0.
617        // A managed cluster with at least one running replica still panics
618        // via `concretize_replica_location` in `apply_cluster_replica_update`.
619        if matches!(diff, StateDiff::Addition) {
620            if let mz_catalog::durable::ClusterVariant::Managed(managed) = &cluster.config.variant {
621                if !self.cluster_replica_sizes.0.contains_key(&managed.size) {
622                    soft_panic_or_log!(
623                        "managed cluster {} ({}) references unknown replica size {:?}; \
624                         mz_clusters.disk will resolve to false",
625                        cluster.name,
626                        cluster.id,
627                        managed.size,
628                    );
629                }
630            }
631        }
632        apply_inverted_lookup(&mut self.clusters_by_name, &cluster.name, cluster.id, diff);
633        apply_with_update(
634            &mut self.clusters_by_id,
635            cluster,
636            |cluster| cluster.id,
637            diff,
638            &mut retractions.clusters,
639        );
640    }
641
642    #[instrument(level = "debug")]
643    fn apply_network_policy_update(
644        &mut self,
645        policy: mz_catalog::durable::NetworkPolicy,
646        diff: StateDiff,
647        retractions: &mut InProgressRetractions,
648    ) {
649        apply_inverted_lookup(
650            &mut self.network_policies_by_name,
651            &policy.name,
652            policy.id,
653            diff,
654        );
655        apply_with_update(
656            &mut self.network_policies_by_id,
657            policy,
658            |policy| policy.id,
659            diff,
660            &mut retractions.network_policies,
661        );
662    }
663
664    #[instrument(level = "debug")]
665    fn apply_cluster_replica_size_update(
666        &mut self,
667        size: mz_catalog::durable::ClusterReplicaSize,
668        diff: StateDiff,
669    ) {
670        let sizes = &mut self.cluster_replica_sizes.0;
671        match diff {
672            StateDiff::Addition => {
673                sizes.insert(size.name, size.allocation);
674            }
675            StateDiff::Retraction => {
676                sizes.remove(&size.name);
677            }
678        }
679    }
680
681    #[instrument(level = "debug")]
682    fn apply_introspection_source_index_update(
683        &mut self,
684        introspection_source_index: mz_catalog::durable::IntrospectionSourceIndex,
685        diff: StateDiff,
686        retractions: &mut InProgressRetractions,
687    ) {
688        let cluster = self
689            .clusters_by_id
690            .get_mut(&introspection_source_index.cluster_id)
691            .expect("catalog out of sync");
692        let log = BUILTIN_LOG_LOOKUP
693            .get(introspection_source_index.name.as_str())
694            .expect("missing log");
695        apply_inverted_lookup(
696            &mut cluster.log_indexes,
697            &log.variant,
698            introspection_source_index.index_id,
699            diff,
700        );
701
702        match diff {
703            StateDiff::Addition => {
704                if let Some(mut entry) = retractions
705                    .introspection_source_indexes
706                    .remove(&introspection_source_index.item_id)
707                {
708                    // This should only happen during startup as a result of builtin migrations. We
709                    // create a new index item and replace the old one with it.
710                    let (index_name, index) = self.create_introspection_source_index(
711                        introspection_source_index.cluster_id,
712                        log,
713                        introspection_source_index.index_id,
714                    );
715                    assert_eq!(entry.id, introspection_source_index.item_id);
716                    assert_eq!(entry.oid, introspection_source_index.oid);
717                    assert_eq!(entry.name, index_name);
718                    entry.item = index;
719                    self.insert_entry(entry);
720                } else {
721                    self.insert_introspection_source_index(
722                        introspection_source_index.cluster_id,
723                        log,
724                        introspection_source_index.item_id,
725                        introspection_source_index.index_id,
726                        introspection_source_index.oid,
727                    );
728                }
729            }
730            StateDiff::Retraction => {
731                let entry = self.drop_item(introspection_source_index.item_id);
732                retractions
733                    .introspection_source_indexes
734                    .insert(entry.id, entry);
735            }
736        }
737    }
738
739    #[instrument(level = "debug")]
740    fn apply_cluster_replica_update(
741        &mut self,
742        cluster_replica: mz_catalog::durable::ClusterReplica,
743        diff: StateDiff,
744        _retractions: &mut InProgressRetractions,
745    ) {
746        let cluster = self
747            .clusters_by_id
748            .get(&cluster_replica.cluster_id)
749            .expect("catalog out of sync");
750
751        // Mirror the cluster-side soft signal: if a managed replica's size
752        // is no longer in the in-memory size map, skip in-memory
753        // registration rather than panicking. The mz_cluster_replicas MV
754        // resolves `disk` from mz_cluster_replica_size_internal (which
755        // retains rows for disabled sizes), so SQL still returns sensible
756        // results. We tolerate disabled sizes here (allow_disabled=true)
757        // because an existing replica must remain queryable even if the
758        // operator has since disabled its size.
759        if let mz_catalog::durable::ReplicaLocation::Managed { size, .. } =
760            &cluster_replica.config.location
761        {
762            if !self.cluster_replica_sizes.0.contains_key(size) {
763                soft_panic_or_log!(
764                    "cluster replica {}.{} ({}) references unknown replica size {:?}; \
765                     skipping in-memory registration",
766                    cluster.name,
767                    cluster_replica.name,
768                    cluster_replica.replica_id,
769                    size,
770                );
771                return;
772            }
773        }
774
775        // Pass no availability-zone override: a rebuild from the durable record
776        // keeps the AZ list the replica was provisioned under, which may differ
777        // from the cluster's current pool while a graceful reconfiguration is in
778        // flight — the cluster controller tells realized- from target-shape
779        // replicas by exactly this list.
780        let location = self
781            .concretize_replica_location(cluster_replica.config.location, &vec![], None, true)
782            .expect("catalog in unexpected state");
783        let cluster = self
784            .clusters_by_id
785            .get_mut(&cluster_replica.cluster_id)
786            .expect("catalog out of sync");
787        apply_inverted_lookup(
788            &mut cluster.replica_id_by_name_,
789            &cluster_replica.name,
790            cluster_replica.replica_id,
791            diff,
792        );
793        match diff {
794            StateDiff::Retraction => {
795                let prev = cluster.replicas_by_id_.remove(&cluster_replica.replica_id);
796                assert!(
797                    prev.is_some(),
798                    "retraction does not match existing value: {:?}",
799                    cluster_replica.replica_id
800                );
801            }
802            StateDiff::Addition => {
803                let logging = ReplicaLogging {
804                    log_logging: cluster_replica.config.logging.log_logging,
805                    interval: cluster_replica.config.logging.interval,
806                };
807                let config = ReplicaConfig {
808                    location,
809                    compute: ComputeReplicaConfig {
810                        logging,
811                        arrangement_compression: cluster_replica.config.arrangement_compression,
812                    },
813                };
814                let mem_cluster_replica = ClusterReplica {
815                    name: cluster_replica.name.clone(),
816                    cluster_id: cluster_replica.cluster_id,
817                    replica_id: cluster_replica.replica_id,
818                    config,
819                    owner_id: cluster_replica.owner_id,
820                };
821                let prev = cluster
822                    .replicas_by_id_
823                    .insert(cluster_replica.replica_id, mem_cluster_replica);
824                assert_eq!(
825                    prev, None,
826                    "values must be explicitly retracted before inserting a new value: {:?}",
827                    cluster_replica.replica_id
828                );
829            }
830        }
831    }
832
833    #[instrument(level = "debug")]
834    fn apply_system_object_mapping_update(
835        &mut self,
836        system_object_mapping: mz_catalog::durable::SystemObjectMapping,
837        diff: StateDiff,
838        retractions: &mut InProgressRetractions,
839        local_expression_cache: &mut LocalExpressionCache,
840    ) {
841        let item_id = system_object_mapping.unique_identifier.catalog_id;
842        let global_id = system_object_mapping.unique_identifier.global_id;
843
844        if system_object_mapping.unique_identifier.runtime_alterable() {
845            // Runtime-alterable system objects have real entries in the items
846            // collection and so get handled through the normal `insert_item`
847            // and `drop_item` code paths.
848            return;
849        }
850
851        if let StateDiff::Retraction = diff {
852            let entry = self.drop_item(item_id);
853            retractions.system_object_mappings.insert(item_id, entry);
854            return;
855        }
856
857        if let Some(entry) = retractions.system_object_mappings.remove(&item_id) {
858            // This implies that we updated the fingerprint for some builtin item. The retraction
859            // was parsed, planned, and optimized using the compiled in definition, not the
860            // definition from a previous version. So we can just stick the old entry back into the
861            // catalog.
862            self.insert_entry(entry);
863            return;
864        }
865
866        let builtin = BUILTIN_LOOKUP
867            .get(&system_object_mapping.description)
868            .expect("missing builtin")
869            .1;
870        let schema_name = builtin.schema();
871        let schema_id = self
872            .ambient_schemas_by_name
873            .get(schema_name)
874            .unwrap_or_else(|| panic!("unknown ambient schema: {schema_name}"));
875        let name = QualifiedItemName {
876            qualifiers: ItemQualifiers {
877                database_spec: ResolvedDatabaseSpecifier::Ambient,
878                schema_spec: SchemaSpecifier::Id(*schema_id),
879            },
880            item: builtin.name().into(),
881        };
882        match builtin {
883            Builtin::Log(log) => {
884                let mut acl_items = vec![rbac::owner_privilege(
885                    mz_sql::catalog::ObjectType::Source,
886                    MZ_SYSTEM_ROLE_ID,
887                )];
888                acl_items.extend_from_slice(&log.access);
889                self.insert_item(
890                    item_id,
891                    log.oid,
892                    name.clone(),
893                    CatalogItem::Log(Log {
894                        variant: log.variant,
895                        global_id,
896                    }),
897                    MZ_SYSTEM_ROLE_ID,
898                    PrivilegeMap::from_mz_acl_items(acl_items),
899                );
900            }
901
902            Builtin::Table(table) => {
903                let mut acl_items = vec![rbac::owner_privilege(
904                    mz_sql::catalog::ObjectType::Table,
905                    MZ_SYSTEM_ROLE_ID,
906                )];
907                acl_items.extend_from_slice(&table.access);
908
909                self.insert_item(
910                    item_id,
911                    table.oid,
912                    name.clone(),
913                    CatalogItem::Table(Table {
914                        create_sql: None,
915                        desc: VersionedRelationDesc::new(table.desc.clone()),
916                        collections: [(RelationVersion::root(), global_id)].into_iter().collect(),
917                        conn_id: None,
918                        resolved_ids: ResolvedIds::empty(),
919                        custom_logical_compaction_window: table.is_retained_metrics_object.then(
920                            || {
921                                self.system_config()
922                                    .metrics_retention()
923                                    .try_into()
924                                    .expect("invalid metrics retention")
925                            },
926                        ),
927                        is_retained_metrics_object: table.is_retained_metrics_object,
928                        data_source: TableDataSource::TableWrites {
929                            defaults: vec![Expr::null(); table.desc.arity()],
930                        },
931                    }),
932                    MZ_SYSTEM_ROLE_ID,
933                    PrivilegeMap::from_mz_acl_items(acl_items),
934                );
935            }
936            Builtin::Index(index) => {
937                let custom_logical_compaction_window =
938                    index.is_retained_metrics_object.then(|| {
939                        self.system_config()
940                            .metrics_retention()
941                            .try_into()
942                            .expect("invalid metrics retention")
943                    });
944                // Indexes can't be versioned.
945                let versions = BTreeMap::new();
946
947                let item = self
948                    .parse_item(
949                        global_id,
950                        &index.create_sql(),
951                        &versions,
952                        None,
953                        index.is_retained_metrics_object,
954                        custom_logical_compaction_window,
955                        local_expression_cache,
956                        None,
957                    )
958                    .unwrap_or_else(|e| {
959                        panic!(
960                            "internal error: failed to load bootstrap index:\n\
961                                    {}\n\
962                                    error:\n\
963                                    {:?}\n\n\
964                                    make sure that the schema name is specified in the builtin index's create sql statement.",
965                            index.name, e
966                        )
967                    });
968                let CatalogItem::Index(_) = item else {
969                    panic!(
970                        "internal error: builtin index {}'s SQL does not begin with \"CREATE INDEX\".",
971                        index.name
972                    );
973                };
974
975                self.insert_item(
976                    item_id,
977                    index.oid,
978                    name,
979                    item,
980                    MZ_SYSTEM_ROLE_ID,
981                    PrivilegeMap::default(),
982                );
983            }
984            Builtin::View(_) => {
985                // parse_views is responsible for inserting all builtin views.
986                unreachable!("views added elsewhere");
987            }
988
989            // Note: Element types must be loaded before array types.
990            Builtin::Type(typ) => {
991                let typ = self.resolve_builtin_type_references(typ);
992                if let CatalogType::Array { element_reference } = typ.details.typ {
993                    let entry = self.get_entry_mut(&element_reference);
994                    let item_type = match &mut entry.item {
995                        CatalogItem::Type(item_type) => item_type,
996                        _ => unreachable!("types can only reference other types"),
997                    };
998                    item_type.details.array_id = Some(item_id);
999                }
1000
1001                let schema_id = self.resolve_system_schema(typ.schema);
1002
1003                self.insert_item(
1004                    item_id,
1005                    typ.oid,
1006                    QualifiedItemName {
1007                        qualifiers: ItemQualifiers {
1008                            database_spec: ResolvedDatabaseSpecifier::Ambient,
1009                            schema_spec: SchemaSpecifier::Id(schema_id),
1010                        },
1011                        item: typ.name.to_owned(),
1012                    },
1013                    CatalogItem::Type(Type {
1014                        create_sql: None,
1015                        global_id,
1016                        details: typ.details.clone(),
1017                        resolved_ids: ResolvedIds::empty(),
1018                    }),
1019                    MZ_SYSTEM_ROLE_ID,
1020                    PrivilegeMap::from_mz_acl_items(vec![
1021                        rbac::default_builtin_object_privilege(mz_sql::catalog::ObjectType::Type),
1022                        rbac::owner_privilege(mz_sql::catalog::ObjectType::Type, MZ_SYSTEM_ROLE_ID),
1023                    ]),
1024                );
1025            }
1026
1027            Builtin::Func(func) => {
1028                // This OID is never used. `func` has a `Vec` of implementations and
1029                // each implementation has its own OID. Those are the OIDs that are
1030                // actually used by the system.
1031                let oid = INVALID_OID;
1032                self.insert_item(
1033                    item_id,
1034                    oid,
1035                    name.clone(),
1036                    CatalogItem::Func(Func {
1037                        inner: func.inner,
1038                        global_id,
1039                    }),
1040                    MZ_SYSTEM_ROLE_ID,
1041                    PrivilegeMap::default(),
1042                );
1043            }
1044
1045            Builtin::Source(coll) => {
1046                let mut acl_items = vec![rbac::owner_privilege(
1047                    mz_sql::catalog::ObjectType::Source,
1048                    MZ_SYSTEM_ROLE_ID,
1049                )];
1050                acl_items.extend_from_slice(&coll.access);
1051
1052                self.insert_item(
1053                    item_id,
1054                    coll.oid,
1055                    name.clone(),
1056                    CatalogItem::Source(Source {
1057                        create_sql: None,
1058                        data_source: coll.data_source.clone(),
1059                        desc: coll.desc.clone(),
1060                        global_id,
1061                        timeline: Timeline::EpochMilliseconds,
1062                        resolved_ids: ResolvedIds::empty(),
1063                        custom_logical_compaction_window: coll.is_retained_metrics_object.then(
1064                            || {
1065                                self.system_config()
1066                                    .metrics_retention()
1067                                    .try_into()
1068                                    .expect("invalid metrics retention")
1069                            },
1070                        ),
1071                        is_retained_metrics_object: coll.is_retained_metrics_object,
1072                    }),
1073                    MZ_SYSTEM_ROLE_ID,
1074                    PrivilegeMap::from_mz_acl_items(acl_items),
1075                );
1076            }
1077            Builtin::MaterializedView(mv) => {
1078                let mut acl_items = vec![rbac::owner_privilege(
1079                    mz_sql::catalog::ObjectType::MaterializedView,
1080                    MZ_SYSTEM_ROLE_ID,
1081                )];
1082                acl_items.extend_from_slice(&mv.access);
1083
1084                let custom_logical_compaction_window = mv.is_retained_metrics_object.then(|| {
1085                    self.system_config()
1086                        .metrics_retention()
1087                        .try_into()
1088                        .expect("invalid metrics retention")
1089                });
1090
1091                // Builtin materialized views can't be versioned.
1092                let versions = BTreeMap::new();
1093
1094                let mut item = self
1095                    .parse_item(
1096                        global_id,
1097                        &mv.create_sql(),
1098                        &versions,
1099                        None,
1100                        mv.is_retained_metrics_object,
1101                        custom_logical_compaction_window,
1102                        local_expression_cache,
1103                        None,
1104                    )
1105                    .unwrap_or_else(|e| {
1106                        panic!(
1107                            "internal error: failed to load bootstrap materialized view:\n\
1108                             {}\n\
1109                             error:\n\
1110                             {e:?}\n\n\
1111                             make sure that the schema name is specified in the builtin \
1112                             materialized view's create sql statement.",
1113                            mv.name,
1114                        )
1115                    });
1116                let CatalogItem::MaterializedView(catalog_mv) = &mut item else {
1117                    panic!(
1118                        "internal error: builtin materialized view {}'s SQL does not begin \
1119                         with \"CREATE MATERIALIZED VIEW\".",
1120                        mv.name,
1121                    );
1122                };
1123
1124                // The optimizer can only infer keys from MV definitions, but cannot infer
1125                // uniqueness present in the input data. Extend with the keys declared in the
1126                // builtin definition, to allow supplying additional key knowledge.
1127                let mut desc = catalog_mv.desc.latest();
1128                for key in &mv.desc.typ().keys {
1129                    desc = desc.with_key(key.clone());
1130                }
1131                catalog_mv.desc = VersionedRelationDesc::new(desc);
1132
1133                self.insert_item(
1134                    item_id,
1135                    mv.oid,
1136                    name,
1137                    item,
1138                    MZ_SYSTEM_ROLE_ID,
1139                    PrivilegeMap::from_mz_acl_items(acl_items),
1140                );
1141            }
1142            Builtin::Connection(connection) => {
1143                // Connections can't be versioned.
1144                let versions = BTreeMap::new();
1145                let mut item = self
1146                    .parse_item(
1147                        global_id,
1148                        connection.sql,
1149                        &versions,
1150                        None,
1151                        false,
1152                        None,
1153                        local_expression_cache,
1154                        None,
1155                    )
1156                    .unwrap_or_else(|e| {
1157                        panic!(
1158                            "internal error: failed to load bootstrap connection:\n\
1159                                    {}\n\
1160                                    error:\n\
1161                                    {:?}\n\n\
1162                                    make sure that the schema name is specified in the builtin connection's create sql statement.",
1163                            connection.name, e
1164                        )
1165                    });
1166                let CatalogItem::Connection(_) = &mut item else {
1167                    panic!(
1168                        "internal error: builtin connection {}'s SQL does not begin with \"CREATE CONNECTION\".",
1169                        connection.name
1170                    );
1171                };
1172
1173                let mut acl_items = vec![rbac::owner_privilege(
1174                    mz_sql::catalog::ObjectType::Connection,
1175                    connection.owner_id.clone(),
1176                )];
1177                acl_items.extend_from_slice(connection.access);
1178
1179                self.insert_item(
1180                    item_id,
1181                    connection.oid,
1182                    name.clone(),
1183                    item,
1184                    connection.owner_id.clone(),
1185                    PrivilegeMap::from_mz_acl_items(acl_items),
1186                );
1187            }
1188        }
1189    }
1190
1191    /// Whether `update` concerns an ephemeral item whose owning session is not
1192    /// connected to this process, in which case applying it must be a no-op.
1193    fn is_nonlocal_ephemeral_item_update(&self, update: &StateUpdate) -> bool {
1194        let StateUpdateKind::Item(item) = &update.kind else {
1195            return false;
1196        };
1197        // Only ephemeral items have ephemeral_owner_session
1198        let Some(owner) = item.ephemeral_owner_session else {
1199            return false;
1200        };
1201        match update.diff {
1202            // An addition is local when the owning session is connected here.
1203            StateDiff::Addition => !self.temporary_namespaces.contains_uuid(&owner),
1204            // A retraction must be applied iff the matching addition above
1205            // was applied here, and entry presence records exactly that.
1206            StateDiff::Retraction => !self.entry_by_id.contains_key(&item.id),
1207        }
1208    }
1209
1210    #[instrument(level = "debug")]
1211    fn apply_item_update(
1212        &mut self,
1213        item: mz_catalog::durable::Item,
1214        diff: StateDiff,
1215        retractions: &mut InProgressRetractions,
1216        local_expression_cache: &mut LocalExpressionCache,
1217    ) -> Result<(), CatalogError> {
1218        match diff {
1219            StateDiff::Addition => {
1220                let key = item.key();
1221                let mz_catalog::durable::Item {
1222                    id,
1223                    oid,
1224                    global_id,
1225                    schema_id,
1226                    name,
1227                    create_sql,
1228                    owner_id,
1229                    privileges,
1230                    extra_versions,
1231                    ephemeral_owner_session,
1232                } = item;
1233
1234                // Temporary items live in the temporary schema of the owning
1235                // session's connection, not in the schema named by
1236                // `schema_id` (which is the temporary schema sentinel).
1237                // Updates for sessions not connected to this process are
1238                // filtered out in `apply_updates_inner`, so the mapping must
1239                // exist here.
1240                let conn_id = ephemeral_owner_session.map(|owner| {
1241                    self.temporary_namespaces
1242                        .conn_for_uuid(&owner)
1243                        .cloned()
1244                        .unwrap_or_else(|| {
1245                            panic!("no session record applied for temporary item owner {owner}")
1246                        })
1247                });
1248                let name = match &conn_id {
1249                    Some(_) => QualifiedItemName {
1250                        qualifiers: ItemQualifiers {
1251                            database_spec: ResolvedDatabaseSpecifier::Ambient,
1252                            schema_spec: SchemaSpecifier::Temporary,
1253                        },
1254                        item: name.clone(),
1255                    },
1256                    None => {
1257                        let schema = self.find_non_temp_schema(&schema_id);
1258                        QualifiedItemName {
1259                            qualifiers: ItemQualifiers {
1260                                database_spec: schema.database().clone(),
1261                                schema_spec: schema.id().clone(),
1262                            },
1263                            item: name.clone(),
1264                        }
1265                    }
1266                };
1267                let entry = match retractions.items.remove(&key) {
1268                    Some(mut retraction) => {
1269                        assert_eq!(retraction.id, id);
1270
1271                        // We only reparse the SQL if it's changed. Otherwise, we use the existing
1272                        // item. This is a performance optimization and not needed for correctness.
1273                        // This makes it difficult to use the `UpdateFrom` trait, but the structure
1274                        // is still the same as the trait.
1275                        if retraction.create_sql() != create_sql {
1276                            let mut catalog_item = self
1277                                .deserialize_item(
1278                                    global_id,
1279                                    &create_sql,
1280                                    &extra_versions,
1281                                    local_expression_cache,
1282                                    Some(retraction.item),
1283                                )
1284                                .unwrap_or_else(|e| {
1285                                    panic!("{e:?}: invalid persisted SQL: {create_sql}")
1286                                });
1287                            if conn_id.is_some() {
1288                                // Have to patch up the item because parsing
1289                                // doesn't take into account temporary
1290                                // schemas/conn_id.
1291                                // NOTE(aljoscha): I don't like how we're patching
1292                                // this in here, but it's but one of the ways in
1293                                // which temporary items are a bit weird. So, here
1294                                // we are ...
1295                                catalog_item.set_conn_id(conn_id.clone());
1296                                // Deserializing replans the SQL, and the
1297                                // planner's canonical printing can differ from
1298                                // `create_sql`, for example when a feature flag
1299                                // changed how references are printed since
1300                                // `create_sql` was produced. Keep the exact
1301                                // input. A later op in the same transaction
1302                                // retracts this item by re-serializing it, and
1303                                // that retraction must cancel byte-for-byte
1304                                // against this addition during consolidation,
1305                                // else two retractions of the same id survive
1306                                // and applying them panics.
1307                                catalog_item.set_create_sql(create_sql);
1308                            }
1309                            retraction.item = catalog_item;
1310                        }
1311
1312                        retraction.id = id;
1313                        retraction.oid = oid;
1314                        retraction.name = name;
1315                        retraction.owner_id = owner_id;
1316                        retraction.privileges = PrivilegeMap::from_mz_acl_items(privileges);
1317                        retraction
1318                    }
1319                    None => {
1320                        let mut catalog_item = self
1321                            .deserialize_item(
1322                                global_id,
1323                                &create_sql,
1324                                &extra_versions,
1325                                local_expression_cache,
1326                                None,
1327                            )
1328                            .unwrap_or_else(|e| {
1329                                panic!("{e:?}: invalid persisted SQL: {create_sql}")
1330                            });
1331
1332                        if conn_id.is_some() {
1333                            // See the patch-up comments on the reparse above.
1334                            catalog_item.set_conn_id(conn_id.clone());
1335                            catalog_item.set_create_sql(create_sql);
1336                        }
1337
1338                        CatalogEntry {
1339                            item: catalog_item,
1340                            referenced_by: Vec::new(),
1341                            used_by: Vec::new(),
1342                            id,
1343                            oid,
1344                            name,
1345                            owner_id,
1346                            privileges: PrivilegeMap::from_mz_acl_items(privileges),
1347                        }
1348                    }
1349                };
1350
1351                self.insert_entry(entry);
1352            }
1353            StateDiff::Retraction => {
1354                let entry = self.drop_item(item.id);
1355                let key = item.into_key_value().0;
1356                retractions.items.insert(key, entry);
1357            }
1358        }
1359        Ok(())
1360    }
1361
1362    #[instrument(level = "debug")]
1363    fn apply_comment_update(
1364        &mut self,
1365        comment: mz_catalog::durable::Comment,
1366        diff: StateDiff,
1367        _retractions: &mut InProgressRetractions,
1368    ) {
1369        match diff {
1370            StateDiff::Addition => {
1371                let prev = Arc::make_mut(&mut self.comments).update_comment(
1372                    comment.object_id,
1373                    comment.sub_component,
1374                    Some(comment.comment),
1375                );
1376                assert_eq!(
1377                    prev, None,
1378                    "values must be explicitly retracted before inserting a new value"
1379                );
1380            }
1381            StateDiff::Retraction => {
1382                let prev = Arc::make_mut(&mut self.comments).update_comment(
1383                    comment.object_id,
1384                    comment.sub_component,
1385                    None,
1386                );
1387                assert_eq!(
1388                    prev,
1389                    Some(comment.comment),
1390                    "retraction does not match existing value: ({:?}, {:?})",
1391                    comment.object_id,
1392                    comment.sub_component,
1393                );
1394            }
1395        }
1396    }
1397
1398    #[instrument(level = "debug")]
1399    fn apply_source_references_update(
1400        &mut self,
1401        source_references: mz_catalog::durable::SourceReferences,
1402        diff: StateDiff,
1403        _retractions: &mut InProgressRetractions,
1404    ) {
1405        match diff {
1406            StateDiff::Addition => {
1407                let prev = self
1408                    .source_references
1409                    .insert(source_references.source_id, source_references.into());
1410                assert!(
1411                    prev.is_none(),
1412                    "values must be explicitly retracted before inserting a new value: {prev:?}"
1413                );
1414            }
1415            StateDiff::Retraction => {
1416                let prev = self.source_references.remove(&source_references.source_id);
1417                assert!(
1418                    prev.is_some(),
1419                    "retraction for a non-existent existing value: {source_references:?}"
1420                );
1421            }
1422        }
1423    }
1424
1425    #[instrument(level = "debug")]
1426    fn apply_storage_collection_metadata_update(
1427        &mut self,
1428        storage_collection_metadata: mz_catalog::durable::StorageCollectionMetadata,
1429        diff: StateDiff,
1430        _retractions: &mut InProgressRetractions,
1431    ) {
1432        apply_inverted_lookup(
1433            &mut Arc::make_mut(&mut self.storage_metadata).collection_metadata,
1434            &storage_collection_metadata.id,
1435            storage_collection_metadata.shard,
1436            diff,
1437        );
1438    }
1439
1440    #[instrument(level = "debug")]
1441    fn apply_unfinalized_shard_update(
1442        &mut self,
1443        unfinalized_shard: mz_catalog::durable::UnfinalizedShard,
1444        diff: StateDiff,
1445        _retractions: &mut InProgressRetractions,
1446    ) {
1447        match diff {
1448            StateDiff::Addition => {
1449                let newly_inserted = Arc::make_mut(&mut self.storage_metadata)
1450                    .unfinalized_shards
1451                    .insert(unfinalized_shard.shard);
1452                assert!(
1453                    newly_inserted,
1454                    "values must be explicitly retracted before inserting a new value: {unfinalized_shard:?}",
1455                );
1456            }
1457            StateDiff::Retraction => {
1458                let removed = Arc::make_mut(&mut self.storage_metadata)
1459                    .unfinalized_shards
1460                    .remove(&unfinalized_shard.shard);
1461                assert!(
1462                    removed,
1463                    "retraction does not match existing value: {unfinalized_shard:?}"
1464                );
1465            }
1466        }
1467    }
1468
1469    /// Generate a list of `BuiltinTableUpdate`s that correspond to a single update made to the
1470    /// durable catalog.
1471    #[instrument(level = "debug")]
1472    pub(crate) fn generate_builtin_table_update(
1473        &self,
1474        kind: StateUpdateKind,
1475        diff: StateDiff,
1476    ) -> Vec<BuiltinTableUpdate<&'static BuiltinTable>> {
1477        let diff = diff.into();
1478        match kind {
1479            // mz_roles and mz_role_parameters are MaterializedViews backed by
1480            // mz_internal.mz_catalog_raw, so role rows do not produce builtin
1481            // table updates here.
1482            StateUpdateKind::Role(_) => Vec::new(),
1483            StateUpdateKind::RoleAuth(role_auth) => {
1484                vec![self.pack_role_auth_update(role_auth.role_id, diff)]
1485            }
1486            // mz_default_privileges and mz_system_privileges are MaterializedViews
1487            // backed by mz_internal.mz_catalog_raw, so privilege rows do not
1488            // produce builtin table updates here.
1489            StateUpdateKind::DefaultPrivilege(_) => Vec::new(),
1490            StateUpdateKind::SystemPrivilege(_) => Vec::new(),
1491            StateUpdateKind::SystemConfiguration(_) => Vec::new(),
1492            // mz_internal.mz_{cluster,replica}_system_parameters are
1493            // MaterializedViews backed by mz_internal.mz_catalog_raw, so the
1494            // durable scoped-configuration rows do not produce builtin table
1495            // updates here. (The in-memory working copy used for resolution is
1496            // maintained separately in `apply_*_system_configuration_update`.)
1497            StateUpdateKind::ClusterSystemConfiguration(_) => Vec::new(),
1498            StateUpdateKind::ReplicaSystemConfiguration(_) => Vec::new(),
1499            // mz_clusters and mz_cluster_schedules are MaterializedViews backed
1500            // by mz_internal.mz_catalog_raw, so cluster rows do not produce
1501            // builtin table updates here.
1502            StateUpdateKind::Cluster(_) => Vec::new(),
1503            StateUpdateKind::IntrospectionSourceIndex(introspection_source_index) => {
1504                self.pack_item_update(introspection_source_index.item_id, diff)
1505            }
1506            // mz_cluster_replicas is a MaterializedView backed by
1507            // mz_internal.mz_catalog_raw.
1508            StateUpdateKind::ClusterReplica(_) => Vec::new(),
1509            StateUpdateKind::ClusterReplicaSize(size) => {
1510                Self::pack_replica_size_update(&size.name, &size.allocation, diff)
1511            }
1512            StateUpdateKind::SystemObjectMapping(system_object_mapping) => {
1513                // Runtime-alterable system objects have real entries in the
1514                // items collection and so get handled through the normal
1515                // `StateUpdateKind::Item`.`
1516                if !system_object_mapping.unique_identifier.runtime_alterable() {
1517                    self.pack_item_update(system_object_mapping.unique_identifier.catalog_id, diff)
1518                } else {
1519                    vec![]
1520                }
1521            }
1522            StateUpdateKind::Item(item) => self.pack_item_update(item.id, diff),
1523            StateUpdateKind::Comment(_) => Vec::new(),
1524            StateUpdateKind::SourceReferences(_) => Vec::new(),
1525            // mz_audit_events is a MaterializedView backed by
1526            // mz_internal.mz_catalog_raw, so audit log rows do not produce
1527            // builtin table updates here.
1528            StateUpdateKind::AuditLog(_) => Vec::new(),
1529            StateUpdateKind::Database(_)
1530            | StateUpdateKind::Schema(_)
1531            | StateUpdateKind::NetworkPolicy(_)
1532            | StateUpdateKind::QueryPolicy(_)
1533            | StateUpdateKind::StorageCollectionMetadata(_)
1534            | StateUpdateKind::UnfinalizedShard(_) => Vec::new(),
1535        }
1536    }
1537
1538    fn get_entry_mut(&mut self, id: &CatalogItemId) -> &mut CatalogEntry {
1539        self.entry_by_id
1540            .get_mut(id)
1541            .unwrap_or_else(|| panic!("catalog out of sync, missing id {id}"))
1542    }
1543
1544    /// Set the optimized plan for the item identified by `id`.
1545    ///
1546    /// # Panics
1547    /// If the item is not an `Index`, `MaterializedView`, or `MetricSink`.
1548    pub(super) fn set_optimized_plan(
1549        &mut self,
1550        id: GlobalId,
1551        plan: DataflowDescription<mz_expr::OptimizedMirRelationExpr>,
1552    ) {
1553        let item_id = self.entry_by_global_id[&id];
1554        let entry = self.get_entry_mut(&item_id);
1555        match entry.item_mut() {
1556            CatalogItem::Index(idx) => idx.optimized_plan = Some(Arc::new(plan)),
1557            CatalogItem::MaterializedView(mv) => mv.optimized_plan = Some(Arc::new(plan)),
1558            CatalogItem::MetricSink(ms) => ms.optimized_plan = Some(Arc::new(plan)),
1559            other => panic!("set_optimized_plan called on {} ({:?})", id, other.typ()),
1560        }
1561    }
1562
1563    /// Set the physical plan for the item identified by `id`.
1564    ///
1565    /// # Panics
1566    /// If the item is not an `Index`, `MaterializedView`, or `MetricSink`.
1567    pub(super) fn set_physical_plan(
1568        &mut self,
1569        id: GlobalId,
1570        plan: mz_compute_types::dataflows::LirDataflowDescription,
1571    ) {
1572        let item_id = self.entry_by_global_id[&id];
1573        let entry = self.get_entry_mut(&item_id);
1574        match entry.item_mut() {
1575            CatalogItem::Index(idx) => idx.physical_plan = Some(Arc::new(plan)),
1576            CatalogItem::MaterializedView(mv) => mv.physical_plan = Some(Arc::new(plan)),
1577            CatalogItem::MetricSink(ms) => ms.physical_plan = Some(Arc::new(plan)),
1578            other => panic!("set_physical_plan called on {} ({:?})", id, other.typ()),
1579        }
1580    }
1581
1582    /// Set the `DataflowMetainfo` for the item identified by `id`.
1583    ///
1584    /// # Panics
1585    /// If the item is not an `Index`, `MaterializedView`, or `MetricSink`.
1586    pub(super) fn set_dataflow_metainfo(
1587        &mut self,
1588        id: GlobalId,
1589        metainfo: DataflowMetainfo<Arc<OptimizerNotice>>,
1590    ) {
1591        // Add entries to the `notices_by_dep_id` lookup map.
1592        for notice in metainfo.optimizer_notices.iter() {
1593            for dep_id in notice.dependencies.iter() {
1594                self.notices_by_dep_id
1595                    .entry(*dep_id)
1596                    .or_default()
1597                    .push(Arc::clone(notice));
1598            }
1599            if let Some(item_id) = notice.item_id {
1600                soft_assert_eq_or_log!(
1601                    item_id,
1602                    id,
1603                    "notice.item_id should match the id for whom we are saving the notice"
1604                );
1605            }
1606        }
1607        // Set the metainfo on the catalog object.
1608        let item_id = self.entry_by_global_id[&id];
1609        let entry = self.get_entry_mut(&item_id);
1610        match entry.item_mut() {
1611            CatalogItem::Index(idx) => idx.dataflow_metainfo = Some(metainfo),
1612            CatalogItem::MaterializedView(mv) => mv.dataflow_metainfo = Some(metainfo),
1613            CatalogItem::MetricSink(ms) => ms.dataflow_metainfo = Some(metainfo),
1614            other => panic!("set_dataflow_metainfo called on {} ({:?})", id, other.typ()),
1615        }
1616    }
1617
1618    /// Clean up optimizer notices for the given dropped catalog entries.
1619    ///
1620    /// This extracts notices directly from the owned entries (which
1621    /// have already been removed from the catalog maps), cleans up
1622    /// the `notices_by_dep_id` reverse index, and removes notices
1623    /// from other (still-live) catalog objects that depended on the
1624    /// dropped items.
1625    ///
1626    /// Returns the set of all dropped notices for builtin table
1627    /// retraction.
1628    #[mz_ore::instrument(level = "trace")]
1629    pub(super) fn drop_optimizer_notices(
1630        &mut self,
1631        dropped_entries: Vec<CatalogEntry>,
1632    ) -> BTreeSet<Arc<OptimizerNotice>> {
1633        let mut dropped_notices = BTreeSet::new();
1634        let mut drop_ids = BTreeSet::new();
1635
1636        // Extract notices directly from the owned dropped entries.
1637        for mut entry in dropped_entries {
1638            drop_ids.extend(entry.global_ids());
1639            if let Some(metainfo) = entry.item_mut().dataflow_metainfo_mut() {
1640                soft_assert_or_log!(
1641                    metainfo.optimizer_notices.iter().all_unique(),
1642                    "should have been pushed there by \
1643                     `push_optimizer_notice_dedup`"
1644                );
1645                for n in metainfo.optimizer_notices.drain(..) {
1646                    // Clean up notices_by_dep_id for this notice's
1647                    // dependencies.
1648                    for dep_id in n.dependencies.iter() {
1649                        if let Some(notices) = self.notices_by_dep_id.get_mut(dep_id) {
1650                            notices.retain(|x| &n != x);
1651                            if notices.is_empty() {
1652                                self.notices_by_dep_id.remove(dep_id);
1653                            }
1654                        }
1655                    }
1656                    dropped_notices.insert(n);
1657                }
1658            }
1659        }
1660
1661        // Remove notices_by_dep_id entries keyed by the dropped IDs.
1662        // These are notices on OTHER items that depend on a dropped
1663        // item. We need to remove them from those items' metainfo.
1664        for id in &drop_ids {
1665            if let Some(notices) = self.notices_by_dep_id.remove(id) {
1666                for n in notices.into_iter() {
1667                    // Remove the notice from the catalog object it
1668                    // lives on (if that object still exists — it
1669                    // may have been dropped too, in which case the
1670                    // notice was already collected above).
1671                    if let Some(item_id) = n.item_id.as_ref() {
1672                        if let Some(entry) = self.try_get_entry_by_global_id(item_id) {
1673                            let catalog_item_id = entry.id();
1674                            let entry = self.get_entry_mut(&catalog_item_id);
1675                            if let Some(m) = entry.item_mut().dataflow_metainfo_mut() {
1676                                m.optimizer_notices.retain(|x| &n != x);
1677                            }
1678                        }
1679                    }
1680                    dropped_notices.insert(n);
1681                }
1682            }
1683        }
1684
1685        // Clean up notices_by_dep_id entries for dependency IDs
1686        // that are NOT being dropped but had dropped notices.
1687        let todo_dep_ids: BTreeSet<GlobalId> = dropped_notices
1688            .iter()
1689            .flat_map(|n| n.dependencies.iter())
1690            .filter(|dep_id| !drop_ids.contains(dep_id))
1691            .copied()
1692            .collect();
1693        for id in todo_dep_ids {
1694            if let Some(notices) = self.notices_by_dep_id.get_mut(&id) {
1695                notices.retain(|n| !dropped_notices.contains(n));
1696                if notices.is_empty() {
1697                    self.notices_by_dep_id.remove(&id);
1698                }
1699            }
1700        }
1701
1702        dropped_notices
1703    }
1704
1705    fn get_schema_mut(
1706        &mut self,
1707        database_spec: &ResolvedDatabaseSpecifier,
1708        schema_spec: &SchemaSpecifier,
1709        conn_id: &ConnectionId,
1710    ) -> &mut Schema {
1711        // Keep in sync with `get_schemas`
1712        match (database_spec, schema_spec) {
1713            (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Temporary) => self
1714                .temporary_namespaces
1715                .schema_mut(conn_id)
1716                .expect("catalog out of sync"),
1717            (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Id(id)) => self
1718                .ambient_schemas_by_id
1719                .get_mut(id)
1720                .expect("catalog out of sync"),
1721            (ResolvedDatabaseSpecifier::Id(database_id), SchemaSpecifier::Id(schema_id)) => self
1722                .database_by_id
1723                .get_mut(database_id)
1724                .expect("catalog out of sync")
1725                .schemas_by_id
1726                .get_mut(schema_id)
1727                .expect("catalog out of sync"),
1728            (ResolvedDatabaseSpecifier::Id(_), SchemaSpecifier::Temporary) => {
1729                unreachable!("temporary schemas are in the ambient database")
1730            }
1731        }
1732    }
1733
1734    /// Install builtin views to the catalog. This is its own function so that views can be
1735    /// optimized in parallel.
1736    ///
1737    /// The implementation is similar to `apply_updates_for_bootstrap` and determines dependency
1738    /// problems by sniffing out specific errors and then retrying once those dependencies are
1739    /// complete. This doesn't work for everything (casts, function implementations) so we also need
1740    /// to have a bucket for everything at the end. Additionally, because this executes in parellel,
1741    /// we must maintain a completed set otherwise races could result in orphaned views languishing
1742    /// in awaiting with nothing retriggering the attempt.
1743    #[instrument(name = "catalog::parse_views")]
1744    async fn parse_builtin_views(
1745        state: &mut CatalogState,
1746        builtin_views: Vec<(&'static BuiltinView, CatalogItemId, GlobalId)>,
1747        retractions: &mut InProgressRetractions,
1748        local_expression_cache: &mut LocalExpressionCache,
1749    ) -> Vec<BuiltinTableUpdate<&'static BuiltinTable>> {
1750        let mut builtin_table_updates = Vec::with_capacity(builtin_views.len());
1751        let (updates, additions): (Vec<_>, Vec<_>) =
1752            builtin_views
1753                .into_iter()
1754                .partition_map(|(view, item_id, gid)| {
1755                    match retractions.system_object_mappings.remove(&item_id) {
1756                        Some(entry) => Either::Left(entry),
1757                        None => Either::Right((view, item_id, gid)),
1758                    }
1759                });
1760
1761        for entry in updates {
1762            // This implies that we updated the fingerprint for some builtin view. The retraction
1763            // was parsed, planned, and optimized using the compiled in definition, not the
1764            // definition from a previous version. So we can just stick the old entry back into the
1765            // catalog.
1766            let item_id = entry.id();
1767            state.insert_entry(entry);
1768            builtin_table_updates.extend(state.pack_item_update(item_id, Diff::ONE));
1769        }
1770
1771        let mut handles = Vec::new();
1772        let mut awaiting_id_dependencies: BTreeMap<CatalogItemId, Vec<CatalogItemId>> =
1773            BTreeMap::new();
1774        let mut awaiting_name_dependencies: BTreeMap<String, Vec<CatalogItemId>> = BTreeMap::new();
1775        // Some errors are due to the implementation of casts or SQL functions that depend on some
1776        // view. Instead of figuring out the exact view dependency, delay these until the end.
1777        let mut awaiting_all = Vec::new();
1778        // Completed views, needed to avoid race conditions.
1779        let mut completed_ids: BTreeSet<CatalogItemId> = BTreeSet::new();
1780        let mut completed_names: BTreeSet<String> = BTreeSet::new();
1781
1782        // Avoid some reference lifetime issues by not passing `builtin` into the spawned task.
1783        let mut views: BTreeMap<CatalogItemId, (&BuiltinView, GlobalId)> = additions
1784            .into_iter()
1785            .map(|(view, item_id, gid)| (item_id, (view, gid)))
1786            .collect();
1787        let item_ids: Vec<_> = views.keys().copied().collect();
1788
1789        let mut ready: VecDeque<CatalogItemId> = views.keys().cloned().collect();
1790        while !handles.is_empty() || !ready.is_empty() || !awaiting_all.is_empty() {
1791            if handles.is_empty() && ready.is_empty() {
1792                // Enqueue the views that were waiting for all the others.
1793                ready.extend(awaiting_all.drain(..));
1794            }
1795
1796            // Spawn tasks for all ready views.
1797            if !ready.is_empty() {
1798                let spawn_state = Arc::new(state.clone());
1799                while let Some(id) = ready.pop_front() {
1800                    let (view, global_id) = views.get(&id).expect("must exist");
1801                    let global_id = *global_id;
1802                    let create_sql = view.create_sql();
1803                    // Views can't be versioned.
1804                    let versions = BTreeMap::new();
1805
1806                    let span = info_span!(parent: None, "parse builtin view", name = view.name);
1807                    OpenTelemetryContext::obtain().attach_as_parent_to(&span);
1808                    let task_state = Arc::clone(&spawn_state);
1809                    let cached_expr = local_expression_cache.remove_cached_expression(&global_id);
1810                    let handle = mz_ore::task::spawn_blocking(
1811                        || "parse view",
1812                        move || {
1813                            span.in_scope(|| {
1814                                let res = task_state.parse_item_inner(
1815                                    global_id,
1816                                    &create_sql,
1817                                    &versions,
1818                                    None,
1819                                    false,
1820                                    None,
1821                                    cached_expr,
1822                                    None,
1823                                );
1824                                (id, global_id, res)
1825                            })
1826                        },
1827                    );
1828                    handles.push(handle);
1829                }
1830            }
1831
1832            // Wait for a view to be ready.
1833            let (selected, _idx, remaining) = future::select_all(handles).await;
1834            handles = remaining;
1835            let (id, global_id, res) = selected;
1836            let mut insert_cached_expr = |cached_expr| {
1837                if let Some(cached_expr) = cached_expr {
1838                    local_expression_cache.insert_cached_expression(global_id, cached_expr);
1839                }
1840            };
1841            match res {
1842                Ok((item, uncached_expr)) => {
1843                    if let Some((uncached_expr, optimizer_features)) = uncached_expr {
1844                        local_expression_cache.insert_uncached_expression(
1845                            global_id,
1846                            uncached_expr,
1847                            optimizer_features,
1848                            RelationVersion::root(),
1849                        );
1850                    }
1851                    // Add item to catalog.
1852                    let (view, _gid) = views.remove(&id).expect("must exist");
1853                    let schema_id = state
1854                        .ambient_schemas_by_name
1855                        .get(view.schema)
1856                        .unwrap_or_else(|| panic!("unknown ambient schema: {}", view.schema));
1857                    let qname = QualifiedItemName {
1858                        qualifiers: ItemQualifiers {
1859                            database_spec: ResolvedDatabaseSpecifier::Ambient,
1860                            schema_spec: SchemaSpecifier::Id(*schema_id),
1861                        },
1862                        item: view.name.into(),
1863                    };
1864                    let mut acl_items = vec![rbac::owner_privilege(
1865                        mz_sql::catalog::ObjectType::View,
1866                        MZ_SYSTEM_ROLE_ID,
1867                    )];
1868                    acl_items.extend_from_slice(&view.access);
1869
1870                    state.insert_item(
1871                        id,
1872                        view.oid,
1873                        qname,
1874                        item,
1875                        MZ_SYSTEM_ROLE_ID,
1876                        PrivilegeMap::from_mz_acl_items(acl_items),
1877                    );
1878
1879                    // Enqueue any items waiting on this dependency.
1880                    let mut resolved_dependent_items = Vec::new();
1881                    if let Some(dependent_items) = awaiting_id_dependencies.remove(&id) {
1882                        resolved_dependent_items.extend(dependent_items);
1883                    }
1884                    let entry = state.get_entry(&id);
1885                    let full_name = state.resolve_full_name(entry.name(), None).to_string();
1886                    if let Some(dependent_items) = awaiting_name_dependencies.remove(&full_name) {
1887                        resolved_dependent_items.extend(dependent_items);
1888                    }
1889                    ready.extend(resolved_dependent_items);
1890
1891                    completed_ids.insert(id);
1892                    completed_names.insert(full_name);
1893                }
1894                // If we were missing a dependency, wait for it to be added.
1895                Err((
1896                    AdapterError::PlanError(plan::PlanError::InvalidId(missing_dep)),
1897                    cached_expr,
1898                )) => {
1899                    insert_cached_expr(cached_expr);
1900                    if completed_ids.contains(&missing_dep) {
1901                        ready.push_back(id);
1902                    } else {
1903                        awaiting_id_dependencies
1904                            .entry(missing_dep)
1905                            .or_default()
1906                            .push(id);
1907                    }
1908                }
1909                // If we were missing a dependency, wait for it to be added.
1910                Err((
1911                    AdapterError::PlanError(plan::PlanError::Catalog(
1912                        SqlCatalogError::UnknownItem(missing_dep),
1913                    )),
1914                    cached_expr,
1915                )) => {
1916                    insert_cached_expr(cached_expr);
1917                    match CatalogItemId::from_str(&missing_dep) {
1918                        Ok(missing_dep) => {
1919                            if completed_ids.contains(&missing_dep) {
1920                                ready.push_back(id);
1921                            } else {
1922                                awaiting_id_dependencies
1923                                    .entry(missing_dep)
1924                                    .or_default()
1925                                    .push(id);
1926                            }
1927                        }
1928                        Err(_) => {
1929                            if completed_names.contains(&missing_dep) {
1930                                ready.push_back(id);
1931                            } else {
1932                                awaiting_name_dependencies
1933                                    .entry(missing_dep)
1934                                    .or_default()
1935                                    .push(id);
1936                            }
1937                        }
1938                    }
1939                }
1940                Err((
1941                    AdapterError::PlanError(plan::PlanError::InvalidCast { .. }),
1942                    cached_expr,
1943                )) => {
1944                    insert_cached_expr(cached_expr);
1945                    awaiting_all.push(id);
1946                }
1947                Err((e, _)) => {
1948                    let (bad_view, _gid) = views.get(&id).expect("must exist");
1949                    panic!(
1950                        "internal error: failed to load bootstrap view:\n\
1951                            {name}\n\
1952                            error:\n\
1953                            {e:?}\n\n\
1954                            Make sure that the schema name is specified in the builtin view's create sql statement.
1955                            ",
1956                        name = bad_view.name,
1957                    )
1958                }
1959            }
1960        }
1961
1962        assert!(awaiting_id_dependencies.is_empty());
1963        assert!(
1964            awaiting_name_dependencies.is_empty(),
1965            "awaiting_name_dependencies: {awaiting_name_dependencies:?}"
1966        );
1967        assert!(awaiting_all.is_empty());
1968        assert!(views.is_empty());
1969
1970        // Generate a builtin table update for all the new views.
1971        builtin_table_updates.extend(
1972            item_ids
1973                .into_iter()
1974                .flat_map(|id| state.pack_item_update(id, Diff::ONE)),
1975        );
1976
1977        builtin_table_updates
1978    }
1979
1980    /// Associates a name, `CatalogItemId`, and entry.
1981    fn insert_entry(&mut self, entry: CatalogEntry) {
1982        if !entry.id.is_system() {
1983            if let Some(cluster_id) = entry.item.cluster_id() {
1984                self.clusters_by_id
1985                    .get_mut(&cluster_id)
1986                    .expect("catalog out of sync")
1987                    .bound_objects
1988                    .insert(entry.id);
1989            };
1990        }
1991
1992        for u in entry.references().items() {
1993            match self.entry_by_id.get_mut(u) {
1994                Some(metadata) => metadata.referenced_by.push(entry.id()),
1995                None => panic!(
1996                    "Catalog: missing dependent catalog item {} while installing {}",
1997                    u,
1998                    self.resolve_full_name(entry.name(), entry.conn_id())
1999                ),
2000            }
2001        }
2002        for u in entry.uses() {
2003            // Ignore self for self-referential tasks (e.g. Continual Tasks), if
2004            // present.
2005            if u == entry.id() {
2006                continue;
2007            }
2008            match self.entry_by_id.get_mut(&u) {
2009                Some(metadata) => metadata.used_by.push(entry.id()),
2010                None => panic!(
2011                    "Catalog: missing dependent catalog item {} while installing {}",
2012                    u,
2013                    self.resolve_full_name(entry.name(), entry.conn_id())
2014                ),
2015            }
2016        }
2017        for gid in entry.item.global_ids() {
2018            self.entry_by_global_id.insert(gid, entry.id());
2019        }
2020        let conn_id = entry.item().conn_id().unwrap_or(&SYSTEM_CONN_ID);
2021        // Lazily create the temporary schema if this is a temporary item and the schema
2022        // doesn't exist yet.
2023        if entry.name().qualifiers.schema_spec == SchemaSpecifier::Temporary {
2024            self.temporary_namespaces
2025                .ensure_schema(conn_id, entry.owner_id);
2026        }
2027        let schema = self.get_schema_mut(
2028            &entry.name().qualifiers.database_spec,
2029            &entry.name().qualifiers.schema_spec,
2030            conn_id,
2031        );
2032
2033        let prev_id = match entry.item() {
2034            CatalogItem::Func(_) => schema
2035                .functions
2036                .insert(entry.name().item.clone(), entry.id()),
2037            CatalogItem::Type(_) => schema.types.insert(entry.name().item.clone(), entry.id()),
2038            _ => schema.items.insert(entry.name().item.clone(), entry.id()),
2039        };
2040
2041        assert!(
2042            prev_id.is_none(),
2043            "builtin name collision on {:?}",
2044            entry.name().item.clone()
2045        );
2046
2047        self.entry_by_id.insert(entry.id(), entry.clone());
2048    }
2049
2050    /// Associates a name, [`CatalogItemId`], and entry.
2051    fn insert_item(
2052        &mut self,
2053        id: CatalogItemId,
2054        oid: u32,
2055        name: QualifiedItemName,
2056        item: CatalogItem,
2057        owner_id: RoleId,
2058        privileges: PrivilegeMap,
2059    ) {
2060        let entry = CatalogEntry {
2061            item,
2062            name,
2063            id,
2064            oid,
2065            used_by: Vec::new(),
2066            referenced_by: Vec::new(),
2067            owner_id,
2068            privileges,
2069        };
2070
2071        self.insert_entry(entry);
2072    }
2073
2074    #[mz_ore::instrument(level = "trace")]
2075    fn drop_item(&mut self, id: CatalogItemId) -> CatalogEntry {
2076        let metadata = self.entry_by_id.remove(&id).expect("catalog out of sync");
2077        for u in metadata.references().items() {
2078            if let Some(dep_metadata) = self.entry_by_id.get_mut(u) {
2079                dep_metadata.referenced_by.retain(|u| *u != metadata.id())
2080            }
2081        }
2082        for u in metadata.uses() {
2083            if let Some(dep_metadata) = self.entry_by_id.get_mut(&u) {
2084                dep_metadata.used_by.retain(|u| *u != metadata.id())
2085            }
2086        }
2087        for gid in metadata.global_ids() {
2088            self.entry_by_global_id.remove(&gid);
2089        }
2090
2091        let conn_id = metadata.item().conn_id().unwrap_or(&SYSTEM_CONN_ID);
2092        let schema = self.get_schema_mut(
2093            &metadata.name().qualifiers.database_spec,
2094            &metadata.name().qualifiers.schema_spec,
2095            conn_id,
2096        );
2097        if metadata.item_type() == CatalogItemType::Type {
2098            schema
2099                .types
2100                .remove(&metadata.name().item)
2101                .expect("catalog out of sync");
2102        } else {
2103            // Functions would need special handling, but we don't yet support
2104            // dropping functions.
2105            assert_ne!(metadata.item_type(), CatalogItemType::Func);
2106
2107            schema
2108                .items
2109                .remove(&metadata.name().item)
2110                .expect("catalog out of sync");
2111        };
2112
2113        if !id.is_system() {
2114            if let Some(cluster_id) = metadata.item().cluster_id() {
2115                assert!(
2116                    self.clusters_by_id
2117                        .get_mut(&cluster_id)
2118                        .expect("catalog out of sync")
2119                        .bound_objects
2120                        .remove(&id),
2121                    "catalog out of sync"
2122                );
2123            }
2124        }
2125
2126        metadata
2127    }
2128
2129    fn insert_introspection_source_index(
2130        &mut self,
2131        cluster_id: ClusterId,
2132        log: &'static BuiltinLog,
2133        item_id: CatalogItemId,
2134        global_id: GlobalId,
2135        oid: u32,
2136    ) {
2137        let (index_name, index) =
2138            self.create_introspection_source_index(cluster_id, log, global_id);
2139        self.insert_item(
2140            item_id,
2141            oid,
2142            index_name,
2143            index,
2144            MZ_SYSTEM_ROLE_ID,
2145            PrivilegeMap::default(),
2146        );
2147    }
2148
2149    fn create_introspection_source_index(
2150        &self,
2151        cluster_id: ClusterId,
2152        log: &'static BuiltinLog,
2153        global_id: GlobalId,
2154    ) -> (QualifiedItemName, CatalogItem) {
2155        let source_name = FullItemName {
2156            database: RawDatabaseSpecifier::Ambient,
2157            schema: log.schema.into(),
2158            item: log.name.into(),
2159        };
2160        let index_name = format!("{}_{}_primary_idx", log.name, cluster_id);
2161        let mut index_name = QualifiedItemName {
2162            qualifiers: ItemQualifiers {
2163                database_spec: ResolvedDatabaseSpecifier::Ambient,
2164                schema_spec: SchemaSpecifier::Id(self.get_mz_introspection_schema_id()),
2165            },
2166            item: index_name.clone(),
2167        };
2168        index_name = self.find_available_name(index_name, &SYSTEM_CONN_ID);
2169        let index_item_name = index_name.item.clone();
2170        let (log_item_id, log_global_id) = self.resolve_builtin_log(log);
2171        let index = CatalogItem::Index(Index {
2172            global_id,
2173            on: log_global_id,
2174            keys: log
2175                .variant
2176                .index_by()
2177                .into_iter()
2178                .map(MirScalarExpr::column)
2179                .collect(),
2180            create_sql: index_sql(
2181                index_item_name,
2182                cluster_id,
2183                source_name,
2184                &log.variant.desc(),
2185                &log.variant.index_by(),
2186            ),
2187            conn_id: None,
2188            resolved_ids: [(log_item_id, log_global_id)].into_iter().collect(),
2189            cluster_id,
2190            is_retained_metrics_object: false,
2191            custom_logical_compaction_window: None,
2192            optimized_plan: None,
2193            physical_plan: None,
2194            dataflow_metainfo: None,
2195        });
2196        (index_name, index)
2197    }
2198
2199    /// Insert system configuration `name` with `value`.
2200    ///
2201    /// Return a `bool` value indicating whether the configuration was modified
2202    /// by the call.
2203    fn insert_system_configuration(&mut self, name: &str, value: VarInput) -> Result<bool, Error> {
2204        Ok(Arc::make_mut(&mut self.system_configuration).set(name, value)?)
2205    }
2206
2207    /// Reset system configuration `name`.
2208    ///
2209    /// Return a `bool` value indicating whether the configuration was modified
2210    /// by the call.
2211    fn remove_system_configuration(&mut self, name: &str) -> Result<bool, Error> {
2212        Ok(Arc::make_mut(&mut self.system_configuration).reset(name)?)
2213    }
2214}
2215
2216/// Sort [`StateUpdate`]s in dependency order.
2217///
2218/// # Panics
2219///
2220/// This function assumes that all provided `updates` have the same timestamp and will panic
2221/// otherwise. It also requires that the provided `updates` are consolidated, i.e. all contained
2222/// `StateUpdateKinds` are unique.
2223fn sort_updates(updates: Vec<StateUpdate>) -> Vec<StateUpdate> {
2224    fn push_update<T>(
2225        update: T,
2226        diff: StateDiff,
2227        retractions: &mut Vec<T>,
2228        additions: &mut Vec<T>,
2229    ) {
2230        match diff {
2231            StateDiff::Retraction => retractions.push(update),
2232            StateDiff::Addition => additions.push(update),
2233        }
2234    }
2235
2236    soft_assert_no_log!(
2237        updates.iter().map(|update| update.ts).all_equal(),
2238        "all timestamps should be equal: {updates:?}"
2239    );
2240    soft_assert_no_log!(
2241        {
2242            let mut dedup = BTreeSet::new();
2243            updates.iter().all(|update| dedup.insert(&update.kind))
2244        },
2245        "updates should be consolidated: {updates:?}"
2246    );
2247
2248    // Partition updates by type so that we can weave different update types into the right spots.
2249    let mut pre_cluster_retractions = Vec::new();
2250    let mut pre_cluster_additions = Vec::new();
2251    let mut cluster_retractions = Vec::new();
2252    let mut cluster_additions = Vec::new();
2253    let mut builtin_item_updates = Vec::new();
2254    let mut item_retractions = Vec::new();
2255    let mut item_additions = Vec::new();
2256    let mut post_item_retractions = Vec::new();
2257    let mut post_item_additions = Vec::new();
2258    for update in updates {
2259        let diff = update.diff.clone();
2260        match update.kind {
2261            StateUpdateKind::Role(_)
2262            | StateUpdateKind::RoleAuth(_)
2263            | StateUpdateKind::Database(_)
2264            | StateUpdateKind::Schema(_)
2265            | StateUpdateKind::DefaultPrivilege(_)
2266            | StateUpdateKind::SystemPrivilege(_)
2267            | StateUpdateKind::SystemConfiguration(_)
2268            | StateUpdateKind::QueryPolicy(_)
2269            | StateUpdateKind::NetworkPolicy(_)
2270            | StateUpdateKind::ClusterReplicaSize(_) => push_update(
2271                update,
2272                diff,
2273                &mut pre_cluster_retractions,
2274                &mut pre_cluster_additions,
2275            ),
2276            StateUpdateKind::Cluster(_)
2277            | StateUpdateKind::ClusterSystemConfiguration(_)
2278            | StateUpdateKind::IntrospectionSourceIndex(_)
2279            | StateUpdateKind::ClusterReplica(_)
2280            | StateUpdateKind::ReplicaSystemConfiguration(_) => push_update(
2281                update,
2282                diff,
2283                &mut cluster_retractions,
2284                &mut cluster_additions,
2285            ),
2286            StateUpdateKind::SystemObjectMapping(system_object_mapping) => {
2287                builtin_item_updates.push((system_object_mapping, update.ts, update.diff))
2288            }
2289            StateUpdateKind::Item(item) => push_update(
2290                (item, update.ts, update.diff),
2291                diff,
2292                &mut item_retractions,
2293                &mut item_additions,
2294            ),
2295            StateUpdateKind::Comment(_)
2296            | StateUpdateKind::SourceReferences(_)
2297            | StateUpdateKind::AuditLog(_)
2298            | StateUpdateKind::StorageCollectionMetadata(_)
2299            | StateUpdateKind::UnfinalizedShard(_) => push_update(
2300                update,
2301                diff,
2302                &mut post_item_retractions,
2303                &mut post_item_additions,
2304            ),
2305        }
2306    }
2307
2308    // Sort builtin item updates by dependency. The builtin definition order must be a dependency
2309    // order, so we can use that to avoid a more expensive topo sorting.
2310    let builtin_item_updates = builtin_item_updates
2311        .into_iter()
2312        .map(|(system_object_mapping, ts, diff)| {
2313            let idx = BUILTIN_LOOKUP
2314                .get(&system_object_mapping.description)
2315                .expect("missing builtin")
2316                .0;
2317            (idx, system_object_mapping, ts, diff)
2318        })
2319        .sorted_by_key(|(idx, _, _, _)| *idx)
2320        .map(|(_, system_object_mapping, ts, diff)| (system_object_mapping, ts, diff));
2321
2322    // Partition builtins based on whether or not they should be applied before or after clusters.
2323    // Clusters depend on sources (introspection logs), so sources need to be applied first.
2324    // Everything else can be applied after clusters.
2325    let mut builtin_source_retractions = Vec::new();
2326    let mut builtin_source_additions = Vec::new();
2327    let mut other_builtin_retractions = Vec::new();
2328    let mut other_builtin_additions = Vec::new();
2329    for (builtin_item_update, ts, diff) in builtin_item_updates {
2330        let object_type = builtin_item_update.description.object_type;
2331        let update = StateUpdate {
2332            kind: StateUpdateKind::SystemObjectMapping(builtin_item_update),
2333            ts,
2334            diff,
2335        };
2336        if object_type == CatalogItemType::Source {
2337            push_update(
2338                update,
2339                diff,
2340                &mut builtin_source_retractions,
2341                &mut builtin_source_additions,
2342            );
2343        } else {
2344            push_update(
2345                update,
2346                diff,
2347                &mut other_builtin_retractions,
2348                &mut other_builtin_additions,
2349            );
2350        }
2351    }
2352
2353    /// Sort items by their dependencies using topological sort.
2354    ///
2355    /// # Panics
2356    ///
2357    /// This function requires that all provided items have unique item IDs.
2358    fn sort_items_topological(items: &mut Vec<(mz_catalog::durable::Item, Timestamp, StateDiff)>) {
2359        tracing::debug!(?items, "sorting items by dependencies");
2360
2361        let key_fn = |item: &(mz_catalog::durable::Item, _, _)| item.0.id;
2362        let dependencies_fn = |item: &(mz_catalog::durable::Item, _, _)| {
2363            let statement = mz_sql::parse::parse(&item.0.create_sql)
2364                .expect("valid create_sql")
2365                .into_element()
2366                .ast;
2367            mz_sql::names::dependencies(&statement).expect("failed to find dependencies of item")
2368        };
2369        sort_topological(items, key_fn, dependencies_fn);
2370    }
2371
2372    /// Sort item updates by dependency.
2373    ///
2374    /// First we group items into groups that are totally ordered by dependency. For example, when
2375    /// sorting all items by dependency we know that all tables can come after all sources, because
2376    /// a source can never depend on a table. Second, we sort the items in each group in
2377    /// topological order, or by ID, depending on the type.
2378    ///
2379    /// It used to be the case that the ID order of ALL items matched the dependency order. However,
2380    /// certain migrations shuffled item IDs around s.t. this was no longer true. A much better
2381    /// approach would be to investigate each item, discover their exact dependencies, and then
2382    /// perform a topological sort. This is non-trivial because we only have the CREATE SQL of each
2383    /// item here. Within the SQL the dependent items are sometimes referred to by ID and sometimes
2384    /// referred to by name.
2385    ///
2386    /// The logic of this function should match [`sort_temp_item_updates`].
2387    fn sort_item_updates(
2388        item_updates: Vec<(mz_catalog::durable::Item, Timestamp, StateDiff)>,
2389    ) -> VecDeque<(mz_catalog::durable::Item, Timestamp, StateDiff)> {
2390        // Partition items into groups s.t. each item in one group has a predefined order with all
2391        // items in other groups. For example, all sinks are ordered greater than all tables.
2392        let mut types = Vec::new();
2393        // N.B. Functions can depend on system tables, but not user tables.
2394        // TODO(udf): This will change when UDFs are supported.
2395        let mut funcs = Vec::new();
2396        let mut secrets = Vec::new();
2397        let mut connections = Vec::new();
2398        let mut sources = Vec::new();
2399        let mut tables = Vec::new();
2400        let mut derived_items = Vec::new();
2401        let mut sinks = Vec::new();
2402        for update in item_updates {
2403            match update.0.item_type() {
2404                CatalogItemType::Type => types.push(update),
2405                CatalogItemType::Func => funcs.push(update),
2406                CatalogItemType::Secret => secrets.push(update),
2407                CatalogItemType::Connection => connections.push(update),
2408                CatalogItemType::Source => sources.push(update),
2409                CatalogItemType::Table => tables.push(update),
2410                CatalogItemType::View
2411                | CatalogItemType::MaterializedView
2412                | CatalogItemType::Index
2413                | CatalogItemType::MetricSink => derived_items.push(update),
2414                CatalogItemType::Sink => sinks.push(update),
2415            }
2416        }
2417
2418        // For some groups, the items in them can depend on each other and can be `ALTER`ed so that
2419        // an item ends up depending on an item with a greater ID. Thus we need to perform
2420        // topological sort for these groups.
2421        sort_items_topological(&mut connections);
2422        sort_items_topological(&mut derived_items);
2423
2424        // Other groups we can simply sort by ID.
2425        for group in [
2426            &mut types,
2427            &mut funcs,
2428            &mut secrets,
2429            &mut sources,
2430            &mut tables,
2431            &mut sinks,
2432        ] {
2433            group.sort_by_key(|(item, _, _)| item.id);
2434        }
2435
2436        iter::empty()
2437            .chain(types)
2438            .chain(funcs)
2439            .chain(secrets)
2440            .chain(connections)
2441            .chain(sources)
2442            .chain(tables)
2443            .chain(derived_items)
2444            .chain(sinks)
2445            .collect()
2446    }
2447
2448    // Temporary and non-temporary items sort together: the type groups order
2449    // cross-type dependencies and the topological sorts order dependencies
2450    // within a group, regardless of which items are temporary.
2451    fn into_state_updates(
2452        item_updates: VecDeque<(mz_catalog::durable::Item, Timestamp, StateDiff)>,
2453    ) -> Vec<StateUpdate> {
2454        item_updates
2455            .into_iter()
2456            .map(|(item, ts, diff)| StateUpdate {
2457                kind: StateUpdateKind::Item(item),
2458                ts,
2459                diff,
2460            })
2461            .collect()
2462    }
2463    let item_retractions = into_state_updates(sort_item_updates(item_retractions));
2464    let item_additions = into_state_updates(sort_item_updates(item_additions));
2465
2466    // Put everything back together.
2467    iter::empty()
2468        // All retractions must be reversed.
2469        .chain(post_item_retractions.into_iter().rev())
2470        .chain(item_retractions.into_iter().rev())
2471        .chain(other_builtin_retractions.into_iter().rev())
2472        .chain(cluster_retractions.into_iter().rev())
2473        .chain(builtin_source_retractions.into_iter().rev())
2474        .chain(pre_cluster_retractions.into_iter().rev())
2475        .chain(pre_cluster_additions)
2476        .chain(builtin_source_additions)
2477        .chain(cluster_additions)
2478        .chain(other_builtin_additions)
2479        .chain(item_additions)
2480        .chain(post_item_additions)
2481        .collect()
2482}
2483
2484/// Groups of updates of certain types are applied in batches to improve
2485/// performance. A constraint is that updates must be applied in order. This
2486/// process is modeled as a state machine that batches then applies groups of
2487/// updates.
2488enum ApplyState {
2489    /// Additions of builtin views.
2490    BuiltinViewAdditions(Vec<(&'static BuiltinView, CatalogItemId, GlobalId)>),
2491    /// Item updates that aren't builtin view additions.
2492    ///
2493    /// This contains all updates whose application requires calling
2494    /// `parse_item` and thus toggling the `enable_for_item_parsing` feature
2495    /// flags.
2496    Items(Vec<StateUpdate>),
2497    /// All other updates.
2498    Updates(Vec<StateUpdate>),
2499}
2500
2501impl ApplyState {
2502    fn new(update: StateUpdate) -> Self {
2503        use StateUpdateKind::*;
2504        match &update.kind {
2505            SystemObjectMapping(som)
2506                if som.description.object_type == CatalogItemType::View
2507                    && update.diff == StateDiff::Addition =>
2508            {
2509                let view_addition = lookup_builtin_view_addition(som.clone());
2510                Self::BuiltinViewAdditions(vec![view_addition])
2511            }
2512
2513            IntrospectionSourceIndex(_) | SystemObjectMapping(_) | Item(_) => {
2514                Self::Items(vec![update])
2515            }
2516
2517            Role(_)
2518            | RoleAuth(_)
2519            | Database(_)
2520            | Schema(_)
2521            | DefaultPrivilege(_)
2522            | SystemPrivilege(_)
2523            | SystemConfiguration(_)
2524            | ClusterSystemConfiguration(_)
2525            | ReplicaSystemConfiguration(_)
2526            | Cluster(_)
2527            | NetworkPolicy(_)
2528            | ClusterReplicaSize(_)
2529            | QueryPolicy(_)
2530            | ClusterReplica(_)
2531            | SourceReferences(_)
2532            | Comment(_)
2533            | AuditLog(_)
2534            | StorageCollectionMetadata(_)
2535            | UnfinalizedShard(_) => Self::Updates(vec![update]),
2536        }
2537    }
2538
2539    /// Apply all updates that have been batched in `self`.
2540    ///
2541    /// We make sure to enable all "enable_for_item_parsing" feature flags when applying item
2542    /// updates during bootstrap. See [`CatalogState::with_enable_for_item_parsing`] for more
2543    /// details.
2544    async fn apply(
2545        self,
2546        state: &mut CatalogState,
2547        retractions: &mut InProgressRetractions,
2548        local_expression_cache: &mut LocalExpressionCache,
2549    ) -> (
2550        Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
2551        Vec<ParsedStateUpdate>,
2552    ) {
2553        match self {
2554            Self::BuiltinViewAdditions(builtin_view_additions) => {
2555                let restore = Arc::clone(&state.system_configuration);
2556                Arc::make_mut(&mut state.system_configuration).enable_for_item_parsing();
2557                let builtin_table_updates = CatalogState::parse_builtin_views(
2558                    state,
2559                    builtin_view_additions,
2560                    retractions,
2561                    local_expression_cache,
2562                )
2563                .await;
2564                state.system_configuration = restore;
2565                (builtin_table_updates, Vec::new())
2566            }
2567            Self::Items(updates) => state.with_enable_for_item_parsing(|state| {
2568                state
2569                    .apply_updates_inner(updates, retractions, local_expression_cache)
2570                    .expect("corrupt catalog")
2571            }),
2572            Self::Updates(updates) => state
2573                .apply_updates_inner(updates, retractions, local_expression_cache)
2574                .expect("corrupt catalog"),
2575        }
2576    }
2577
2578    async fn step(
2579        self,
2580        next: Self,
2581        state: &mut CatalogState,
2582        retractions: &mut InProgressRetractions,
2583        local_expression_cache: &mut LocalExpressionCache,
2584    ) -> (
2585        Self,
2586        (
2587            Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
2588            Vec<ParsedStateUpdate>,
2589        ),
2590    ) {
2591        match (self, next) {
2592            (
2593                Self::BuiltinViewAdditions(mut builtin_view_additions),
2594                Self::BuiltinViewAdditions(next_builtin_view_additions),
2595            ) => {
2596                // Continue batching builtin view additions.
2597                builtin_view_additions.extend(next_builtin_view_additions);
2598                (
2599                    Self::BuiltinViewAdditions(builtin_view_additions),
2600                    (Vec::new(), Vec::new()),
2601                )
2602            }
2603            (Self::Items(mut updates), Self::Items(next_updates)) => {
2604                // Continue batching item updates.
2605                updates.extend(next_updates);
2606                (Self::Items(updates), (Vec::new(), Vec::new()))
2607            }
2608            (Self::Updates(mut updates), Self::Updates(next_updates)) => {
2609                // Continue batching updates.
2610                updates.extend(next_updates);
2611                (Self::Updates(updates), (Vec::new(), Vec::new()))
2612            }
2613            (apply_state, next_apply_state) => {
2614                // Apply the current batch and start batching new apply state.
2615                let updates = apply_state
2616                    .apply(state, retractions, local_expression_cache)
2617                    .await;
2618                (next_apply_state, updates)
2619            }
2620        }
2621    }
2622}
2623
2624/// Trait abstracting over map operations needed by [`apply_inverted_lookup`] and
2625/// [`apply_with_update`]. Both [`BTreeMap`] and [`imbl::OrdMap`] implement this.
2626trait MutableMap<K, V> {
2627    fn insert(&mut self, key: K, value: V) -> Option<V>;
2628    fn remove(&mut self, key: &K) -> Option<V>;
2629}
2630
2631impl<K: Ord, V> MutableMap<K, V> for BTreeMap<K, V> {
2632    fn insert(&mut self, key: K, value: V) -> Option<V> {
2633        BTreeMap::insert(self, key, value)
2634    }
2635    fn remove(&mut self, key: &K) -> Option<V> {
2636        BTreeMap::remove(self, key)
2637    }
2638}
2639
2640impl<K: Ord + Clone, V: Clone> MutableMap<K, V> for imbl::OrdMap<K, V> {
2641    fn insert(&mut self, key: K, value: V) -> Option<V> {
2642        imbl::OrdMap::insert(self, key, value)
2643    }
2644    fn remove(&mut self, key: &K) -> Option<V> {
2645        imbl::OrdMap::remove(self, key)
2646    }
2647}
2648
2649/// Helper method to updated inverted lookup maps. The keys are generally names and the values are
2650/// generally IDs.
2651///
2652/// Importantly, when retracting it's expected that the existing value will match `value` exactly.
2653fn apply_inverted_lookup<K, V>(map: &mut impl MutableMap<K, V>, key: &K, value: V, diff: StateDiff)
2654where
2655    K: Ord + Clone + Debug,
2656    V: PartialEq + Debug,
2657{
2658    match diff {
2659        StateDiff::Retraction => {
2660            let prev = map.remove(key);
2661            assert_eq!(
2662                prev,
2663                Some(value),
2664                "retraction does not match existing value: {key:?}"
2665            );
2666        }
2667        StateDiff::Addition => {
2668            let prev = map.insert(key.clone(), value);
2669            assert_eq!(
2670                prev, None,
2671                "values must be explicitly retracted before inserting a new value: {key:?}"
2672            );
2673        }
2674    }
2675}
2676
2677/// Helper method to update catalog state, that may need to be updated from a previously retracted
2678/// object.
2679fn apply_with_update<K, V, D>(
2680    map: &mut impl MutableMap<K, V>,
2681    durable: D,
2682    key_fn: impl FnOnce(&D) -> K,
2683    diff: StateDiff,
2684    retractions: &mut BTreeMap<D::Key, V>,
2685) where
2686    K: Ord,
2687    V: UpdateFrom<D> + PartialEq + Debug,
2688    D: DurableType,
2689    D::Key: Ord,
2690{
2691    match diff {
2692        StateDiff::Retraction => {
2693            let mem_key = key_fn(&durable);
2694            let value = map
2695                .remove(&mem_key)
2696                .expect("retraction does not match existing value: {key:?}");
2697            let durable_key = durable.into_key_value().0;
2698            retractions.insert(durable_key, value);
2699        }
2700        StateDiff::Addition => {
2701            let mem_key = key_fn(&durable);
2702            let durable_key = durable.key();
2703            let value = match retractions.remove(&durable_key) {
2704                Some(mut retraction) => {
2705                    retraction.update_from(durable);
2706                    retraction
2707                }
2708                None => durable.into(),
2709            };
2710            let prev = map.insert(mem_key, value);
2711            assert_eq!(
2712                prev, None,
2713                "values must be explicitly retracted before inserting a new value"
2714            );
2715        }
2716    }
2717}
2718
2719/// Looks up a [`BuiltinView`] from a [`SystemObjectMapping`].
2720fn lookup_builtin_view_addition(
2721    mapping: SystemObjectMapping,
2722) -> (&'static BuiltinView, CatalogItemId, GlobalId) {
2723    let (_, builtin) = BUILTIN_LOOKUP
2724        .get(&mapping.description)
2725        .expect("missing builtin view");
2726    let Builtin::View(view) = builtin else {
2727        unreachable!("programming error, expected BuiltinView found {builtin:?}");
2728    };
2729
2730    (
2731        view,
2732        mapping.unique_identifier.catalog_id,
2733        mapping.unique_identifier.global_id,
2734    )
2735}