Skip to main content

mz_catalog/durable/
transaction.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
10use std::collections::{BTreeMap, BTreeSet};
11use std::fmt::Debug;
12use std::num::NonZeroU32;
13use std::time::Duration;
14
15use anyhow::anyhow;
16use derivative::Derivative;
17use itertools::Itertools;
18use mz_audit_log::VersionedEvent;
19use mz_compute_client::logging::{ComputeLog, DifferentialLog, LogVariant, TimelyLog};
20use mz_controller::clusters::ReplicaAllocation;
21use mz_controller_types::{ClusterId, ReplicaId};
22use mz_ore::cast::{u64_to_usize, usize_to_u64};
23use mz_ore::collections::{CollectionExt, HashSet};
24use mz_ore::now::SYSTEM_TIME;
25use mz_ore::vec::VecExt;
26use mz_ore::{soft_assert_no_log, soft_assert_or_log, soft_panic_or_log};
27use mz_persist_types::ShardId;
28use mz_pgrepr::oid::FIRST_USER_OID;
29use mz_proto::TryFromProtoError;
30use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
31use mz_repr::cluster_replica_size_id::ClusterReplicaSizeId;
32use mz_repr::network_policy_id::NetworkPolicyId;
33use mz_repr::query_policy_id::QueryPolicyId;
34use mz_repr::role_id::RoleId;
35use mz_repr::{CatalogItemId, Diff, GlobalId, RelationVersion};
36use mz_sql::catalog::{
37    CatalogError as SqlCatalogError, CatalogItemType, ObjectType, PasswordAction,
38    RoleAttributesRaw, RoleMembership, RoleVars,
39};
40use mz_sql::names::{CommentObjectId, DatabaseId, ResolvedDatabaseSpecifier, SchemaId};
41use mz_sql::plan::NetworkPolicyRule;
42use mz_sql::plan::{QueryPolicyMode, QueryPolicyRule};
43use mz_sql_parser::ast::QualifiedReplica;
44use mz_storage_client::controller::StorageTxn;
45use mz_storage_types::controller::StorageError;
46use tracing::warn;
47use uuid::Uuid;
48
49use crate::builtin::BuiltinLog;
50use crate::durable::initialize::{
51    ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT, SYSTEM_CONFIG_SYNCED_KEY,
52    WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL, WITH_0DT_DEPLOYMENT_MAX_WAIT,
53};
54use crate::durable::objects::serialization::{RustType, proto};
55use crate::durable::objects::{
56    AuditLogKey, Cluster, ClusterConfig, ClusterIntrospectionSourceIndexKey,
57    ClusterIntrospectionSourceIndexValue, ClusterKey, ClusterReplica, ClusterReplicaKey,
58    ClusterReplicaSize, ClusterReplicaSizeKey, ClusterReplicaSizeValue, ClusterReplicaValue,
59    ClusterSystemConfiguration, ClusterSystemConfigurationKey, ClusterSystemConfigurationValue,
60    ClusterValue, CommentKey, CommentValue, Config, ConfigKey, ConfigValue, Database, DatabaseKey,
61    DatabaseValue, DefaultPrivilegesKey, DefaultPrivilegesValue, DurableType, GidMappingKey,
62    GidMappingValue, IdAllocKey, IdAllocValue, IndexColumnsKey, IndexColumnsValue,
63    IntrospectionSourceIndex, Item, ItemColumnsKey, ItemColumnsValue, ItemKey, ItemMetadata,
64    ItemValue, NetworkPolicyKey, NetworkPolicyValue, QueryPolicy, QueryPolicyKey, QueryPolicyValue,
65    ReplicaConfig, ReplicaSystemConfiguration, ReplicaSystemConfigurationKey,
66    ReplicaSystemConfigurationValue, Role, RoleKey, RoleValue, Schema, SchemaKey, SchemaValue,
67    ServerConfigurationKey, ServerConfigurationValue, SettingKey, SettingValue, SourceReference,
68    SourceReferencesKey, SourceReferencesValue, StorageCollectionMetadataKey,
69    StorageCollectionMetadataValue, SystemObjectDescription, SystemObjectMapping,
70    SystemPrivilegesKey, SystemPrivilegesValue, TxnWalShardValue, UnfinalizedShardKey,
71};
72use crate::durable::{
73    AUDIT_LOG_ID_ALLOC_KEY, BUILTIN_MIGRATION_SHARD_KEY, CATALOG_CONTENT_VERSION_KEY, CatalogError,
74    DATABASE_ID_ALLOC_KEY, DefaultPrivilege, DurableCatalogError, DurableCatalogState,
75    EXPRESSION_CACHE_SHARD_KEY, MOCK_AUTHENTICATION_NONCE_KEY, NetworkPolicy, OID_ALLOC_KEY,
76    SCHEMA_ID_ALLOC_KEY, SYSTEM_CLUSTER_ID_ALLOC_KEY, SYSTEM_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY,
77    SYSTEM_ITEM_ALLOC_KEY, SYSTEM_REPLICA_ID_ALLOC_KEY, Snapshot, SystemConfiguration,
78    USER_ITEM_ALLOC_KEY, USER_NETWORK_POLICY_ID_ALLOC_KEY, USER_QUERY_POLICY_ID_ALLOC_KEY,
79    USER_ROLE_ID_ALLOC_KEY,
80};
81use crate::memory::objects::{StateDiff, StateUpdate, StateUpdateKind};
82
83type Timestamp = u64;
84
85#[derive(Debug, PartialEq)]
86struct CommitCapability;
87
88/// A [`Transaction`] batches multiple catalog operations together and commits them atomically.
89/// An operation also logically groups multiple catalog updates together.
90#[derive(Derivative)]
91#[derivative(Debug)]
92pub struct Transaction<'a> {
93    #[derivative(Debug = "ignore")]
94    #[derivative(PartialEq = "ignore")]
95    durable_catalog: &'a mut dyn DurableCatalogState,
96    databases: TableTransaction<DatabaseKey, DatabaseValue>,
97    schemas: TableTransaction<SchemaKey, SchemaValue>,
98    items: TableTransaction<ItemKey, ItemValue>,
99    item_columns: TableTransaction<ItemColumnsKey, ItemColumnsValue>,
100    index_columns: TableTransaction<IndexColumnsKey, IndexColumnsValue>,
101    comments: TableTransaction<CommentKey, CommentValue>,
102    roles: TableTransaction<RoleKey, RoleValue>,
103    role_auth: TableTransaction<RoleAuthKey, RoleAuthValue>,
104    clusters: TableTransaction<ClusterKey, ClusterValue>,
105    cluster_replicas: TableTransaction<ClusterReplicaKey, ClusterReplicaValue>,
106    introspection_sources:
107        TableTransaction<ClusterIntrospectionSourceIndexKey, ClusterIntrospectionSourceIndexValue>,
108    id_allocator: TableTransaction<IdAllocKey, IdAllocValue>,
109    configs: TableTransaction<ConfigKey, ConfigValue>,
110    settings: TableTransaction<SettingKey, SettingValue>,
111    system_gid_mapping: TableTransaction<GidMappingKey, GidMappingValue>,
112    system_configurations: TableTransaction<ServerConfigurationKey, ServerConfigurationValue>,
113    cluster_system_configurations:
114        TableTransaction<ClusterSystemConfigurationKey, ClusterSystemConfigurationValue>,
115    replica_system_configurations:
116        TableTransaction<ReplicaSystemConfigurationKey, ReplicaSystemConfigurationValue>,
117    default_privileges: TableTransaction<DefaultPrivilegesKey, DefaultPrivilegesValue>,
118    source_references: TableTransaction<SourceReferencesKey, SourceReferencesValue>,
119    system_privileges: TableTransaction<SystemPrivilegesKey, SystemPrivilegesValue>,
120    network_policies: TableTransaction<NetworkPolicyKey, NetworkPolicyValue>,
121    cluster_replica_sizes: TableTransaction<ClusterReplicaSizeKey, ClusterReplicaSizeValue>,
122    query_policies: TableTransaction<QueryPolicyKey, QueryPolicyValue>,
123    storage_collection_metadata:
124        TableTransaction<StorageCollectionMetadataKey, StorageCollectionMetadataValue>,
125    unfinalized_shards: TableTransaction<UnfinalizedShardKey, ()>,
126    txn_wal_shard: TableTransaction<(), TxnWalShardValue>,
127    // Don't make this a table transaction so that it's not read into the
128    // in-memory cache.
129    audit_log_updates: Vec<(AuditLogKey, Diff, Timestamp)>,
130    /// The upper of `durable_catalog` at the start of the transaction.
131    upper: mz_repr::Timestamp,
132    /// The ID of the current operation of this transaction.
133    op_id: Timestamp,
134    // `DryRunTransaction` removes this token. Commit entry points check it.
135    // Decomposition transfers it to `TransactionBatch` before exposing the
136    // durable handle.
137    commit_capability: Option<CommitCapability>,
138}
139
140/// A catalog transaction that can be evaluated but cannot be committed.
141#[derive(Debug)]
142pub struct DryRunTransaction<'a> {
143    transaction: Transaction<'a>,
144}
145
146impl<'a> DryRunTransaction<'a> {
147    /// Permanently revokes commit permission and returns a dry-run transaction.
148    pub fn new(mut transaction: Transaction<'a>) -> Self {
149        transaction.commit_capability = None;
150        Self { transaction }
151    }
152
153    /// Returns a mutable view for evaluating catalog operations.
154    pub fn transaction_mut(&mut self) -> &mut Transaction<'a> {
155        &mut self.transaction
156    }
157
158    /// Exports the current dry-run state as a [`Snapshot`].
159    pub fn current_snapshot(&self) -> Snapshot {
160        self.transaction.current_snapshot()
161    }
162}
163
164impl<'a> Transaction<'a> {
165    pub(super) fn new(
166        durable_catalog: &'a mut dyn DurableCatalogState,
167        Snapshot {
168            databases,
169            schemas,
170            roles,
171            role_auth,
172            items,
173            item_columns,
174            index_columns,
175            comments,
176            clusters,
177            network_policies,
178            cluster_replica_sizes,
179            query_policies,
180            cluster_replicas,
181            introspection_sources,
182            id_allocator,
183            configs,
184            settings,
185            source_references,
186            system_object_mappings,
187            system_configurations,
188            cluster_system_configurations,
189            replica_system_configurations,
190            default_privileges,
191            system_privileges,
192            storage_collection_metadata,
193            unfinalized_shards,
194            txn_wal_shard,
195        }: Snapshot,
196        upper: mz_repr::Timestamp,
197    ) -> Result<Transaction<'a>, CatalogError> {
198        // For these collections uniqueness is plain equality of the name fields, so the same
199        // predicate answers both "do these two conflict?" and "did this update keep the same key?".
200        let database_unique_fn: fn(&DatabaseValue, &DatabaseValue) -> bool =
201            |a, b| a.name == b.name;
202        let schema_unique_fn: fn(&SchemaValue, &SchemaValue) -> bool =
203            |a, b| a.database_id == b.database_id && a.name == b.name;
204        let role_key: fn(&RoleValue, &RoleValue) -> bool = |a, b| a.name == b.name;
205        let cluster_unique_fn: fn(&ClusterValue, &ClusterValue) -> bool = |a, b| a.name == b.name;
206        let network_policy_unique_fn: fn(&NetworkPolicyValue, &NetworkPolicyValue) -> bool =
207            |a, b| a.name == b.name;
208        let cluster_replica_size_unique_fn: fn(
209            &ClusterReplicaSizeValue,
210            &ClusterReplicaSizeValue,
211        ) -> bool = |a, b| a.name == b.name;
212        let cluster_replica_unique_fn: fn(&ClusterReplicaValue, &ClusterReplicaValue) -> bool =
213            |a, b| a.cluster_id == b.cluster_id && a.name == b.name;
214
215        Ok(Transaction {
216            durable_catalog,
217            databases: TableTransaction::new_with_uniqueness_fn(
218                databases,
219                database_unique_fn,
220                database_unique_fn,
221            )?,
222            schemas: TableTransaction::new_with_uniqueness_fn(
223                schemas,
224                schema_unique_fn,
225                schema_unique_fn,
226            )?,
227            // Temporary items from different sessions may share a name in the
228            // temporary schema (whose durable schema id is a sentinel shared
229            // by every session), so name uniqueness is additionally scoped by
230            // the owning session.
231            items: TableTransaction::new_with_uniqueness_fn(
232                items,
233                |a: &ItemValue, b| {
234                    a.schema_id == b.schema_id
235                        && a.name == b.name
236                        && a.ephemeral_owner_session == b.ephemeral_owner_session
237                        && {
238                            // `item_type` is slow, only compute if needed.
239                            let a_type = a.item_type();
240                            let b_type = b.item_type();
241                            (a_type != CatalogItemType::Type && b_type != CatalogItemType::Type)
242                                || (a_type == CatalogItemType::Type && b_type.conflicts_with_type())
243                                || (b_type == CatalogItemType::Type && a_type.conflicts_with_type())
244                        }
245                },
246                |prev: &ItemValue, next| {
247                    prev.schema_id == next.schema_id
248                        && prev.name == next.name
249                        && prev.ephemeral_owner_session == next.ephemeral_owner_session
250                        // `item_type` is slow, only compute it once name and schema match.
251                        && prev.item_type() == next.item_type()
252                },
253            )?,
254            item_columns: TableTransaction::new(item_columns)?,
255            index_columns: TableTransaction::new(index_columns)?,
256            comments: TableTransaction::new(comments)?,
257            roles: TableTransaction::new_with_uniqueness_fn(roles, role_key, role_key)?,
258            role_auth: TableTransaction::new(role_auth)?,
259            clusters: TableTransaction::new_with_uniqueness_fn(
260                clusters,
261                cluster_unique_fn,
262                cluster_unique_fn,
263            )?,
264            network_policies: TableTransaction::new_with_uniqueness_fn(
265                network_policies,
266                network_policy_unique_fn,
267                network_policy_unique_fn,
268            )?,
269            cluster_replica_sizes: TableTransaction::new_with_uniqueness_fn(
270                cluster_replica_sizes,
271                cluster_replica_size_unique_fn,
272                cluster_replica_size_unique_fn,
273            )?,
274            query_policies: TableTransaction::new_with_uniqueness_fn(
275                query_policies,
276                |a: &QueryPolicyValue, b| a.name == b.name,
277                |prev: &QueryPolicyValue, next| prev.name == next.name,
278            )?,
279            cluster_replicas: TableTransaction::new_with_uniqueness_fn(
280                cluster_replicas,
281                cluster_replica_unique_fn,
282                cluster_replica_unique_fn,
283            )?,
284            introspection_sources: TableTransaction::new(introspection_sources)?,
285            id_allocator: TableTransaction::new(id_allocator)?,
286            configs: TableTransaction::new(configs)?,
287            settings: TableTransaction::new(settings)?,
288            source_references: TableTransaction::new(source_references)?,
289            system_gid_mapping: TableTransaction::new(system_object_mappings)?,
290            system_configurations: TableTransaction::new(system_configurations)?,
291            cluster_system_configurations: TableTransaction::new(cluster_system_configurations)?,
292            replica_system_configurations: TableTransaction::new(replica_system_configurations)?,
293            default_privileges: TableTransaction::new(default_privileges)?,
294            system_privileges: TableTransaction::new(system_privileges)?,
295            storage_collection_metadata: TableTransaction::new(storage_collection_metadata)?,
296            unfinalized_shards: TableTransaction::new(unfinalized_shards)?,
297            // Uniqueness violations for this value occur at the key rather than
298            // the value (the key is the unit struct `()` so this is a singleton
299            // value).
300            txn_wal_shard: TableTransaction::new(txn_wal_shard)?,
301            audit_log_updates: Vec::new(),
302            upper,
303            op_id: 0,
304            commit_capability: Some(CommitCapability),
305        })
306    }
307
308    pub fn get_item(&self, id: &CatalogItemId) -> Option<Item> {
309        let key = ItemKey { id: *id };
310        self.items
311            .get(&key)
312            .map(|v| DurableType::from_key_value(key, v.clone()))
313    }
314
315    pub fn get_items(&self) -> impl Iterator<Item = Item> + use<> {
316        self.items
317            .items()
318            .into_iter()
319            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
320            .sorted_by_key(|Item { id, .. }| *id)
321    }
322
323    pub fn insert_audit_log_event(&mut self, event: VersionedEvent) {
324        self.insert_audit_log_events([event]);
325    }
326
327    pub fn insert_audit_log_events(&mut self, events: impl IntoIterator<Item = VersionedEvent>) {
328        let events = events
329            .into_iter()
330            .map(|event| (AuditLogKey { event }, Diff::ONE, self.op_id));
331        self.audit_log_updates.extend(events);
332    }
333
334    pub fn insert_user_database(
335        &mut self,
336        database_name: &str,
337        owner_id: RoleId,
338        privileges: Vec<MzAclItem>,
339        temporary_oids: &HashSet<u32>,
340    ) -> Result<(DatabaseId, u32), CatalogError> {
341        let id = self.get_and_increment_id(DATABASE_ID_ALLOC_KEY.to_string())?;
342        let id = DatabaseId::User(id);
343        let oid = self.allocate_oid(temporary_oids)?;
344        self.insert_database(id, database_name, owner_id, privileges, oid)?;
345        Ok((id, oid))
346    }
347
348    pub(crate) fn insert_database(
349        &mut self,
350        id: DatabaseId,
351        database_name: &str,
352        owner_id: RoleId,
353        privileges: Vec<MzAclItem>,
354        oid: u32,
355    ) -> Result<u32, CatalogError> {
356        match self.databases.insert(
357            DatabaseKey { id },
358            DatabaseValue {
359                name: database_name.to_string(),
360                owner_id,
361                privileges,
362                oid,
363            },
364            self.op_id,
365        ) {
366            Ok(_) => Ok(oid),
367            Err(_) => Err(SqlCatalogError::DatabaseAlreadyExists(database_name.to_owned()).into()),
368        }
369    }
370
371    pub fn insert_user_schema(
372        &mut self,
373        database_id: DatabaseId,
374        schema_name: &str,
375        owner_id: RoleId,
376        privileges: Vec<MzAclItem>,
377        temporary_oids: &HashSet<u32>,
378    ) -> Result<(SchemaId, u32), CatalogError> {
379        let id = self.get_and_increment_id(SCHEMA_ID_ALLOC_KEY.to_string())?;
380        let id = SchemaId::User(id);
381        let oid = self.allocate_oid(temporary_oids)?;
382        self.insert_schema(
383            id,
384            Some(database_id),
385            schema_name.to_string(),
386            owner_id,
387            privileges,
388            oid,
389        )?;
390        Ok((id, oid))
391    }
392
393    pub fn insert_system_schema(
394        &mut self,
395        schema_id: u64,
396        schema_name: &str,
397        owner_id: RoleId,
398        privileges: Vec<MzAclItem>,
399        oid: u32,
400    ) -> Result<(), CatalogError> {
401        let id = SchemaId::System(schema_id);
402        self.insert_schema(id, None, schema_name.to_string(), owner_id, privileges, oid)
403    }
404
405    pub(crate) fn insert_schema(
406        &mut self,
407        schema_id: SchemaId,
408        database_id: Option<DatabaseId>,
409        schema_name: String,
410        owner_id: RoleId,
411        privileges: Vec<MzAclItem>,
412        oid: u32,
413    ) -> Result<(), CatalogError> {
414        match self.schemas.insert(
415            SchemaKey { id: schema_id },
416            SchemaValue {
417                database_id,
418                name: schema_name.clone(),
419                owner_id,
420                privileges,
421                oid,
422            },
423            self.op_id,
424        ) {
425            Ok(_) => Ok(()),
426            Err(_) => Err(SqlCatalogError::SchemaAlreadyExists(schema_name).into()),
427        }
428    }
429
430    pub fn insert_builtin_role(
431        &mut self,
432        id: RoleId,
433        name: String,
434        attributes: RoleAttributesRaw,
435        membership: RoleMembership,
436        vars: RoleVars,
437        oid: u32,
438    ) -> Result<RoleId, CatalogError> {
439        soft_assert_or_log!(id.is_builtin(), "ID {id:?} is not builtin");
440        self.insert_role(id, name, attributes, membership, vars, oid)?;
441        Ok(id)
442    }
443
444    pub fn insert_user_role(
445        &mut self,
446        name: String,
447        attributes: RoleAttributesRaw,
448        membership: RoleMembership,
449        vars: RoleVars,
450        temporary_oids: &HashSet<u32>,
451    ) -> Result<(RoleId, u32), CatalogError> {
452        let id = self.get_and_increment_id(USER_ROLE_ID_ALLOC_KEY.to_string())?;
453        let id = RoleId::User(id);
454        let oid = self.allocate_oid(temporary_oids)?;
455        self.insert_role(id, name, attributes, membership, vars, oid)?;
456        Ok((id, oid))
457    }
458
459    fn insert_role(
460        &mut self,
461        id: RoleId,
462        name: String,
463        attributes: RoleAttributesRaw,
464        membership: RoleMembership,
465        vars: RoleVars,
466        oid: u32,
467    ) -> Result<(), CatalogError> {
468        if let Some(ref password) = attributes.password {
469            let hash = mz_auth::hash::scram256_hash(
470                password,
471                &attributes
472                    .scram_iterations
473                    .or_else(|| {
474                        soft_panic_or_log!(
475                            "Hash iterations must be set if a password is provided."
476                        );
477                        None
478                    })
479                    // This should never happen, but rather than panicking we'll
480                    // set a known secure value as a fallback.
481                    .unwrap_or_else(|| NonZeroU32::new(600_000).expect("known valid")),
482            )
483            .expect("password hash should be valid");
484            match self.role_auth.insert(
485                RoleAuthKey { role_id: id },
486                RoleAuthValue {
487                    password_hash: Some(hash),
488                    updated_at: SYSTEM_TIME(),
489                },
490                self.op_id,
491            ) {
492                Ok(_) => {}
493                Err(_) => {
494                    return Err(SqlCatalogError::RoleAlreadyExists(name).into());
495                }
496            }
497        }
498
499        match self.roles.insert(
500            RoleKey { id },
501            RoleValue {
502                name: name.clone(),
503                attributes: attributes.into(),
504                membership,
505                vars,
506                oid,
507            },
508            self.op_id,
509        ) {
510            Ok(_) => Ok(()),
511            Err(_) => Err(SqlCatalogError::RoleAlreadyExists(name).into()),
512        }
513    }
514
515    /// Panics if any introspection source id is not a system id
516    pub fn insert_user_cluster(
517        &mut self,
518        cluster_id: ClusterId,
519        cluster_name: &str,
520        introspection_source_indexes: Vec<(&'static BuiltinLog, CatalogItemId, GlobalId)>,
521        owner_id: RoleId,
522        privileges: Vec<MzAclItem>,
523        config: ClusterConfig,
524        temporary_oids: &HashSet<u32>,
525    ) -> Result<(), CatalogError> {
526        self.insert_cluster(
527            cluster_id,
528            cluster_name,
529            introspection_source_indexes,
530            owner_id,
531            privileges,
532            config,
533            temporary_oids,
534        )
535    }
536
537    /// Panics if any introspection source id is not a system id
538    pub fn insert_system_cluster(
539        &mut self,
540        cluster_name: &str,
541        introspection_source_indexes: Vec<(&'static BuiltinLog, CatalogItemId, GlobalId)>,
542        privileges: Vec<MzAclItem>,
543        owner_id: RoleId,
544        config: ClusterConfig,
545        temporary_oids: &HashSet<u32>,
546    ) -> Result<ClusterId, CatalogError> {
547        let cluster_id = self.get_and_increment_id(SYSTEM_CLUSTER_ID_ALLOC_KEY.to_string())?;
548        let cluster_id = ClusterId::system(cluster_id).ok_or(SqlCatalogError::IdExhaustion)?;
549        self.insert_cluster(
550            cluster_id,
551            cluster_name,
552            introspection_source_indexes,
553            owner_id,
554            privileges,
555            config,
556            temporary_oids,
557        )?;
558        Ok(cluster_id)
559    }
560
561    fn insert_cluster(
562        &mut self,
563        cluster_id: ClusterId,
564        cluster_name: &str,
565        introspection_source_indexes: Vec<(&'static BuiltinLog, CatalogItemId, GlobalId)>,
566        owner_id: RoleId,
567        privileges: Vec<MzAclItem>,
568        config: ClusterConfig,
569        temporary_oids: &HashSet<u32>,
570    ) -> Result<(), CatalogError> {
571        self.validate_query_policy_reference(config.query_policy)?;
572        if let Err(_) = self.clusters.insert(
573            ClusterKey { id: cluster_id },
574            ClusterValue {
575                name: cluster_name.to_string(),
576                owner_id,
577                privileges,
578                config,
579            },
580            self.op_id,
581        ) {
582            return Err(SqlCatalogError::ClusterAlreadyExists(cluster_name.to_owned()).into());
583        };
584
585        let amount = usize_to_u64(introspection_source_indexes.len());
586        let oids = self.allocate_oids(amount, temporary_oids)?;
587        let introspection_source_indexes: Vec<_> = introspection_source_indexes
588            .into_iter()
589            .zip_eq(oids)
590            .map(|((builtin, item_id, index_id), oid)| (builtin, item_id, index_id, oid))
591            .collect();
592        for (builtin, item_id, index_id, oid) in introspection_source_indexes {
593            let introspection_source_index = IntrospectionSourceIndex {
594                cluster_id,
595                name: builtin.name.to_string(),
596                item_id,
597                index_id,
598                oid,
599            };
600            let (key, value) = introspection_source_index.into_key_value();
601            self.introspection_sources
602                .insert(key, value, self.op_id)
603                .expect("no uniqueness violation");
604        }
605
606        Ok(())
607    }
608
609    pub fn rename_cluster(
610        &mut self,
611        cluster_id: ClusterId,
612        cluster_name: &str,
613        cluster_to_name: &str,
614    ) -> Result<(), CatalogError> {
615        let key = ClusterKey { id: cluster_id };
616
617        match self.clusters.update(
618            |k, v| {
619                if *k == key {
620                    let mut value = v.clone();
621                    value.name = cluster_to_name.to_string();
622                    Some(value)
623                } else {
624                    None
625                }
626            },
627            self.op_id,
628        )? {
629            Diff::ZERO => Err(SqlCatalogError::UnknownCluster(cluster_name.to_string()).into()),
630            Diff::ONE => Ok(()),
631            n => panic!(
632                "Expected to update single cluster {cluster_name} ({cluster_id}), updated {n}"
633            ),
634        }
635    }
636
637    pub fn rename_cluster_replica(
638        &mut self,
639        replica_id: ReplicaId,
640        replica_name: &QualifiedReplica,
641        replica_to_name: &str,
642    ) -> Result<(), CatalogError> {
643        let key = ClusterReplicaKey { id: replica_id };
644
645        match self.cluster_replicas.update(
646            |k, v| {
647                if *k == key {
648                    let mut value = v.clone();
649                    value.name = replica_to_name.to_string();
650                    Some(value)
651                } else {
652                    None
653                }
654            },
655            self.op_id,
656        )? {
657            Diff::ZERO => {
658                Err(SqlCatalogError::UnknownClusterReplica(replica_name.to_string()).into())
659            }
660            Diff::ONE => Ok(()),
661            n => panic!(
662                "Expected to update single cluster replica {replica_name} ({replica_id}), updated {n}"
663            ),
664        }
665    }
666
667    pub fn insert_cluster_replica_with_id(
668        &mut self,
669        cluster_id: ClusterId,
670        replica_id: ReplicaId,
671        replica_name: &str,
672        config: ReplicaConfig,
673        owner_id: RoleId,
674    ) -> Result<(), CatalogError> {
675        if let Err(_) = self.cluster_replicas.insert(
676            ClusterReplicaKey { id: replica_id },
677            ClusterReplicaValue {
678                cluster_id,
679                name: replica_name.into(),
680                config,
681                owner_id,
682            },
683            self.op_id,
684        ) {
685            let cluster = self
686                .clusters
687                .get(&ClusterKey { id: cluster_id })
688                .expect("cluster exists");
689            return Err(SqlCatalogError::DuplicateReplica(
690                replica_name.to_string(),
691                cluster.name.to_string(),
692            )
693            .into());
694        };
695        Ok(())
696    }
697
698    pub fn insert_user_query_policy(
699        &mut self,
700        name: String,
701        mode: QueryPolicyMode,
702        rules: Vec<QueryPolicyRule>,
703        privileges: Vec<MzAclItem>,
704        owner_id: RoleId,
705        temporary_oids: &HashSet<u32>,
706    ) -> Result<QueryPolicyId, CatalogError> {
707        let oid = self.allocate_oid(temporary_oids)?;
708        let id = QueryPolicyId::User(
709            self.get_and_increment_id(USER_QUERY_POLICY_ID_ALLOC_KEY.to_string())?,
710        );
711        self.query_policies
712            .insert(
713                QueryPolicyKey { id },
714                QueryPolicyValue {
715                    name: name.clone(),
716                    mode,
717                    rules,
718                    privileges,
719                    owner_id,
720                    oid,
721                },
722                self.op_id,
723            )
724            .map_err(|_| SqlCatalogError::QueryPolicyAlreadyExists(name))?;
725        Ok(id)
726    }
727
728    pub fn update_query_policy(&mut self, policy: QueryPolicy) -> Result<(), CatalogError> {
729        let id = policy.id;
730        let (key, value) = policy.into_key_value();
731        if self.query_policies.update_by_key(key, value, self.op_id)? {
732            Ok(())
733        } else {
734            Err(SqlCatalogError::UnknownQueryPolicy(id.to_string()).into())
735        }
736    }
737
738    /// Removes policies and returns the surviving clusters detached by CASCADE.
739    pub fn remove_query_policies(
740        &mut self,
741        ids: &BTreeSet<QueryPolicyId>,
742        cascade: bool,
743    ) -> Result<Vec<ClusterId>, CatalogError> {
744        let mut detached_clusters = Vec::new();
745        if ids.is_empty() {
746            return Ok(detached_clusters);
747        }
748        if !cascade {
749            // Check references in the same durable working copy as the deletion.
750            // A sequencer's catalog snapshot can predate a staged attachment.
751            for policy in self
752                .clusters
753                .items()
754                .values()
755                .filter_map(|c| c.config.query_policy)
756            {
757                if ids.contains(&policy) {
758                    let policy = self
759                        .query_policies
760                        .get(&QueryPolicyKey { id: policy })
761                        .expect("referenced query policy exists");
762                    return Err(SqlCatalogError::QueryPolicyInUse(policy.name.clone()).into());
763                }
764            }
765        } else {
766            let clusters: Vec<_> = self
767                .clusters
768                .items()
769                .into_iter()
770                .filter_map(|(key, value)| {
771                    value
772                        .config
773                        .query_policy
774                        .filter(|id| ids.contains(id))
775                        .map(|_| {
776                            let mut value = value.clone();
777                            value.config.query_policy = None;
778                            (key.clone(), value)
779                        })
780                })
781                .collect();
782            detached_clusters = clusters.iter().map(|(key, _)| key.id).collect();
783            self.clusters.update_by_keys(clusters, self.op_id)?;
784        }
785        let to_remove = ids
786            .iter()
787            .map(|id| (QueryPolicyKey { id: *id }, None))
788            .collect();
789        let previous = self.query_policies.set_many(to_remove, self.op_id)?;
790        for (key, value) in previous {
791            assert!(key.id.is_user(), "cannot delete non-user query policy");
792            if value.is_none() {
793                return Err(SqlCatalogError::UnknownQueryPolicy(key.id.to_string()).into());
794            }
795        }
796        Ok(detached_clusters)
797    }
798
799    fn validate_query_policy_reference(
800        &self,
801        id: Option<QueryPolicyId>,
802    ) -> Result<(), CatalogError> {
803        if let Some(id) = id {
804            if self.query_policies.get(&QueryPolicyKey { id }).is_none() {
805                return Err(SqlCatalogError::UnknownQueryPolicy(id.to_string()).into());
806            }
807        }
808        Ok(())
809    }
810
811    pub fn insert_user_network_policy(
812        &mut self,
813        name: String,
814        rules: Vec<NetworkPolicyRule>,
815        privileges: Vec<MzAclItem>,
816        owner_id: RoleId,
817        temporary_oids: &HashSet<u32>,
818    ) -> Result<NetworkPolicyId, CatalogError> {
819        let oid = self.allocate_oid(temporary_oids)?;
820        let id = self.get_and_increment_id(USER_NETWORK_POLICY_ID_ALLOC_KEY.to_string())?;
821        let id = NetworkPolicyId::User(id);
822        self.insert_network_policy(id, name, rules, privileges, owner_id, oid)
823    }
824
825    pub fn insert_network_policy(
826        &mut self,
827        id: NetworkPolicyId,
828        name: String,
829        rules: Vec<NetworkPolicyRule>,
830        privileges: Vec<MzAclItem>,
831        owner_id: RoleId,
832        oid: u32,
833    ) -> Result<NetworkPolicyId, CatalogError> {
834        match self.network_policies.insert(
835            NetworkPolicyKey { id },
836            NetworkPolicyValue {
837                name: name.clone(),
838                rules,
839                privileges,
840                owner_id,
841                oid,
842            },
843            self.op_id,
844        ) {
845            Ok(_) => Ok(id),
846            Err(_) => Err(SqlCatalogError::NetworkPolicyAlreadyExists(name).into()),
847        }
848    }
849
850    /// Updates persisted information about persisted introspection source
851    /// indexes.
852    ///
853    /// Panics if provided id is not a system id.
854    pub fn update_introspection_source_index_gids(
855        &mut self,
856        mappings: impl Iterator<
857            Item = (
858                ClusterId,
859                impl Iterator<Item = (String, CatalogItemId, GlobalId, u32)>,
860            ),
861        >,
862    ) -> Result<(), CatalogError> {
863        for (cluster_id, updates) in mappings {
864            for (name, item_id, index_id, oid) in updates {
865                let introspection_source_index = IntrospectionSourceIndex {
866                    cluster_id,
867                    name,
868                    item_id,
869                    index_id,
870                    oid,
871                };
872                let (key, value) = introspection_source_index.into_key_value();
873
874                let prev = self
875                    .introspection_sources
876                    .set(key, Some(value), self.op_id)?;
877                if prev.is_none() {
878                    return Err(SqlCatalogError::FailedBuiltinSchemaMigration(format!(
879                        "{index_id}"
880                    ))
881                    .into());
882                }
883            }
884        }
885        Ok(())
886    }
887
888    pub fn insert_user_item(
889        &mut self,
890        id: CatalogItemId,
891        global_id: GlobalId,
892        schema_id: SchemaId,
893        item_name: &str,
894        create_sql: String,
895        owner_id: RoleId,
896        privileges: Vec<MzAclItem>,
897        temporary_oids: &HashSet<u32>,
898        versions: BTreeMap<RelationVersion, GlobalId>,
899        ephemeral_owner_session: Option<Uuid>,
900    ) -> Result<u32, CatalogError> {
901        let oid = self.allocate_oid(temporary_oids)?;
902        self.insert_item(
903            id,
904            oid,
905            global_id,
906            schema_id,
907            item_name,
908            create_sql,
909            owner_id,
910            privileges,
911            versions,
912            ephemeral_owner_session,
913        )?;
914        Ok(oid)
915    }
916
917    pub fn insert_item(
918        &mut self,
919        id: CatalogItemId,
920        oid: u32,
921        global_id: GlobalId,
922        schema_id: SchemaId,
923        item_name: &str,
924        create_sql: String,
925        owner_id: RoleId,
926        privileges: Vec<MzAclItem>,
927        extra_versions: BTreeMap<RelationVersion, GlobalId>,
928        ephemeral_owner_session: Option<Uuid>,
929    ) -> Result<(), CatalogError> {
930        match self.items.insert(
931            ItemKey { id },
932            ItemValue {
933                schema_id,
934                name: item_name.to_string(),
935                create_sql,
936                owner_id,
937                privileges,
938                oid,
939                global_id,
940                extra_versions,
941                ephemeral_owner_session,
942            },
943            self.op_id,
944        ) {
945            Ok(_) => Ok(()),
946            Err(_) => Err(SqlCatalogError::ItemAlreadyExists(id, item_name.to_owned()).into()),
947        }
948    }
949
950    /// Records `metadata` as the planner-resolved metadata of item `id`,
951    /// replacing whatever it had.
952    pub fn set_item_metadata(
953        &mut self,
954        id: CatalogItemId,
955        metadata: ItemMetadata,
956    ) -> Result<(), CatalogError> {
957        let ItemMetadata {
958            columns,
959            index_columns,
960        } = metadata;
961        // An item without columns or keys has no row, so a relation without
962        // columns and an item that is not a relation read the same.
963        let columns = (!columns.is_empty()).then_some(ItemColumnsValue { columns });
964        let key = ItemColumnsKey { id };
965        if self.item_columns.get(&key) != columns.as_ref() {
966            self.item_columns.set(key, columns, self.op_id)?;
967        }
968        let index_columns = (!index_columns.is_empty()).then_some(IndexColumnsValue {
969            columns: index_columns,
970        });
971        let key = IndexColumnsKey { id };
972        if self.index_columns.get(&key) != index_columns.as_ref() {
973            self.index_columns.set(key, index_columns, self.op_id)?;
974        }
975        Ok(())
976    }
977
978    /// Deletes the recorded columns and index keys of item `id`.
979    fn delete_item_metadata(&mut self, id: CatalogItemId) {
980        self.item_columns
981            .delete_by_key(ItemColumnsKey { id }, self.op_id);
982        self.index_columns
983            .delete_by_key(IndexColumnsKey { id }, self.op_id);
984    }
985
986    /// Removes every item owned by an ephemeral session from the transaction,
987    /// along with the durable state a graceful drop would have removed with
988    /// it: storage collection metadata (moving the backing shards to the
989    /// finalization WAL), recorded columns and index keys, comments, and
990    /// source references.
991    ///
992    /// Used to reclaim temporary items when the catalog is opened with write
993    /// intent, at which point every session that could own one is dead.
994    ///
995    /// This must mirror everything the graceful `Op::DropObjects` path
996    /// persists for a temporary item, because nothing revisits the leftovers:
997    /// bootstrap only ever inserts collection metadata for items present in
998    /// the catalog, and shard finalization is driven solely by the
999    /// `unfinalized_shards` collection, so a metadata row that outlives its
1000    /// item leaks the persist shard permanently.
1001    pub fn remove_ephemeral_items(&mut self) {
1002        let mut keys = Vec::new();
1003        let mut item_ids = BTreeSet::new();
1004        let mut global_ids = BTreeSet::new();
1005        for (key, value) in self.items.items() {
1006            if value.ephemeral_owner_session.is_none() {
1007                continue;
1008            }
1009            item_ids.insert(key.id);
1010            global_ids.insert(value.global_id);
1011            global_ids.extend(value.extra_versions.values().copied());
1012            keys.push(key.clone());
1013        }
1014        self.items.delete_by_keys(keys, self.op_id);
1015        for id in &item_ids {
1016            self.delete_item_metadata(*id);
1017        }
1018
1019        // Move the items' storage mappings to the finalization WAL, like
1020        // `StorageCollections::prepare_state` does for a graceful drop. Every
1021        // version of a table maps to the same shard, and a shard that a
1022        // remaining mapping still references must not be finalized. No
1023        // remaining mapping can reference one today (only replacement
1024        // materialized views share shards, and those cannot be temporary),
1025        // so this mirrors `prepare_state`'s guard defensively.
1026        let dropped_mappings = self.delete_collection_metadata(global_ids);
1027        let mut dropped_shards: BTreeSet<_> = dropped_mappings
1028            .into_iter()
1029            .map(|(_, shard)| shard)
1030            .collect();
1031        let live_shards: BTreeSet<_> = self.get_collection_metadata().into_values().collect();
1032        dropped_shards.retain(|shard| {
1033            let live = live_shards.contains(shard);
1034            if live {
1035                soft_panic_or_log!(
1036                    "shard {shard} of a reclaimed ephemeral item is still referenced by a \
1037                     live collection, not finalizing it"
1038                );
1039            }
1040            !live
1041        });
1042        self.insert_unfinalized_shards(dropped_shards).expect(
1043            "inserting unfinalized shards only fails on duplicate values, which it ignores",
1044        );
1045
1046        // Comments on ephemeral items would otherwise dangle and, because
1047        // item ids are reused, could later re-attach to an unrelated object.
1048        self.comments.delete(
1049            |key, _value| match key.object_id {
1050                CommentObjectId::Table(item_id)
1051                | CommentObjectId::View(item_id)
1052                | CommentObjectId::MaterializedView(item_id)
1053                | CommentObjectId::Source(item_id)
1054                | CommentObjectId::Sink(item_id)
1055                | CommentObjectId::MetricSink(item_id)
1056                | CommentObjectId::Index(item_id)
1057                | CommentObjectId::Func(item_id)
1058                | CommentObjectId::Connection(item_id)
1059                | CommentObjectId::Type(item_id)
1060                | CommentObjectId::Secret(item_id) => item_ids.contains(&item_id),
1061                CommentObjectId::Role(_)
1062                | CommentObjectId::Database(_)
1063                | CommentObjectId::Schema(_)
1064                | CommentObjectId::Cluster(_)
1065                | CommentObjectId::ClusterReplica(_)
1066                | CommentObjectId::QueryPolicy(_)
1067                | CommentObjectId::NetworkPolicy(_) => false,
1068            },
1069            self.op_id,
1070        );
1071
1072        // Only sources hold source references and sources cannot be temporary
1073        // today, so this is defensive.
1074        self.source_references
1075            .delete(|key, _value| item_ids.contains(&key.source_id), self.op_id);
1076    }
1077
1078    pub fn get_and_increment_id(&mut self, key: String) -> Result<u64, CatalogError> {
1079        Ok(self.get_and_increment_id_by(key, 1)?.into_element())
1080    }
1081
1082    pub fn get_and_increment_id_by(
1083        &mut self,
1084        key: String,
1085        amount: u64,
1086    ) -> Result<Vec<u64>, CatalogError> {
1087        assert!(
1088            key != SYSTEM_ITEM_ALLOC_KEY || !self.durable_catalog.is_bootstrap_complete(),
1089            "system item IDs cannot be allocated outside of bootstrap"
1090        );
1091
1092        let current_id = self
1093            .id_allocator
1094            .items()
1095            .get(&IdAllocKey { name: key.clone() })
1096            .unwrap_or_else(|| panic!("{key} id allocator missing"))
1097            .next_id;
1098        let next_id = current_id
1099            .checked_add(amount)
1100            .ok_or(SqlCatalogError::IdExhaustion)?;
1101        let prev = self.id_allocator.set(
1102            IdAllocKey { name: key },
1103            Some(IdAllocValue { next_id }),
1104            self.op_id,
1105        )?;
1106        assert_eq!(
1107            prev,
1108            Some(IdAllocValue {
1109                next_id: current_id
1110            })
1111        );
1112        Ok((current_id..next_id).collect())
1113    }
1114
1115    pub fn allocate_system_item_ids(
1116        &mut self,
1117        amount: u64,
1118    ) -> Result<Vec<(CatalogItemId, GlobalId)>, CatalogError> {
1119        assert!(
1120            !self.durable_catalog.is_bootstrap_complete(),
1121            "we can only allocate system item IDs during bootstrap"
1122        );
1123        Ok(self
1124            .get_and_increment_id_by(SYSTEM_ITEM_ALLOC_KEY.to_string(), amount)?
1125            .into_iter()
1126            // TODO(alter_table): Use separate ID allocators.
1127            .map(|x| (CatalogItemId::System(x), GlobalId::System(x)))
1128            .collect())
1129    }
1130
1131    /// Allocates an ID for an introspection source index. These IDs are deterministically derived
1132    /// from the `cluster_id` and `log_variant`.
1133    ///
1134    /// Introspection source indexes are a special edge case of items. They are considered system
1135    /// items, but they are the only system item that can be created by the user at any time. All
1136    /// other system items can only be created by the system during the startup of an upgrade.
1137    ///
1138    /// Furthermore, all other system item IDs are allocated deterministically in the same order
1139    /// during startup. Therefore, all read-only `environmentd` processes during an upgrade will
1140    /// allocate the same system IDs to the same items, and due to the way catalog fencing works,
1141    /// only one of them can successfully write the IDs down to the catalog. This removes the need
1142    /// for `environmentd` processes to coordinate system IDs allocated during read-only mode.
1143    ///
1144    /// Since introspection IDs can be allocated at any time, read-only instances would either need
1145    /// to coordinate across processes when allocating a new ID or allocate them deterministically.
1146    /// We opted to allocate the IDs deterministically to avoid the overhead of coordination.
1147    ///
1148    /// Introspection source index IDs are 64 bit integers, with the following format (not to
1149    /// scale):
1150    ///
1151    /// -------------------------------------------------------------
1152    /// | Cluster ID Variant | Cluster ID Inner Value | Log Variant |
1153    /// |--------------------|------------------------|-------------|
1154    /// |       8-bits       |         48-bits        |   8-bits    |
1155    /// -------------------------------------------------------------
1156    ///
1157    /// Cluster ID Variant:      A unique number indicating the variant of cluster the index belongs
1158    ///                          to.
1159    /// Cluster ID Inner Value:  A per variant unique number indicating the cluster the index
1160    ///                          belongs to.
1161    /// Log Variant:             A unique number indicating the log variant this index is on.
1162    pub fn allocate_introspection_source_index_id(
1163        cluster_id: &ClusterId,
1164        log_variant: LogVariant,
1165    ) -> (CatalogItemId, GlobalId) {
1166        let cluster_variant: u8 = match cluster_id {
1167            ClusterId::System(_) => 1,
1168            ClusterId::User(_) => 2,
1169        };
1170        let cluster_id: u64 = cluster_id.inner_id();
1171        const CLUSTER_ID_MASK: u64 = 0xFFFF << 48;
1172        assert_eq!(
1173            CLUSTER_ID_MASK & cluster_id,
1174            0,
1175            "invalid cluster ID: {cluster_id}"
1176        );
1177        let log_variant: u8 = match log_variant {
1178            LogVariant::Timely(TimelyLog::Operates) => 1,
1179            LogVariant::Timely(TimelyLog::Channels) => 2,
1180            LogVariant::Timely(TimelyLog::Elapsed) => 3,
1181            LogVariant::Timely(TimelyLog::Histogram) => 4,
1182            LogVariant::Timely(TimelyLog::Addresses) => 5,
1183            LogVariant::Timely(TimelyLog::Parks) => 6,
1184            LogVariant::Timely(TimelyLog::MessagesSent) => 7,
1185            LogVariant::Timely(TimelyLog::MessagesReceived) => 8,
1186            LogVariant::Timely(TimelyLog::Reachability) => 9,
1187            LogVariant::Timely(TimelyLog::BatchesSent) => 10,
1188            LogVariant::Timely(TimelyLog::BatchesReceived) => 11,
1189            LogVariant::Differential(DifferentialLog::ArrangementBatches) => 12,
1190            LogVariant::Differential(DifferentialLog::ArrangementRecords) => 13,
1191            LogVariant::Differential(DifferentialLog::Sharing) => 14,
1192            LogVariant::Differential(DifferentialLog::BatcherRecords) => 15,
1193            LogVariant::Differential(DifferentialLog::BatcherSize) => 16,
1194            LogVariant::Differential(DifferentialLog::BatcherCapacity) => 17,
1195            LogVariant::Differential(DifferentialLog::BatcherAllocations) => 18,
1196            LogVariant::Compute(ComputeLog::DataflowCurrent) => 19,
1197            LogVariant::Compute(ComputeLog::FrontierCurrent) => 20,
1198            LogVariant::Compute(ComputeLog::PeekCurrent) => 21,
1199            LogVariant::Compute(ComputeLog::PeekDuration) => 22,
1200            LogVariant::Compute(ComputeLog::ImportFrontierCurrent) => 23,
1201            LogVariant::Compute(ComputeLog::ArrangementHeapSize) => 24,
1202            LogVariant::Compute(ComputeLog::ArrangementHeapCapacity) => 25,
1203            LogVariant::Compute(ComputeLog::ArrangementHeapAllocations) => 26,
1204            LogVariant::Compute(ComputeLog::ErrorCount) => 28,
1205            LogVariant::Compute(ComputeLog::HydrationTime) => 29,
1206            LogVariant::Compute(ComputeLog::LirMapping) => 30,
1207            LogVariant::Compute(ComputeLog::DataflowGlobal) => 31,
1208            LogVariant::Compute(ComputeLog::OperatorHydrationStatus) => 32,
1209            LogVariant::Compute(ComputeLog::PrometheusMetrics) => 33,
1210            LogVariant::Compute(ComputeLog::ResourceUsage) => 34,
1211        };
1212
1213        let mut id: u64 = u64::from(cluster_variant) << 56;
1214        id |= cluster_id << 8;
1215        id |= u64::from(log_variant);
1216
1217        (
1218            CatalogItemId::IntrospectionSourceIndex(id),
1219            GlobalId::IntrospectionSourceIndex(id),
1220        )
1221    }
1222
1223    pub fn allocate_user_item_ids(
1224        &mut self,
1225        amount: u64,
1226    ) -> Result<Vec<(CatalogItemId, GlobalId)>, CatalogError> {
1227        Ok(self
1228            .get_and_increment_id_by(USER_ITEM_ALLOC_KEY.to_string(), amount)?
1229            .into_iter()
1230            // TODO(alter_table): Use separate ID allocators.
1231            .map(|x| (CatalogItemId::User(x), GlobalId::User(x)))
1232            .collect())
1233    }
1234
1235    pub fn allocate_system_replica_id(&mut self) -> Result<ReplicaId, CatalogError> {
1236        let id = self.get_and_increment_id(SYSTEM_REPLICA_ID_ALLOC_KEY.to_string())?;
1237        Ok(ReplicaId::System(id))
1238    }
1239
1240    pub fn allocate_audit_log_id(&mut self) -> Result<u64, CatalogError> {
1241        self.get_and_increment_id(AUDIT_LOG_ID_ALLOC_KEY.to_string())
1242    }
1243
1244    /// Allocates `amount` OIDs. OIDs can be recycled if they aren't currently assigned to any
1245    /// object.
1246    #[mz_ore::instrument]
1247    fn allocate_oids(
1248        &mut self,
1249        amount: u64,
1250        temporary_oids: &HashSet<u32>,
1251    ) -> Result<Vec<u32>, CatalogError> {
1252        /// Struct representing an OID for a user object. Allocated OIDs can be recycled, so when we've
1253        /// allocated [`u32::MAX`] we'll wrap back around to [`FIRST_USER_OID`].
1254        struct UserOid(u32);
1255
1256        impl UserOid {
1257            fn new(oid: u32) -> Result<UserOid, anyhow::Error> {
1258                if oid < FIRST_USER_OID {
1259                    Err(anyhow!("invalid user OID {oid}"))
1260                } else {
1261                    Ok(UserOid(oid))
1262                }
1263            }
1264        }
1265
1266        impl std::ops::AddAssign<u32> for UserOid {
1267            fn add_assign(&mut self, rhs: u32) {
1268                let (res, overflow) = self.0.overflowing_add(rhs);
1269                self.0 = if overflow { FIRST_USER_OID + res } else { res };
1270            }
1271        }
1272
1273        if amount > u32::MAX.into() {
1274            return Err(CatalogError::Catalog(SqlCatalogError::OidExhaustion));
1275        }
1276
1277        // This is potentially slow to do everytime we allocate an OID. A faster approach might be
1278        // to have an ID allocator that is updated everytime an OID is allocated or de-allocated.
1279        // However, benchmarking shows that this doesn't make a noticeable difference and the other
1280        // approach requires making sure that allocator always stays in-sync which can be
1281        // error-prone. If DDL starts slowing down, this is a good place to try and optimize.
1282        let mut allocated_oids = HashSet::with_capacity(
1283            self.databases.len()
1284                + self.schemas.len()
1285                + self.roles.len()
1286                + self.query_policies.len()
1287                + self.items.len()
1288                + self.introspection_sources.len()
1289                + temporary_oids.len(),
1290        );
1291        self.databases.for_values(|_, value| {
1292            allocated_oids.insert(value.oid);
1293        });
1294        self.schemas.for_values(|_, value| {
1295            allocated_oids.insert(value.oid);
1296        });
1297        self.roles.for_values(|_, value| {
1298            allocated_oids.insert(value.oid);
1299        });
1300        self.query_policies.for_values(|_, value| {
1301            allocated_oids.insert(value.oid);
1302        });
1303        self.items.for_values(|_, value| {
1304            allocated_oids.insert(value.oid);
1305        });
1306        self.introspection_sources.for_values(|_, value| {
1307            allocated_oids.insert(value.oid);
1308        });
1309
1310        let is_allocated = |oid| allocated_oids.contains(&oid) || temporary_oids.contains(&oid);
1311
1312        let start_oid: u32 = self
1313            .id_allocator
1314            .items()
1315            .get(&IdAllocKey {
1316                name: OID_ALLOC_KEY.to_string(),
1317            })
1318            .unwrap_or_else(|| panic!("{OID_ALLOC_KEY} id allocator missing"))
1319            .next_id
1320            .try_into()
1321            .expect("we should never persist an oid outside of the u32 range");
1322        let mut current_oid = UserOid::new(start_oid)
1323            .expect("we should never persist an oid outside of user OID range");
1324        let mut oids = Vec::new();
1325        while oids.len() < u64_to_usize(amount) {
1326            if !is_allocated(current_oid.0) {
1327                oids.push(current_oid.0);
1328            }
1329            current_oid += 1;
1330
1331            if current_oid.0 == start_oid && oids.len() < u64_to_usize(amount) {
1332                // We've exhausted all possible OIDs and still don't have `amount`.
1333                return Err(CatalogError::Catalog(SqlCatalogError::OidExhaustion));
1334            }
1335        }
1336
1337        let next_id = current_oid.0;
1338        let prev = self.id_allocator.set(
1339            IdAllocKey {
1340                name: OID_ALLOC_KEY.to_string(),
1341            },
1342            Some(IdAllocValue {
1343                next_id: next_id.into(),
1344            }),
1345            self.op_id,
1346        )?;
1347        assert_eq!(
1348            prev,
1349            Some(IdAllocValue {
1350                next_id: start_oid.into(),
1351            })
1352        );
1353
1354        Ok(oids)
1355    }
1356
1357    /// Allocates a single OID. OIDs can be recycled if they aren't currently assigned to any
1358    /// object.
1359    pub fn allocate_oid(&mut self, temporary_oids: &HashSet<u32>) -> Result<u32, CatalogError> {
1360        self.allocate_oids(1, temporary_oids)
1361            .map(|oids| oids.into_element())
1362    }
1363
1364    /// Creates a noncommittable fork of the current table contents, including pending writes.
1365    ///
1366    /// Changes to the fork are discarded. Pending audit events stay with the parent.
1367    /// This copies the full catalog snapshot and borrows the parent's durable handle.
1368    pub fn fork_dry_run(&mut self) -> Result<DryRunTransaction<'_>, CatalogError> {
1369        let snapshot = self.current_snapshot();
1370        let upper = self.upper;
1371        Transaction::new(&mut *self.durable_catalog, snapshot, upper).map(DryRunTransaction::new)
1372    }
1373
1374    /// Exports the current state of this transaction as a [`Snapshot`].
1375    ///
1376    /// This merges each `TableTransaction`'s initial data with its pending
1377    /// changes to produce the current view, then converts back to proto types.
1378    /// Used to persist transaction state between incremental DDL dry runs so
1379    /// the next dry run's fresh `Transaction` starts in sync with the
1380    /// accumulated `CatalogState`.
1381    pub fn current_snapshot(&self) -> Snapshot {
1382        Snapshot {
1383            databases: self.databases.current_items_proto(),
1384            schemas: self.schemas.current_items_proto(),
1385            roles: self.roles.current_items_proto(),
1386            role_auth: self.role_auth.current_items_proto(),
1387            items: self.items.current_items_proto(),
1388            item_columns: self.item_columns.current_items_proto(),
1389            index_columns: self.index_columns.current_items_proto(),
1390            comments: self.comments.current_items_proto(),
1391            clusters: self.clusters.current_items_proto(),
1392            network_policies: self.network_policies.current_items_proto(),
1393            cluster_replica_sizes: self.cluster_replica_sizes.current_items_proto(),
1394            query_policies: self.query_policies.current_items_proto(),
1395            cluster_replicas: self.cluster_replicas.current_items_proto(),
1396            introspection_sources: self.introspection_sources.current_items_proto(),
1397            id_allocator: self.id_allocator.current_items_proto(),
1398            configs: self.configs.current_items_proto(),
1399            settings: self.settings.current_items_proto(),
1400            system_object_mappings: self.system_gid_mapping.current_items_proto(),
1401            system_configurations: self.system_configurations.current_items_proto(),
1402            cluster_system_configurations: self.cluster_system_configurations.current_items_proto(),
1403            replica_system_configurations: self.replica_system_configurations.current_items_proto(),
1404            default_privileges: self.default_privileges.current_items_proto(),
1405            source_references: self.source_references.current_items_proto(),
1406            system_privileges: self.system_privileges.current_items_proto(),
1407            storage_collection_metadata: self.storage_collection_metadata.current_items_proto(),
1408            unfinalized_shards: self.unfinalized_shards.current_items_proto(),
1409            txn_wal_shard: self.txn_wal_shard.current_items_proto(),
1410        }
1411    }
1412
1413    pub(crate) fn insert_id_allocator(
1414        &mut self,
1415        name: String,
1416        next_id: u64,
1417    ) -> Result<(), CatalogError> {
1418        match self.id_allocator.insert(
1419            IdAllocKey { name: name.clone() },
1420            IdAllocValue { next_id },
1421            self.op_id,
1422        ) {
1423            Ok(_) => Ok(()),
1424            Err(_) => Err(SqlCatalogError::IdAllocatorAlreadyExists(name).into()),
1425        }
1426    }
1427
1428    /// Removes the database `id` from the transaction.
1429    ///
1430    /// Returns an error if `id` is not found.
1431    ///
1432    /// Runtime is linear with respect to the total number of databases in the catalog.
1433    /// DO NOT call this function in a loop, use [`Self::remove_databases`] instead.
1434    pub fn remove_database(&mut self, id: &DatabaseId) -> Result<(), CatalogError> {
1435        let prev = self
1436            .databases
1437            .set(DatabaseKey { id: *id }, None, self.op_id)?;
1438        if prev.is_some() {
1439            Ok(())
1440        } else {
1441            Err(SqlCatalogError::UnknownDatabase(id.to_string()).into())
1442        }
1443    }
1444
1445    /// Removes all databases in `databases` from the transaction.
1446    ///
1447    /// Returns an error if any id in `databases` is not found.
1448    ///
1449    /// NOTE: On error, there still may be some databases removed from the transaction. It
1450    /// is up to the caller to either abort the transaction or commit.
1451    pub fn remove_databases(
1452        &mut self,
1453        databases: &BTreeSet<DatabaseId>,
1454    ) -> Result<(), CatalogError> {
1455        if databases.is_empty() {
1456            return Ok(());
1457        }
1458
1459        let to_remove = databases
1460            .iter()
1461            .map(|id| (DatabaseKey { id: *id }, None))
1462            .collect();
1463        let mut prev = self.databases.set_many(to_remove, self.op_id)?;
1464        prev.retain(|_k, val| val.is_none());
1465
1466        if !prev.is_empty() {
1467            let err = prev.keys().map(|k| k.id.to_string()).join(", ");
1468            return Err(SqlCatalogError::UnknownDatabase(err).into());
1469        }
1470
1471        Ok(())
1472    }
1473
1474    /// Removes the schema identified by `database_id` and `schema_id` from the transaction.
1475    ///
1476    /// Returns an error if `(database_id, schema_id)` is not found.
1477    ///
1478    /// Runtime is linear with respect to the total number of schemas in the catalog.
1479    /// DO NOT call this function in a loop, use [`Self::remove_schemas`] instead.
1480    pub fn remove_schema(
1481        &mut self,
1482        database_id: &Option<DatabaseId>,
1483        schema_id: &SchemaId,
1484    ) -> Result<(), CatalogError> {
1485        let prev = self
1486            .schemas
1487            .set(SchemaKey { id: *schema_id }, None, self.op_id)?;
1488        if prev.is_some() {
1489            Ok(())
1490        } else {
1491            let database_name = match database_id {
1492                Some(id) => format!("{id}."),
1493                None => "".to_string(),
1494            };
1495            Err(SqlCatalogError::UnknownSchema(format!("{}.{}", database_name, schema_id)).into())
1496        }
1497    }
1498
1499    /// Removes all schemas in `schemas` from the transaction.
1500    ///
1501    /// Returns an error if any id in `schemas` is not found.
1502    ///
1503    /// NOTE: On error, there still may be some schemas removed from the transaction. It
1504    /// is up to the caller to either abort the transaction or commit.
1505    pub fn remove_schemas(
1506        &mut self,
1507        schemas: &BTreeMap<SchemaId, ResolvedDatabaseSpecifier>,
1508    ) -> Result<(), CatalogError> {
1509        if schemas.is_empty() {
1510            return Ok(());
1511        }
1512
1513        let to_remove = schemas
1514            .iter()
1515            .map(|(schema_id, _)| (SchemaKey { id: *schema_id }, None))
1516            .collect();
1517        let mut prev = self.schemas.set_many(to_remove, self.op_id)?;
1518        prev.retain(|_k, v| v.is_none());
1519
1520        if !prev.is_empty() {
1521            let err = prev
1522                .keys()
1523                .map(|k| {
1524                    let db_spec = schemas.get(&k.id).expect("should_exist");
1525                    let db_name = match db_spec {
1526                        ResolvedDatabaseSpecifier::Id(id) => format!("{id}."),
1527                        ResolvedDatabaseSpecifier::Ambient => "".to_string(),
1528                    };
1529                    format!("{}.{}", db_name, k.id)
1530                })
1531                .join(", ");
1532
1533            return Err(SqlCatalogError::UnknownSchema(err).into());
1534        }
1535
1536        Ok(())
1537    }
1538
1539    pub fn remove_source_references(
1540        &mut self,
1541        source_id: CatalogItemId,
1542    ) -> Result<(), CatalogError> {
1543        let deleted = self
1544            .source_references
1545            .delete_by_key(SourceReferencesKey { source_id }, self.op_id)
1546            .is_some();
1547        if deleted {
1548            Ok(())
1549        } else {
1550            Err(SqlCatalogError::UnknownItem(source_id.to_string()).into())
1551        }
1552    }
1553
1554    /// Removes all user roles in `roles` from the transaction.
1555    ///
1556    /// Returns an error if any id in `roles` is not found.
1557    ///
1558    /// NOTE: On error, there still may be some roles removed from the transaction. It
1559    /// is up to the caller to either abort the transaction or commit.
1560    pub fn remove_user_roles(&mut self, roles: &BTreeSet<RoleId>) -> Result<(), CatalogError> {
1561        assert!(
1562            roles.iter().all(|id| id.is_user()),
1563            "cannot delete non-user roles"
1564        );
1565        self.remove_roles(roles)
1566    }
1567
1568    /// Removes all roles in `roles` from the transaction.
1569    ///
1570    /// Returns an error if any id in `roles` is not found.
1571    ///
1572    /// NOTE: On error, there still may be some roles removed from the transaction. It
1573    /// is up to the caller to either abort the transaction or commit.
1574    pub fn remove_roles(&mut self, roles: &BTreeSet<RoleId>) -> Result<(), CatalogError> {
1575        if roles.is_empty() {
1576            return Ok(());
1577        }
1578
1579        let to_remove_keys = roles
1580            .iter()
1581            .map(|role_id| RoleKey { id: *role_id })
1582            .collect::<Vec<_>>();
1583
1584        let to_remove_roles = to_remove_keys
1585            .iter()
1586            .map(|role_key| (role_key.clone(), None))
1587            .collect();
1588
1589        let mut prev = self.roles.set_many(to_remove_roles, self.op_id)?;
1590
1591        let to_remove_role_auth = to_remove_keys
1592            .iter()
1593            .map(|role_key| {
1594                (
1595                    RoleAuthKey {
1596                        role_id: role_key.id,
1597                    },
1598                    None,
1599                )
1600            })
1601            .collect();
1602
1603        let mut role_auth_prev = self.role_auth.set_many(to_remove_role_auth, self.op_id)?;
1604
1605        prev.retain(|_k, v| v.is_none());
1606        if !prev.is_empty() {
1607            let err = prev.keys().map(|k| k.id.to_string()).join(", ");
1608            return Err(SqlCatalogError::UnknownRole(err).into());
1609        }
1610
1611        role_auth_prev.retain(|_k, v| v.is_none());
1612        // The reason we don't to the same check as above is that the role auth table
1613        // is not required to have all roles in the role table.
1614
1615        Ok(())
1616    }
1617
1618    /// Removes all cluster in `clusters` from the transaction.
1619    ///
1620    /// Returns an error if any id in `clusters` is not found.
1621    ///
1622    /// NOTE: On error, there still may be some clusters removed from the transaction. It is up to
1623    /// the caller to either abort the transaction or commit.
1624    pub fn remove_clusters(&mut self, clusters: &BTreeSet<ClusterId>) -> Result<(), CatalogError> {
1625        if clusters.is_empty() {
1626            return Ok(());
1627        }
1628
1629        let to_remove = clusters
1630            .iter()
1631            .map(|cluster_id| (ClusterKey { id: *cluster_id }, None))
1632            .collect();
1633        let mut prev = self.clusters.set_many(to_remove, self.op_id)?;
1634
1635        prev.retain(|_k, v| v.is_none());
1636        if !prev.is_empty() {
1637            let err = prev.keys().map(|k| k.id.to_string()).join(", ");
1638            return Err(SqlCatalogError::UnknownCluster(err).into());
1639        }
1640
1641        // Cascade delete introspection sources and cluster replicas.
1642        //
1643        // TODO(benesch): this doesn't seem right. Cascade deletions should
1644        // be entirely the domain of the higher catalog layer, not the
1645        // storage layer.
1646        self.cluster_replicas
1647            .delete(|_k, v| clusters.contains(&v.cluster_id), self.op_id);
1648        self.introspection_sources
1649            .delete(|k, _v| clusters.contains(&k.cluster_id), self.op_id);
1650
1651        Ok(())
1652    }
1653
1654    /// Removes the cluster replica `id` from the transaction.
1655    ///
1656    /// Returns an error if `id` is not found.
1657    ///
1658    /// Runtime is linear with respect to the total number of cluster replicas in the catalog.
1659    /// DO NOT call this function in a loop, use [`Self::remove_cluster_replicas`] instead.
1660    pub fn remove_cluster_replica(&mut self, id: ReplicaId) -> Result<(), CatalogError> {
1661        let deleted = self
1662            .cluster_replicas
1663            .delete_by_key(ClusterReplicaKey { id }, self.op_id)
1664            .is_some();
1665        if deleted {
1666            Ok(())
1667        } else {
1668            Err(SqlCatalogError::UnknownClusterReplica(id.to_string()).into())
1669        }
1670    }
1671
1672    /// Removes all cluster replicas in `replicas` from the transaction.
1673    ///
1674    /// Returns an error if any id in `replicas` is not found.
1675    ///
1676    /// NOTE: On error, there still may be some cluster replicas removed from the transaction. It
1677    /// is up to the caller to either abort the transaction or commit.
1678    pub fn remove_cluster_replicas(
1679        &mut self,
1680        replicas: &BTreeSet<ReplicaId>,
1681    ) -> Result<(), CatalogError> {
1682        if replicas.is_empty() {
1683            return Ok(());
1684        }
1685
1686        let to_remove = replicas
1687            .iter()
1688            .map(|replica_id| (ClusterReplicaKey { id: *replica_id }, None))
1689            .collect();
1690        let mut prev = self.cluster_replicas.set_many(to_remove, self.op_id)?;
1691
1692        prev.retain(|_k, v| v.is_none());
1693        if !prev.is_empty() {
1694            let err = prev.keys().map(|k| k.id.to_string()).join(", ");
1695            return Err(SqlCatalogError::UnknownClusterReplica(err).into());
1696        }
1697
1698        Ok(())
1699    }
1700
1701    /// Removes item `id` from the transaction.
1702    ///
1703    /// Returns an error if `id` is not found.
1704    ///
1705    /// Runtime is linear with respect to the total number of items in the catalog.
1706    /// DO NOT call this function in a loop, use [`Self::remove_items`] instead.
1707    pub fn remove_item(&mut self, id: CatalogItemId) -> Result<(), CatalogError> {
1708        let prev = self.items.set(ItemKey { id }, None, self.op_id)?;
1709        if prev.is_some() {
1710            self.delete_item_metadata(id);
1711            Ok(())
1712        } else {
1713            Err(SqlCatalogError::UnknownItem(id.to_string()).into())
1714        }
1715    }
1716
1717    /// Removes all items in `ids` from the transaction.
1718    ///
1719    /// Returns an error if any id in `ids` is not found.
1720    ///
1721    /// NOTE: On error, there still may be some items removed from the transaction. It is
1722    /// up to the caller to either abort the transaction or commit.
1723    pub fn remove_items(&mut self, ids: &BTreeSet<CatalogItemId>) -> Result<(), CatalogError> {
1724        if ids.is_empty() {
1725            return Ok(());
1726        }
1727
1728        let ks: Vec<_> = ids.clone().into_iter().map(|id| ItemKey { id }).collect();
1729        let n = self.items.delete_by_keys(ks, self.op_id).len();
1730        for id in ids {
1731            self.delete_item_metadata(*id);
1732        }
1733        if n == ids.len() {
1734            Ok(())
1735        } else {
1736            let item_ids = self.items.items().keys().map(|k| k.id).collect();
1737            let mut unknown = ids.difference(&item_ids);
1738            Err(SqlCatalogError::UnknownItem(unknown.join(", ")).into())
1739        }
1740    }
1741
1742    /// Removes all system object mappings in `descriptions` from the transaction.
1743    ///
1744    /// Returns an error if any description in `descriptions` is not found.
1745    ///
1746    /// NOTE: On error, there still may be some items removed from the transaction. It is
1747    /// up to the caller to either abort the transaction or commit.
1748    pub fn remove_system_object_mappings(
1749        &mut self,
1750        descriptions: BTreeSet<SystemObjectDescription>,
1751    ) -> Result<(), CatalogError> {
1752        if descriptions.is_empty() {
1753            return Ok(());
1754        }
1755
1756        let ks: Vec<_> = descriptions
1757            .clone()
1758            .into_iter()
1759            .map(|desc| GidMappingKey {
1760                schema_name: desc.schema_name,
1761                object_type: desc.object_type,
1762                object_name: desc.object_name,
1763            })
1764            .collect();
1765        let n = self.system_gid_mapping.delete_by_keys(ks, self.op_id).len();
1766
1767        if n == descriptions.len() {
1768            Ok(())
1769        } else {
1770            let item_descriptions = self
1771                .system_gid_mapping
1772                .items()
1773                .keys()
1774                .map(|k| SystemObjectDescription {
1775                    schema_name: k.schema_name.clone(),
1776                    object_type: k.object_type.clone(),
1777                    object_name: k.object_name.clone(),
1778                })
1779                .collect();
1780            let mut unknown = descriptions.difference(&item_descriptions).map(|desc| {
1781                format!(
1782                    "{} {}.{}",
1783                    desc.object_type, desc.schema_name, desc.object_name
1784                )
1785            });
1786            Err(SqlCatalogError::UnknownItem(unknown.join(", ")).into())
1787        }
1788    }
1789
1790    /// Removes all introspection source indexes in `indexes` from the transaction.
1791    ///
1792    /// Returns an error if any index in `indexes` is not found.
1793    ///
1794    /// NOTE: On error, there still may be some indexes removed from the transaction. It is
1795    /// up to the caller to either abort the transaction or commit.
1796    pub fn remove_introspection_source_indexes(
1797        &mut self,
1798        introspection_source_indexes: BTreeSet<(ClusterId, String)>,
1799    ) -> Result<(), CatalogError> {
1800        if introspection_source_indexes.is_empty() {
1801            return Ok(());
1802        }
1803
1804        let ks: Vec<_> = introspection_source_indexes
1805            .clone()
1806            .into_iter()
1807            .map(|(cluster_id, name)| ClusterIntrospectionSourceIndexKey { cluster_id, name })
1808            .collect();
1809        let n = self
1810            .introspection_sources
1811            .delete_by_keys(ks, self.op_id)
1812            .len();
1813        if n == introspection_source_indexes.len() {
1814            Ok(())
1815        } else {
1816            let txn_indexes = self
1817                .introspection_sources
1818                .items()
1819                .keys()
1820                .map(|k| (k.cluster_id, k.name.clone()))
1821                .collect();
1822            let mut unknown = introspection_source_indexes
1823                .difference(&txn_indexes)
1824                .map(|(cluster_id, name)| format!("{cluster_id} {name}"));
1825            Err(SqlCatalogError::UnknownItem(unknown.join(", ")).into())
1826        }
1827    }
1828
1829    /// Updates item `id` in the transaction to `item_name` and `item`.
1830    ///
1831    /// Returns an error if `id` is not found.
1832    ///
1833    /// Runtime is linear with respect to the total number of items in the catalog.
1834    /// DO NOT call this function in a loop, use [`Self::update_items`] instead.
1835    pub fn update_item(&mut self, id: CatalogItemId, item: Item) -> Result<(), CatalogError> {
1836        let updated =
1837            self.items
1838                .update_by_key(ItemKey { id }, item.into_key_value().1, self.op_id)?;
1839        if updated {
1840            Ok(())
1841        } else {
1842            Err(SqlCatalogError::UnknownItem(id.to_string()).into())
1843        }
1844    }
1845
1846    /// Updates all items with ids matching the keys of `items` in the transaction, to the
1847    /// corresponding value in `items`.
1848    ///
1849    /// Returns an error if any id in `items` is not found.
1850    ///
1851    /// NOTE: On error, there still may be some items updated in the transaction. It is
1852    /// up to the caller to either abort the transaction or commit.
1853    pub fn update_items(
1854        &mut self,
1855        items: BTreeMap<CatalogItemId, Item>,
1856    ) -> Result<(), CatalogError> {
1857        if items.is_empty() {
1858            return Ok(());
1859        }
1860
1861        let update_ids: BTreeSet<_> = items.keys().cloned().collect();
1862        let kvs: Vec<_> = items
1863            .clone()
1864            .into_iter()
1865            .map(|(id, item)| (ItemKey { id }, item.into_key_value().1))
1866            .collect();
1867        let n = self.items.update_by_keys(kvs, self.op_id)?;
1868        let n = usize::try_from(n.into_inner()).expect("Must be positive and fit in usize");
1869        if n == update_ids.len() {
1870            Ok(())
1871        } else {
1872            let item_ids: BTreeSet<_> = self.items.items().keys().map(|k| k.id).collect();
1873            let mut unknown = update_ids.difference(&item_ids);
1874            Err(SqlCatalogError::UnknownItem(unknown.join(", ")).into())
1875        }
1876    }
1877
1878    /// Updates role `id` in the transaction to `role`.
1879    ///
1880    /// Returns an error if `id` is not found.
1881    ///
1882    /// Runtime is linear with respect to the total number of items in the catalog.
1883    /// DO NOT call this function in a loop, implement and use some `Self::update_roles` instead.
1884    /// You should model it after [`Self::update_items`].
1885    pub fn update_role(
1886        &mut self,
1887        id: RoleId,
1888        role: Role,
1889        password: PasswordAction,
1890    ) -> Result<(), CatalogError> {
1891        let key = RoleKey { id };
1892        if self.roles.get(&key).is_some() {
1893            let auth_key = RoleAuthKey { role_id: id };
1894
1895            match password {
1896                PasswordAction::Set(new_password) => {
1897                    let hash = mz_auth::hash::scram256_hash(
1898                        &new_password.password,
1899                        &new_password.scram_iterations,
1900                    )
1901                    .expect("password hash should be valid");
1902                    let value = RoleAuthValue {
1903                        password_hash: Some(hash),
1904                        updated_at: SYSTEM_TIME(),
1905                    };
1906
1907                    if self.role_auth.get(&auth_key).is_some() {
1908                        self.role_auth
1909                            .update_by_key(auth_key.clone(), value, self.op_id)?;
1910                    } else {
1911                        self.role_auth.insert(auth_key.clone(), value, self.op_id)?;
1912                    }
1913                }
1914                PasswordAction::Clear => {
1915                    let value = RoleAuthValue {
1916                        password_hash: None,
1917                        updated_at: SYSTEM_TIME(),
1918                    };
1919                    if self.role_auth.get(&auth_key).is_some() {
1920                        self.role_auth
1921                            .update_by_key(auth_key.clone(), value, self.op_id)?;
1922                    }
1923                }
1924                PasswordAction::NoChange => {}
1925            }
1926
1927            self.roles
1928                .update_by_key(key, role.into_key_value().1, self.op_id)?;
1929
1930            Ok(())
1931        } else {
1932            Err(SqlCatalogError::UnknownRole(id.to_string()).into())
1933        }
1934    }
1935
1936    /// Updates all [`Role`]s with ids matching the keys of `roles` in the transaction, to the
1937    /// corresponding value in `roles`.
1938    ///
1939    /// This function does *not* write role_authentication information to the catalog.
1940    /// It is purely for updating the role itself.
1941    ///
1942    /// Returns an error if any id in `roles` is not found.
1943    ///
1944    /// NOTE: On error, there still may be some roles updated in the transaction. It is
1945    /// up to the caller to either abort the transaction or commit.
1946    pub fn update_roles_without_auth(
1947        &mut self,
1948        roles: BTreeMap<RoleId, Role>,
1949    ) -> Result<(), CatalogError> {
1950        if roles.is_empty() {
1951            return Ok(());
1952        }
1953
1954        let update_role_ids: BTreeSet<_> = roles.keys().cloned().collect();
1955        let kvs: Vec<_> = roles
1956            .into_iter()
1957            .map(|(id, role)| (RoleKey { id }, role.into_key_value().1))
1958            .collect();
1959        let n = self.roles.update_by_keys(kvs, self.op_id)?;
1960        let n = usize::try_from(n.into_inner()).expect("Must be positive and fit in usize");
1961
1962        if n == update_role_ids.len() {
1963            Ok(())
1964        } else {
1965            let role_ids: BTreeSet<_> = self.roles.items().keys().map(|k| k.id).collect();
1966            let mut unknown = update_role_ids.difference(&role_ids);
1967            Err(SqlCatalogError::UnknownRole(unknown.join(", ")).into())
1968        }
1969    }
1970
1971    /// Updates persisted mapping from system objects to global IDs and fingerprints. Each element
1972    /// of `mappings` should be (old-global-id, new-system-object-mapping).
1973    ///
1974    /// Panics if provided id is not a system id.
1975    pub fn update_system_object_mappings(
1976        &mut self,
1977        mappings: BTreeMap<CatalogItemId, SystemObjectMapping>,
1978    ) -> Result<(), CatalogError> {
1979        if mappings.is_empty() {
1980            return Ok(());
1981        }
1982
1983        let n = self.system_gid_mapping.update(
1984            |_k, v| {
1985                if let Some(mapping) = mappings.get(&CatalogItemId::from(v.catalog_id)) {
1986                    let (_, new_value) = mapping.clone().into_key_value();
1987                    Some(new_value)
1988                } else {
1989                    None
1990                }
1991            },
1992            self.op_id,
1993        )?;
1994
1995        if usize::try_from(n.into_inner()).expect("update diff should fit into usize")
1996            != mappings.len()
1997        {
1998            let id_str = mappings.keys().map(|id| id.to_string()).join(",");
1999            return Err(SqlCatalogError::FailedBuiltinSchemaMigration(id_str).into());
2000        }
2001
2002        Ok(())
2003    }
2004
2005    /// Updates cluster `id` in the transaction to `cluster`.
2006    ///
2007    /// Returns an error if `id` is not found.
2008    ///
2009    /// Runtime is linear with respect to the total number of clusters in the catalog.
2010    /// DO NOT call this function in a loop.
2011    pub fn update_cluster(&mut self, id: ClusterId, cluster: Cluster) -> Result<(), CatalogError> {
2012        self.validate_query_policy_reference(cluster.config.query_policy)?;
2013        let updated = self.clusters.update_by_key(
2014            ClusterKey { id },
2015            cluster.into_key_value().1,
2016            self.op_id,
2017        )?;
2018        if updated {
2019            Ok(())
2020        } else {
2021            Err(SqlCatalogError::UnknownCluster(id.to_string()).into())
2022        }
2023    }
2024
2025    /// Updates cluster replica `replica_id` in the transaction to `replica`.
2026    ///
2027    /// Returns an error if `replica_id` is not found.
2028    ///
2029    /// Runtime is linear with respect to the total number of cluster replicas in the catalog.
2030    /// DO NOT call this function in a loop.
2031    pub fn update_cluster_replica(
2032        &mut self,
2033        replica_id: ReplicaId,
2034        replica: ClusterReplica,
2035    ) -> Result<(), CatalogError> {
2036        let updated = self.cluster_replicas.update_by_key(
2037            ClusterReplicaKey { id: replica_id },
2038            replica.into_key_value().1,
2039            self.op_id,
2040        )?;
2041        if updated {
2042            Ok(())
2043        } else {
2044            Err(SqlCatalogError::UnknownClusterReplica(replica_id.to_string()).into())
2045        }
2046    }
2047
2048    /// Updates database `id` in the transaction to `database`.
2049    ///
2050    /// Returns an error if `id` is not found.
2051    ///
2052    /// Runtime is linear with respect to the total number of databases in the catalog.
2053    /// DO NOT call this function in a loop.
2054    pub fn update_database(
2055        &mut self,
2056        id: DatabaseId,
2057        database: Database,
2058    ) -> Result<(), CatalogError> {
2059        let updated = self.databases.update_by_key(
2060            DatabaseKey { id },
2061            database.into_key_value().1,
2062            self.op_id,
2063        )?;
2064        if updated {
2065            Ok(())
2066        } else {
2067            Err(SqlCatalogError::UnknownDatabase(id.to_string()).into())
2068        }
2069    }
2070
2071    /// Updates schema `schema_id` in the transaction to `schema`.
2072    ///
2073    /// Returns an error if `schema_id` is not found.
2074    ///
2075    /// Runtime is linear with respect to the total number of schemas in the catalog.
2076    /// DO NOT call this function in a loop.
2077    pub fn update_schema(
2078        &mut self,
2079        schema_id: SchemaId,
2080        schema: Schema,
2081    ) -> Result<(), CatalogError> {
2082        let updated = self.schemas.update_by_key(
2083            SchemaKey { id: schema_id },
2084            schema.into_key_value().1,
2085            self.op_id,
2086        )?;
2087        if updated {
2088            Ok(())
2089        } else {
2090            Err(SqlCatalogError::UnknownSchema(schema_id.to_string()).into())
2091        }
2092    }
2093
2094    /// Updates `network_policy_id` in the transaction to `network policy`.
2095    ///
2096    /// Returns an error if `id` is not found.
2097    ///
2098    /// Runtime is linear with respect to the total number of databases in the catalog.
2099    /// DO NOT call this function in a loop.
2100    pub fn update_network_policy(
2101        &mut self,
2102        id: NetworkPolicyId,
2103        network_policy: NetworkPolicy,
2104    ) -> Result<(), CatalogError> {
2105        let updated = self.network_policies.update_by_key(
2106            NetworkPolicyKey { id },
2107            network_policy.into_key_value().1,
2108            self.op_id,
2109        )?;
2110        if updated {
2111            Ok(())
2112        } else {
2113            Err(SqlCatalogError::UnknownNetworkPolicy(id.to_string()).into())
2114        }
2115    }
2116    /// Removes all network policies in `network policies` from the transaction.
2117    ///
2118    /// Returns an error if any id in `network policy` is not found.
2119    ///
2120    /// NOTE: On error, there still may be some roles removed from the transaction. It
2121    /// is up to the caller to either abort the transaction or commit.
2122    pub fn remove_network_policies(
2123        &mut self,
2124        network_policies: &BTreeSet<NetworkPolicyId>,
2125    ) -> Result<(), CatalogError> {
2126        if network_policies.is_empty() {
2127            return Ok(());
2128        }
2129
2130        let to_remove = network_policies
2131            .iter()
2132            .map(|policy_id| (NetworkPolicyKey { id: *policy_id }, None))
2133            .collect();
2134        let mut prev = self.network_policies.set_many(to_remove, self.op_id)?;
2135        assert!(
2136            prev.iter().all(|(k, _)| k.id.is_user()),
2137            "cannot delete non-user network policy"
2138        );
2139
2140        prev.retain(|_k, v| v.is_none());
2141        if !prev.is_empty() {
2142            let err = prev.keys().map(|k| k.id.to_string()).join(", ");
2143            return Err(SqlCatalogError::UnknownNetworkPolicy(err).into());
2144        }
2145
2146        Ok(())
2147    }
2148    /// Set persisted default privilege.
2149    ///
2150    /// DO NOT call this function in a loop, use [`Self::set_default_privileges`] instead.
2151    pub fn set_default_privilege(
2152        &mut self,
2153        role_id: RoleId,
2154        database_id: Option<DatabaseId>,
2155        schema_id: Option<SchemaId>,
2156        object_type: ObjectType,
2157        grantee: RoleId,
2158        privileges: Option<AclMode>,
2159    ) -> Result<(), CatalogError> {
2160        self.default_privileges.set(
2161            DefaultPrivilegesKey {
2162                role_id,
2163                database_id,
2164                schema_id,
2165                object_type,
2166                grantee,
2167            },
2168            privileges.map(|privileges| DefaultPrivilegesValue { privileges }),
2169            self.op_id,
2170        )?;
2171        Ok(())
2172    }
2173
2174    /// Set persisted default privileges.
2175    pub fn set_default_privileges(
2176        &mut self,
2177        default_privileges: Vec<DefaultPrivilege>,
2178    ) -> Result<(), CatalogError> {
2179        if default_privileges.is_empty() {
2180            return Ok(());
2181        }
2182
2183        let default_privileges = default_privileges
2184            .into_iter()
2185            .map(DurableType::into_key_value)
2186            .map(|(k, v)| (k, Some(v)))
2187            .collect();
2188        self.default_privileges
2189            .set_many(default_privileges, self.op_id)?;
2190        Ok(())
2191    }
2192
2193    /// Set persisted system privilege.
2194    ///
2195    /// DO NOT call this function in a loop, use [`Self::set_system_privileges`] instead.
2196    pub fn set_system_privilege(
2197        &mut self,
2198        grantee: RoleId,
2199        grantor: RoleId,
2200        acl_mode: Option<AclMode>,
2201    ) -> Result<(), CatalogError> {
2202        self.system_privileges.set(
2203            SystemPrivilegesKey { grantee, grantor },
2204            acl_mode.map(|acl_mode| SystemPrivilegesValue { acl_mode }),
2205            self.op_id,
2206        )?;
2207        Ok(())
2208    }
2209
2210    /// Set persisted system privileges.
2211    pub fn set_system_privileges(
2212        &mut self,
2213        system_privileges: Vec<MzAclItem>,
2214    ) -> Result<(), CatalogError> {
2215        if system_privileges.is_empty() {
2216            return Ok(());
2217        }
2218
2219        let system_privileges = system_privileges
2220            .into_iter()
2221            .map(DurableType::into_key_value)
2222            .map(|(k, v)| (k, Some(v)))
2223            .collect();
2224        self.system_privileges
2225            .set_many(system_privileges, self.op_id)?;
2226        Ok(())
2227    }
2228
2229    /// Set persisted setting.
2230    pub fn set_setting(&mut self, name: String, value: Option<String>) -> Result<(), CatalogError> {
2231        self.settings.set(
2232            SettingKey { name },
2233            value.map(|value| SettingValue { value }),
2234            self.op_id,
2235        )?;
2236        Ok(())
2237    }
2238
2239    pub fn set_catalog_content_version(&mut self, version: String) -> Result<(), CatalogError> {
2240        self.set_setting(CATALOG_CONTENT_VERSION_KEY.to_string(), Some(version))
2241    }
2242
2243    /// Insert persisted introspection source index.
2244    pub fn insert_introspection_source_indexes(
2245        &mut self,
2246        introspection_source_indexes: Vec<(ClusterId, String, CatalogItemId, GlobalId)>,
2247        temporary_oids: &HashSet<u32>,
2248    ) -> Result<(), CatalogError> {
2249        if introspection_source_indexes.is_empty() {
2250            return Ok(());
2251        }
2252
2253        let amount = usize_to_u64(introspection_source_indexes.len());
2254        let oids = self.allocate_oids(amount, temporary_oids)?;
2255        let introspection_source_indexes: Vec<_> = introspection_source_indexes
2256            .into_iter()
2257            .zip_eq(oids)
2258            .map(
2259                |((cluster_id, name, item_id, index_id), oid)| IntrospectionSourceIndex {
2260                    cluster_id,
2261                    name,
2262                    item_id,
2263                    index_id,
2264                    oid,
2265                },
2266            )
2267            .collect();
2268
2269        for introspection_source_index in introspection_source_indexes {
2270            let (key, value) = introspection_source_index.into_key_value();
2271            self.introspection_sources.insert(key, value, self.op_id)?;
2272        }
2273
2274        Ok(())
2275    }
2276
2277    /// Set persisted system object mappings.
2278    pub fn set_system_object_mappings(
2279        &mut self,
2280        mappings: Vec<SystemObjectMapping>,
2281    ) -> Result<(), CatalogError> {
2282        if mappings.is_empty() {
2283            return Ok(());
2284        }
2285
2286        let mappings = mappings
2287            .into_iter()
2288            .map(DurableType::into_key_value)
2289            .map(|(k, v)| (k, Some(v)))
2290            .collect();
2291        self.system_gid_mapping.set_many(mappings, self.op_id)?;
2292        Ok(())
2293    }
2294
2295    /// Set persisted replica.
2296    pub fn set_replicas(&mut self, replicas: Vec<ClusterReplica>) -> Result<(), CatalogError> {
2297        if replicas.is_empty() {
2298            return Ok(());
2299        }
2300
2301        let replicas = replicas
2302            .into_iter()
2303            .map(DurableType::into_key_value)
2304            .map(|(k, v)| (k, Some(v)))
2305            .collect();
2306        self.cluster_replicas.set_many(replicas, self.op_id)?;
2307        Ok(())
2308    }
2309
2310    /// Set persisted configuration.
2311    pub fn set_config(&mut self, key: String, value: Option<u64>) -> Result<(), CatalogError> {
2312        match value {
2313            Some(value) => {
2314                let config = Config { key, value };
2315                let (key, value) = config.into_key_value();
2316                self.configs.set(key, Some(value), self.op_id)?;
2317            }
2318            None => {
2319                self.configs.set(ConfigKey { key }, None, self.op_id)?;
2320            }
2321        }
2322        Ok(())
2323    }
2324
2325    /// Get the value of a persisted config.
2326    pub fn get_config(&self, key: String) -> Option<u64> {
2327        self.configs
2328            .get(&ConfigKey { key })
2329            .map(|entry| entry.value)
2330    }
2331
2332    /// Get the value of a persisted setting.
2333    pub fn get_setting(&self, name: String) -> Option<&str> {
2334        self.settings
2335            .get(&SettingKey { name })
2336            .map(|entry| &*entry.value)
2337    }
2338
2339    pub fn get_builtin_migration_shard(&self) -> Option<ShardId> {
2340        self.get_setting(BUILTIN_MIGRATION_SHARD_KEY.to_string())
2341            .map(|shard_id| shard_id.parse().expect("valid ShardId"))
2342    }
2343
2344    pub fn set_builtin_migration_shard(&mut self, shard_id: ShardId) -> Result<(), CatalogError> {
2345        self.set_setting(
2346            BUILTIN_MIGRATION_SHARD_KEY.to_string(),
2347            Some(shard_id.to_string()),
2348        )
2349    }
2350
2351    pub fn get_expression_cache_shard(&self) -> Option<ShardId> {
2352        self.get_setting(EXPRESSION_CACHE_SHARD_KEY.to_string())
2353            .map(|shard_id| shard_id.parse().expect("valid ShardId"))
2354    }
2355
2356    pub fn set_expression_cache_shard(&mut self, shard_id: ShardId) -> Result<(), CatalogError> {
2357        self.set_setting(
2358            EXPRESSION_CACHE_SHARD_KEY.to_string(),
2359            Some(shard_id.to_string()),
2360        )
2361    }
2362
2363    /// Updates the catalog `with_0dt_deployment_max_wait` "config" value to
2364    /// match the `with_0dt_deployment_max_wait` "system var" value.
2365    ///
2366    /// These are mirrored so that we can toggle the flag with Launch Darkly,
2367    /// but use it in boot before Launch Darkly is available.
2368    pub fn set_0dt_deployment_max_wait(&mut self, value: Duration) -> Result<(), CatalogError> {
2369        self.set_config(
2370            WITH_0DT_DEPLOYMENT_MAX_WAIT.into(),
2371            Some(
2372                value
2373                    .as_millis()
2374                    .try_into()
2375                    .expect("max wait fits into u64"),
2376            ),
2377        )
2378    }
2379
2380    /// Updates the catalog `with_0dt_deployment_ddl_check_interval` "config"
2381    /// value to match the `with_0dt_deployment_ddl_check_interval` "system var"
2382    /// value.
2383    ///
2384    /// These are mirrored so that we can toggle the flag with Launch Darkly,
2385    /// but use it in boot before Launch Darkly is available.
2386    pub fn set_0dt_deployment_ddl_check_interval(
2387        &mut self,
2388        value: Duration,
2389    ) -> Result<(), CatalogError> {
2390        self.set_config(
2391            WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.into(),
2392            Some(
2393                value
2394                    .as_millis()
2395                    .try_into()
2396                    .expect("ddl check interval fits into u64"),
2397            ),
2398        )
2399    }
2400
2401    /// Updates the catalog `0dt_deployment_panic_after_timeout` "config" value to
2402    /// match the `0dt_deployment_panic_after_timeout` "system var" value.
2403    ///
2404    /// These are mirrored so that we can toggle the flag with Launch Darkly,
2405    /// but use it in boot before Launch Darkly is available.
2406    pub fn set_enable_0dt_deployment_panic_after_timeout(
2407        &mut self,
2408        value: bool,
2409    ) -> Result<(), CatalogError> {
2410        self.set_config(
2411            ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.into(),
2412            Some(u64::from(value)),
2413        )
2414    }
2415
2416    /// Removes the catalog `with_0dt_deployment_max_wait` "config" value to
2417    /// match the `with_0dt_deployment_max_wait` "system var" value.
2418    ///
2419    /// These are mirrored so that we can toggle the flag with LaunchDarkly,
2420    /// but use it in boot before LaunchDarkly is available.
2421    pub fn reset_0dt_deployment_max_wait(&mut self) -> Result<(), CatalogError> {
2422        self.set_config(WITH_0DT_DEPLOYMENT_MAX_WAIT.into(), None)
2423    }
2424
2425    /// Removes the catalog `with_0dt_deployment_ddl_check_interval` "config"
2426    /// value to match the `with_0dt_deployment_ddl_check_interval` "system var"
2427    /// value.
2428    ///
2429    /// These are mirrored so that we can toggle the flag with LaunchDarkly, but
2430    /// use it in boot before LaunchDarkly is available.
2431    pub fn reset_0dt_deployment_ddl_check_interval(&mut self) -> Result<(), CatalogError> {
2432        self.set_config(WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.into(), None)
2433    }
2434
2435    /// Removes the catalog `enable_0dt_deployment_panic_after_timeout` "config"
2436    /// value to match the `enable_0dt_deployment_panic_after_timeout` "system
2437    /// var" value.
2438    ///
2439    /// These are mirrored so that we can toggle the flag with LaunchDarkly, but
2440    /// use it in boot before LaunchDarkly is available.
2441    pub fn reset_enable_0dt_deployment_panic_after_timeout(&mut self) -> Result<(), CatalogError> {
2442        self.set_config(ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.into(), None)
2443    }
2444
2445    /// Updates the catalog `system_config_synced` "config" value to true.
2446    pub fn set_system_config_synced_once(&mut self) -> Result<(), CatalogError> {
2447        self.set_config(SYSTEM_CONFIG_SYNCED_KEY.into(), Some(1))
2448    }
2449
2450    pub fn update_comment(
2451        &mut self,
2452        object_id: CommentObjectId,
2453        sub_component: Option<usize>,
2454        comment: Option<String>,
2455    ) -> Result<(), CatalogError> {
2456        let key = CommentKey {
2457            object_id,
2458            sub_component,
2459        };
2460        let value = comment.map(|c| CommentValue { comment: c });
2461        self.comments.set(key, value, self.op_id)?;
2462
2463        Ok(())
2464    }
2465
2466    pub fn drop_comments(
2467        &mut self,
2468        object_ids: &BTreeSet<CommentObjectId>,
2469    ) -> Result<(), CatalogError> {
2470        if object_ids.is_empty() {
2471            return Ok(());
2472        }
2473
2474        self.comments
2475            .delete(|k, _v| object_ids.contains(&k.object_id), self.op_id);
2476        Ok(())
2477    }
2478
2479    pub fn update_source_references(
2480        &mut self,
2481        source_id: CatalogItemId,
2482        references: Vec<SourceReference>,
2483        updated_at: u64,
2484    ) -> Result<(), CatalogError> {
2485        let key = SourceReferencesKey { source_id };
2486        let value = SourceReferencesValue {
2487            references,
2488            updated_at,
2489        };
2490        self.source_references.set(key, Some(value), self.op_id)?;
2491        Ok(())
2492    }
2493
2494    /// Upserts persisted system configuration `name` to `value`.
2495    pub fn upsert_system_config(&mut self, name: &str, value: String) -> Result<(), CatalogError> {
2496        let key = ServerConfigurationKey {
2497            name: name.to_string(),
2498        };
2499        let value = ServerConfigurationValue { value };
2500        self.system_configurations
2501            .set(key, Some(value), self.op_id)?;
2502        Ok(())
2503    }
2504
2505    /// Removes persisted system configuration `name`.
2506    pub fn remove_system_config(&mut self, name: &str) {
2507        let key = ServerConfigurationKey {
2508            name: name.to_string(),
2509        };
2510        self.system_configurations
2511            .set(key, None, self.op_id)
2512            .expect("cannot have uniqueness violation");
2513    }
2514
2515    /// Removes all persisted system configurations.
2516    pub fn clear_system_configs(&mut self) {
2517        self.system_configurations.delete(|_k, _v| true, self.op_id);
2518    }
2519
2520    /// Returns the persisted cluster-coherent scoped system configurations.
2521    pub fn get_cluster_system_configurations(
2522        &self,
2523    ) -> impl Iterator<Item = ClusterSystemConfiguration> + use<'_> {
2524        self.cluster_system_configurations
2525            .items()
2526            .into_iter()
2527            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2528    }
2529
2530    /// Upserts the persisted cluster-coherent scoped configuration `name` = `value`
2531    /// for `cluster_id`.
2532    pub fn upsert_cluster_system_config(
2533        &mut self,
2534        cluster_id: ClusterId,
2535        name: &str,
2536        value: String,
2537    ) -> Result<(), CatalogError> {
2538        let key = ClusterSystemConfigurationKey {
2539            cluster_id,
2540            name: name.to_string(),
2541        };
2542        let value = ClusterSystemConfigurationValue { value };
2543        self.cluster_system_configurations
2544            .set(key, Some(value), self.op_id)?;
2545        Ok(())
2546    }
2547
2548    /// Removes the persisted cluster-coherent scoped configuration `name` for
2549    /// `cluster_id`.
2550    pub fn remove_cluster_system_config(&mut self, cluster_id: ClusterId, name: &str) {
2551        let key = ClusterSystemConfigurationKey {
2552            cluster_id,
2553            name: name.to_string(),
2554        };
2555        self.cluster_system_configurations
2556            .set(key, None, self.op_id)
2557            .expect("cannot have uniqueness violation");
2558    }
2559
2560    /// Returns the persisted replica-local scoped system configurations.
2561    pub fn get_replica_system_configurations(
2562        &self,
2563    ) -> impl Iterator<Item = ReplicaSystemConfiguration> + use<'_> {
2564        self.replica_system_configurations
2565            .items()
2566            .into_iter()
2567            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2568    }
2569
2570    /// Upserts the persisted replica-local scoped configuration `name` = `value`
2571    /// for `replica_id`.
2572    pub fn upsert_replica_system_config(
2573        &mut self,
2574        replica_id: ReplicaId,
2575        name: &str,
2576        value: String,
2577    ) -> Result<(), CatalogError> {
2578        let key = ReplicaSystemConfigurationKey {
2579            replica_id,
2580            name: name.to_string(),
2581        };
2582        let value = ReplicaSystemConfigurationValue { value };
2583        self.replica_system_configurations
2584            .set(key, Some(value), self.op_id)?;
2585        Ok(())
2586    }
2587
2588    /// Removes the persisted replica-local scoped configuration `name` for
2589    /// `replica_id`.
2590    pub fn remove_replica_system_config(&mut self, replica_id: ReplicaId, name: &str) {
2591        let key = ReplicaSystemConfigurationKey {
2592            replica_id,
2593            name: name.to_string(),
2594        };
2595        self.replica_system_configurations
2596            .set(key, None, self.op_id)
2597            .expect("cannot have uniqueness violation");
2598    }
2599
2600    pub(crate) fn insert_config(&mut self, key: String, value: u64) -> Result<(), CatalogError> {
2601        match self.configs.insert(
2602            ConfigKey { key: key.clone() },
2603            ConfigValue { value },
2604            self.op_id,
2605        ) {
2606            Ok(_) => Ok(()),
2607            Err(_) => Err(SqlCatalogError::ConfigAlreadyExists(key).into()),
2608        }
2609    }
2610
2611    pub fn get_clusters(&self) -> impl Iterator<Item = Cluster> + use<'_> {
2612        self.clusters
2613            .items()
2614            .into_iter()
2615            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2616    }
2617
2618    pub fn get_cluster_replicas(&self) -> impl Iterator<Item = ClusterReplica> + use<'_> {
2619        self.cluster_replicas
2620            .items()
2621            .into_iter()
2622            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2623    }
2624
2625    pub fn get_databases(&self) -> impl Iterator<Item = Database> + use<'_> {
2626        self.databases
2627            .items()
2628            .into_iter()
2629            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2630    }
2631
2632    pub fn get_roles(&self) -> impl Iterator<Item = Role> + use<'_> {
2633        self.roles
2634            .items()
2635            .into_iter()
2636            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2637    }
2638
2639    pub fn get_query_policies(&self) -> impl Iterator<Item = QueryPolicy> + use<'_> {
2640        self.query_policies
2641            .items()
2642            .into_iter()
2643            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2644    }
2645
2646    pub fn get_network_policies(&self) -> impl Iterator<Item = NetworkPolicy> + use<'_> {
2647        self.network_policies
2648            .items()
2649            .into_iter()
2650            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2651    }
2652
2653    pub fn get_cluster_replica_sizes(&self) -> impl Iterator<Item = ClusterReplicaSize> + use<'_> {
2654        self.cluster_replica_sizes
2655            .items()
2656            .into_iter()
2657            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2658    }
2659
2660    pub fn insert_system_cluster_replica_size(
2661        &mut self,
2662        name: String,
2663        allocation: ReplicaAllocation,
2664    ) -> Result<ClusterReplicaSizeId, CatalogError> {
2665        let id = self.get_and_increment_id(SYSTEM_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY.to_string())?;
2666        let id = ClusterReplicaSizeId::System(id);
2667        let (key, value) = ClusterReplicaSize {
2668            id,
2669            name,
2670            allocation,
2671        }
2672        .into_key_value();
2673        self.cluster_replica_sizes.insert(key, value, self.op_id)?;
2674        Ok(id)
2675    }
2676
2677    pub fn update_cluster_replica_size(
2678        &mut self,
2679        size: ClusterReplicaSize,
2680    ) -> Result<(), CatalogError> {
2681        let id = size.id;
2682        let (key, value) = size.into_key_value();
2683        if self
2684            .cluster_replica_sizes
2685            .update_by_key(key, value, self.op_id)?
2686        {
2687            Ok(())
2688        } else {
2689            Err(SqlCatalogError::UnknownClusterReplicaSize(id.to_string()).into())
2690        }
2691    }
2692
2693    pub fn remove_cluster_replica_size(
2694        &mut self,
2695        id: ClusterReplicaSizeId,
2696    ) -> Result<(), CatalogError> {
2697        match self
2698            .cluster_replica_sizes
2699            .delete_by_key(ClusterReplicaSizeKey { id }, self.op_id)
2700        {
2701            Some(_) => Ok(()),
2702            None => Err(SqlCatalogError::UnknownClusterReplicaSize(id.to_string()).into()),
2703        }
2704    }
2705
2706    pub fn get_system_object_mappings(
2707        &self,
2708    ) -> impl Iterator<Item = SystemObjectMapping> + use<'_> {
2709        self.system_gid_mapping
2710            .items()
2711            .into_iter()
2712            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2713    }
2714
2715    pub fn get_schemas(&self) -> impl Iterator<Item = Schema> + use<'_> {
2716        self.schemas
2717            .items()
2718            .into_iter()
2719            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2720    }
2721
2722    pub fn get_system_configurations(&self) -> impl Iterator<Item = SystemConfiguration> + use<'_> {
2723        self.system_configurations
2724            .items()
2725            .into_iter()
2726            .map(|(k, v)| DurableType::from_key_value(k.clone(), v.clone()))
2727    }
2728
2729    pub fn get_schema(&self, id: &SchemaId) -> Option<Schema> {
2730        let key = SchemaKey { id: *id };
2731        self.schemas
2732            .get(&key)
2733            .map(|v| DurableType::from_key_value(key, v.clone()))
2734    }
2735
2736    pub fn get_introspection_source_indexes(
2737        &self,
2738        cluster_id: ClusterId,
2739    ) -> BTreeMap<&str, (GlobalId, u32)> {
2740        self.introspection_sources
2741            .items()
2742            .into_iter()
2743            .filter(|(k, _v)| k.cluster_id == cluster_id)
2744            .map(|(k, v)| (k.name.as_str(), (v.global_id.into(), v.oid)))
2745            .collect()
2746    }
2747
2748    pub fn get_catalog_content_version(&self) -> Option<&str> {
2749        self.settings
2750            .get(&SettingKey {
2751                name: CATALOG_CONTENT_VERSION_KEY.to_string(),
2752            })
2753            .map(|value| &*value.value)
2754    }
2755
2756    pub fn get_authentication_mock_nonce(&self) -> Option<String> {
2757        self.settings
2758            .get(&SettingKey {
2759                name: MOCK_AUTHENTICATION_NONCE_KEY.to_string(),
2760            })
2761            .map(|value| value.value.clone())
2762    }
2763
2764    /// Commit the current operation within the transaction. This does not cause anything to be
2765    /// written durably, but signals to the current transaction that we are moving on to the next
2766    /// operation.
2767    ///
2768    /// Returns the updates of the committed operation.
2769    #[must_use]
2770    pub fn get_and_commit_op_updates(&mut self) -> Vec<StateUpdate> {
2771        let updates = self.get_op_updates();
2772        self.commit_op();
2773        updates
2774    }
2775
2776    fn get_op_updates(&self) -> Vec<StateUpdate> {
2777        fn get_collection_op_updates<'a, T>(
2778            table_txn: &'a TableTransaction<T::Key, T::Value>,
2779            kind_fn: impl Fn(T) -> StateUpdateKind + 'a,
2780            op: Timestamp,
2781        ) -> impl Iterator<Item = (StateUpdateKind, StateDiff)> + 'a
2782        where
2783            T::Key: Ord + Eq + Clone + Debug,
2784            T::Value: Ord + Clone + Debug,
2785            T: DurableType,
2786        {
2787            table_txn
2788                .pending
2789                .iter()
2790                .flat_map(|(k, vs)| vs.into_iter().map(move |v| (k, v)))
2791                .filter_map(move |(k, v)| {
2792                    if v.ts == op {
2793                        let key = k.clone();
2794                        let value = v.value.clone();
2795                        let diff = v.diff.clone().try_into().expect("invalid diff");
2796                        let update = DurableType::from_key_value(key, value);
2797                        let kind = kind_fn(update);
2798                        Some((kind, diff))
2799                    } else {
2800                        None
2801                    }
2802                })
2803        }
2804
2805        fn get_large_collection_op_updates<'a, T>(
2806            collection: &'a Vec<(T::Key, Diff, Timestamp)>,
2807            kind_fn: impl Fn(T) -> StateUpdateKind + 'a,
2808            op: Timestamp,
2809        ) -> impl Iterator<Item = (StateUpdateKind, StateDiff)> + 'a
2810        where
2811            T::Key: Ord + Eq + Clone + Debug,
2812            T: DurableType<Value = ()>,
2813        {
2814            collection.iter().filter_map(move |(k, diff, ts)| {
2815                if *ts == op {
2816                    let key = k.clone();
2817                    let diff = diff.clone().try_into().expect("invalid diff");
2818                    let update = DurableType::from_key_value(key, ());
2819                    let kind = kind_fn(update);
2820                    Some((kind, diff))
2821                } else {
2822                    None
2823                }
2824            })
2825        }
2826
2827        let Transaction {
2828            durable_catalog: _,
2829            databases,
2830            schemas,
2831            items,
2832            comments,
2833            roles,
2834            role_auth,
2835            clusters,
2836            network_policies,
2837            cluster_replica_sizes,
2838            query_policies,
2839            cluster_replicas,
2840            introspection_sources,
2841            system_gid_mapping,
2842            system_configurations,
2843            cluster_system_configurations,
2844            replica_system_configurations,
2845            default_privileges,
2846            source_references,
2847            system_privileges,
2848            audit_log_updates,
2849            storage_collection_metadata,
2850            unfinalized_shards,
2851            // Not representable as a `StateUpdate`.
2852            id_allocator: _,
2853            configs: _,
2854            settings: _,
2855            txn_wal_shard: _,
2856            // Not consumed by the in-memory catalog, which plans items itself.
2857            item_columns: _,
2858            index_columns: _,
2859            upper,
2860            op_id: _,
2861            commit_capability: _,
2862        } = &self;
2863
2864        let updates = std::iter::empty()
2865            .chain(get_collection_op_updates(
2866                roles,
2867                StateUpdateKind::Role,
2868                self.op_id,
2869            ))
2870            .chain(get_collection_op_updates(
2871                role_auth,
2872                StateUpdateKind::RoleAuth,
2873                self.op_id,
2874            ))
2875            .chain(get_collection_op_updates(
2876                databases,
2877                StateUpdateKind::Database,
2878                self.op_id,
2879            ))
2880            .chain(get_collection_op_updates(
2881                schemas,
2882                StateUpdateKind::Schema,
2883                self.op_id,
2884            ))
2885            .chain(get_collection_op_updates(
2886                default_privileges,
2887                StateUpdateKind::DefaultPrivilege,
2888                self.op_id,
2889            ))
2890            .chain(get_collection_op_updates(
2891                system_privileges,
2892                StateUpdateKind::SystemPrivilege,
2893                self.op_id,
2894            ))
2895            .chain(get_collection_op_updates(
2896                system_configurations,
2897                StateUpdateKind::SystemConfiguration,
2898                self.op_id,
2899            ))
2900            .chain(get_collection_op_updates(
2901                cluster_system_configurations,
2902                StateUpdateKind::ClusterSystemConfiguration,
2903                self.op_id,
2904            ))
2905            .chain(get_collection_op_updates(
2906                replica_system_configurations,
2907                StateUpdateKind::ReplicaSystemConfiguration,
2908                self.op_id,
2909            ))
2910            .chain(get_collection_op_updates(
2911                clusters,
2912                StateUpdateKind::Cluster,
2913                self.op_id,
2914            ))
2915            .chain(get_collection_op_updates(
2916                network_policies,
2917                StateUpdateKind::NetworkPolicy,
2918                self.op_id,
2919            ))
2920            .chain(get_collection_op_updates(
2921                cluster_replica_sizes,
2922                StateUpdateKind::ClusterReplicaSize,
2923                self.op_id,
2924            ))
2925            .chain(get_collection_op_updates(
2926                query_policies,
2927                StateUpdateKind::QueryPolicy,
2928                self.op_id,
2929            ))
2930            .chain(get_collection_op_updates(
2931                introspection_sources,
2932                StateUpdateKind::IntrospectionSourceIndex,
2933                self.op_id,
2934            ))
2935            .chain(get_collection_op_updates(
2936                cluster_replicas,
2937                StateUpdateKind::ClusterReplica,
2938                self.op_id,
2939            ))
2940            .chain(get_collection_op_updates(
2941                system_gid_mapping,
2942                StateUpdateKind::SystemObjectMapping,
2943                self.op_id,
2944            ))
2945            .chain(get_collection_op_updates(
2946                items,
2947                StateUpdateKind::Item,
2948                self.op_id,
2949            ))
2950            .chain(get_collection_op_updates(
2951                comments,
2952                StateUpdateKind::Comment,
2953                self.op_id,
2954            ))
2955            .chain(get_collection_op_updates(
2956                source_references,
2957                StateUpdateKind::SourceReferences,
2958                self.op_id,
2959            ))
2960            .chain(get_collection_op_updates(
2961                storage_collection_metadata,
2962                StateUpdateKind::StorageCollectionMetadata,
2963                self.op_id,
2964            ))
2965            .chain(get_collection_op_updates(
2966                unfinalized_shards,
2967                StateUpdateKind::UnfinalizedShard,
2968                self.op_id,
2969            ))
2970            .chain(get_large_collection_op_updates(
2971                audit_log_updates,
2972                StateUpdateKind::AuditLog,
2973                self.op_id,
2974            ))
2975            .map(|(kind, diff)| StateUpdate {
2976                kind,
2977                ts: upper.clone(),
2978                diff,
2979            })
2980            .collect();
2981
2982        updates
2983    }
2984
2985    pub fn is_savepoint(&self) -> bool {
2986        self.durable_catalog.is_savepoint()
2987    }
2988
2989    pub fn is_read_only(&self) -> bool {
2990        self.durable_catalog.is_read_only()
2991    }
2992
2993    fn commit_op(&mut self) {
2994        self.op_id += 1;
2995    }
2996
2997    pub fn op_id(&self) -> Timestamp {
2998        self.op_id
2999    }
3000
3001    pub fn upper(&self) -> mz_repr::Timestamp {
3002        self.upper
3003    }
3004
3005    fn ensure_committable(&self) -> Result<(), CatalogError> {
3006        match self.commit_capability {
3007            Some(_) => Ok(()),
3008            None => Err(DurableCatalogError::DryRunTransaction.into()),
3009        }
3010    }
3011
3012    /// Verifies that this process has not missed catalog content updates.
3013    pub(super) async fn ensure_not_out_of_sync(&mut self) -> Result<(), CatalogError> {
3014        self.durable_catalog
3015            .ensure_not_out_of_sync(self.upper)
3016            .await
3017    }
3018
3019    pub(crate) fn into_parts(
3020        self,
3021    ) -> Result<(TransactionBatch, &'a mut dyn DurableCatalogState), CatalogError> {
3022        let commit_capability = self
3023            .commit_capability
3024            .ok_or(DurableCatalogError::DryRunTransaction)?;
3025        let audit_log_updates = self
3026            .audit_log_updates
3027            .into_iter()
3028            .map(|(k, diff, _op)| (k.into_proto(), (), diff))
3029            .collect();
3030
3031        let txn_batch = TransactionBatch {
3032            databases: self.databases.pending(),
3033            schemas: self.schemas.pending(),
3034            items: self.items.pending(),
3035            item_columns: self.item_columns.pending(),
3036            index_columns: self.index_columns.pending(),
3037            comments: self.comments.pending(),
3038            roles: self.roles.pending(),
3039            role_auth: self.role_auth.pending(),
3040            clusters: self.clusters.pending(),
3041            cluster_replicas: self.cluster_replicas.pending(),
3042            network_policies: self.network_policies.pending(),
3043            cluster_replica_sizes: self.cluster_replica_sizes.pending(),
3044            query_policies: self.query_policies.pending(),
3045            introspection_sources: self.introspection_sources.pending(),
3046            id_allocator: self.id_allocator.pending(),
3047            configs: self.configs.pending(),
3048            source_references: self.source_references.pending(),
3049            settings: self.settings.pending(),
3050            system_gid_mapping: self.system_gid_mapping.pending(),
3051            system_configurations: self.system_configurations.pending(),
3052            cluster_system_configurations: self.cluster_system_configurations.pending(),
3053            replica_system_configurations: self.replica_system_configurations.pending(),
3054            default_privileges: self.default_privileges.pending(),
3055            system_privileges: self.system_privileges.pending(),
3056            storage_collection_metadata: self.storage_collection_metadata.pending(),
3057            unfinalized_shards: self.unfinalized_shards.pending(),
3058            txn_wal_shard: self.txn_wal_shard.pending(),
3059            audit_log_updates,
3060            upper: self.upper,
3061            _commit_capability: commit_capability,
3062        };
3063        Ok((txn_batch, self.durable_catalog))
3064    }
3065
3066    /// Commits the storage transaction to durable storage.
3067    ///
3068    /// [`DurableCatalogError::DryRunTransaction`] is a pre-effect
3069    /// programming error that leaves durable state unchanged. Any other error
3070    /// outside read-only mode indicates the catalog may be in an indeterminate
3071    /// state and needs to be fully re-read before proceeding. In general, such
3072    /// errors must be fatal to the calling process. We do not panic/halt here so
3073    /// initialization can report them.
3074    ///
3075    /// The transaction is committed at `commit_ts`.
3076    ///
3077    /// Returns what the upper was directly after the transaction committed.
3078    ///
3079    /// In read-only mode, this will return an error for non-empty transactions indicating that the
3080    /// catalog is not writeable.
3081    #[mz_ore::instrument(level = "debug")]
3082    pub(crate) async fn commit_internal(
3083        self,
3084        commit_ts: mz_repr::Timestamp,
3085    ) -> Result<(&'a mut dyn DurableCatalogState, mz_repr::Timestamp), CatalogError> {
3086        self.ensure_committable()?;
3087        let (mut txn_batch, durable_catalog) = self.into_parts()?;
3088        let TransactionBatch {
3089            databases,
3090            schemas,
3091            items,
3092            item_columns,
3093            index_columns,
3094            comments,
3095            roles,
3096            role_auth,
3097            clusters,
3098            cluster_replicas,
3099            network_policies,
3100            cluster_replica_sizes,
3101            query_policies,
3102            introspection_sources,
3103            id_allocator,
3104            configs,
3105            source_references,
3106            settings,
3107            system_gid_mapping,
3108            system_configurations,
3109            cluster_system_configurations,
3110            replica_system_configurations,
3111            default_privileges,
3112            system_privileges,
3113            storage_collection_metadata,
3114            unfinalized_shards,
3115            txn_wal_shard,
3116            audit_log_updates,
3117            upper: _,
3118            _commit_capability: _,
3119        } = &mut txn_batch;
3120        // Consolidate in memory because it will likely be faster than consolidating after the
3121        // transaction has been made durable.
3122        differential_dataflow::consolidation::consolidate_updates(databases);
3123        differential_dataflow::consolidation::consolidate_updates(schemas);
3124        differential_dataflow::consolidation::consolidate_updates(items);
3125        differential_dataflow::consolidation::consolidate_updates(item_columns);
3126        differential_dataflow::consolidation::consolidate_updates(index_columns);
3127        differential_dataflow::consolidation::consolidate_updates(comments);
3128        differential_dataflow::consolidation::consolidate_updates(roles);
3129        differential_dataflow::consolidation::consolidate_updates(role_auth);
3130        differential_dataflow::consolidation::consolidate_updates(clusters);
3131        differential_dataflow::consolidation::consolidate_updates(cluster_replicas);
3132        differential_dataflow::consolidation::consolidate_updates(network_policies);
3133        differential_dataflow::consolidation::consolidate_updates(cluster_replica_sizes);
3134        differential_dataflow::consolidation::consolidate_updates(query_policies);
3135        differential_dataflow::consolidation::consolidate_updates(introspection_sources);
3136        differential_dataflow::consolidation::consolidate_updates(id_allocator);
3137        differential_dataflow::consolidation::consolidate_updates(configs);
3138        differential_dataflow::consolidation::consolidate_updates(settings);
3139        differential_dataflow::consolidation::consolidate_updates(source_references);
3140        differential_dataflow::consolidation::consolidate_updates(system_gid_mapping);
3141        differential_dataflow::consolidation::consolidate_updates(system_configurations);
3142        differential_dataflow::consolidation::consolidate_updates(cluster_system_configurations);
3143        differential_dataflow::consolidation::consolidate_updates(replica_system_configurations);
3144        differential_dataflow::consolidation::consolidate_updates(default_privileges);
3145        differential_dataflow::consolidation::consolidate_updates(system_privileges);
3146        differential_dataflow::consolidation::consolidate_updates(storage_collection_metadata);
3147        differential_dataflow::consolidation::consolidate_updates(unfinalized_shards);
3148        differential_dataflow::consolidation::consolidate_updates(txn_wal_shard);
3149        differential_dataflow::consolidation::consolidate_updates(audit_log_updates);
3150
3151        let upper = durable_catalog
3152            .commit_transaction(txn_batch, commit_ts)
3153            .await?;
3154        Ok((durable_catalog, upper))
3155    }
3156
3157    /// Commits the storage transaction to durable storage.
3158    ///
3159    /// [`DurableCatalogError::DryRunTransaction`] is a pre-effect
3160    /// programming error that leaves durable state unchanged. Any other error
3161    /// outside read-only mode indicates the catalog may be in an indeterminate
3162    /// state and needs to be fully re-read before proceeding. In general, such
3163    /// errors must be fatal to the calling process. We do not panic/halt here so
3164    /// initialization can report them.
3165    ///
3166    /// In read-only mode, this will return an error for non-empty transactions indicating that the
3167    /// catalog is not writeable.
3168    ///
3169    /// IMPORTANT: It is assumed that the committer of this transaction has already applied all
3170    /// updates from this transaction. Therefore, updates from this transaction will not be returned
3171    /// when calling [`crate::durable::ReadOnlyDurableCatalogState::sync_to_current_updates`] or
3172    /// [`crate::durable::ReadOnlyDurableCatalogState::sync_updates`].
3173    ///
3174    /// An alternative implementation would be for the caller to explicitly consume their updates
3175    /// after committing and only then apply the updates in-memory. While this removes assumptions
3176    /// about the caller in this method, in practice it results in duplicate work on every commit.
3177    #[mz_ore::instrument(level = "debug")]
3178    pub async fn commit(self, commit_ts: mz_repr::Timestamp) -> Result<(), CatalogError> {
3179        self.ensure_committable()?;
3180        let op_updates = self.get_op_updates();
3181        assert!(
3182            op_updates.is_empty(),
3183            "unconsumed transaction updates: {op_updates:?}"
3184        );
3185
3186        let (durable_storage, upper) = self.commit_internal(commit_ts).await?;
3187        // Drain all the updates from the commit since it is assumed that they were already applied.
3188        let updates = durable_storage.sync_updates(upper).await?;
3189        // Writable and savepoint catalogs should have consumed all updates before committing a
3190        // transaction, otherwise the commit was performed with an out of date state.
3191        // Read-only catalogs can only commit empty transactions, so they don't need to consume all
3192        // updates before committing.
3193        //
3194        // The off-loop group committer can advance the catalog upper without content while this
3195        // transaction is open. The commit then rebases above `commit_ts`. Its returned `upper` is
3196        // the exclusive upper of the successful write.
3197        soft_assert_no_log!(
3198            durable_storage.is_read_only()
3199                || updates
3200                    .iter()
3201                    .all(|update| update.ts >= commit_ts && update.ts < upper),
3202            "unconsumed updates existed before transaction commit: commit_ts={commit_ts:?}, upper={upper:?}, updates:{updates:?}"
3203        );
3204        Ok(())
3205    }
3206}
3207
3208use crate::durable::async_trait;
3209
3210use super::objects::{RoleAuthKey, RoleAuthValue};
3211
3212#[async_trait]
3213impl StorageTxn for Transaction<'_> {
3214    fn get_collection_metadata(&self) -> BTreeMap<GlobalId, ShardId> {
3215        self.storage_collection_metadata
3216            .items()
3217            .into_iter()
3218            .map(
3219                |(
3220                    StorageCollectionMetadataKey { id },
3221                    StorageCollectionMetadataValue { shard },
3222                )| { (*id, shard.clone()) },
3223            )
3224            .collect()
3225    }
3226
3227    fn insert_collection_metadata(
3228        &mut self,
3229        metadata: BTreeMap<GlobalId, ShardId>,
3230    ) -> Result<(), StorageError> {
3231        for (id, shard) in metadata {
3232            self.storage_collection_metadata
3233                .insert(
3234                    StorageCollectionMetadataKey { id },
3235                    StorageCollectionMetadataValue {
3236                        shard: shard.clone(),
3237                    },
3238                    self.op_id,
3239                )
3240                .map_err(|err| match err {
3241                    DurableCatalogError::DuplicateKey => {
3242                        StorageError::CollectionMetadataAlreadyExists(id)
3243                    }
3244                    DurableCatalogError::UniquenessViolation => {
3245                        StorageError::PersistShardAlreadyInUse(shard)
3246                    }
3247                    err => StorageError::Generic(anyhow::anyhow!(err)),
3248                })?;
3249        }
3250        Ok(())
3251    }
3252
3253    fn delete_collection_metadata(&mut self, ids: BTreeSet<GlobalId>) -> Vec<(GlobalId, ShardId)> {
3254        let ks: Vec<_> = ids
3255            .into_iter()
3256            .map(|id| StorageCollectionMetadataKey { id })
3257            .collect();
3258        self.storage_collection_metadata
3259            .delete_by_keys(ks, self.op_id)
3260            .into_iter()
3261            .map(
3262                |(
3263                    StorageCollectionMetadataKey { id },
3264                    StorageCollectionMetadataValue { shard },
3265                )| (id, shard),
3266            )
3267            .collect()
3268    }
3269
3270    fn get_unfinalized_shards(&self) -> BTreeSet<ShardId> {
3271        self.unfinalized_shards
3272            .items()
3273            .into_iter()
3274            .map(|(UnfinalizedShardKey { shard }, ())| *shard)
3275            .collect()
3276    }
3277
3278    fn insert_unfinalized_shards(&mut self, s: BTreeSet<ShardId>) -> Result<(), StorageError> {
3279        for shard in s {
3280            match self
3281                .unfinalized_shards
3282                .insert(UnfinalizedShardKey { shard }, (), self.op_id)
3283            {
3284                // Inserting duplicate keys has no effect.
3285                Ok(()) | Err(DurableCatalogError::DuplicateKey) => {}
3286                Err(e) => Err(StorageError::Generic(anyhow::anyhow!(e)))?,
3287            };
3288        }
3289        Ok(())
3290    }
3291
3292    fn remove_unfinalized_shards(&mut self, shards: BTreeSet<ShardId>) {
3293        let ks: Vec<_> = shards
3294            .into_iter()
3295            .map(|shard| UnfinalizedShardKey { shard })
3296            .collect();
3297        let _ = self.unfinalized_shards.delete_by_keys(ks, self.op_id);
3298    }
3299
3300    fn get_txn_wal_shard(&self) -> Option<ShardId> {
3301        self.txn_wal_shard
3302            .values()
3303            .iter()
3304            .next()
3305            .map(|TxnWalShardValue { shard }| *shard)
3306    }
3307
3308    fn write_txn_wal_shard(&mut self, shard: ShardId) -> Result<(), StorageError> {
3309        self.txn_wal_shard
3310            .insert((), TxnWalShardValue { shard }, self.op_id)
3311            .map_err(|err| match err {
3312                DurableCatalogError::DuplicateKey => StorageError::TxnWalShardAlreadyExists,
3313                err => StorageError::Generic(anyhow::anyhow!(err)),
3314            })
3315    }
3316}
3317
3318/// Describes a set of changes to apply as the result of a catalog transaction.
3319#[derive(Debug, PartialEq)]
3320pub struct TransactionBatch {
3321    pub(crate) databases: Vec<(proto::DatabaseKey, proto::DatabaseValue, Diff)>,
3322    pub(crate) schemas: Vec<(proto::SchemaKey, proto::SchemaValue, Diff)>,
3323    pub(crate) items: Vec<(proto::ItemKey, proto::ItemValue, Diff)>,
3324    pub(crate) item_columns: Vec<(proto::ItemColumnsKey, proto::ItemColumnsValue, Diff)>,
3325    pub(crate) index_columns: Vec<(proto::IndexColumnsKey, proto::IndexColumnsValue, Diff)>,
3326    pub(crate) comments: Vec<(proto::CommentKey, proto::CommentValue, Diff)>,
3327    pub(crate) roles: Vec<(proto::RoleKey, proto::RoleValue, Diff)>,
3328    pub(crate) role_auth: Vec<(proto::RoleAuthKey, proto::RoleAuthValue, Diff)>,
3329    pub(crate) clusters: Vec<(proto::ClusterKey, proto::ClusterValue, Diff)>,
3330    pub(crate) cluster_replicas: Vec<(proto::ClusterReplicaKey, proto::ClusterReplicaValue, Diff)>,
3331    pub(crate) network_policies: Vec<(proto::NetworkPolicyKey, proto::NetworkPolicyValue, Diff)>,
3332    pub(crate) cluster_replica_sizes: Vec<(
3333        proto::ClusterReplicaSizeKey,
3334        proto::ClusterReplicaSizeValue,
3335        Diff,
3336    )>,
3337    pub(crate) query_policies: Vec<(proto::QueryPolicyKey, proto::QueryPolicyValue, Diff)>,
3338    pub(crate) introspection_sources: Vec<(
3339        proto::ClusterIntrospectionSourceIndexKey,
3340        proto::ClusterIntrospectionSourceIndexValue,
3341        Diff,
3342    )>,
3343    pub(crate) id_allocator: Vec<(proto::IdAllocKey, proto::IdAllocValue, Diff)>,
3344    pub(crate) configs: Vec<(proto::ConfigKey, proto::ConfigValue, Diff)>,
3345    pub(crate) settings: Vec<(proto::SettingKey, proto::SettingValue, Diff)>,
3346    pub(crate) system_gid_mapping: Vec<(proto::GidMappingKey, proto::GidMappingValue, Diff)>,
3347    pub(crate) system_configurations: Vec<(
3348        proto::ServerConfigurationKey,
3349        proto::ServerConfigurationValue,
3350        Diff,
3351    )>,
3352    pub(crate) cluster_system_configurations: Vec<(
3353        proto::ClusterSystemConfigurationKey,
3354        proto::ClusterSystemConfigurationValue,
3355        Diff,
3356    )>,
3357    pub(crate) replica_system_configurations: Vec<(
3358        proto::ReplicaSystemConfigurationKey,
3359        proto::ReplicaSystemConfigurationValue,
3360        Diff,
3361    )>,
3362    pub(crate) default_privileges: Vec<(
3363        proto::DefaultPrivilegesKey,
3364        proto::DefaultPrivilegesValue,
3365        Diff,
3366    )>,
3367    pub(crate) source_references: Vec<(
3368        proto::SourceReferencesKey,
3369        proto::SourceReferencesValue,
3370        Diff,
3371    )>,
3372    pub(crate) system_privileges: Vec<(
3373        proto::SystemPrivilegesKey,
3374        proto::SystemPrivilegesValue,
3375        Diff,
3376    )>,
3377    pub(crate) storage_collection_metadata: Vec<(
3378        proto::StorageCollectionMetadataKey,
3379        proto::StorageCollectionMetadataValue,
3380        Diff,
3381    )>,
3382    pub(crate) unfinalized_shards: Vec<(proto::UnfinalizedShardKey, (), Diff)>,
3383    pub(crate) txn_wal_shard: Vec<((), proto::TxnWalShardValue, Diff)>,
3384    pub(crate) audit_log_updates: Vec<(proto::AuditLogKey, (), Diff)>,
3385    /// The upper of the catalog when the transaction started.
3386    pub(crate) upper: mz_repr::Timestamp,
3387    // A private, non-cloneable capability keeps batches constructible only by
3388    // transaction decomposition.
3389    _commit_capability: CommitCapability,
3390}
3391
3392impl TransactionBatch {
3393    pub fn is_empty(&self) -> bool {
3394        let TransactionBatch {
3395            databases,
3396            schemas,
3397            items,
3398            item_columns,
3399            index_columns,
3400            comments,
3401            roles,
3402            role_auth,
3403            clusters,
3404            cluster_replicas,
3405            network_policies,
3406            cluster_replica_sizes,
3407            query_policies,
3408            introspection_sources,
3409            id_allocator,
3410            configs,
3411            settings,
3412            source_references,
3413            system_gid_mapping,
3414            system_configurations,
3415            cluster_system_configurations,
3416            replica_system_configurations,
3417            default_privileges,
3418            system_privileges,
3419            storage_collection_metadata,
3420            unfinalized_shards,
3421            txn_wal_shard,
3422            audit_log_updates,
3423            upper: _,
3424            _commit_capability: _,
3425        } = self;
3426        databases.is_empty()
3427            && schemas.is_empty()
3428            && items.is_empty()
3429            && item_columns.is_empty()
3430            && index_columns.is_empty()
3431            && comments.is_empty()
3432            && roles.is_empty()
3433            && role_auth.is_empty()
3434            && clusters.is_empty()
3435            && cluster_replicas.is_empty()
3436            && network_policies.is_empty()
3437            && cluster_replica_sizes.is_empty()
3438            && query_policies.is_empty()
3439            && introspection_sources.is_empty()
3440            && id_allocator.is_empty()
3441            && configs.is_empty()
3442            && settings.is_empty()
3443            && source_references.is_empty()
3444            && system_gid_mapping.is_empty()
3445            && system_configurations.is_empty()
3446            && cluster_system_configurations.is_empty()
3447            && replica_system_configurations.is_empty()
3448            && default_privileges.is_empty()
3449            && system_privileges.is_empty()
3450            && storage_collection_metadata.is_empty()
3451            && unfinalized_shards.is_empty()
3452            && txn_wal_shard.is_empty()
3453            && audit_log_updates.is_empty()
3454    }
3455}
3456
3457#[derive(Debug, Clone, PartialEq, Eq)]
3458struct TransactionUpdate<V> {
3459    value: V,
3460    ts: Timestamp,
3461    diff: Diff,
3462}
3463
3464/// Utility trait to check for plan validity.
3465trait UniqueName {
3466    /// Does the item have a unique name? If yes, we can check for name equality in validity
3467    /// checking.
3468    const HAS_UNIQUE_NAME: bool;
3469    /// The unique name, only returns a meaningful name if [`Self::HAS_UNIQUE_NAME`] is `true`.
3470    fn unique_name(&self) -> &str;
3471}
3472
3473mod unique_name {
3474    use crate::durable::objects::*;
3475
3476    macro_rules! impl_unique_name {
3477        ($($t:ty),* $(,)?) => {
3478            $(
3479                impl crate::durable::transaction::UniqueName for $t {
3480                    const HAS_UNIQUE_NAME: bool = true;
3481                    fn unique_name(&self) -> &str {
3482                        &self.name
3483                    }
3484                }
3485            )*
3486        };
3487    }
3488
3489    macro_rules! impl_no_unique_name {
3490        ($($t:ty),* $(,)?) => {
3491            $(
3492                impl crate::durable::transaction::UniqueName for $t {
3493                    const HAS_UNIQUE_NAME: bool = false;
3494                    fn unique_name(&self) -> &str {
3495                       ""
3496                    }
3497                }
3498            )*
3499        };
3500    }
3501
3502    impl_unique_name! {
3503        ClusterReplicaSizeValue,
3504        ClusterReplicaValue,
3505        ClusterValue,
3506        DatabaseValue,
3507        ItemValue,
3508        NetworkPolicyValue,
3509        QueryPolicyValue,
3510        RoleValue,
3511        SchemaValue,
3512    }
3513
3514    impl_no_unique_name!(
3515        (),
3516        ClusterIntrospectionSourceIndexValue,
3517        ClusterSystemConfigurationValue,
3518        CommentValue,
3519        ConfigValue,
3520        DefaultPrivilegesValue,
3521        GidMappingValue,
3522        IdAllocValue,
3523        IndexColumnsValue,
3524        ItemColumnsValue,
3525        ReplicaSystemConfigurationValue,
3526        ServerConfigurationValue,
3527        SettingValue,
3528        SourceReferencesValue,
3529        StorageCollectionMetadataValue,
3530        SystemPrivilegesValue,
3531        TxnWalShardValue,
3532        RoleAuthValue,
3533    );
3534
3535    #[cfg(test)]
3536    mod test {
3537        impl_no_unique_name!(String,);
3538    }
3539}
3540
3541/// A collection's uniqueness constraint.
3542///
3543/// `violation` reports whether two values conflict, i.e. cannot both exist.
3544///
3545/// `is_unique_key_unchanged_after_update` reports whether an update left
3546/// unchanged every field `violation` reads. It is used as an optimization
3547/// since `violation` is an expensive operation to run.
3548#[derive(Debug)]
3549struct UniquenessCheck<V> {
3550    violation: fn(a: &V, b: &V) -> bool,
3551    is_unique_key_unchanged_after_update: fn(prev: &V, next: &V) -> bool,
3552}
3553
3554/// TableTransaction emulates some features of a typical SQL transaction over
3555/// table for a Collection.
3556///
3557/// It supports:
3558/// - uniqueness constraints
3559/// - transactional reads and writes (including read-your-writes before commit)
3560///
3561/// `K` is the primary key type. Multiple entries with the same key are disallowed.
3562/// `V` is the an arbitrary value type.
3563#[derive(Debug)]
3564struct TableTransaction<K, V> {
3565    initial: BTreeMap<K, V>,
3566    // The desired updates to keys after commit.
3567    // Invariant: Value is sorted by `ts`.
3568    pending: BTreeMap<K, Vec<TransactionUpdate<V>>>,
3569    // `None` for collections with no uniqueness constraint.
3570    uniqueness_check: Option<UniquenessCheck<V>>,
3571}
3572
3573impl<K, V> TableTransaction<K, V>
3574where
3575    K: Ord + Eq + Clone + Debug,
3576    V: Ord + Clone + Debug + UniqueName,
3577{
3578    /// Create a new TableTransaction with initial data.
3579    ///
3580    /// Internally the catalog serializes data as protobuf. All fields in a proto message are
3581    /// optional, which makes using them in Rust cumbersome. Generic parameters `KP` and `VP` are
3582    /// protobuf types which deserialize to `K` and `V` that a [`TableTransaction`] is generic
3583    /// over.
3584    fn new<KP, VP>(initial: BTreeMap<KP, VP>) -> Result<Self, TryFromProtoError>
3585    where
3586        K: RustType<KP>,
3587        V: RustType<VP>,
3588    {
3589        let initial = initial
3590            .into_iter()
3591            .map(RustType::from_proto)
3592            .collect::<Result<_, _>>()?;
3593
3594        Ok(Self {
3595            initial,
3596            pending: BTreeMap::new(),
3597            uniqueness_check: None,
3598        })
3599    }
3600
3601    /// Like [`Self::new`], but with the collection's uniqueness constraint.
3602    /// See [`UniquenessCheck`] for more details on the uniqueness constraint.
3603    fn new_with_uniqueness_fn<KP, VP>(
3604        initial: BTreeMap<KP, VP>,
3605        uniqueness_violation: fn(a: &V, b: &V) -> bool,
3606        is_unique_key_unchanged_after_update: fn(prev: &V, next: &V) -> bool,
3607    ) -> Result<Self, TryFromProtoError>
3608    where
3609        K: RustType<KP>,
3610        V: RustType<VP>,
3611    {
3612        let initial = initial
3613            .into_iter()
3614            .map(RustType::from_proto)
3615            .collect::<Result<_, _>>()?;
3616
3617        Ok(Self {
3618            initial,
3619            pending: BTreeMap::new(),
3620            uniqueness_check: Some(UniquenessCheck {
3621                violation: uniqueness_violation,
3622                is_unique_key_unchanged_after_update,
3623            }),
3624        })
3625    }
3626
3627    /// Consumes and returns the pending changes and their diffs. `Diff` is
3628    /// guaranteed to be 1 or -1.
3629    fn pending<KP, VP>(self) -> Vec<(KP, VP, Diff)>
3630    where
3631        K: RustType<KP>,
3632        V: RustType<VP>,
3633    {
3634        soft_assert_no_log!(self.verify().is_ok());
3635        // Pending describes the desired final state for some keys. K,V pairs should be
3636        // retracted if they already exist and were deleted or are being updated.
3637        self.pending
3638            .into_iter()
3639            .flat_map(|(k, v)| {
3640                let mut v: Vec<_> = v
3641                    .into_iter()
3642                    .map(|TransactionUpdate { value, ts: _, diff }| (value, diff))
3643                    .collect();
3644                differential_dataflow::consolidation::consolidate(&mut v);
3645                v.into_iter().map(move |(v, diff)| (k.clone(), v, diff))
3646            })
3647            .map(|(key, val, diff)| (key.into_proto(), val.into_proto(), diff))
3648            .collect()
3649    }
3650
3651    /// Verifies that no items in `self` violate `self.uniqueness_check`.
3652    ///
3653    /// Runtime is O(n^2), where n is the number of items in `self`, if
3654    /// [`UniqueName::HAS_UNIQUE_NAME`] is false for `V`. Prefer using [`Self::verify_keys`].
3655    fn verify(&self) -> Result<(), DurableCatalogError> {
3656        if let Some(check) = &self.uniqueness_check {
3657            // Compare each value to each other value and ensure they are unique.
3658            let items = self.values();
3659            if V::HAS_UNIQUE_NAME {
3660                let by_name: BTreeMap<_, _> = items
3661                    .iter()
3662                    .enumerate()
3663                    .map(|(v, vi)| (vi.unique_name(), (v, vi)))
3664                    .collect();
3665                for (i, vi) in items.iter().enumerate() {
3666                    if let Some((j, vj)) = by_name.get(vi.unique_name()) {
3667                        if i != *j && (check.violation)(vi, *vj) {
3668                            return Err(DurableCatalogError::UniquenessViolation);
3669                        }
3670                    }
3671                }
3672            } else {
3673                for (i, vi) in items.iter().enumerate() {
3674                    for (j, vj) in items.iter().enumerate() {
3675                        if i != j && (check.violation)(vi, vj) {
3676                            return Err(DurableCatalogError::UniquenessViolation);
3677                        }
3678                    }
3679                }
3680            }
3681        }
3682        soft_assert_no_log!(
3683            self.pending
3684                .values()
3685                .all(|pending| { pending.is_sorted_by(|a, b| a.ts <= b.ts) }),
3686            "pending should be sorted by timestamp: {:?}",
3687            self.pending
3688        );
3689        Ok(())
3690    }
3691
3692    /// Verifies that no items in `self` violate `self.uniqueness_check` with `keys`.
3693    ///
3694    /// Runtime is O(n * k), where n is the number of items in `self` and k is the number of
3695    /// items in `keys`.
3696    fn verify_keys<'a>(
3697        &self,
3698        keys: impl IntoIterator<Item = &'a K>,
3699    ) -> Result<(), DurableCatalogError>
3700    where
3701        K: 'a,
3702    {
3703        if let Some(check) = &self.uniqueness_check {
3704            let entries: Vec<_> = keys
3705                .into_iter()
3706                .filter_map(|key| self.get(key).map(|value| (key, value)))
3707                .collect();
3708            // Compare each value in `entries` to each value in `self` and ensure they are unique.
3709            for (ki, vi) in self.items() {
3710                for (kj, vj) in &entries {
3711                    if ki != *kj && (check.violation)(vi, vj) {
3712                        return Err(DurableCatalogError::UniquenessViolation);
3713                    }
3714                }
3715            }
3716        }
3717        soft_assert_no_log!(self.verify().is_ok());
3718        Ok(())
3719    }
3720
3721    /// Iterates over the items viewable in the current transaction in arbitrary
3722    /// order and applies `f` on all key, value pairs.
3723    fn for_values<'a, F: FnMut(&'a K, &'a V)>(&'a self, mut f: F) {
3724        let mut seen = BTreeSet::new();
3725        for k in self.pending.keys() {
3726            seen.insert(k);
3727            let v = self.get(k);
3728            // Deleted items don't exist so shouldn't be visited, but still suppress
3729            // visiting the key later.
3730            if let Some(v) = v {
3731                f(k, v);
3732            }
3733        }
3734        for (k, v) in self.initial.iter() {
3735            // Add on initial items that don't have updates.
3736            if !seen.contains(k) {
3737                f(k, v);
3738            }
3739        }
3740    }
3741
3742    /// Returns the current value of `k`.
3743    fn get(&self, k: &K) -> Option<&V> {
3744        let pending = self.pending.get(k).map(Vec::as_slice).unwrap_or_default();
3745        let mut updates = Vec::with_capacity(pending.len() + 1);
3746        if let Some(initial) = self.initial.get(k) {
3747            updates.push((initial, Diff::ONE));
3748        }
3749        updates.extend(
3750            pending
3751                .into_iter()
3752                .map(|TransactionUpdate { value, ts: _, diff }| (value, *diff)),
3753        );
3754
3755        differential_dataflow::consolidation::consolidate(&mut updates);
3756        assert!(updates.len() <= 1);
3757        updates.into_iter().next().map(|(v, _)| v)
3758    }
3759
3760    /// Returns the items viewable in the current transaction. The items are
3761    /// cloned, so this is an expensive operation. Prefer using [`Self::items`], or
3762    /// [`Self::for_values`].
3763    // Used by tests.
3764    #[cfg(test)]
3765    fn items_cloned(&self) -> BTreeMap<K, V> {
3766        let mut items = BTreeMap::new();
3767        self.for_values(|k, v| {
3768            items.insert(k.clone(), v.clone());
3769        });
3770        items
3771    }
3772
3773    /// Returns the current items as proto-typed key-value pairs, suitable for
3774    /// constructing a [`Snapshot`]. This merges `initial` and `pending` to
3775    /// produce the current view and converts back to proto types.
3776    fn current_items_proto<KP, VP>(&self) -> BTreeMap<KP, VP>
3777    where
3778        K: RustType<KP>,
3779        V: RustType<VP>,
3780        KP: Ord,
3781    {
3782        let mut items = BTreeMap::new();
3783        self.for_values(|k, v| {
3784            items.insert(k.into_proto(), v.into_proto());
3785        });
3786        items
3787    }
3788
3789    /// Returns the items viewable in the current transaction as references. Returns a map
3790    /// of references.
3791    fn items(&self) -> BTreeMap<&K, &V> {
3792        let mut items = BTreeMap::new();
3793        self.for_values(|k, v| {
3794            items.insert(k, v);
3795        });
3796        items
3797    }
3798
3799    /// Returns the values viewable in the current transaction as references.
3800    fn values(&self) -> BTreeSet<&V> {
3801        let mut items = BTreeSet::new();
3802        self.for_values(|_, v| {
3803            items.insert(v);
3804        });
3805        items
3806    }
3807
3808    /// Returns the number of items viewable in the current transaction.
3809    fn len(&self) -> usize {
3810        let mut count = 0;
3811        self.for_values(|_, _| {
3812            count += 1;
3813        });
3814        count
3815    }
3816
3817    /// Iterates over the items viewable in the current transaction, and provides a
3818    /// map where additional pending items can be inserted, which will be appended
3819    /// to current pending items. Does not verify uniqueness.
3820    fn for_values_mut<F: FnMut(&mut BTreeMap<K, Vec<TransactionUpdate<V>>>, &K, &V)>(
3821        &mut self,
3822        mut f: F,
3823    ) {
3824        let mut pending = BTreeMap::new();
3825        self.for_values(|k, v| f(&mut pending, k, v));
3826        for (k, updates) in pending {
3827            self.pending.entry(k).or_default().extend(updates);
3828        }
3829    }
3830
3831    /// Inserts a new k,v pair.
3832    ///
3833    /// Returns an error if the uniqueness check failed or the key already exists.
3834    fn insert(&mut self, k: K, v: V, ts: Timestamp) -> Result<(), DurableCatalogError> {
3835        let mut violation = None;
3836        let uniqueness_violation = self.uniqueness_check.as_ref().map(|check| check.violation);
3837        self.for_values(|for_k, for_v| {
3838            if &k == for_k {
3839                violation = Some(DurableCatalogError::DuplicateKey);
3840            }
3841            if let Some(uniqueness_violation) = uniqueness_violation {
3842                if uniqueness_violation(for_v, &v) {
3843                    violation = Some(DurableCatalogError::UniquenessViolation);
3844                }
3845            }
3846        });
3847        if let Some(violation) = violation {
3848            return Err(violation);
3849        }
3850        self.pending.entry(k).or_default().push(TransactionUpdate {
3851            value: v,
3852            ts,
3853            diff: Diff::ONE,
3854        });
3855        soft_assert_no_log!(self.verify().is_ok());
3856        Ok(())
3857    }
3858
3859    /// Updates k, v pairs. `f` is a function that can return `Some(V)` if the
3860    /// value should be updated, otherwise `None`. Returns the number of changed
3861    /// entries.
3862    ///
3863    /// Returns an error if the uniqueness check failed.
3864    ///
3865    /// Prefer using [`Self::update_by_key`] or [`Self::update_by_keys`], which generally have
3866    /// better performance.
3867    fn update<F: Fn(&K, &V) -> Option<V>>(
3868        &mut self,
3869        f: F,
3870        ts: Timestamp,
3871    ) -> Result<Diff, DurableCatalogError> {
3872        let mut changed = Diff::ZERO;
3873        let mut keys = BTreeSet::new();
3874        // Keep a copy of pending in case of uniqueness violation.
3875        let pending = self.pending.clone();
3876        self.for_values_mut(|p, k, v| {
3877            if let Some(next) = f(k, v) {
3878                changed += Diff::ONE;
3879                keys.insert(k.clone());
3880                let updates = p.entry(k.clone()).or_default();
3881                updates.push(TransactionUpdate {
3882                    value: v.clone(),
3883                    ts,
3884                    diff: Diff::MINUS_ONE,
3885                });
3886                updates.push(TransactionUpdate {
3887                    value: next,
3888                    ts,
3889                    diff: Diff::ONE,
3890                });
3891            }
3892        });
3893        // Check for uniqueness violation.
3894        if let Err(err) = self.verify_keys(&keys) {
3895            self.pending = pending;
3896            Err(err)
3897        } else {
3898            Ok(changed)
3899        }
3900    }
3901
3902    /// Updates `k`, `v` pair if `k` already exists in `self`.
3903    ///
3904    /// Returns `true` if `k` was updated, `false` otherwise.
3905    /// Returns an error if the uniqueness check failed.
3906    fn update_by_key(&mut self, k: K, v: V, ts: Timestamp) -> Result<bool, DurableCatalogError> {
3907        if let Some(cur_v) = self.get(&k) {
3908            if v != *cur_v {
3909                self.set(k, Some(v), ts)?;
3910            }
3911            Ok(true)
3912        } else {
3913            Ok(false)
3914        }
3915    }
3916
3917    /// Updates k, v pairs. Keys that don't already exist in `self` are ignored.
3918    ///
3919    /// Returns the number of changed entries.
3920    /// Returns an error if the uniqueness check failed.
3921    fn update_by_keys(
3922        &mut self,
3923        kvs: impl IntoIterator<Item = (K, V)>,
3924        ts: Timestamp,
3925    ) -> Result<Diff, DurableCatalogError> {
3926        let kvs: Vec<_> = kvs
3927            .into_iter()
3928            .filter_map(|(k, v)| match self.get(&k) {
3929                // Record if updating this entry would be a no-op.
3930                Some(cur_v) => Some((*cur_v == v, k, v)),
3931                None => None,
3932            })
3933            .collect();
3934        let changed = kvs.len();
3935        let changed =
3936            Diff::try_from(changed).map_err(|e| DurableCatalogError::Internal(e.to_string()))?;
3937        let kvs = kvs
3938            .into_iter()
3939            // Filter out no-ops to save some work.
3940            .filter(|(no_op, _, _)| !no_op)
3941            .map(|(_, k, v)| (k, Some(v)))
3942            .collect();
3943        self.set_many(kvs, ts)?;
3944        Ok(changed)
3945    }
3946
3947    /// Whether changing a key's value from `prev` to `next` can introduce a uniqueness violation
3948    fn update_needs_uniqueness_check(&self, prev: Option<&V>, next: Option<&V>) -> bool {
3949        match (&self.uniqueness_check, prev, next) {
3950            // No uniqueness constraint, or a delete: nothing to check.
3951            (None, _, _) | (_, _, None) => false,
3952            // An update: a scan is only needed if it changed the unique key.
3953            (Some(check), Some(prev), Some(next)) => {
3954                !(check.is_unique_key_unchanged_after_update)(prev, next)
3955            }
3956            // An insert: must check.
3957            (Some(_), None, Some(_)) => true,
3958        }
3959    }
3960
3961    /// Set the value for a key. Returns the previous entry if the key existed,
3962    /// otherwise None.
3963    ///
3964    /// Returns an error if the uniqueness check failed.
3965    ///
3966    /// DO NOT call this function in a loop, use [`Self::set_many`] instead.
3967    fn set(&mut self, k: K, v: Option<V>, ts: Timestamp) -> Result<Option<V>, DurableCatalogError> {
3968        let prev = self.get(&k).cloned();
3969        let needs_uniqueness_check = self.update_needs_uniqueness_check(prev.as_ref(), v.as_ref());
3970        let entry = self.pending.entry(k.clone()).or_default();
3971        let restore_len = entry.len();
3972
3973        match (v, prev.clone()) {
3974            (Some(v), Some(prev)) => {
3975                entry.push(TransactionUpdate {
3976                    value: prev,
3977                    ts,
3978                    diff: Diff::MINUS_ONE,
3979                });
3980                entry.push(TransactionUpdate {
3981                    value: v,
3982                    ts,
3983                    diff: Diff::ONE,
3984                });
3985            }
3986            (Some(v), None) => {
3987                entry.push(TransactionUpdate {
3988                    value: v,
3989                    ts,
3990                    diff: Diff::ONE,
3991                });
3992            }
3993            (None, Some(prev)) => {
3994                entry.push(TransactionUpdate {
3995                    value: prev,
3996                    ts,
3997                    diff: Diff::MINUS_ONE,
3998                });
3999            }
4000            (None, None) => {}
4001        }
4002
4003        // Check for uniqueness violation
4004        if needs_uniqueness_check {
4005            if let Err(err) = self.verify_keys([&k]) {
4006                // Revert self.pending to the state it was in before calling this
4007                // function.
4008                let pending = self.pending.get_mut(&k).expect("inserted above");
4009                pending.truncate(restore_len);
4010                return Err(err);
4011            }
4012        }
4013        Ok(prev)
4014    }
4015
4016    /// Set the values for many keys. Returns the previous entry for each key if the key existed,
4017    /// otherwise None.
4018    ///
4019    /// Returns an error if any uniqueness check failed.
4020    fn set_many(
4021        &mut self,
4022        kvs: BTreeMap<K, Option<V>>,
4023        ts: Timestamp,
4024    ) -> Result<BTreeMap<K, Option<V>>, DurableCatalogError> {
4025        if kvs.is_empty() {
4026            return Ok(BTreeMap::new());
4027        }
4028
4029        let mut prevs = BTreeMap::new();
4030        let mut restores = BTreeMap::new();
4031        // Only the keys whose update can introduce a uniqueness violation need scanning.
4032        let mut keys_to_verify_uniqueness = Vec::new();
4033
4034        for (k, v) in kvs {
4035            let prev = self.get(&k).cloned();
4036            if self.update_needs_uniqueness_check(prev.as_ref(), v.as_ref()) {
4037                keys_to_verify_uniqueness.push(k.clone());
4038            }
4039            let entry = self.pending.entry(k.clone()).or_default();
4040            restores.insert(k.clone(), entry.len());
4041
4042            match (v, prev.clone()) {
4043                (Some(v), Some(prev)) => {
4044                    entry.push(TransactionUpdate {
4045                        value: prev,
4046                        ts,
4047                        diff: Diff::MINUS_ONE,
4048                    });
4049                    entry.push(TransactionUpdate {
4050                        value: v,
4051                        ts,
4052                        diff: Diff::ONE,
4053                    });
4054                }
4055                (Some(v), None) => {
4056                    entry.push(TransactionUpdate {
4057                        value: v,
4058                        ts,
4059                        diff: Diff::ONE,
4060                    });
4061                }
4062                (None, Some(prev)) => {
4063                    entry.push(TransactionUpdate {
4064                        value: prev,
4065                        ts,
4066                        diff: Diff::MINUS_ONE,
4067                    });
4068                }
4069                (None, None) => {}
4070            }
4071
4072            prevs.insert(k, prev);
4073        }
4074
4075        // Check for uniqueness violation.
4076        if let Err(err) = self.verify_keys(keys_to_verify_uniqueness.iter()) {
4077            for (k, restore_len) in restores {
4078                // Revert self.pending to the state it was in before calling this
4079                // function.
4080                let pending = self.pending.get_mut(&k).expect("inserted above");
4081                pending.truncate(restore_len);
4082            }
4083            Err(err)
4084        } else {
4085            Ok(prevs)
4086        }
4087    }
4088
4089    /// Deletes items for which `f` returns true. Returns the keys and values of
4090    /// the deleted entries.
4091    ///
4092    /// Prefer using [`Self::delete_by_key`] or [`Self::delete_by_keys`], which generally have
4093    /// better performance.
4094    fn delete<F: Fn(&K, &V) -> bool>(&mut self, f: F, ts: Timestamp) -> Vec<(K, V)> {
4095        let mut deleted = Vec::new();
4096        self.for_values_mut(|p, k, v| {
4097            if f(k, v) {
4098                deleted.push((k.clone(), v.clone()));
4099                p.entry(k.clone()).or_default().push(TransactionUpdate {
4100                    value: v.clone(),
4101                    ts,
4102                    diff: Diff::MINUS_ONE,
4103                });
4104            }
4105        });
4106        soft_assert_no_log!(self.verify().is_ok());
4107        deleted
4108    }
4109
4110    /// Deletes item with key `k`.
4111    ///
4112    /// Returns the value of the deleted entry, if it existed.
4113    fn delete_by_key(&mut self, k: K, ts: Timestamp) -> Option<V> {
4114        self.set(k, None, ts)
4115            .expect("deleting an entry cannot violate uniqueness")
4116    }
4117
4118    /// Deletes items with key in `ks`.
4119    ///
4120    /// Returns the keys and values of the deleted entries.
4121    fn delete_by_keys(&mut self, ks: impl IntoIterator<Item = K>, ts: Timestamp) -> Vec<(K, V)> {
4122        let kvs = ks.into_iter().map(|k| (k, None)).collect();
4123        let prevs = self
4124            .set_many(kvs, ts)
4125            .expect("deleting entries cannot violate uniqueness");
4126        prevs
4127            .into_iter()
4128            .filter_map(|(k, v)| v.map(|v| (k, v)))
4129            .collect()
4130    }
4131}
4132
4133#[cfg(test)]
4134#[allow(clippy::unwrap_used)]
4135mod tests {
4136    use super::*;
4137
4138    use mz_controller::clusters::ReplicaLogging;
4139    use mz_ore::now::SYSTEM_TIME;
4140    use mz_ore::{assert_none, assert_ok};
4141    use mz_persist_client::cache::PersistClientCache;
4142    use mz_persist_types::PersistLocation;
4143    use semver::Version;
4144
4145    use crate::durable::{
4146        ReplicaConfig, ReplicaLocation, TestCatalogStateBuilder, test_bootstrap_args,
4147    };
4148    use crate::memory;
4149
4150    #[mz_ore::test]
4151    fn test_table_transaction_simple() {
4152        fn uniqueness_violation(a: &String, b: &String) -> bool {
4153            a == b
4154        }
4155        let mut table = TableTransaction::new_with_uniqueness_fn(
4156            BTreeMap::from([(1i64.to_le_bytes().to_vec(), "a".to_string())]),
4157            uniqueness_violation,
4158            uniqueness_violation,
4159        )
4160        .unwrap();
4161
4162        // Ideally, we compare for errors here, but it's hard/impossible to implement PartialEq
4163        // for DurableCatalogError.
4164        assert_ok!(table.insert(2i64.to_le_bytes().to_vec(), "b".to_string(), 0));
4165        assert_ok!(table.insert(3i64.to_le_bytes().to_vec(), "c".to_string(), 0));
4166        assert!(
4167            table
4168                .insert(1i64.to_le_bytes().to_vec(), "c".to_string(), 0)
4169                .is_err()
4170        );
4171        assert!(
4172            table
4173                .insert(4i64.to_le_bytes().to_vec(), "c".to_string(), 0)
4174                .is_err()
4175        );
4176    }
4177
4178    #[mz_ore::test]
4179    fn test_skip_scan_when_unique_key_unchanged() {
4180        fn first_char_same(prev: &String, next: &String) -> bool {
4181            prev.chars().next() == next.chars().next()
4182        }
4183
4184        // Panics if the uniqueness scan ever runs
4185        fn panic_uniqueness_violation(_: &String, _: &String) -> bool {
4186            panic!("uniqueness scan ran for an update that kept the same unique key");
4187        }
4188        let mut table = TableTransaction::new_with_uniqueness_fn(
4189            BTreeMap::from([
4190                (1i64.to_le_bytes().to_vec(), "a1".to_string()),
4191                (2i64.to_le_bytes().to_vec(), "b1".to_string()),
4192            ]),
4193            panic_uniqueness_violation,
4194            // We treat the first character as the unique key.
4195            first_char_same,
4196        )
4197        .unwrap();
4198        // Same first char, so the unique key didn't change and the update must not scan
4199        // for uniqueness.
4200        assert!(
4201            table
4202                .update_by_key(1i64.to_le_bytes().to_vec(), "a2".to_string(), 0)
4203                .unwrap()
4204        );
4205
4206        // An update that changes the unique key must still run the scan and detect a collision.
4207        fn real_uniqueness_violation(a: &String, b: &String) -> bool {
4208            a.chars().next() == b.chars().next()
4209        }
4210        let mut table = TableTransaction::new_with_uniqueness_fn(
4211            BTreeMap::from([
4212                (1i64.to_le_bytes().to_vec(), "a1".to_string()),
4213                (2i64.to_le_bytes().to_vec(), "b1".to_string()),
4214            ]),
4215            real_uniqueness_violation,
4216            first_char_same,
4217        )
4218        .unwrap();
4219        // Changing key 1's first char from 'a' to 'b' changes its unique key and collides
4220        // with key 2.
4221        assert!(
4222            table
4223                .update_by_key(1i64.to_le_bytes().to_vec(), "b2".to_string(), 0)
4224                .is_err()
4225        );
4226    }
4227
4228    #[mz_ore::test]
4229    fn test_table_transaction() {
4230        fn uniqueness_violation(a: &String, b: &String) -> bool {
4231            a == b
4232        }
4233        let mut table: BTreeMap<Vec<u8>, String> = BTreeMap::new();
4234
4235        fn commit(
4236            table: &mut BTreeMap<Vec<u8>, String>,
4237            mut pending: Vec<(Vec<u8>, String, Diff)>,
4238        ) {
4239            // Sort by diff so that we process retractions first.
4240            pending.sort_by(|a, b| a.2.cmp(&b.2));
4241            for (k, v, diff) in pending {
4242                if diff == Diff::MINUS_ONE {
4243                    let prev = table.remove(&k);
4244                    assert_eq!(prev, Some(v));
4245                } else if diff == Diff::ONE {
4246                    let prev = table.insert(k, v);
4247                    assert_eq!(prev, None);
4248                } else {
4249                    panic!("unexpected diff: {diff}");
4250                }
4251            }
4252        }
4253
4254        table.insert(1i64.to_le_bytes().to_vec(), "v1".to_string());
4255        table.insert(2i64.to_le_bytes().to_vec(), "v2".to_string());
4256        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4257            table.clone(),
4258            uniqueness_violation,
4259            uniqueness_violation,
4260        )
4261        .unwrap();
4262        assert_eq!(table_txn.items_cloned(), table);
4263        assert_eq!(table_txn.delete(|_k, _v| false, 0).len(), 0);
4264        assert_eq!(table_txn.delete(|_k, v| v == "v2", 1).len(), 1);
4265        assert_eq!(
4266            table_txn.items_cloned(),
4267            BTreeMap::from([(1i64.to_le_bytes().to_vec(), "v1".to_string())])
4268        );
4269        assert_eq!(
4270            table_txn
4271                .update(|_k, _v| Some("v3".to_string()), 2)
4272                .unwrap(),
4273            Diff::ONE
4274        );
4275
4276        // Uniqueness violation.
4277        table_txn
4278            .insert(3i64.to_le_bytes().to_vec(), "v3".to_string(), 3)
4279            .unwrap_err();
4280
4281        table_txn
4282            .insert(3i64.to_le_bytes().to_vec(), "v4".to_string(), 4)
4283            .unwrap();
4284        assert_eq!(
4285            table_txn.items_cloned(),
4286            BTreeMap::from([
4287                (1i64.to_le_bytes().to_vec(), "v3".to_string()),
4288                (3i64.to_le_bytes().to_vec(), "v4".to_string()),
4289            ])
4290        );
4291        let err = table_txn
4292            .update(|_k, _v| Some("v1".to_string()), 5)
4293            .unwrap_err();
4294        assert!(
4295            matches!(err, DurableCatalogError::UniquenessViolation),
4296            "unexpected err: {err:?}"
4297        );
4298        let pending = table_txn.pending();
4299        assert_eq!(
4300            pending,
4301            vec![
4302                (
4303                    1i64.to_le_bytes().to_vec(),
4304                    "v1".to_string(),
4305                    Diff::MINUS_ONE
4306                ),
4307                (1i64.to_le_bytes().to_vec(), "v3".to_string(), Diff::ONE),
4308                (
4309                    2i64.to_le_bytes().to_vec(),
4310                    "v2".to_string(),
4311                    Diff::MINUS_ONE
4312                ),
4313                (3i64.to_le_bytes().to_vec(), "v4".to_string(), Diff::ONE),
4314            ]
4315        );
4316        commit(&mut table, pending);
4317        assert_eq!(
4318            table,
4319            BTreeMap::from([
4320                (1i64.to_le_bytes().to_vec(), "v3".to_string()),
4321                (3i64.to_le_bytes().to_vec(), "v4".to_string())
4322            ])
4323        );
4324
4325        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4326            table.clone(),
4327            uniqueness_violation,
4328            uniqueness_violation,
4329        )
4330        .unwrap();
4331        // Deleting then creating an item that has a uniqueness violation should work.
4332        assert_eq!(
4333            table_txn.delete(|k, _v| k == &1i64.to_le_bytes(), 0).len(),
4334            1
4335        );
4336        table_txn
4337            .insert(1i64.to_le_bytes().to_vec(), "v3".to_string(), 0)
4338            .unwrap();
4339        // Uniqueness violation in value.
4340        table_txn
4341            .insert(5i64.to_le_bytes().to_vec(), "v3".to_string(), 0)
4342            .unwrap_err();
4343        // Key already exists, expect error.
4344        table_txn
4345            .insert(1i64.to_le_bytes().to_vec(), "v5".to_string(), 0)
4346            .unwrap_err();
4347        assert_eq!(
4348            table_txn.delete(|k, _v| k == &1i64.to_le_bytes(), 0).len(),
4349            1
4350        );
4351        // Both the inserts work now because the key and uniqueness violation are gone.
4352        table_txn
4353            .insert(5i64.to_le_bytes().to_vec(), "v3".to_string(), 0)
4354            .unwrap();
4355        table_txn
4356            .insert(1i64.to_le_bytes().to_vec(), "v5".to_string(), 0)
4357            .unwrap();
4358        let pending = table_txn.pending();
4359        assert_eq!(
4360            pending,
4361            vec![
4362                (
4363                    1i64.to_le_bytes().to_vec(),
4364                    "v3".to_string(),
4365                    Diff::MINUS_ONE
4366                ),
4367                (1i64.to_le_bytes().to_vec(), "v5".to_string(), Diff::ONE),
4368                (5i64.to_le_bytes().to_vec(), "v3".to_string(), Diff::ONE),
4369            ]
4370        );
4371        commit(&mut table, pending);
4372        assert_eq!(
4373            table,
4374            BTreeMap::from([
4375                (1i64.to_le_bytes().to_vec(), "v5".to_string()),
4376                (3i64.to_le_bytes().to_vec(), "v4".to_string()),
4377                (5i64.to_le_bytes().to_vec(), "v3".to_string()),
4378            ])
4379        );
4380
4381        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4382            table.clone(),
4383            uniqueness_violation,
4384            uniqueness_violation,
4385        )
4386        .unwrap();
4387        assert_eq!(table_txn.delete(|_k, _v| true, 0).len(), 3);
4388        table_txn
4389            .insert(1i64.to_le_bytes().to_vec(), "v1".to_string(), 0)
4390            .unwrap();
4391
4392        commit(&mut table, table_txn.pending());
4393        assert_eq!(
4394            table,
4395            BTreeMap::from([(1i64.to_le_bytes().to_vec(), "v1".to_string()),])
4396        );
4397
4398        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4399            table.clone(),
4400            uniqueness_violation,
4401            uniqueness_violation,
4402        )
4403        .unwrap();
4404        assert_eq!(table_txn.delete(|_k, _v| true, 0).len(), 1);
4405        table_txn
4406            .insert(1i64.to_le_bytes().to_vec(), "v2".to_string(), 0)
4407            .unwrap();
4408        commit(&mut table, table_txn.pending());
4409        assert_eq!(
4410            table,
4411            BTreeMap::from([(1i64.to_le_bytes().to_vec(), "v2".to_string()),])
4412        );
4413
4414        // Verify we don't try to delete v3 or v4 during commit.
4415        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4416            table.clone(),
4417            uniqueness_violation,
4418            uniqueness_violation,
4419        )
4420        .unwrap();
4421        assert_eq!(table_txn.delete(|_k, _v| true, 0).len(), 1);
4422        table_txn
4423            .insert(1i64.to_le_bytes().to_vec(), "v3".to_string(), 0)
4424            .unwrap();
4425        table_txn
4426            .insert(1i64.to_le_bytes().to_vec(), "v4".to_string(), 1)
4427            .unwrap_err();
4428        assert_eq!(table_txn.delete(|_k, _v| true, 1).len(), 1);
4429        table_txn
4430            .insert(1i64.to_le_bytes().to_vec(), "v5".to_string(), 1)
4431            .unwrap();
4432        commit(&mut table, table_txn.pending());
4433        assert_eq!(
4434            table.clone().into_iter().collect::<Vec<_>>(),
4435            vec![(1i64.to_le_bytes().to_vec(), "v5".to_string())]
4436        );
4437
4438        // Test `set`.
4439        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4440            table.clone(),
4441            uniqueness_violation,
4442            uniqueness_violation,
4443        )
4444        .unwrap();
4445        // Uniqueness violation.
4446        table_txn
4447            .set(2i64.to_le_bytes().to_vec(), Some("v5".to_string()), 0)
4448            .unwrap_err();
4449        table_txn
4450            .set(3i64.to_le_bytes().to_vec(), Some("v6".to_string()), 1)
4451            .unwrap();
4452        table_txn.set(2i64.to_le_bytes().to_vec(), None, 2).unwrap();
4453        table_txn.set(1i64.to_le_bytes().to_vec(), None, 2).unwrap();
4454        let pending = table_txn.pending();
4455        assert_eq!(
4456            pending,
4457            vec![
4458                (
4459                    1i64.to_le_bytes().to_vec(),
4460                    "v5".to_string(),
4461                    Diff::MINUS_ONE
4462                ),
4463                (3i64.to_le_bytes().to_vec(), "v6".to_string(), Diff::ONE),
4464            ]
4465        );
4466        commit(&mut table, pending);
4467        assert_eq!(
4468            table,
4469            BTreeMap::from([(3i64.to_le_bytes().to_vec(), "v6".to_string())])
4470        );
4471
4472        // Duplicate `set`.
4473        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4474            table.clone(),
4475            uniqueness_violation,
4476            uniqueness_violation,
4477        )
4478        .unwrap();
4479        table_txn
4480            .set(3i64.to_le_bytes().to_vec(), Some("v6".to_string()), 0)
4481            .unwrap();
4482        let pending = table_txn.pending::<Vec<u8>, String>();
4483        assert!(pending.is_empty());
4484
4485        // Test `set_many`.
4486        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4487            table.clone(),
4488            uniqueness_violation,
4489            uniqueness_violation,
4490        )
4491        .unwrap();
4492        // Uniqueness violation.
4493        table_txn
4494            .set_many(
4495                BTreeMap::from([
4496                    (1i64.to_le_bytes().to_vec(), Some("v6".to_string())),
4497                    (42i64.to_le_bytes().to_vec(), Some("v1".to_string())),
4498                ]),
4499                0,
4500            )
4501            .unwrap_err();
4502        table_txn
4503            .set_many(
4504                BTreeMap::from([
4505                    (1i64.to_le_bytes().to_vec(), Some("v6".to_string())),
4506                    (3i64.to_le_bytes().to_vec(), Some("v1".to_string())),
4507                ]),
4508                1,
4509            )
4510            .unwrap();
4511        table_txn
4512            .set_many(
4513                BTreeMap::from([
4514                    (42i64.to_le_bytes().to_vec(), Some("v7".to_string())),
4515                    (3i64.to_le_bytes().to_vec(), None),
4516                ]),
4517                2,
4518            )
4519            .unwrap();
4520        let pending = table_txn.pending();
4521        assert_eq!(
4522            pending,
4523            vec![
4524                (1i64.to_le_bytes().to_vec(), "v6".to_string(), Diff::ONE),
4525                (
4526                    3i64.to_le_bytes().to_vec(),
4527                    "v6".to_string(),
4528                    Diff::MINUS_ONE
4529                ),
4530                (42i64.to_le_bytes().to_vec(), "v7".to_string(), Diff::ONE),
4531            ]
4532        );
4533        commit(&mut table, pending);
4534        assert_eq!(
4535            table,
4536            BTreeMap::from([
4537                (1i64.to_le_bytes().to_vec(), "v6".to_string()),
4538                (42i64.to_le_bytes().to_vec(), "v7".to_string())
4539            ])
4540        );
4541
4542        // Duplicate `set_many`.
4543        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4544            table.clone(),
4545            uniqueness_violation,
4546            uniqueness_violation,
4547        )
4548        .unwrap();
4549        table_txn
4550            .set_many(
4551                BTreeMap::from([
4552                    (1i64.to_le_bytes().to_vec(), Some("v6".to_string())),
4553                    (42i64.to_le_bytes().to_vec(), Some("v7".to_string())),
4554                ]),
4555                0,
4556            )
4557            .unwrap();
4558        let pending = table_txn.pending::<Vec<u8>, String>();
4559        assert!(pending.is_empty());
4560        commit(&mut table, pending);
4561        assert_eq!(
4562            table,
4563            BTreeMap::from([
4564                (1i64.to_le_bytes().to_vec(), "v6".to_string()),
4565                (42i64.to_le_bytes().to_vec(), "v7".to_string())
4566            ])
4567        );
4568
4569        // Test `update_by_key`
4570        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4571            table.clone(),
4572            uniqueness_violation,
4573            uniqueness_violation,
4574        )
4575        .unwrap();
4576        // Uniqueness violation.
4577        table_txn
4578            .update_by_key(1i64.to_le_bytes().to_vec(), "v7".to_string(), 0)
4579            .unwrap_err();
4580        assert!(
4581            table_txn
4582                .update_by_key(1i64.to_le_bytes().to_vec(), "v8".to_string(), 1)
4583                .unwrap()
4584        );
4585        assert!(
4586            !table_txn
4587                .update_by_key(5i64.to_le_bytes().to_vec(), "v8".to_string(), 2)
4588                .unwrap()
4589        );
4590        let pending = table_txn.pending();
4591        assert_eq!(
4592            pending,
4593            vec![
4594                (
4595                    1i64.to_le_bytes().to_vec(),
4596                    "v6".to_string(),
4597                    Diff::MINUS_ONE
4598                ),
4599                (1i64.to_le_bytes().to_vec(), "v8".to_string(), Diff::ONE),
4600            ]
4601        );
4602        commit(&mut table, pending);
4603        assert_eq!(
4604            table,
4605            BTreeMap::from([
4606                (1i64.to_le_bytes().to_vec(), "v8".to_string()),
4607                (42i64.to_le_bytes().to_vec(), "v7".to_string())
4608            ])
4609        );
4610
4611        // Duplicate `update_by_key`.
4612        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4613            table.clone(),
4614            uniqueness_violation,
4615            uniqueness_violation,
4616        )
4617        .unwrap();
4618        assert!(
4619            table_txn
4620                .update_by_key(1i64.to_le_bytes().to_vec(), "v8".to_string(), 0)
4621                .unwrap()
4622        );
4623        let pending = table_txn.pending::<Vec<u8>, String>();
4624        assert!(pending.is_empty());
4625        commit(&mut table, pending);
4626        assert_eq!(
4627            table,
4628            BTreeMap::from([
4629                (1i64.to_le_bytes().to_vec(), "v8".to_string()),
4630                (42i64.to_le_bytes().to_vec(), "v7".to_string())
4631            ])
4632        );
4633
4634        // Test `update_by_keys`
4635        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4636            table.clone(),
4637            uniqueness_violation,
4638            uniqueness_violation,
4639        )
4640        .unwrap();
4641        // Uniqueness violation.
4642        table_txn
4643            .update_by_keys(
4644                [
4645                    (1i64.to_le_bytes().to_vec(), "v7".to_string()),
4646                    (5i64.to_le_bytes().to_vec(), "v7".to_string()),
4647                ],
4648                0,
4649            )
4650            .unwrap_err();
4651        let n = table_txn
4652            .update_by_keys(
4653                [
4654                    (1i64.to_le_bytes().to_vec(), "v9".to_string()),
4655                    (5i64.to_le_bytes().to_vec(), "v7".to_string()),
4656                ],
4657                1,
4658            )
4659            .unwrap();
4660        assert_eq!(n, Diff::ONE);
4661        let n = table_txn
4662            .update_by_keys(
4663                [
4664                    (15i64.to_le_bytes().to_vec(), "v9".to_string()),
4665                    (5i64.to_le_bytes().to_vec(), "v7".to_string()),
4666                ],
4667                2,
4668            )
4669            .unwrap();
4670        assert_eq!(n, Diff::ZERO);
4671        let pending = table_txn.pending();
4672        assert_eq!(
4673            pending,
4674            vec![
4675                (
4676                    1i64.to_le_bytes().to_vec(),
4677                    "v8".to_string(),
4678                    Diff::MINUS_ONE
4679                ),
4680                (1i64.to_le_bytes().to_vec(), "v9".to_string(), Diff::ONE),
4681            ]
4682        );
4683        commit(&mut table, pending);
4684        assert_eq!(
4685            table,
4686            BTreeMap::from([
4687                (1i64.to_le_bytes().to_vec(), "v9".to_string()),
4688                (42i64.to_le_bytes().to_vec(), "v7".to_string())
4689            ])
4690        );
4691
4692        // Duplicate `update_by_keys`.
4693        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4694            table.clone(),
4695            uniqueness_violation,
4696            uniqueness_violation,
4697        )
4698        .unwrap();
4699        let n = table_txn
4700            .update_by_keys(
4701                [
4702                    (1i64.to_le_bytes().to_vec(), "v9".to_string()),
4703                    (42i64.to_le_bytes().to_vec(), "v7".to_string()),
4704                ],
4705                0,
4706            )
4707            .unwrap();
4708        assert_eq!(n, Diff::from(2));
4709        let pending = table_txn.pending::<Vec<u8>, String>();
4710        assert!(pending.is_empty());
4711        commit(&mut table, pending);
4712        assert_eq!(
4713            table,
4714            BTreeMap::from([
4715                (1i64.to_le_bytes().to_vec(), "v9".to_string()),
4716                (42i64.to_le_bytes().to_vec(), "v7".to_string())
4717            ])
4718        );
4719
4720        // Test `delete_by_key`
4721        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4722            table.clone(),
4723            uniqueness_violation,
4724            uniqueness_violation,
4725        )
4726        .unwrap();
4727        let prev = table_txn.delete_by_key(1i64.to_le_bytes().to_vec(), 0);
4728        assert_eq!(prev, Some("v9".to_string()));
4729        let prev = table_txn.delete_by_key(5i64.to_le_bytes().to_vec(), 1);
4730        assert_none!(prev);
4731        let prev = table_txn.delete_by_key(1i64.to_le_bytes().to_vec(), 2);
4732        assert_none!(prev);
4733        let pending = table_txn.pending();
4734        assert_eq!(
4735            pending,
4736            vec![(
4737                1i64.to_le_bytes().to_vec(),
4738                "v9".to_string(),
4739                Diff::MINUS_ONE
4740            ),]
4741        );
4742        commit(&mut table, pending);
4743        assert_eq!(
4744            table,
4745            BTreeMap::from([(42i64.to_le_bytes().to_vec(), "v7".to_string())])
4746        );
4747
4748        // Test `delete_by_keys`
4749        let mut table_txn = TableTransaction::new_with_uniqueness_fn(
4750            table.clone(),
4751            uniqueness_violation,
4752            uniqueness_violation,
4753        )
4754        .unwrap();
4755        let prevs = table_txn.delete_by_keys(
4756            [42i64.to_le_bytes().to_vec(), 55i64.to_le_bytes().to_vec()],
4757            0,
4758        );
4759        assert_eq!(
4760            prevs,
4761            vec![(42i64.to_le_bytes().to_vec(), "v7".to_string())]
4762        );
4763        let prevs = table_txn.delete_by_keys(
4764            [42i64.to_le_bytes().to_vec(), 55i64.to_le_bytes().to_vec()],
4765            1,
4766        );
4767        assert_eq!(prevs, vec![]);
4768        let prevs = table_txn.delete_by_keys(
4769            [10i64.to_le_bytes().to_vec(), 55i64.to_le_bytes().to_vec()],
4770            2,
4771        );
4772        assert_eq!(prevs, vec![]);
4773        let pending = table_txn.pending();
4774        assert_eq!(
4775            pending,
4776            vec![(
4777                42i64.to_le_bytes().to_vec(),
4778                "v7".to_string(),
4779                Diff::MINUS_ONE
4780            ),]
4781        );
4782        commit(&mut table, pending);
4783        assert_eq!(table, BTreeMap::new());
4784    }
4785
4786    #[mz_ore::test(tokio::test)]
4787    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
4788    async fn test_savepoint() {
4789        const VERSION: Version = Version::new(26, 0, 0);
4790        let mut persist_cache = PersistClientCache::new_no_metrics();
4791        persist_cache.cfg.build_version = VERSION;
4792        let persist_client = persist_cache
4793            .open(PersistLocation::new_in_mem())
4794            .await
4795            .unwrap();
4796        let state_builder = TestCatalogStateBuilder::new(persist_client)
4797            .with_default_deploy_generation()
4798            .with_version(VERSION);
4799
4800        // Initialize catalog.
4801        let _ = state_builder
4802            .clone()
4803            .unwrap_build()
4804            .await
4805            .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4806            .await
4807            .unwrap();
4808        let mut savepoint_state = state_builder
4809            .unwrap_build()
4810            .await
4811            .open_savepoint(SYSTEM_TIME().into(), &test_bootstrap_args())
4812            .await
4813            .unwrap();
4814
4815        let initial_snapshot = savepoint_state.sync_to_current_updates().await.unwrap();
4816        assert!(!initial_snapshot.is_empty());
4817
4818        let db_name = "db";
4819        let db_owner = RoleId::User(42);
4820        let db_privileges = Vec::new();
4821        let mut txn = savepoint_state.transaction().await.unwrap();
4822        let (db_id, db_oid) = txn
4823            .insert_user_database(db_name, db_owner, db_privileges.clone(), &HashSet::new())
4824            .unwrap();
4825        let commit_ts = txn.upper();
4826        txn.commit_internal(commit_ts).await.unwrap();
4827        let updates = savepoint_state.sync_to_current_updates().await.unwrap();
4828        let update = updates.into_element();
4829
4830        assert_eq!(update.diff, StateDiff::Addition);
4831
4832        let db = match update.kind {
4833            memory::objects::StateUpdateKind::Database(db) => db,
4834            update => panic!("unexpected update: {update:?}"),
4835        };
4836
4837        assert_eq!(db_id, db.id);
4838        assert_eq!(db_oid, db.oid);
4839        assert_eq!(db_name, db.name);
4840        assert_eq!(db_owner, db.owner_id);
4841        assert_eq!(db_privileges, db.privileges);
4842    }
4843
4844    #[mz_ore::test(tokio::test)]
4845    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
4846    async fn test_dry_run_transaction_rejects_internal_commit() {
4847        const VERSION: Version = Version::new(26, 0, 0);
4848        let mut persist_cache = PersistClientCache::new_no_metrics();
4849        persist_cache.cfg.build_version = VERSION;
4850        let persist_client = persist_cache
4851            .open(PersistLocation::new_in_mem())
4852            .await
4853            .unwrap();
4854        let mut state = TestCatalogStateBuilder::new(persist_client)
4855            .with_default_deploy_generation()
4856            .with_version(VERSION)
4857            .unwrap_build()
4858            .await
4859            .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4860            .await
4861            .unwrap();
4862        let _ = state.sync_to_current_updates().await.unwrap();
4863
4864        let initial_id = state.get_next_id(USER_ITEM_ALLOC_KEY).await.unwrap();
4865        let initial_upper = state.current_upper().await;
4866        let snapshot = state.snapshot().await.unwrap();
4867        let mut dry_run = state.transaction_from_snapshot(snapshot).unwrap();
4868        let ids = dry_run
4869            .transaction_mut()
4870            .get_and_increment_id_by(USER_ITEM_ALLOC_KEY.to_string(), 1)
4871            .unwrap();
4872        assert_eq!(ids, vec![initial_id]);
4873
4874        let transaction = dry_run.transaction;
4875        let err = transaction
4876            .commit_internal(initial_upper)
4877            .await
4878            .unwrap_err();
4879        assert!(matches!(
4880            err,
4881            CatalogError::Durable(DurableCatalogError::DryRunTransaction)
4882        ));
4883        assert_eq!(state.current_upper().await, initial_upper);
4884        assert_eq!(
4885            state.get_next_id(USER_ITEM_ALLOC_KEY).await.unwrap(),
4886            initial_id
4887        );
4888    }
4889
4890    #[mz_ore::test(tokio::test)]
4891    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
4892    async fn test_dry_run_transaction_rejects_into_parts_escape() {
4893        const VERSION: Version = Version::new(26, 0, 0);
4894        let mut persist_cache = PersistClientCache::new_no_metrics();
4895        persist_cache.cfg.build_version = VERSION;
4896        let persist_client = persist_cache
4897            .open(PersistLocation::new_in_mem())
4898            .await
4899            .unwrap();
4900        let mut dry_run_state = TestCatalogStateBuilder::new(persist_client.clone())
4901            .with_default_deploy_generation()
4902            .with_version(VERSION)
4903            .unwrap_build()
4904            .await
4905            .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4906            .await
4907            .unwrap();
4908        let mut replacement_state = TestCatalogStateBuilder::new(persist_client)
4909            .with_default_deploy_generation()
4910            .with_version(VERSION)
4911            .unwrap_build()
4912            .await
4913            .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4914            .await
4915            .unwrap();
4916        let _ = dry_run_state.sync_to_current_updates().await.unwrap();
4917        let _ = replacement_state.sync_to_current_updates().await.unwrap();
4918
4919        let initial_id = dry_run_state
4920            .get_next_id(USER_ITEM_ALLOC_KEY)
4921            .await
4922            .unwrap();
4923        let initial_upper = dry_run_state.current_upper().await;
4924        let snapshot = dry_run_state.snapshot().await.unwrap();
4925        let mut dry_run = dry_run_state.transaction_from_snapshot(snapshot).unwrap();
4926        let ids = dry_run
4927            .transaction_mut()
4928            .get_and_increment_id_by(USER_ITEM_ALLOC_KEY.to_string(), 1)
4929            .unwrap();
4930        assert_eq!(ids, vec![initial_id]);
4931
4932        let replacement = replacement_state.transaction().await.unwrap();
4933        let escaped = std::mem::replace(dry_run.transaction_mut(), replacement);
4934        drop(dry_run);
4935
4936        let err = match escaped.into_parts() {
4937            Ok(_) => panic!("dry-run transaction decomposed into committable parts"),
4938            Err(err) => err,
4939        };
4940        assert!(matches!(
4941            err,
4942            CatalogError::Durable(DurableCatalogError::DryRunTransaction)
4943        ));
4944        assert_eq!(dry_run_state.current_upper().await, initial_upper);
4945        assert_eq!(
4946            dry_run_state
4947                .get_next_id(USER_ITEM_ALLOC_KEY)
4948                .await
4949                .unwrap(),
4950            initial_id
4951        );
4952    }
4953
4954    /// Regression test for DB-147: inserting a replica with an explicit id must not consume the
4955    /// `IdAlloc` counter, and the durable allocator must advance independently so a later
4956    /// allocation never collides with an explicitly inserted id.
4957    #[mz_ore::test(tokio::test)]
4958    #[cfg_attr(miri, ignore)] //  unsupported operation: can't call foreign function `TLS_client_method` on OS `linux`
4959    async fn test_insert_replica_with_id_does_not_consume_allocator() {
4960        const VERSION: Version = Version::new(26, 0, 0);
4961        let mut persist_cache = PersistClientCache::new_no_metrics();
4962        persist_cache.cfg.build_version = VERSION;
4963        let persist_client = persist_cache
4964            .open(PersistLocation::new_in_mem())
4965            .await
4966            .unwrap();
4967        let state_builder = TestCatalogStateBuilder::new(persist_client)
4968            .with_default_deploy_generation()
4969            .with_version(VERSION);
4970        let mut state = state_builder
4971            .unwrap_build()
4972            .await
4973            .open(SYSTEM_TIME().into(), &test_bootstrap_args())
4974            .await
4975            .unwrap();
4976
4977        // The cluster does not need to exist: `insert_cluster_replica_with_id` only writes a
4978        // `cluster_replicas` row and does not validate the referenced cluster.
4979        let cluster_id = ClusterId::User(1);
4980        let owner_id = RoleId::User(1);
4981        let config = ReplicaConfig {
4982            location: ReplicaLocation::Managed {
4983                size: "1".to_string(),
4984                availability_zones: Vec::new(),
4985                internal: false,
4986                billed_as: None,
4987                pending: false,
4988            },
4989            logging: ReplicaLogging {
4990                log_logging: false,
4991                interval: Some(Duration::from_secs(1)),
4992            },
4993            arrangement_compression: false,
4994        };
4995
4996        // Step 1: allocate one user replica id out-of-band via the durable allocator.
4997        let commit_ts = state.current_upper().await;
4998        let a = state
4999            .allocate_user_replica_ids(1, commit_ts)
5000            .await
5001            .unwrap()
5002            .into_element();
5003        assert!(a.is_user());
5004
5005        let initial_updates = state.sync_to_current_updates().await.unwrap();
5006        assert!(!initial_updates.is_empty());
5007
5008        // Step 2: insert a replica with that explicit id and commit.
5009        let mut txn = state.transaction().await.unwrap();
5010        txn.insert_cluster_replica_with_id(cluster_id, a, "explicit", config, owner_id)
5011            .unwrap();
5012        let commit_ts = txn.upper();
5013        txn.commit_internal(commit_ts).await.unwrap();
5014        let _ = state.sync_to_current_updates().await.unwrap();
5015
5016        // Step 3: allocate one more user replica id.
5017        let commit_ts = state.current_upper().await;
5018        let b = state
5019            .allocate_user_replica_ids(1, commit_ts)
5020            .await
5021            .unwrap()
5022            .into_element();
5023
5024        // Step 4: the explicit insert consumed zero ids, so the allocator's next value is the
5025        // direct successor of the first allocation.
5026        assert_eq!(b.inner_id(), a.inner_id() + 1);
5027
5028        // Step 5: the explicitly inserted replica is present in the committed state.
5029        let txn = state.transaction().await.unwrap();
5030        let found = txn
5031            .get_cluster_replicas()
5032            .any(|replica| replica.replica_id == a);
5033        assert!(found, "explicitly inserted replica {a} not found");
5034    }
5035
5036    #[mz_ore::test]
5037    fn test_allocate_introspection_source_index_id() {
5038        let cluster_variant: u8 = 0b0000_0001;
5039        let cluster_id_inner: u64 =
5040            0b0000_0000_1100_0101_1100_0011_1010_1101_0000_1011_1111_1001_0110_1010;
5041        let timely_messages_received_log_variant: u8 = 0b0000_1000;
5042
5043        let cluster_id = ClusterId::System(cluster_id_inner);
5044        let log_variant = LogVariant::Timely(TimelyLog::MessagesReceived);
5045
5046        let introspection_source_index_id: u64 =
5047            0b0000_0001_1100_0101_1100_0011_1010_1101_0000_1011_1111_1001_0110_1010_0000_1000;
5048
5049        // Sanity check that `introspection_source_index_id` contains `cluster_variant`.
5050        {
5051            let mut cluster_variant_mask = 0xFF << 56;
5052            cluster_variant_mask &= introspection_source_index_id;
5053            cluster_variant_mask >>= 56;
5054            assert_eq!(cluster_variant_mask, u64::from(cluster_variant));
5055        }
5056
5057        // Sanity check that `introspection_source_index_id` contains `cluster_id_inner`.
5058        {
5059            let mut cluster_id_inner_mask = 0xFFFF_FFFF_FFFF << 8;
5060            cluster_id_inner_mask &= introspection_source_index_id;
5061            cluster_id_inner_mask >>= 8;
5062            assert_eq!(cluster_id_inner_mask, cluster_id_inner);
5063        }
5064
5065        // Sanity check that `introspection_source_index_id` contains `timely_messages_received_log_variant`.
5066        {
5067            let mut log_variant_mask = 0xFF;
5068            log_variant_mask &= introspection_source_index_id;
5069            assert_eq!(
5070                log_variant_mask,
5071                u64::from(timely_messages_received_log_variant)
5072            );
5073        }
5074
5075        let (catalog_item_id, global_id) =
5076            Transaction::allocate_introspection_source_index_id(&cluster_id, log_variant);
5077
5078        assert_eq!(
5079            catalog_item_id,
5080            CatalogItemId::IntrospectionSourceIndex(introspection_source_index_id)
5081        );
5082        assert_eq!(
5083            global_id,
5084            GlobalId::IntrospectionSourceIndex(introspection_source_index_id)
5085        );
5086    }
5087}