1mod 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
69use 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 pub state: CatalogState,
78 pub migrated_storage_collections_0dt: BTreeSet<CatalogItemId>,
88 pub new_builtin_collections: BTreeSet<GlobalId>,
90 pub builtin_table_updates: Vec<BuiltinTableUpdate>,
92 pub last_seen_version: Option<Version>,
99 pub expr_cache_handle: Option<ExpressionCacheHandle>,
101 pub cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
103 pub uncached_local_exprs: BTreeMap<GlobalId, LocalExpressions>,
105}
106
107pub struct OpenCatalogResult {
108 pub catalog: Catalog,
110 pub last_seen_version: Option<Version>,
112 pub migrated_storage_collections_0dt: BTreeSet<CatalogItemId>,
114 pub new_builtin_collections: BTreeSet<GlobalId>,
116 pub builtin_table_updates: Vec<BuiltinTableUpdate>,
118 pub cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
120 pub uncached_local_exprs: BTreeMap<GlobalId, LocalExpressions>,
122}
123
124impl Catalog {
125 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 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 let new_builtin_collections = {
212 migrate::durable_migrate(
213 &mut txn,
214 state.config.environment_id.organization_id(),
215 config.boot_ts,
216 )?;
217 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 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 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 {
263 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 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 state.system_config().sync_dyncfgs();
356
357 {
361 if let Some(password) = config.external_login_password_mz_system {
362 let role_auth = RoleAuth {
363 role_id: MZ_SYSTEM_ROLE_ID,
364 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 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 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 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 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 post_item_updates.extend(migrate_result.post_item_updates);
493 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 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 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 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 if !txn.is_read_only() {
562 state.refresh_item_metadata(&mut txn)?;
563 }
564
565 set_migration_version(&mut txn, config.build_info.semver_version())?;
567
568 txn.commit(config.boot_ts).await?;
569
570 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 #[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 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 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 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 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 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 self.state = state;
734 Ok(())
735 }
736
737 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 pub async fn expire(self) {
779 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 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
799fn 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 let mut builtin_descs = HashSet::new();
808
809 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 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 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 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 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 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 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 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 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 let delete_exceptions: HashSet<SystemObjectDescription> = [].into();
999 assert!(
1003 deleted_system_objects
1004 .iter()
1005 .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 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 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 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 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 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 let old_roles = durable_roles.values().map(|role| role.id).collect();
1167 txn.remove_roles(&old_roles)?;
1168
1169 Ok(())
1170}
1171
1172fn 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 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
1225fn 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 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 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 let ClusterVariant::Managed(managed) = &cluster.config.variant else {
1309 continue;
1310 };
1311
1312 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 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 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 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 to_drop.extend(
1387 surplus
1388 .into_values()
1389 .map(|replica| (cluster.name.clone(), replica)),
1390 );
1391 }
1392
1393 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
1428fn managed_replica_config(managed: &ClusterVariantManaged) -> ReplicaConfig {
1442 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
1469fn 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 let session_vars = SessionVars::new_unchecked(&BUILD_INFO, SYSTEM_USER.clone(), None);
1488
1489 let mut invalid_roles_vars = BTreeMap::new();
1491 for (name, value) in &role.vars.map {
1492 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 invalid_roles_vars.is_empty() {
1504 return None;
1505 }
1506
1507 tracing::warn!(?role, ?invalid_roles_vars, "removing invalid role vars");
1508
1509 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
1523fn remove_pending_cluster_replicas_migration(
1532 tx: &mut Transaction,
1533 boot_ts: mz_repr::Timestamp,
1534) -> Result<(), anyhow::Error> {
1535 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 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 pub system_cluster: BootstrapBuiltinClusterConfig,
1591 pub catalog_server_cluster: BootstrapBuiltinClusterConfig,
1593 pub probe_cluster: BootstrapBuiltinClusterConfig,
1595 pub support_cluster: BootstrapBuiltinClusterConfig,
1597 pub analytics_cluster: BootstrapBuiltinClusterConfig,
1599}
1600
1601impl BuiltinBootstrapClusterConfigMap {
1602 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
1626pub(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 #[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 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 assert_eq!(billed_as, None);
1708 assert!(!internal);
1709 assert!(!pending);
1710 }
1711 ReplicaLocation::Unmanaged { .. } => panic!("expected a managed location"),
1712 }
1713 }
1714
1715 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 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 async fn recorded(catalog: &Catalog) -> Snapshot {
1770 catalog.storage().await.snapshot().await.expect("snapshot")
1771 }
1772
1773 #[mz_ore::test(tokio::test)]
1780 #[cfg_attr(miri, ignore)] 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 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 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 {
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 {
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 {
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 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 #[mz_ore::test(tokio::test)]
1926 #[cfg_attr(miri, ignore)] 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 {
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 {
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 {
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}