Skip to main content

mz_adapter/catalog/
open.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 opening a [`Catalog`].
11
12mod builtin_schema_migration;
13
14use std::collections::{BTreeMap, BTreeSet};
15use std::num::NonZeroU32;
16use std::sync::Arc;
17use std::sync::atomic::AtomicU64;
18use std::time::{Duration, Instant};
19
20use futures::future::{BoxFuture, FutureExt};
21use itertools::{Either, Itertools};
22use mz_adapter_types::bootstrap_builtin_cluster_config::BootstrapBuiltinClusterConfig;
23use mz_adapter_types::dyncfgs::ENABLE_EXPRESSION_CACHE;
24use mz_audit_log::{
25    CreateOrDropClusterReplicaReasonV1, EventDetails, EventType, ObjectType, VersionedEvent,
26};
27use mz_auth::hash::scram256_hash;
28use mz_catalog::builtin::{
29    BUILTIN_CLUSTERS, BUILTIN_PREFIXES, BUILTIN_ROLES, BUILTINS, Builtin, Fingerprint,
30    MZ_CATALOG_RAW, RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL,
31};
32use mz_catalog::config::{ClusterReplicaSizeMap, StateConfig};
33use mz_catalog::durable::objects::{
34    SystemObjectDescription, SystemObjectMapping, SystemObjectUniqueIdentifier,
35};
36use mz_catalog::durable::{
37    ClusterReplica, ClusterReplicaSize, ClusterVariant, ClusterVariantManaged, ReplicaConfig,
38    ReplicaLocation, Transaction, managed_cluster_replica_name,
39};
40use mz_catalog::expr_cache::{
41    ExpressionCacheConfig, ExpressionCacheHandle, GlobalExpressions, LocalExpressions,
42    latest_item_version,
43};
44use mz_catalog::memory::error::{Error, ErrorKind};
45use mz_catalog::memory::objects::{
46    CommentsMap, DefaultPrivileges, RoleAuth, StateUpdate, StateUpdateKind,
47};
48use mz_controller::clusters::ReplicaLogging;
49use mz_controller_types::ClusterId;
50use mz_ore::cast::usize_to_u64;
51use mz_ore::collections::HashSet;
52use mz_ore::now::{SYSTEM_TIME, to_datetime};
53use mz_ore::{instrument, soft_assert_no_log};
54use mz_repr::adt::mz_acl_item::PrivilegeMap;
55use mz_repr::namespaces::is_unstable_schema;
56use mz_repr::{CatalogItemId, Diff, GlobalId, RelationVersion, Timestamp};
57use mz_sql::catalog::{CatalogError as SqlCatalogError, CatalogItemType, RoleMembership, RoleVars};
58use mz_sql::func::OP_IMPLS;
59use mz_sql::names::CommentObjectId;
60use mz_sql::rbac;
61use mz_sql::session::user::{MZ_SYSTEM_ROLE_ID, SYSTEM_USER};
62use mz_sql::session::vars::{SessionVars, SystemVars, VarError, VarInput};
63use mz_storage_client::controller::{StorageMetadata, StorageTxn};
64use mz_storage_client::storage_collections::StorageCollections;
65use semver::Version;
66use tracing::{Instrument, info, warn};
67use uuid::Uuid;
68
69// DO NOT add any more imports from `crate` outside of `crate::catalog`.
70use crate::AdapterError;
71use crate::catalog::migrate::{self, get_migration_version, set_migration_version};
72use crate::catalog::state::LocalExpressionCache;
73use crate::catalog::{BuiltinTableUpdate, Catalog, CatalogState, Config, is_reserved_name};
74
75pub struct InitializeStateResult {
76    /// An initialized [`CatalogState`].
77    pub state: CatalogState,
78    /// Items whose builtin schema migration allocated a fresh, self-owned persist shard from the
79    /// migration shard: `Replacement`-migrated items and builtin storage collections that had no
80    /// shard yet, in practice new ones. Only used by 0dt migration.
81    ///
82    /// Derived by filtering to items with a global id in `MigrationRunResult::new_shards`, which
83    /// only `get_or_insert_shards` populates. `Evolution` migrates in place and reuses the leader's
84    /// shard, so it never lands here. Read-only write paths depend on that: force-writing a shard
85    /// while read-only is safe only because we exclusively own it (see
86    /// `ComputeController::allow_writes_in_read_only`).
87    pub migrated_storage_collections_0dt: BTreeSet<CatalogItemId>,
88    /// A set of new builtin items.
89    pub new_builtin_collections: BTreeSet<GlobalId>,
90    /// A list of builtin table updates corresponding to the initialized state.
91    pub builtin_table_updates: Vec<BuiltinTableUpdate>,
92    /// The version of the binary that last committed catalog migrations, or `None` for a newly
93    /// initialized catalog.
94    ///
95    /// While this environment is read-only during a 0dt deployment, this is the version of the
96    /// leader environment: the read-only catalog transaction is a savepoint, so our own bump of
97    /// the setting never lands.
98    pub last_seen_version: Option<Version>,
99    /// A handle to the expression cache if it's enabled.
100    pub expr_cache_handle: Option<ExpressionCacheHandle>,
101    /// The global expressions that were cached in `expr_cache_handle`.
102    pub cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
103    /// The local expressions that were NOT cached in `expr_cache_handle`.
104    pub uncached_local_exprs: BTreeMap<GlobalId, LocalExpressions>,
105}
106
107pub struct OpenCatalogResult {
108    /// An opened [`Catalog`].
109    pub catalog: Catalog,
110    /// See [`InitializeStateResult::last_seen_version`].
111    pub last_seen_version: Option<Version>,
112    /// See [`InitializeStateResult::migrated_storage_collections_0dt`].
113    pub migrated_storage_collections_0dt: BTreeSet<CatalogItemId>,
114    /// A set of new builtin items.
115    pub new_builtin_collections: BTreeSet<GlobalId>,
116    /// A list of builtin table updates corresponding to the initialized state.
117    pub builtin_table_updates: Vec<BuiltinTableUpdate>,
118    /// The global expressions that were cached in the expression cache.
119    pub cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
120    /// The local expressions that were NOT cached in the expression cache.
121    pub uncached_local_exprs: BTreeMap<GlobalId, LocalExpressions>,
122}
123
124impl Catalog {
125    /// Initializes a CatalogState. Separate from [`Catalog::open`] to avoid depending on state
126    /// external to a [mz_catalog::durable::DurableCatalogState]
127    /// (for example: no [mz_secrets::SecretsReader]).
128    pub async fn initialize_state<'a>(
129        config: StateConfig,
130        storage: &'a mut Box<dyn mz_catalog::durable::DurableCatalogState>,
131    ) -> Result<InitializeStateResult, AdapterError> {
132        for builtin_role in BUILTIN_ROLES {
133            assert!(
134                is_reserved_name(builtin_role.name),
135                "builtin role {builtin_role:?} must start with one of the following prefixes {}",
136                BUILTIN_PREFIXES.join(", ")
137            );
138        }
139        for builtin_cluster in BUILTIN_CLUSTERS {
140            assert!(
141                is_reserved_name(builtin_cluster.name),
142                "builtin cluster {builtin_cluster:?} must start with one of the following prefixes {}",
143                BUILTIN_PREFIXES.join(", ")
144            );
145        }
146
147        let mut system_configuration = SystemVars::new().set_unsafe(config.unsafe_mode);
148        if config.all_features {
149            system_configuration.enable_all_feature_flags_by_default();
150        }
151
152        let mut state = CatalogState {
153            database_by_name: imbl::OrdMap::new(),
154            database_by_id: imbl::OrdMap::new(),
155            entry_by_id: imbl::OrdMap::new(),
156            entry_by_global_id: imbl::OrdMap::new(),
157            notices_by_dep_id: imbl::OrdMap::new(),
158            ambient_schemas_by_name: imbl::OrdMap::new(),
159            ambient_schemas_by_id: imbl::OrdMap::new(),
160            clusters_by_name: imbl::OrdMap::new(),
161            clusters_by_id: imbl::OrdMap::new(),
162            roles_by_name: imbl::OrdMap::new(),
163            roles_by_id: imbl::OrdMap::new(),
164            network_policies_by_id: imbl::OrdMap::new(),
165            query_policies_by_id: imbl::OrdMap::new(),
166            query_policies_by_name: imbl::OrdMap::new(),
167            role_auth_by_id: imbl::OrdMap::new(),
168            network_policies_by_name: imbl::OrdMap::new(),
169            system_configuration: Arc::new(system_configuration),
170            scoped_system_parameters: Default::default(),
171            default_privileges: Arc::new(DefaultPrivileges::default()),
172            system_privileges: Arc::new(PrivilegeMap::default()),
173            comments: Arc::new(CommentsMap::default()),
174            source_references: imbl::OrdMap::new(),
175            storage_metadata: Arc::new(StorageMetadata::default()),
176            temporary_namespaces: Default::default(),
177            mock_authentication_nonce: Default::default(),
178            config: mz_sql::catalog::CatalogConfig {
179                start_time: to_datetime((config.now)()),
180                start_instant: Instant::now(),
181                nonce: rand::random(),
182                environment_id: config.environment_id,
183                session_id: Uuid::new_v4(),
184                build_info: config.build_info,
185                now: config.now.clone(),
186                connection_context: config.connection_context,
187                aws_account_id: config
188                    .aws_principal_context
189                    .as_ref()
190                    .map(|c| c.aws_account_id.clone()),
191                helm_chart_version: config.helm_chart_version,
192            },
193            // Populated from the durable catalog, which `sync_builtin_cluster_replica_sizes`
194            // reconciles with `config.cluster_replica_sizes`.
195            cluster_replica_sizes: ClusterReplicaSizeMap(BTreeMap::new()),
196            availability_zones: config.availability_zones,
197            egress_addresses: config.egress_addresses,
198            aws_principal_context: config.aws_principal_context,
199            aws_privatelink_availability_zones: config.aws_privatelink_availability_zones,
200            http_host_name: config.http_host_name,
201            license_key: config.license_key,
202        };
203
204        let deploy_generation = storage.get_deployment_generation().await?;
205
206        let mut updates: Vec<_> = storage.sync_to_current_updates().await?;
207        assert!(!updates.is_empty(), "initial catalog snapshot is missing");
208        let mut txn = storage.transaction().await?;
209
210        // Migrate/update durable data before we start loading the in-memory catalog.
211        let new_builtin_collections = {
212            migrate::durable_migrate(
213                &mut txn,
214                state.config.environment_id.organization_id(),
215                config.boot_ts,
216            )?;
217            // Overwrite and persist selected parameter values in `remote_system_parameters` that
218            // was pulled from a remote frontend (e.g. LaunchDarkly) if present.
219            if let Some(remote_system_parameters) = config.remote_system_parameters {
220                for (name, value) in remote_system_parameters {
221                    txn.upsert_system_config(&name, value)?;
222                }
223                txn.set_system_config_synced_once()?;
224            }
225            // Add any new builtin objects and remove old ones.
226            let new_builtin_collections = add_new_remove_old_builtin_items_migration(&mut txn)?;
227            let builtin_bootstrap_cluster_config_map = BuiltinBootstrapClusterConfigMap {
228                system_cluster: config.builtin_system_cluster_config,
229                catalog_server_cluster: config.builtin_catalog_server_cluster_config,
230                probe_cluster: config.builtin_probe_cluster_config,
231                support_cluster: config.builtin_support_cluster_config,
232                analytics_cluster: config.builtin_analytics_cluster_config,
233            };
234            add_new_remove_old_builtin_clusters_migration(
235                &mut txn,
236                &builtin_bootstrap_cluster_config_map,
237                config.boot_ts,
238            )?;
239            add_new_remove_old_builtin_introspection_source_migration(&mut txn)?;
240            reconcile_builtin_cluster_replicas(
241                &mut txn,
242                &builtin_bootstrap_cluster_config_map,
243                config.boot_ts,
244            )?;
245            add_new_remove_old_builtin_roles_migration(&mut txn)?;
246            // A read-only catalog can't commit, so it uses the durable sizes.
247            if !txn.is_read_only() {
248                sync_builtin_cluster_replica_sizes(&mut txn, &config.cluster_replica_sizes)?;
249            }
250            remove_invalid_config_param_role_defaults_migration(&mut txn)?;
251            remove_pending_cluster_replicas_migration(&mut txn, config.boot_ts)?;
252
253            new_builtin_collections
254        };
255
256        let op_updates = txn.get_and_commit_op_updates();
257        updates.extend(op_updates);
258
259        let mut builtin_table_updates = Vec::new();
260
261        // Seed the in-memory catalog with values that don't come from the durable catalog.
262        {
263            // Set defaults from configuration passed in the provided `system_parameter_defaults`
264            // map.
265            for (name, value) in config.system_parameter_defaults {
266                match state.set_system_configuration_default(&name, VarInput::Flat(&value)) {
267                    Ok(_) => (),
268                    Err(Error {
269                        kind: ErrorKind::VarError(VarError::UnknownParameter(name)),
270                    }) => {
271                        warn!(%name, "cannot load unknown system parameter from catalog storage to set default parameter");
272                    }
273                    Err(e) => return Err(e.into()),
274                };
275            }
276        }
277
278        // Make life easier by consolidating all updates, so that we end up with only positive
279        // diffs.
280        let mut updates = into_consolidatable_updates_startup(updates, config.boot_ts);
281        differential_dataflow::consolidation::consolidate_updates(&mut updates);
282        soft_assert_no_log!(
283            updates.iter().all(|(_, _, diff)| *diff == Diff::ONE),
284            "consolidated updates should be positive during startup: {updates:?}"
285        );
286
287        let mut pre_item_updates = Vec::new();
288        let mut system_item_updates = Vec::new();
289        let mut item_updates = Vec::new();
290        let mut post_item_updates = Vec::new();
291        let mut audit_log_updates = Vec::new();
292        for (kind, ts, diff) in updates {
293            match kind {
294                StateUpdateKind::Role(_)
295                | StateUpdateKind::RoleAuth(_)
296                | StateUpdateKind::Database(_)
297                | StateUpdateKind::Schema(_)
298                | StateUpdateKind::DefaultPrivilege(_)
299                | StateUpdateKind::SystemPrivilege(_)
300                | StateUpdateKind::SystemConfiguration(_)
301                | StateUpdateKind::ClusterSystemConfiguration(_)
302                | StateUpdateKind::ReplicaSystemConfiguration(_)
303                | StateUpdateKind::Cluster(_)
304                | StateUpdateKind::NetworkPolicy(_)
305                | StateUpdateKind::ClusterReplicaSize(_)
306                | StateUpdateKind::QueryPolicy(_)
307                | StateUpdateKind::ClusterReplica(_) => pre_item_updates.push(StateUpdate {
308                    kind,
309                    ts,
310                    diff: diff.try_into().expect("valid diff"),
311                }),
312                StateUpdateKind::IntrospectionSourceIndex(_)
313                | StateUpdateKind::SystemObjectMapping(_) => {
314                    system_item_updates.push(StateUpdate {
315                        kind,
316                        ts,
317                        diff: diff.try_into().expect("valid diff"),
318                    })
319                }
320                StateUpdateKind::Item(_) => item_updates.push(StateUpdate {
321                    kind,
322                    ts,
323                    diff: diff.try_into().expect("valid diff"),
324                }),
325                StateUpdateKind::Comment(_)
326                | StateUpdateKind::StorageCollectionMetadata(_)
327                | StateUpdateKind::SourceReferences(_)
328                | StateUpdateKind::UnfinalizedShard(_) => {
329                    post_item_updates.push((kind, ts, diff));
330                }
331                StateUpdateKind::AuditLog(_) => {
332                    audit_log_updates.push(StateUpdate {
333                        kind,
334                        ts,
335                        diff: diff.try_into().expect("valid diff"),
336                    });
337                }
338            }
339        }
340
341        let (builtin_table_update, _catalog_updates) = state
342            .apply_updates(pre_item_updates, &mut LocalExpressionCache::Closed)
343            .await;
344        builtin_table_updates.extend(builtin_table_update);
345
346        // Both the `system_parameter_defaults` set above and the durable
347        // `SystemConfiguration` values applied via `pre_item_updates` live in
348        // the `SystemVars` value map by now. Mirror their effective values into
349        // the dyncfg `ConfigSet`, so that startup-only reads observe configured
350        // values rather than compile-time defaults, as with
351        // `ENABLE_EXPRESSION_CACHE` below. `apply_updates` only
352        // syncs the `ConfigSet` when a `SystemConfiguration` update is present,
353        // and a deployment configured purely via `system_parameter_default` has
354        // none, so sync explicitly here.
355        state.system_config().sync_dyncfgs();
356
357        // Ensure mz_system has a password if configured to have one.
358        // It's important we do this after the `pre_item_updates` so that
359        // the mz_system role exists in the catalog.
360        {
361            if let Some(password) = config.external_login_password_mz_system {
362                let role_auth = RoleAuth {
363                    role_id: MZ_SYSTEM_ROLE_ID,
364                    // builtin roles should always use a secure scram iteration
365                    // <https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html>
366                    password_hash: Some(
367                        scram256_hash(&password, &NonZeroU32::new(600_000).expect("known valid"))
368                            .map_err(|_| {
369                            AdapterError::Internal("Failed to hash mz_system password.".to_owned())
370                        })?,
371                    ),
372                    updated_at: SYSTEM_TIME(),
373                };
374                state
375                    .role_auth_by_id
376                    .insert(MZ_SYSTEM_ROLE_ID, role_auth.clone());
377                let builtin_table_update = state.generate_builtin_table_update(
378                    mz_catalog::memory::objects::StateUpdateKind::RoleAuth(role_auth.into()),
379                    mz_catalog::memory::objects::StateDiff::Addition,
380                );
381                builtin_table_updates.extend(builtin_table_update);
382            }
383        }
384
385        let expr_cache_start = Instant::now();
386        info!("startup: coordinator init: catalog open: expr cache open beginning");
387        // We wait until after the `pre_item_updates` to open the cache so we can get accurate
388        // dyncfgs because the `pre_item_updates` contains `SystemConfiguration` updates.
389        let enable_expr_cache_dyncfg = ENABLE_EXPRESSION_CACHE.get(state.system_config().dyncfgs());
390        let expr_cache_enabled = config
391            .enable_expression_cache_override
392            .unwrap_or(enable_expr_cache_dyncfg);
393        let (expr_cache_handle, cached_local_exprs, cached_global_exprs) = if expr_cache_enabled {
394            info!(
395                ?config.enable_expression_cache_override,
396                ?enable_expr_cache_dyncfg,
397                "using expression cache for startup"
398            );
399            let current_items = txn
400                .get_items()
401                .flat_map(|item| {
402                    let item_version = latest_item_version(&item.extra_versions);
403                    std::iter::once(item.global_id)
404                        .chain(item.extra_versions.into_values())
405                        .map(move |gid| (gid, item_version))
406                })
407                .chain(
408                    txn.get_system_object_mappings()
409                        .map(|som| (som.unique_identifier.global_id, RelationVersion::root())),
410                )
411                .collect();
412            let dyncfgs = config.persist_client.dyncfgs().clone();
413            let build_version = if config.build_info.is_dev() {
414                // A single dev version can be used for many different builds, so we need to use
415                // the build version that is also enriched with build metadata.
416                config
417                    .build_info
418                    .semver_version_build()
419                    .expect("build ID is not available on your platform!")
420            } else {
421                config.build_info.semver_version()
422            };
423            let expr_cache_config = ExpressionCacheConfig {
424                build_version,
425                shard_id: txn
426                    .get_expression_cache_shard()
427                    .expect("expression cache shard should exist for opened catalogs"),
428                persist: config.persist_client,
429                current_items,
430                remove_prior_versions: !config.read_only,
431                compact_shard: config.read_only,
432                dyncfgs,
433            };
434            let (expr_cache_handle, cached_local_exprs, cached_global_exprs) =
435                ExpressionCacheHandle::spawn_expression_cache(expr_cache_config).await;
436            (
437                Some(expr_cache_handle),
438                cached_local_exprs,
439                cached_global_exprs,
440            )
441        } else {
442            (None, BTreeMap::new(), BTreeMap::new())
443        };
444        let mut local_expr_cache = LocalExpressionCache::new(cached_local_exprs);
445        info!(
446            "startup: coordinator init: catalog open: expr cache open complete in {:?}",
447            expr_cache_start.elapsed()
448        );
449
450        // When initializing/bootstrapping, we don't use the catalog updates but
451        // instead load the catalog fully and then go ahead and apply commands
452        // to the controller(s). Maybe we _should_ instead use the same logic
453        // and return and use the updates from here. But that's at the very
454        // least future work.
455        let (builtin_table_update, _catalog_updates) = state
456            .apply_updates(system_item_updates, &mut local_expr_cache)
457            .await;
458        builtin_table_updates.extend(builtin_table_update);
459
460        let last_seen_version = get_migration_version(&txn);
461
462        let mz_authentication_mock_nonce =
463            txn.get_authentication_mock_nonce().ok_or_else(|| {
464                Error::new(ErrorKind::SettingError("authentication nonce".to_string()))
465            })?;
466
467        state.mock_authentication_nonce = Some(mz_authentication_mock_nonce);
468
469        // Migrate item ASTs.
470        let (builtin_table_update, _catalog_updates) = if !config.skip_migrations {
471            let migrate_result = migrate::migrate(
472                &mut state,
473                &mut txn,
474                &mut local_expr_cache,
475                item_updates,
476                config.now,
477                config.boot_ts,
478            )
479            .await
480            .map_err(|e| {
481                Error::new(ErrorKind::FailedCatalogMigration {
482                    last_seen_version: last_seen_version
483                        .as_ref()
484                        .map_or_else(|| "new".to_string(), |v| v.to_string()),
485                    this_version: config.build_info.version,
486                    cause: e.to_string(),
487                })
488            })?;
489            if !migrate_result.post_item_updates.is_empty() {
490                // Include any post-item-updates generated by migrations, and then consolidate
491                // them to ensure diffs are all positive.
492                post_item_updates.extend(migrate_result.post_item_updates);
493                // Push everything to the same timestamp so it consolidates cleanly.
494                if let Some(max_ts) = post_item_updates.iter().map(|(_, ts, _)| ts).max().cloned() {
495                    for (_, ts, _) in &mut post_item_updates {
496                        *ts = max_ts;
497                    }
498                }
499                differential_dataflow::consolidation::consolidate_updates(&mut post_item_updates);
500            }
501
502            (
503                migrate_result.builtin_table_updates,
504                migrate_result.catalog_updates,
505            )
506        } else {
507            state
508                .apply_updates(item_updates, &mut local_expr_cache)
509                .await
510        };
511        builtin_table_updates.extend(builtin_table_update);
512
513        let post_item_updates = post_item_updates
514            .into_iter()
515            .map(|(kind, ts, diff)| StateUpdate {
516                kind,
517                ts,
518                diff: diff.try_into().expect("valid diff"),
519            })
520            .collect();
521        let (builtin_table_update, _catalog_updates) = state
522            .apply_updates(post_item_updates, &mut local_expr_cache)
523            .await;
524        builtin_table_updates.extend(builtin_table_update);
525
526        // We don't need to apply the audit logs in memory, yet apply can be expensive when the
527        // audit log grows large. Therefore, we skip the apply step and just generate the builtin
528        // updates.
529        for audit_log_update in audit_log_updates {
530            builtin_table_updates.extend(
531                state.generate_builtin_table_update(audit_log_update.kind, audit_log_update.diff),
532            );
533        }
534
535        // Migrate builtin items.
536        let schema_migration_result = builtin_schema_migration::run(
537            config.build_info,
538            deploy_generation,
539            &mut txn,
540            config.builtin_item_migration_config,
541        )
542        .await?;
543
544        let state_updates = txn.get_and_commit_op_updates();
545
546        // When initializing/bootstrapping, we don't use the catalog updates but
547        // instead load the catalog fully and then go ahead and apply commands
548        // to the controller(s). Maybe we _should_ instead use the same logic
549        // and return and use the updates from here. But that's at the very
550        // least future work.
551        let (table_updates, _catalog_updates) = state
552            .apply_updates(state_updates, &mut local_expr_cache)
553            .await;
554        builtin_table_updates.extend(table_updates);
555        let builtin_table_updates = state.resolve_builtin_table_updates(builtin_table_updates);
556
557        // Every item is now planned, including those the migrations rewrote,
558        // so record what this build's planner produced for each. A read-only
559        // catalog cannot commit the rows and nothing in memory reads them, so
560        // it is left as it is; a savepoint catalog commits them in memory.
561        if !txn.is_read_only() {
562            state.refresh_item_metadata(&mut txn)?;
563        }
564
565        // Bump the migration version immediately before committing.
566        set_migration_version(&mut txn, config.build_info.semver_version())?;
567
568        txn.commit(config.boot_ts).await?;
569
570        // Now that the migration is durable, run any requested deferred cleanup.
571        schema_migration_result.cleanup_action.await;
572
573        Ok(InitializeStateResult {
574            state,
575            migrated_storage_collections_0dt: schema_migration_result.replaced_items,
576            new_builtin_collections: new_builtin_collections.into_iter().collect(),
577            builtin_table_updates,
578            last_seen_version,
579            expr_cache_handle,
580            cached_global_exprs,
581            uncached_local_exprs: local_expr_cache.into_uncached_exprs(),
582        })
583    }
584
585    /// Opens or creates a catalog that stores data at `path`.
586    ///
587    /// Returns the catalog, metadata about builtin objects that have changed
588    /// schemas since last restart, a list of updates to builtin tables that
589    /// describe the initial state of the catalog, and the version of the
590    /// catalog before any migrations were performed.
591    ///
592    /// BOXED FUTURE: As of Nov 2023 the returned Future from this function was 17KB. This would
593    /// get stored on the stack which is bad for runtime performance, and blow up our stack usage.
594    /// Because of that we purposefully move this Future onto the heap (i.e. Box it).
595    #[instrument(name = "catalog::open")]
596    pub fn open(config: Config<'_>) -> BoxFuture<'static, Result<OpenCatalogResult, AdapterError>> {
597        async move {
598            let mut storage = config.storage;
599
600            let InitializeStateResult {
601                state,
602                migrated_storage_collections_0dt,
603                new_builtin_collections,
604                mut builtin_table_updates,
605                last_seen_version,
606                expr_cache_handle,
607                cached_global_exprs,
608                uncached_local_exprs,
609            } =
610                // BOXED FUTURE: As of Nov 2023 the returned Future from this function was 7.5KB. This would
611                // get stored on the stack which is bad for runtime performance, and blow up our stack usage.
612                // Because of that we purposefully move this Future onto the heap (i.e. Box it).
613                Self::initialize_state(config.state, &mut storage)
614                    .instrument(tracing::info_span!("catalog::initialize_state"))
615                    .boxed()
616                    .await?;
617
618            let catalog = Catalog {
619                state,
620                expr_cache_handle,
621                transient_revision: 1,
622                shared_transient_revision: Arc::new(AtomicU64::new(1)),
623                storage: Arc::new(tokio::sync::Mutex::new(storage)),
624            };
625
626            // Operators aren't stored in the catalog, but we would like them in
627            // introspection views.
628            for (op, func) in OP_IMPLS.iter() {
629                match func {
630                    mz_sql::func::Func::Scalar(impls) => {
631                        for imp in impls {
632                            builtin_table_updates.push(catalog.state.resolve_builtin_table_update(
633                                catalog.state.pack_op_update(op, imp.details(), Diff::ONE),
634                            ));
635                        }
636                    }
637                    _ => unreachable!("all operators must be scalar functions"),
638                }
639            }
640
641            for ip in &catalog.state.egress_addresses {
642                builtin_table_updates.push(
643                    catalog
644                        .state
645                        .resolve_builtin_table_update(catalog.state.pack_egress_ip_update(ip)?),
646                );
647            }
648
649            if !catalog.state.license_key.id.is_empty() {
650                builtin_table_updates.push(
651                    catalog.state.resolve_builtin_table_update(
652                        catalog
653                            .state
654                            .pack_license_key_update(&catalog.state.license_key)?,
655                    ),
656                );
657            }
658
659            catalog.storage().await.mark_bootstrap_complete().await;
660
661            Ok(OpenCatalogResult {
662                catalog,
663                last_seen_version,
664                migrated_storage_collections_0dt,
665                new_builtin_collections,
666                builtin_table_updates,
667                cached_global_exprs,
668                uncached_local_exprs,
669            })
670        }
671        .instrument(tracing::info_span!("catalog::open"))
672        .boxed()
673    }
674
675    /// Initializes STORAGE to understand all shards that `self` expects to
676    /// exist.
677    ///
678    /// Note that this must be done before creating/rendering collections
679    /// because the storage controller might not be aware of new system
680    /// collections created between versions.
681    async fn initialize_storage_state(
682        &mut self,
683        storage_collections: &Arc<dyn StorageCollections + Send + Sync>,
684    ) -> Result<(), mz_catalog::durable::CatalogError> {
685        let collections = self
686            .entries()
687            .filter(|entry| entry.item().is_storage_collection())
688            .flat_map(|entry| entry.global_ids())
689            .collect();
690
691        // Clone the state so that any errors that occur do not leak any
692        // transformations on error.
693        let mut state = self.state.clone();
694
695        let mut storage = self.storage().await;
696        let shard_id = storage.shard_id();
697        let mut txn = storage.transaction().await?;
698
699        // Ensure the storage controller knows about the catalog shard and associates it with the
700        // `MZ_CATALOG_RAW` builtin source.
701        let item_id = self.resolve_builtin_storage_collection(&MZ_CATALOG_RAW);
702        let global_id = self.get_entry(&item_id).latest_global_id();
703        match txn.get_collection_metadata().get(&global_id) {
704            None => {
705                txn.insert_collection_metadata([(global_id, shard_id)].into())
706                    .map_err(mz_catalog::durable::DurableCatalogError::from)?;
707            }
708            Some(id) => assert_eq!(*id, shard_id),
709        }
710
711        storage_collections
712            .initialize_state(&mut txn, collections)
713            .await
714            .map_err(mz_catalog::durable::DurableCatalogError::from)?;
715
716        let updates = txn.get_and_commit_op_updates();
717        let (builtin_updates, catalog_updates) = state
718            .apply_updates(updates, &mut LocalExpressionCache::Closed)
719            .await;
720        assert!(
721            builtin_updates.is_empty(),
722            "storage is not allowed to generate catalog changes that would cause changes to builtin tables"
723        );
724        assert!(
725            catalog_updates.is_empty(),
726            "storage is not allowed to generate catalog changes that would change the catalog or controller state"
727        );
728        let commit_ts = txn.upper();
729        txn.commit(commit_ts).await?;
730        drop(storage);
731
732        // Save updated state.
733        self.state = state;
734        Ok(())
735    }
736
737    /// [`mz_controller::Controller`] depends on durable catalog state to boot,
738    /// so make it available and initialize the controller.
739    pub async fn initialize_controller(
740        &mut self,
741        config: mz_controller::ControllerConfig,
742        envd_epoch: core::num::NonZeroI64,
743        read_only: bool,
744    ) -> Result<mz_controller::Controller, mz_catalog::durable::CatalogError> {
745        let controller_start = Instant::now();
746        info!("startup: controller init: beginning");
747
748        let controller = {
749            let mut storage = self.storage().await;
750            let mut tx = storage.transaction().await?;
751            mz_controller::prepare_initialization(&mut tx)
752                .map_err(mz_catalog::durable::DurableCatalogError::from)?;
753            let updates = tx.get_and_commit_op_updates();
754            assert!(
755                updates.is_empty(),
756                "initializing controller should not produce updates: {updates:?}"
757            );
758            let commit_ts = tx.upper();
759            tx.commit(commit_ts).await?;
760
761            let read_only_tx = storage.transaction().await?;
762
763            mz_controller::Controller::new(config, envd_epoch, read_only, &read_only_tx).await
764        };
765
766        self.initialize_storage_state(&controller.storage_collections)
767            .await?;
768
769        info!(
770            "startup: controller init: complete in {:?}",
771            controller_start.elapsed()
772        );
773
774        Ok(controller)
775    }
776
777    /// Politely releases all external resources that can only be released in an async context.
778    pub async fn expire(self) {
779        // If no one else holds a reference to storage, then clean up the storage resources.
780        // Otherwise, hopefully the other reference cleans up the resources when it's dropped.
781        if let Some(storage) = Arc::into_inner(self.storage) {
782            let storage = storage.into_inner();
783            storage.expire().await;
784        }
785    }
786}
787
788impl CatalogState {
789    /// Set the default value for `name`, which is the value it will be reset to.
790    fn set_system_configuration_default(
791        &mut self,
792        name: &str,
793        value: VarInput,
794    ) -> Result<(), Error> {
795        Ok(Arc::make_mut(&mut self.system_configuration).set_default(name, value)?)
796    }
797}
798
799/// Updates the catalog with new and removed builtin items.
800///
801/// Returns the list of new builtin [`GlobalId`]s.
802fn add_new_remove_old_builtin_items_migration(
803    txn: &mut mz_catalog::durable::Transaction<'_>,
804) -> Result<Vec<GlobalId>, mz_catalog::durable::CatalogError> {
805    let mut new_builtin_mappings = Vec::new();
806    // Used to validate unique descriptions.
807    let mut builtin_descs = HashSet::new();
808
809    // We compare the builtin items that are compiled into the binary with the builtin items that
810    // are persisted in the catalog to discover new and deleted builtin items.
811    let mut builtins = Vec::new();
812    for builtin in BUILTINS::iter() {
813        let desc = SystemObjectDescription {
814            schema_name: builtin.schema().to_string(),
815            object_type: builtin.catalog_item_type(),
816            object_name: builtin.name().to_string(),
817        };
818        // Validate that the description is unique.
819        if !builtin_descs.insert(desc.clone()) {
820            panic!(
821                "duplicate builtin description: {:?}, {:?}",
822                SystemObjectDescription {
823                    schema_name: builtin.schema().to_string(),
824                    object_type: builtin.catalog_item_type(),
825                    object_name: builtin.name().to_string(),
826                },
827                builtin
828            );
829        }
830        builtins.push((desc, builtin));
831    }
832
833    let mut system_object_mappings: BTreeMap<_, _> = txn
834        .get_system_object_mappings()
835        .map(|system_object_mapping| {
836            (
837                system_object_mapping.description.clone(),
838                system_object_mapping,
839            )
840        })
841        .collect();
842
843    let (existing_builtins, new_builtins): (Vec<_>, Vec<_>) =
844        builtins.into_iter().partition_map(|(desc, builtin)| {
845            let fingerprint = match builtin.runtime_alterable() {
846                false => builtin.fingerprint(),
847                true => RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL.into(),
848            };
849            match system_object_mappings.remove(&desc) {
850                Some(system_object_mapping) => {
851                    Either::Left((builtin, system_object_mapping, fingerprint))
852                }
853                None => Either::Right((builtin, fingerprint)),
854            }
855        });
856    let new_builtin_ids = txn.allocate_system_item_ids(usize_to_u64(new_builtins.len()))?;
857    let new_builtins: Vec<_> = new_builtins
858        .into_iter()
859        .zip_eq(new_builtin_ids.clone())
860        .collect();
861
862    // Add new builtin items to catalog.
863    for ((builtin, fingerprint), (catalog_id, global_id)) in new_builtins.iter().cloned() {
864        new_builtin_mappings.push(SystemObjectMapping {
865            description: SystemObjectDescription {
866                schema_name: builtin.schema().to_string(),
867                object_type: builtin.catalog_item_type(),
868                object_name: builtin.name().to_string(),
869            },
870            unique_identifier: SystemObjectUniqueIdentifier {
871                catalog_id,
872                global_id,
873                fingerprint,
874            },
875        });
876
877        // Runtime-alterable system objects are durably recorded to the
878        // usual items collection, so that they can be later altered at
879        // runtime by their owner (i.e., outside of the usual builtin
880        // migration framework that requires changes to the binary
881        // itself).
882        let handled_runtime_alterable = match builtin {
883            Builtin::Connection(c) if c.runtime_alterable => {
884                let mut acl_items = vec![rbac::owner_privilege(
885                    mz_sql::catalog::ObjectType::Connection,
886                    c.owner_id.clone(),
887                )];
888                acl_items.extend_from_slice(c.access);
889                // Builtin Connections cannot be versioned.
890                let versions = BTreeMap::new();
891
892                txn.insert_item(
893                    catalog_id,
894                    c.oid,
895                    global_id,
896                    mz_catalog::durable::initialize::resolve_system_schema(c.schema).id,
897                    c.name,
898                    c.sql.into(),
899                    *c.owner_id,
900                    acl_items,
901                    versions,
902                    None,
903                )?;
904                true
905            }
906            _ => false,
907        };
908        assert_eq!(
909            builtin.runtime_alterable(),
910            handled_runtime_alterable,
911            "runtime alterable object was not handled by migration",
912        );
913    }
914    txn.set_system_object_mappings(new_builtin_mappings)?;
915
916    // Update comments of all builtin objects
917    let builtins_with_catalog_ids = existing_builtins
918        .iter()
919        .map(|(b, m, _)| (*b, m.unique_identifier.catalog_id))
920        .chain(
921            new_builtins
922                .into_iter()
923                .map(|((b, _), (catalog_id, _))| (b, catalog_id)),
924        );
925
926    for (builtin, id) in builtins_with_catalog_ids {
927        let (comment_id, desc, comments) = match builtin {
928            Builtin::Source(s) => (CommentObjectId::Source(id), &s.desc, &s.column_comments),
929            Builtin::View(v) => (CommentObjectId::View(id), &v.desc, &v.column_comments),
930            Builtin::Table(t) => (CommentObjectId::Table(id), &t.desc, &t.column_comments),
931            Builtin::MaterializedView(mv) => (
932                CommentObjectId::MaterializedView(id),
933                &mv.desc,
934                &mv.column_comments,
935            ),
936            Builtin::Log(_)
937            | Builtin::Type(_)
938            | Builtin::Func(_)
939            | Builtin::Index(_)
940            | Builtin::Connection(_) => continue,
941        };
942        // Drop comments under every relation-style `CommentObjectId` variant
943        // for this id, not just the current one. When a builtin's type changes
944        // (e.g. Table -> MaterializedView) but its catalog id is preserved, the
945        // prior type's comment rows would otherwise linger forever.
946        txn.drop_comments(&BTreeSet::from_iter([
947            CommentObjectId::Table(id),
948            CommentObjectId::View(id),
949            CommentObjectId::MaterializedView(id),
950            CommentObjectId::Source(id),
951        ]))?;
952
953        let mut comments = comments.clone();
954        for (col_idx, name) in desc.iter_names().enumerate() {
955            if let Some(comment) = comments.remove(name.as_str()) {
956                // Comment column indices are 1 based
957                txn.update_comment(comment_id, Some(col_idx + 1), Some(comment.to_owned()))?;
958            }
959        }
960        assert!(
961            comments.is_empty(),
962            "builtin object contains dangling comments that don't correspond to columns {comments:?}"
963        );
964    }
965
966    // Anything left in `system_object_mappings` must have been deleted and should be removed from
967    // the catalog.
968    let mut deleted_system_objects = BTreeSet::new();
969    let mut deleted_runtime_alterable_system_ids = BTreeSet::new();
970    let mut deleted_comments = BTreeSet::new();
971    for (desc, mapping) in system_object_mappings {
972        deleted_system_objects.insert(mapping.description);
973        if mapping.unique_identifier.fingerprint == RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL {
974            deleted_runtime_alterable_system_ids.insert(mapping.unique_identifier.catalog_id);
975        }
976
977        let id = mapping.unique_identifier.catalog_id;
978        let comment_id = match desc.object_type {
979            CatalogItemType::Table => CommentObjectId::Table(id),
980            CatalogItemType::Source => CommentObjectId::Source(id),
981            CatalogItemType::View => CommentObjectId::View(id),
982            CatalogItemType::MaterializedView => CommentObjectId::MaterializedView(id),
983            CatalogItemType::Sink
984            | CatalogItemType::MetricSink
985            | CatalogItemType::Index
986            | CatalogItemType::Type
987            | CatalogItemType::Func
988            | CatalogItemType::Secret
989            | CatalogItemType::Connection => continue,
990        };
991        deleted_comments.insert(comment_id);
992    }
993    // If you are 100% positive that it is safe to delete a system object outside any of the
994    // unstable schemas, then add it to this set. Make sure that no prod environments are
995    // using this object and that the upgrade checker does not show any issues.
996    //
997    // Objects can be removed from this set after one release.
998    let delete_exceptions: HashSet<SystemObjectDescription> = [].into();
999    // TODO(jkosh44) Technically we could support changing the type of a builtin object outside
1000    // of unstable schemas (i.e. from a table to a view). However, builtin migrations don't currently
1001    // handle that scenario correctly.
1002    assert!(
1003        deleted_system_objects
1004            .iter()
1005            // It's okay if Indexes change because they're inherently ephemeral.
1006            .filter(|object| object.object_type != CatalogItemType::Index)
1007            .all(
1008                |deleted_object| is_unstable_schema(&deleted_object.schema_name)
1009                    || delete_exceptions.contains(deleted_object)
1010            ),
1011        "only objects in unstable schemas can be deleted, deleted objects: {:?}",
1012        deleted_system_objects
1013    );
1014    txn.drop_comments(&deleted_comments)?;
1015    txn.remove_items(&deleted_runtime_alterable_system_ids)?;
1016    txn.remove_system_object_mappings(deleted_system_objects)?;
1017
1018    // Filter down to just the GlobalIds which are used to track the underlying collections.
1019    let new_builtin_collections = new_builtin_ids
1020        .into_iter()
1021        .map(|(_catalog_id, global_id)| global_id)
1022        .collect();
1023
1024    Ok(new_builtin_collections)
1025}
1026
1027fn add_new_remove_old_builtin_clusters_migration(
1028    txn: &mut mz_catalog::durable::Transaction<'_>,
1029    builtin_cluster_config_map: &BuiltinBootstrapClusterConfigMap,
1030    boot_ts: Timestamp,
1031) -> Result<(), mz_catalog::durable::CatalogError> {
1032    let mut durable_clusters: BTreeMap<_, _> = txn
1033        .get_clusters()
1034        .filter(|cluster| cluster.id.is_system())
1035        .map(|cluster| (cluster.name.to_string(), cluster))
1036        .collect();
1037
1038    // Add new clusters.
1039    for builtin_cluster in BUILTIN_CLUSTERS {
1040        if durable_clusters.remove(builtin_cluster.name).is_none() {
1041            let cluster_config = builtin_cluster_config_map.get_config(builtin_cluster.name)?;
1042
1043            let cluster_id = txn.insert_system_cluster(
1044                builtin_cluster.name,
1045                vec![],
1046                builtin_cluster.privileges.to_vec(),
1047                builtin_cluster.owner_id.to_owned(),
1048                mz_catalog::durable::ClusterConfig {
1049                    variant: mz_catalog::durable::ClusterVariant::Managed(ClusterVariantManaged {
1050                        size: cluster_config.size,
1051                        availability_zones: vec![],
1052                        replication_factor: cluster_config.replication_factor,
1053                        logging: default_logging_config(),
1054                        arrangement_compression: false,
1055                        optimizer_feature_overrides: Default::default(),
1056                        schedule: Default::default(),
1057                        auto_scaling_strategy: None,
1058                        reconfiguration: None,
1059                        burst: None,
1060                    }),
1061                    workload_class: None,
1062                    query_policy: None,
1063                },
1064                &HashSet::new(),
1065            )?;
1066
1067            let audit_id = txn.allocate_audit_log_id()?;
1068            txn.insert_audit_log_event(VersionedEvent::new(
1069                audit_id,
1070                EventType::Create,
1071                ObjectType::Cluster,
1072                EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
1073                    id: cluster_id.to_string(),
1074                    name: builtin_cluster.name.to_string(),
1075                }),
1076                None,
1077                boot_ts.into(),
1078            ));
1079        }
1080    }
1081
1082    // Remove old clusters.
1083    let old_clusters = durable_clusters
1084        .values()
1085        .map(|cluster| cluster.id)
1086        .collect();
1087    txn.remove_clusters(&old_clusters)?;
1088
1089    for (_name, cluster) in &durable_clusters {
1090        let audit_id = txn.allocate_audit_log_id()?;
1091        txn.insert_audit_log_event(VersionedEvent::new(
1092            audit_id,
1093            EventType::Drop,
1094            ObjectType::Cluster,
1095            EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
1096                id: cluster.id.to_string(),
1097                name: cluster.name.clone(),
1098            }),
1099            None,
1100            boot_ts.into(),
1101        ));
1102    }
1103
1104    Ok(())
1105}
1106
1107fn add_new_remove_old_builtin_introspection_source_migration(
1108    txn: &mut mz_catalog::durable::Transaction<'_>,
1109) -> Result<(), AdapterError> {
1110    let mut new_indexes = Vec::new();
1111    let mut removed_indexes = BTreeSet::new();
1112    for cluster in txn.get_clusters() {
1113        let mut introspection_source_index_ids = txn.get_introspection_source_indexes(cluster.id);
1114
1115        let mut new_logs = Vec::new();
1116
1117        for log in BUILTINS::logs() {
1118            if introspection_source_index_ids.remove(log.name).is_none() {
1119                new_logs.push(log);
1120            }
1121        }
1122
1123        for log in new_logs {
1124            let (item_id, gid) =
1125                Transaction::allocate_introspection_source_index_id(&cluster.id, log.variant);
1126            new_indexes.push((cluster.id, log.name.to_string(), item_id, gid));
1127        }
1128
1129        // Anything left in `introspection_source_index_ids` must have been deleted and should be
1130        // removed from the catalog.
1131        removed_indexes.extend(
1132            introspection_source_index_ids
1133                .into_keys()
1134                .map(|name| (cluster.id, name.to_string())),
1135        );
1136    }
1137    txn.insert_introspection_source_indexes(new_indexes, &HashSet::new())?;
1138    txn.remove_introspection_source_indexes(removed_indexes)?;
1139    Ok(())
1140}
1141
1142fn add_new_remove_old_builtin_roles_migration(
1143    txn: &mut mz_catalog::durable::Transaction<'_>,
1144) -> Result<(), mz_catalog::durable::CatalogError> {
1145    let mut durable_roles: BTreeMap<_, _> = txn
1146        .get_roles()
1147        .filter(|role| role.id.is_system() || role.id.is_predefined())
1148        .map(|role| (role.name.to_string(), role))
1149        .collect();
1150
1151    // Add new roles.
1152    for builtin_role in BUILTIN_ROLES {
1153        if durable_roles.remove(builtin_role.name).is_none() {
1154            txn.insert_builtin_role(
1155                builtin_role.id,
1156                builtin_role.name.to_string(),
1157                builtin_role.attributes.clone(),
1158                RoleMembership::new(),
1159                RoleVars::default(),
1160                builtin_role.oid,
1161            )?;
1162        }
1163    }
1164
1165    // Remove old roles.
1166    let old_roles = durable_roles.values().map(|role| role.id).collect();
1167    txn.remove_roles(&old_roles)?;
1168
1169    Ok(())
1170}
1171
1172/// Reconciles the system cluster replica sizes in the durable catalog with the
1173/// sizes from `--cluster-replica-sizes`.
1174///
1175/// A size removed from the flag is deleted, unless a replica still uses it. Then
1176/// it is kept but disabled, so the replica can still be scheduled while no new
1177/// replica can pick the size.
1178fn sync_builtin_cluster_replica_sizes(
1179    txn: &mut Transaction<'_>,
1180    config_sizes: &ClusterReplicaSizeMap,
1181) -> Result<(), AdapterError> {
1182    let mut durable_sizes: BTreeMap<_, _> = txn
1183        .get_cluster_replica_sizes()
1184        .filter(|size| size.id.is_system())
1185        .map(|size| (size.name.clone(), size))
1186        .collect();
1187
1188    for (name, allocation) in &config_sizes.0 {
1189        match durable_sizes.remove(name) {
1190            None => {
1191                txn.insert_system_cluster_replica_size(name.clone(), allocation.clone())?;
1192            }
1193            Some(size) if size.allocation != *allocation => {
1194                txn.update_cluster_replica_size(ClusterReplicaSize {
1195                    allocation: allocation.clone(),
1196                    ..size
1197                })?;
1198            }
1199            Some(_) => {}
1200        }
1201    }
1202
1203    // Managed clusters can reference a size without having a replica on it, e.g.
1204    // between refreshes of a scheduled cluster or at replication factor 0.
1205    let clusters: Vec<_> = txn.get_clusters().collect();
1206    let replicas: Vec<_> = txn.get_cluster_replicas().collect();
1207    let in_use: BTreeSet<&str> = clusters
1208        .iter()
1209        .flat_map(|cluster| cluster.config.variant.sizes())
1210        .chain(replicas.iter().filter_map(|r| r.config.location.size()))
1211        .collect();
1212    for (name, mut size) in durable_sizes {
1213        if !in_use.contains(name.as_str()) {
1214            txn.remove_cluster_replica_size(size.id)?;
1215        } else if !size.allocation.disabled {
1216            warn!(%name, "cluster replica size removed from config but still in use, disabling it");
1217            size.allocation.disabled = true;
1218            txn.update_cluster_replica_size(size)?;
1219        }
1220    }
1221
1222    Ok(())
1223}
1224
1225/// Converges each builtin cluster's replica set on the cluster's own managed
1226/// config.
1227///
1228/// A builtin cluster is normally managed, and a managed cluster's replicas are
1229/// derived state: exactly `replication_factor` replicas, named by
1230/// [`managed_cluster_replica_name`]. One can be altered to unmanaged, which leaves
1231/// no factor to derive from, and then its replica set is the operator's.
1232///
1233/// Replicas this creates are shaped from the cluster's config. An existing replica
1234/// is matched by name alone and left untouched, so this converges cardinality and
1235/// names rather than shape. An internal replica is never derived state and is left
1236/// alone entirely.
1237///
1238/// The bootstrap flags seed `replication_factor` and `size` when a cluster is
1239/// first created (see [`add_new_remove_old_builtin_clusters_migration`]) and are
1240/// deliberately not consulted here, so an `ALTER CLUSTER` against a builtin
1241/// cluster survives a restart.
1242///
1243/// This runs at catalog open so the replicas a cluster's config calls for exist as
1244/// early as possible. The coordinator's bootstrap brings up only replicas already
1245/// recorded durably and runs before the cluster controller is spawned, and the
1246/// controller does not run at all while a deployment is read-only.
1247///
1248/// The cluster controller owns these replica sets at runtime and derives its
1249/// target from the same cluster config, so the two converge on the same set
1250/// rather than competing for it. The controller matches replicas by shape and
1251/// count, never by name, so the `r1..rN` this creates satisfy it. This converges
1252/// by name, so a boot after the controller reshaped a cluster renames or
1253/// re-creates replicas it had materialized under generator names. That is
1254/// harmless: every replica is a cold process at boot anyway, so the cost is
1255/// replica-id and audit-log noise.
1256fn reconcile_builtin_cluster_replicas(
1257    txn: &mut Transaction<'_>,
1258    builtin_cluster_config_map: &BuiltinBootstrapClusterConfigMap,
1259    boot_ts: Timestamp,
1260) -> Result<(), AdapterError> {
1261    let builtin_cluster_names: BTreeSet<&str> = BUILTIN_CLUSTERS
1262        .iter()
1263        .map(|cluster| cluster.name)
1264        .collect();
1265
1266    // Replicas of a cluster that is no longer a builtin need no handling here:
1267    // `Transaction::remove_clusters` cascades to a cluster's replicas, and the
1268    // clusters migration has already run against this transaction.
1269    let clusters: Vec<_> = txn
1270        .get_clusters()
1271        .filter(|cluster| {
1272            cluster.id.is_system() && builtin_cluster_names.contains(cluster.name.as_str())
1273        })
1274        .collect();
1275
1276    let builtin_cluster_ids: BTreeSet<ClusterId> =
1277        clusters.iter().map(|cluster| cluster.id).collect();
1278
1279    // Only the builtin clusters' replicas. An environment can have thousands of
1280    // user replicas and none of them are in scope here.
1281    //
1282    // An internal replica is deliberately out of scope. `CREATE CLUSTER REPLICA ...
1283    // INTERNAL` is allowed on a managed cluster, and its name is barred from
1284    // matching the derived `r1..rN` pattern so it cannot collide with one. It is a
1285    // break-glass replica an operator added rather than derived state, so reaping it
1286    // would undo that. The `ALTER CLUSTER` path skips it for the same reason.
1287    let mut replicas_by_cluster: BTreeMap<ClusterId, BTreeMap<String, ClusterReplica>> =
1288        BTreeMap::new();
1289    for replica in txn.get_cluster_replicas().filter(|replica| {
1290        builtin_cluster_ids.contains(&replica.cluster_id)
1291            && !matches!(
1292                replica.config.location,
1293                ReplicaLocation::Managed { internal: true, .. }
1294            )
1295    }) {
1296        replicas_by_cluster
1297            .entry(replica.cluster_id)
1298            .or_default()
1299            .insert(replica.name.clone(), replica);
1300    }
1301
1302    let mut to_drop: Vec<(String, ClusterReplica)> = Vec::new();
1303
1304    for cluster in clusters {
1305        // An unmanaged cluster has no replication factor, so there is no target to
1306        // converge on. Its replica set is whatever an operator made it, and it is
1307        // not ours to reshape.
1308        let ClusterVariant::Managed(managed) = &cluster.config.variant else {
1309            continue;
1310        };
1311
1312        // The bootstrap flags seed a cluster at creation and are never re-applied,
1313        // which is what keeps an `ALTER CLUSTER` from being reverted on every
1314        // restart. That leaves an operator who changed a flag on an existing
1315        // deployment with no feedback, so say so.
1316        let bootstrap_config = builtin_cluster_config_map.get_config(&cluster.name)?;
1317        if bootstrap_config.replication_factor != managed.replication_factor {
1318            warn!(
1319                cluster = %cluster.name,
1320                configured_replication_factor = managed.replication_factor,
1321                bootstrap_replication_factor = bootstrap_config.replication_factor,
1322                "bootstrap replication factor is not applied to an already-existing \
1323                 builtin cluster. Use ALTER CLUSTER ... SET (REPLICATION FACTOR ...) \
1324                 to change it",
1325            );
1326        }
1327
1328        // Reading the cluster's factor is what makes this compose with the other
1329        // writers of a replica set. The controller's on-refresh strategy parks a
1330        // scheduled cluster by writing its factor to 0, so converging on the
1331        // factor honors that instead of resurrecting a replica it just dropped.
1332        let mut surplus = replicas_by_cluster.remove(&cluster.id).unwrap_or_default();
1333        for index in 0..managed.replication_factor {
1334            let replica_name = managed_cluster_replica_name(index);
1335            if surplus.remove(&replica_name).is_some() {
1336                continue;
1337            }
1338
1339            // Builtin replicas live on system clusters. This runs inside the
1340            // catalog-open transaction with no coordinator, so allocating from the
1341            // same transaction is single-source and safe.
1342            let replica_id = txn.allocate_system_replica_id()?;
1343            txn.insert_cluster_replica_with_id(
1344                cluster.id,
1345                replica_id,
1346                &replica_name,
1347                managed_replica_config(managed),
1348                // The cluster's owner, not `mz_system`. `mz_support` and
1349                // `mz_analytics` are owned by their own roles, and replica
1350                // ownership is checked against the replica's own `owner_id`, so
1351                // stamping `mz_system` here would stop those roles from altering
1352                // a replica of a cluster they own.
1353                cluster.owner_id,
1354            )?;
1355            info!(
1356                cluster = %cluster.name, replica = %replica_name, %replica_id,
1357                "creating builtin cluster replica to match the cluster's replication factor"
1358            );
1359
1360            let audit_id = txn.allocate_audit_log_id()?;
1361            txn.insert_audit_log_event(VersionedEvent::new(
1362                audit_id,
1363                EventType::Create,
1364                ObjectType::ClusterReplica,
1365                EventDetails::CreateClusterReplicaV4(mz_audit_log::CreateClusterReplicaV4 {
1366                    cluster_id: cluster.id.to_string(),
1367                    cluster_name: cluster.name.clone(),
1368                    replica_id: Some(replica_id.to_string()),
1369                    replica_name,
1370                    logical_size: managed.size.clone(),
1371                    billed_as: None,
1372                    internal: false,
1373                    reason: CreateOrDropClusterReplicaReasonV1::System,
1374                    scheduling_policies: None,
1375                }),
1376                None,
1377                boot_ts.into(),
1378            ));
1379        }
1380
1381        // Whatever the config does not call for is surplus: a replica left over from
1382        // a higher replication factor, or a `-pending` replica belonging to a
1383        // graceful reconfiguration that a restart interrupted. Dropping the latter
1384        // here means `remove_pending_cluster_replicas_migration` never sees it,
1385        // which matches the abort semantics it would have applied anyway.
1386        to_drop.extend(
1387            surplus
1388                .into_values()
1389                .map(|replica| (cluster.name.clone(), replica)),
1390        );
1391    }
1392
1393    // Batched: `Transaction::remove_cluster_replica` is linear in the total replica
1394    // count, so it must not be called in a loop.
1395    let drop_ids = to_drop
1396        .iter()
1397        .map(|(_cluster_name, replica)| replica.replica_id)
1398        .collect();
1399    txn.remove_cluster_replicas(&drop_ids)?;
1400
1401    for (cluster_name, replica) in to_drop {
1402        info!(
1403            cluster = %cluster_name, replica = %replica.name, replica_id = %replica.replica_id,
1404            "dropping builtin cluster replica not called for by the cluster's replication factor"
1405        );
1406
1407        let audit_id = txn.allocate_audit_log_id()?;
1408        txn.insert_audit_log_event(VersionedEvent::new(
1409            audit_id,
1410            EventType::Drop,
1411            ObjectType::ClusterReplica,
1412            EventDetails::DropClusterReplicaV3(mz_audit_log::DropClusterReplicaV3 {
1413                cluster_id: replica.cluster_id.to_string(),
1414                cluster_name,
1415                replica_id: Some(replica.replica_id.to_string()),
1416                replica_name: replica.name,
1417                reason: CreateOrDropClusterReplicaReasonV1::System,
1418                scheduling_policies: None,
1419            }),
1420            None,
1421            boot_ts.into(),
1422        ));
1423    }
1424
1425    Ok(())
1426}
1427
1428/// The replica config implied by a managed cluster's config.
1429///
1430/// Every field a replica shares with its cluster is taken from the cluster.
1431/// `availability_zones` is the cluster's pool, which is what the provisioning
1432/// paths stamp onto a managed replica.
1433///
1434/// Two things the `ALTER CLUSTER` path does that this does not. It normalizes
1435/// logging through the plan, which discards `log_logging` when no interval is
1436/// set, so for the odd cluster config that has debugging on and logging off the
1437/// two produce different records. And it validates the size against the replica
1438/// size map and the role's allowed sizes, which cannot be done from here because
1439/// the size map is not part of the durable catalog. A builtin cluster's size only
1440/// ever comes from a bootstrap flag or an `ALTER` that already validated it.
1441fn managed_replica_config(managed: &ClusterVariantManaged) -> ReplicaConfig {
1442    // Exhaustive destructure (no `..`): a field added to the managed config is a
1443    // compile error here until we decide whether a replica has to carry it.
1444    let ClusterVariantManaged {
1445        size,
1446        availability_zones,
1447        logging,
1448        arrangement_compression,
1449        replication_factor: _,
1450        optimizer_feature_overrides: _,
1451        schedule: _,
1452        auto_scaling_strategy: _,
1453        reconfiguration: _,
1454        burst: _,
1455    } = managed;
1456    ReplicaConfig {
1457        location: ReplicaLocation::Managed {
1458            size: size.clone(),
1459            availability_zones: availability_zones.clone(),
1460            billed_as: None,
1461            internal: false,
1462            pending: false,
1463        },
1464        logging: logging.clone(),
1465        arrangement_compression: *arrangement_compression,
1466    }
1467}
1468
1469/// Roles can have default values for configuration parameters, e.g. you can set a Role default for
1470/// the 'cluster' parameter.
1471///
1472/// This migration exists to remove the Role default for a configuration parameter, if the persisted
1473/// input is no longer valid. For example if we remove a configuration parameter or change the
1474/// accepted set of values.
1475fn remove_invalid_config_param_role_defaults_migration(
1476    txn: &mut Transaction<'_>,
1477) -> Result<(), AdapterError> {
1478    static BUILD_INFO: mz_build_info::BuildInfo = mz_build_info::build_info!();
1479
1480    let roles_to_migrate: BTreeMap<_, _> = txn
1481        .get_roles()
1482        .filter_map(|mut role| {
1483            // Create an empty SessionVars just so we can check if a var is valid.
1484            //
1485            // TODO(parkmycar): This is a bit hacky, instead we should have a static list of all
1486            // session variables.
1487            let session_vars = SessionVars::new_unchecked(&BUILD_INFO, SYSTEM_USER.clone(), None);
1488
1489            // Iterate over all of the variable defaults for this role.
1490            let mut invalid_roles_vars = BTreeMap::new();
1491            for (name, value) in &role.vars.map {
1492                // If one does not exist or its value is invalid, then mark it for removal.
1493                let Ok(session_var) = session_vars.inspect(name) else {
1494                    invalid_roles_vars.insert(name.clone(), value.clone());
1495                    continue;
1496                };
1497                if session_var.check(value.borrow()).is_err() {
1498                    invalid_roles_vars.insert(name.clone(), value.clone());
1499                }
1500            }
1501
1502            // If the role has no invalid values, nothing to do!
1503            if invalid_roles_vars.is_empty() {
1504                return None;
1505            }
1506
1507            tracing::warn!(?role, ?invalid_roles_vars, "removing invalid role vars");
1508
1509            // Otherwise, remove the variables from the role and return it to be updated.
1510            for (name, _value) in invalid_roles_vars {
1511                role.vars.map.remove(&name);
1512            }
1513            Some(role)
1514        })
1515        .map(|role| (role.id, role))
1516        .collect();
1517
1518    txn.update_roles_without_auth(roles_to_migrate)?;
1519
1520    Ok(())
1521}
1522
1523/// Drops replicas left durably marked `pending`.
1524///
1525/// No runtime path creates one anymore. An upgrade can still come from a version
1526/// whose staged reconfiguration machine crashed between the pending-create commit
1527/// and the finalize, and those replicas are excluded from the cluster
1528/// controller's ownership test, so this catalog-open sweep is their only
1529/// remaining cleaner. It goes away together with the durable `pending` field,
1530/// once no supported upgrade source can still write one.
1531fn remove_pending_cluster_replicas_migration(
1532    tx: &mut Transaction,
1533    boot_ts: mz_repr::Timestamp,
1534) -> Result<(), anyhow::Error> {
1535    // Build a map of cluster_id -> cluster_name for audit events.
1536    let cluster_names: BTreeMap<_, _> = tx.get_clusters().map(|c| (c.id, c.name)).collect();
1537
1538    let occurred_at = boot_ts.into();
1539
1540    for replica in tx.get_cluster_replicas().collect::<Vec<_>>() {
1541        if let mz_catalog::durable::ReplicaLocation::Managed { pending: true, .. } =
1542            replica.config.location
1543        {
1544            let cluster_name = cluster_names
1545                .get(&replica.cluster_id)
1546                .cloned()
1547                .unwrap_or_else(|| "<unknown>".to_string());
1548
1549            info!(
1550                "removing pending cluster replica '{}' from cluster '{}'",
1551                replica.name, cluster_name,
1552            );
1553
1554            tx.remove_cluster_replica(replica.replica_id)?;
1555
1556            // Emit an audit log event so that the drop is visible in
1557            // mz_audit_events, matching the create event that was
1558            // recorded when the pending replica was first created.
1559            let audit_id = tx.allocate_audit_log_id()?;
1560            tx.insert_audit_log_event(VersionedEvent::new(
1561                audit_id,
1562                EventType::Drop,
1563                ObjectType::ClusterReplica,
1564                EventDetails::DropClusterReplicaV3(mz_audit_log::DropClusterReplicaV3 {
1565                    cluster_id: replica.cluster_id.to_string(),
1566                    cluster_name,
1567                    replica_id: Some(replica.replica_id.to_string()),
1568                    replica_name: replica.name,
1569                    reason: CreateOrDropClusterReplicaReasonV1::System,
1570                    scheduling_policies: None,
1571                }),
1572                None,
1573                occurred_at,
1574            ));
1575        }
1576    }
1577    Ok(())
1578}
1579
1580fn default_logging_config() -> ReplicaLogging {
1581    ReplicaLogging {
1582        log_logging: false,
1583        interval: Some(Duration::from_secs(1)),
1584    }
1585}
1586
1587#[derive(Debug)]
1588pub struct BuiltinBootstrapClusterConfigMap {
1589    /// Size and replication factor to default system_cluster on bootstrap
1590    pub system_cluster: BootstrapBuiltinClusterConfig,
1591    /// Size and replication factor to default catalog_server_cluster on bootstrap
1592    pub catalog_server_cluster: BootstrapBuiltinClusterConfig,
1593    /// Size and replication factor to default probe_cluster on bootstrap
1594    pub probe_cluster: BootstrapBuiltinClusterConfig,
1595    /// Size and replication factor to default support_cluster on bootstrap
1596    pub support_cluster: BootstrapBuiltinClusterConfig,
1597    /// Size to default analytics_cluster on bootstrap
1598    pub analytics_cluster: BootstrapBuiltinClusterConfig,
1599}
1600
1601impl BuiltinBootstrapClusterConfigMap {
1602    /// Gets the size of the builtin cluster based on the provided name
1603    fn get_config(
1604        &self,
1605        cluster_name: &str,
1606    ) -> Result<BootstrapBuiltinClusterConfig, mz_catalog::durable::CatalogError> {
1607        let cluster_config = if cluster_name == mz_catalog::builtin::MZ_SYSTEM_CLUSTER.name {
1608            &self.system_cluster
1609        } else if cluster_name == mz_catalog::builtin::MZ_CATALOG_SERVER_CLUSTER.name {
1610            &self.catalog_server_cluster
1611        } else if cluster_name == mz_catalog::builtin::MZ_PROBE_CLUSTER.name {
1612            &self.probe_cluster
1613        } else if cluster_name == mz_catalog::builtin::MZ_SUPPORT_CLUSTER.name {
1614            &self.support_cluster
1615        } else if cluster_name == mz_catalog::builtin::MZ_ANALYTICS_CLUSTER.name {
1616            &self.analytics_cluster
1617        } else {
1618            return Err(mz_catalog::durable::CatalogError::Catalog(
1619                SqlCatalogError::UnexpectedBuiltinCluster(cluster_name.to_owned()),
1620            ));
1621        };
1622        Ok(cluster_config.clone())
1623    }
1624}
1625
1626/// Convert `updates` into a `Vec` that can be consolidated by doing the following:
1627///
1628///   - Update the timestamp of each update to the same value.
1629///   - Convert the diff of each update to a type that implements
1630///     [`differential_dataflow::difference::Semigroup`].
1631///
1632/// WARNING: Do not call outside of startup.
1633pub(crate) fn into_consolidatable_updates_startup(
1634    updates: Vec<StateUpdate>,
1635    ts: Timestamp,
1636) -> Vec<(StateUpdateKind, Timestamp, Diff)> {
1637    updates
1638        .into_iter()
1639        .map(|StateUpdate { kind, ts: _, diff }| (kind, ts, Diff::from(diff)))
1640        .collect()
1641}
1642
1643#[cfg(test)]
1644mod tests {
1645    use mz_catalog::durable::debug::{IndexColumnsCollection, ItemColumnsCollection};
1646    use mz_catalog::durable::{
1647        CatalogError, ClusterVariantManaged, DurableCatalogError, Snapshot,
1648        TestCatalogStateBuilder, test_bootstrap_args,
1649    };
1650    use mz_persist_client::PersistClient;
1651    use mz_repr::GlobalId;
1652    use mz_sql::names::{
1653        DatabaseId, ItemQualifiers, QualifiedItemName, ResolvedDatabaseSpecifier, SchemaId,
1654        SchemaSpecifier,
1655    };
1656    use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
1657
1658    use super::*;
1659    use crate::catalog::{Catalog, Op};
1660
1661    /// A replica the reconciler creates takes every shared field from its
1662    /// cluster. Nothing here may fall back to a default, or a builtin cluster
1663    /// ends up running a replica that disagrees with its own config.
1664    #[mz_ore::test]
1665    fn test_managed_replica_config_derives_every_shared_field() {
1666        let managed = ClusterVariantManaged {
1667            size: "somesize".into(),
1668            availability_zones: vec!["az1".into(), "az2".into()],
1669            logging: ReplicaLogging {
1670                log_logging: true,
1671                interval: Some(Duration::from_millis(10)),
1672            },
1673            arrangement_compression: true,
1674            replication_factor: 3,
1675            optimizer_feature_overrides: Default::default(),
1676            schedule: Default::default(),
1677            auto_scaling_strategy: None,
1678            reconfiguration: None,
1679            burst: None,
1680        };
1681
1682        let config = managed_replica_config(&managed);
1683
1684        // Exhaustive destructures throughout, so a field added to either type is a
1685        // compile error here rather than a silently unasserted one.
1686        let ReplicaConfig {
1687            location,
1688            logging,
1689            arrangement_compression,
1690        } = config;
1691
1692        assert_eq!(logging, managed.logging);
1693        assert_eq!(arrangement_compression, managed.arrangement_compression);
1694        match location {
1695            ReplicaLocation::Managed {
1696                size,
1697                availability_zones,
1698                billed_as,
1699                internal,
1700                pending,
1701            } => {
1702                assert_eq!(size, managed.size);
1703                assert_eq!(availability_zones, managed.availability_zones);
1704                // A builtin replica is neither manually managed nor part of an
1705                // in-flight reconfiguration, and those three traits are what
1706                // exclude a replica from controller ownership.
1707                assert_eq!(billed_as, None);
1708                assert!(!internal);
1709                assert!(!pending);
1710            }
1711            ReplicaLocation::Unmanaged { .. } => panic!("expected a managed location"),
1712        }
1713    }
1714
1715    /// Writes `create_sql` into `catalog` as item `id`, as a transaction would.
1716    async fn create_item(
1717        catalog: &mut Catalog,
1718        id: CatalogItemId,
1719        gid: GlobalId,
1720        name: &str,
1721        create_sql: &str,
1722    ) {
1723        let item = catalog
1724            .state()
1725            .deserialize_item(
1726                gid,
1727                create_sql,
1728                &BTreeMap::new(),
1729                &mut LocalExpressionCache::Closed,
1730                None,
1731            )
1732            .expect("valid create_sql");
1733        let commit_ts = catalog.current_upper().await;
1734        catalog
1735            .transact(
1736                None,
1737                commit_ts,
1738                None,
1739                vec![Op::CreateItem {
1740                    item,
1741                    name: QualifiedItemName {
1742                        qualifiers: ItemQualifiers {
1743                            database_spec: ResolvedDatabaseSpecifier::Id(DatabaseId::User(1)),
1744                            schema_spec: SchemaSpecifier::Id(SchemaId::User(3)),
1745                        },
1746                        item: name.to_string(),
1747                    },
1748                    id,
1749                    owner_id: MZ_SYSTEM_ROLE_ID,
1750                }],
1751            )
1752            .await
1753            .expect("failed to transact");
1754    }
1755
1756    /// Stages a refresh of `catalog` and commits it.
1757    async fn refresh(catalog: &Catalog) -> Result<(), CatalogError> {
1758        let mut storage = catalog.storage().await;
1759        let mut tx = storage.transaction().await.expect("transaction");
1760        catalog
1761            .state()
1762            .refresh_item_metadata(&mut tx)
1763            .expect("refresh");
1764        let commit_ts = tx.upper();
1765        tx.commit(commit_ts).await
1766    }
1767
1768    /// The durable snapshot of `catalog`.
1769    async fn recorded(catalog: &Catalog) -> Snapshot {
1770        catalog.storage().await.snapshot().await.expect("snapshot")
1771    }
1772
1773    /// The bootstrap refresh writes back rows that are missing, which is how
1774    /// items that predate the collections get theirs, and nothing else: a
1775    /// steady-state boot stages no writes. A read-only catalog commits a
1776    /// transaction only when nothing was staged, which tells the two apart,
1777    /// and its open skips the refresh for the same reason, so the refresh is
1778    /// invoked by hand on it. A writable open runs it itself.
1779    #[mz_ore::test(tokio::test)]
1780    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
1781    async fn refresh_writes_only_missing_item_metadata() {
1782        let persist_client = PersistClient::new_for_tests().await;
1783        let organization_id = Uuid::new_v4();
1784        let bootstrap_args = test_bootstrap_args();
1785
1786        let view_id = CatalogItemId::User(1);
1787        let index_id = CatalogItemId::User(2);
1788        let written = {
1789            let mut catalog = Catalog::open_debug_catalog(
1790                persist_client.clone(),
1791                organization_id,
1792                &bootstrap_args,
1793            )
1794            .await
1795            .expect("unable to open debug catalog");
1796            create_item(
1797                &mut catalog,
1798                view_id,
1799                GlobalId::User(1),
1800                "v",
1801                r#"CREATE VIEW "materialize"."public"."v" AS SELECT 1 AS a, NULL::text AS b"#,
1802            )
1803            .await;
1804            create_item(
1805                &mut catalog,
1806                index_id,
1807                GlobalId::User(2),
1808                "v_idx",
1809                r#"CREATE INDEX "v_idx" IN CLUSTER [u1] ON [u1 AS "materialize"."public"."v"] ("a")"#,
1810            )
1811            .await;
1812            let written = recorded(&catalog).await;
1813            catalog.expire().await;
1814            written
1815        };
1816        // Each item recorded its row when it was written.
1817        assert_eq!(written.item_columns.len(), 1, "{:?}", written.item_columns);
1818        assert_eq!(
1819            written.index_columns.len(),
1820            1,
1821            "{:?}",
1822            written.index_columns
1823        );
1824
1825        // We record two columns for the view and one column for the index.
1826        let item_columns = written.item_columns.iter().next();
1827        assert_eq!(
1828            item_columns
1829                .expect("item columns should exist")
1830                .1
1831                .columns
1832                .len(),
1833            2
1834        );
1835
1836        let index_columns = written.index_columns.iter().next();
1837        assert_eq!(
1838            index_columns
1839                .expect("index columns should exist")
1840                .1
1841                .columns
1842                .len(),
1843            1
1844        );
1845
1846        // A fresh boot plans the items again and finds its output recorded.
1847        {
1848            let catalog = Catalog::open_debug_read_only_catalog(
1849                persist_client.clone(),
1850                organization_id,
1851                &bootstrap_args,
1852            )
1853            .await
1854            .expect("unable to open read-only debug catalog");
1855            refresh(&catalog)
1856                .await
1857                .expect("a steady-state refresh stages nothing");
1858            catalog.expire().await;
1859        }
1860
1861        // Drop the view's columns and the index's keys behind the catalog's
1862        // back.
1863        {
1864            let column_key = written.item_columns.keys().next().expect("one row");
1865            let index_key = written.index_columns.keys().next().expect("one row");
1866            let mut debug_state = TestCatalogStateBuilder::new(persist_client.clone())
1867                .with_organization_id(organization_id)
1868                .with_default_deploy_generation()
1869                .unwrap_build()
1870                .await
1871                .open_debug()
1872                .await
1873                .expect("unable to open debug state");
1874            debug_state
1875                .delete::<ItemColumnsCollection>(column_key.clone())
1876                .await
1877                .expect("delete columns");
1878            debug_state
1879                .delete::<IndexColumnsCollection>(index_key.clone())
1880                .await
1881                .expect("delete index keys");
1882        }
1883
1884        // The next refresh stages exactly the two missing rows.
1885        {
1886            let catalog = Catalog::open_debug_read_only_catalog(
1887                persist_client.clone(),
1888                organization_id,
1889                &bootstrap_args,
1890            )
1891            .await
1892            .expect("unable to open read-only debug catalog");
1893            let error = refresh(&catalog)
1894                .await
1895                .expect_err("a refresh with rows missing stages them");
1896            let CatalogError::Durable(DurableCatalogError::NotWritable(message)) = error else {
1897                panic!("unexpected error {error:?}");
1898            };
1899            assert!(
1900                message.contains("2 updates")
1901                    && message.contains("ItemColumns")
1902                    && message.contains("IndexColumns"),
1903                "{message}"
1904            );
1905            catalog.expire().await;
1906        }
1907        {
1908            let catalog = Catalog::open_debug_catalog(
1909                persist_client.clone(),
1910                organization_id,
1911                &bootstrap_args,
1912            )
1913            .await
1914            .expect("unable to open debug catalog");
1915            // A writable open refills the rows itself.
1916            let refilled = recorded(&catalog).await;
1917            assert_eq!(refilled.item_columns, written.item_columns);
1918            assert_eq!(refilled.index_columns, written.index_columns);
1919            catalog.expire().await;
1920        }
1921    }
1922
1923    /// The bootstrap refresh rewrites rows that disagree with what the
1924    /// running build's planner produces, surplus entries included.
1925    #[mz_ore::test(tokio::test)]
1926    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
1927    async fn refresh_rewrites_stale_item_metadata() {
1928        let persist_client = PersistClient::new_for_tests().await;
1929        let organization_id = Uuid::new_v4();
1930        let bootstrap_args = test_bootstrap_args();
1931
1932        let view_id = CatalogItemId::User(1);
1933        let index_id = CatalogItemId::User(2);
1934        let written = {
1935            let mut catalog = Catalog::open_debug_catalog(
1936                persist_client.clone(),
1937                organization_id,
1938                &bootstrap_args,
1939            )
1940            .await
1941            .expect("unable to open debug catalog");
1942            create_item(
1943                &mut catalog,
1944                view_id,
1945                GlobalId::User(1),
1946                "v",
1947                r#"CREATE VIEW "materialize"."public"."v" AS SELECT 1 AS a, NULL::text AS b"#,
1948            )
1949            .await;
1950            create_item(
1951                &mut catalog,
1952                index_id,
1953                GlobalId::User(2),
1954                "v_idx",
1955                r#"CREATE INDEX "v_idx" IN CLUSTER [u1] ON [u1 AS "materialize"."public"."v"] ("a")"#,
1956            )
1957            .await;
1958            let written = recorded(&catalog).await;
1959            catalog.expire().await;
1960            written
1961        };
1962        assert_eq!(written.item_columns.len(), 1, "{:?}", written.item_columns);
1963        assert_eq!(
1964            written.index_columns.len(),
1965            1,
1966            "{:?}",
1967            written.index_columns
1968        );
1969
1970        // Behind the catalog's back, swap the view's two recorded columns,
1971        // change the index key's column and nullability, and add a column and
1972        // a key beyond the planner's output.
1973        {
1974            let (columns_key, columns_value) = written.item_columns.iter().next().expect("one row");
1975            let (index_key, index_value) = written.index_columns.iter().next().expect("one row");
1976            let mut stale_columns = columns_value.clone();
1977            stale_columns.columns.swap(0, 1);
1978            let surplus_column = stale_columns.columns[0].clone();
1979            stale_columns.columns.push(surplus_column);
1980            let mut stale_index = index_value.clone();
1981            let changed_key = &mut stale_index.columns[0];
1982            changed_key.column = changed_key.column.map(|column| column + 1);
1983            changed_key.nullable = !changed_key.nullable;
1984            let surplus_key = index_value.columns[0];
1985            stale_index.columns.push(surplus_key);
1986
1987            let mut debug_state = TestCatalogStateBuilder::new(persist_client.clone())
1988                .with_organization_id(organization_id)
1989                .with_default_deploy_generation()
1990                .unwrap_build()
1991                .await
1992                .open_debug()
1993                .await
1994                .expect("unable to open debug state");
1995            debug_state
1996                .edit::<ItemColumnsCollection>(columns_key.clone(), stale_columns)
1997                .await
1998                .expect("edit columns");
1999            debug_state
2000                .edit::<IndexColumnsCollection>(index_key.clone(), stale_index)
2001                .await
2002                .expect("edit index keys");
2003        }
2004
2005        // The next refresh stages a rewrite of each disagreeing row, a
2006        // retraction and an addition each.
2007        {
2008            let catalog = Catalog::open_debug_read_only_catalog(
2009                persist_client.clone(),
2010                organization_id,
2011                &bootstrap_args,
2012            )
2013            .await
2014            .expect("unable to open read-only debug catalog");
2015            let error = refresh(&catalog)
2016                .await
2017                .expect_err("a refresh with stale rows rewrites them");
2018            let CatalogError::Durable(DurableCatalogError::NotWritable(message)) = error else {
2019                panic!("unexpected error {error:?}");
2020            };
2021            assert!(
2022                message.contains("4 updates")
2023                    && message.contains("ItemColumns")
2024                    && message.contains("IndexColumns"),
2025                "{message}"
2026            );
2027            catalog.expire().await;
2028        }
2029        // A writable open puts the planner's rows back.
2030        {
2031            let catalog = Catalog::open_debug_catalog(
2032                persist_client.clone(),
2033                organization_id,
2034                &bootstrap_args,
2035            )
2036            .await
2037            .expect("unable to open debug catalog");
2038            let rewritten = recorded(&catalog).await;
2039            assert_eq!(rewritten.item_columns, written.item_columns);
2040            assert_eq!(rewritten.index_columns, written.index_columns);
2041            catalog.expire().await;
2042        }
2043    }
2044}