Skip to main content

mz_adapter/catalog/
transact.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Logic related to executing catalog transactions.
11
12use std::borrow::Cow;
13use std::collections::{BTreeMap, BTreeSet};
14use std::sync::Arc;
15use std::sync::atomic;
16use std::time::Duration;
17
18use itertools::Itertools;
19use mz_adapter_types::cluster_state::{
20    BurstAudit, BurstFinishCause, ExpectedClusterState, ReconfigurationAudit,
21};
22use mz_adapter_types::compaction::CompactionWindow;
23use mz_adapter_types::connection::ConnectionId;
24use mz_adapter_types::dyncfgs::{
25    ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT, WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL,
26    WITH_0DT_DEPLOYMENT_MAX_WAIT,
27};
28use mz_audit_log::{
29    AlterClusterReconfigurationV1, BurstFinishCauseV1, ClusterHydrationBurstV1,
30    ClusterReplicaLoggingV1, CreateOrDropClusterReplicaReasonV1, EventDetails, EventType,
31    HydrationBurstLifecycleV1, IdFullNameV1, IdNameV1, ObjectType, ReconfigurationLifecycleV1,
32    RefreshDecisionWithReasonV2, SchedulingDecisionV1, SchedulingDecisionsWithReasonsV2,
33    VersionedEvent,
34};
35use mz_catalog::SYSTEM_CONN_ID;
36use mz_catalog::builtin::BuiltinLog;
37use mz_catalog::durable::{DryRunTransaction, NetworkPolicy, Snapshot, Transaction};
38use mz_catalog::expr_cache::{LocalExpressions, latest_item_version};
39use mz_catalog::memory::error::{AmbiguousRename, Error, ErrorKind};
40use mz_catalog::memory::objects::{
41    CatalogEntry, CatalogItem, ClusterConfig, ClusterVariant, DataSourceDesc, DefaultPrivileges,
42    ReconfigurationState, ReconfigurationStatus, ReconfigurationTarget, SourceReferences,
43};
44use mz_cluster_controller::ctx::RefreshWindowDecision;
45use mz_controller::clusters::{ManagedReplicaLocation, ReplicaConfig, ReplicaLocation};
46use mz_controller_types::{ClusterId, ReplicaId};
47use mz_ore::collections::HashSet;
48use mz_ore::{instrument, soft_assert_or_log};
49use mz_persist_types::ShardId;
50use mz_repr::adt::interval::Interval;
51use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem, PrivilegeMap, merge_mz_acl_items};
52use mz_repr::network_policy_id::NetworkPolicyId;
53use mz_repr::optimize::OptimizerFeatures;
54use mz_repr::query_policy_id::QueryPolicyId;
55use mz_repr::role_id::RoleId;
56use mz_repr::{CatalogItemId, ColumnName, GlobalId, RelationVersion, SqlColumnType, strconv};
57use mz_sql::ast::RawDataType;
58use mz_sql::catalog::{
59    AutoProvisionSource, CatalogDatabase, CatalogError as SqlCatalogError,
60    CatalogItem as SqlCatalogItem, CatalogRole, CatalogSchema, DefaultPrivilegeAclItem,
61    DefaultPrivilegeObject, PasswordAction, PasswordConfig, RoleAttributesRaw, RoleMembership,
62    RoleVars,
63};
64use mz_sql::names::{
65    CommentObjectId, DatabaseId, FullItemName, ObjectId, QualifiedItemName,
66    ResolvedDatabaseSpecifier, SchemaId, SchemaSpecifier, SystemObjectId,
67};
68use mz_sql::plan::{NetworkPolicyRule, PlanError, QueryPolicyMode, QueryPolicyRule};
69use mz_sql::session::user::{MZ_SUPPORT_ROLE_ID, MZ_SYSTEM_ROLE_ID};
70use mz_sql::session::vars::OwnedVarInput;
71use mz_sql::session::vars::{Value as VarValue, VarInput};
72use mz_sql::{DEFAULT_SCHEMA, rbac};
73use mz_sql_parser::ast::{QualifiedReplica, Value};
74use mz_storage_client::storage_collections::StorageCollections;
75use serde::{Deserialize, Serialize};
76use tracing::{info, trace};
77use uuid::Uuid;
78
79use crate::AdapterError;
80use crate::catalog::state::LocalExpressionCache;
81use crate::catalog::{
82    BuiltinTableUpdate, Catalog, CatalogState, UpdatePrivilegeVariant,
83    catalog_type_to_audit_object_type, comment_id_to_audit_object_type, is_reserved_name,
84    is_reserved_role_name, object_type_to_audit_object_type,
85    system_object_type_to_audit_object_type,
86};
87use crate::config::{ScopedParameters, ScopedParametersScope};
88use crate::coord::ConnMeta;
89use crate::coord::catalog_implications::parsed_state_updates::ParsedStateUpdate;
90use crate::util::ResultExt;
91
92/// A manually injected audit event.
93///
94/// Matches [`mz_audit_log::EventV1`], but without the `id` and `occurred_at` fields -- both are
95/// filled in automatically.
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct InjectedAuditEvent {
98    pub event_type: EventType,
99    pub object_type: ObjectType,
100    pub details: EventDetails,
101    pub user: Option<String>,
102}
103
104#[derive(Debug, Clone)]
105pub enum Op {
106    RenameCommand(Arc<super::command::RenameCommand>),
107    /// Publishes rotated public keys, failing if the connection's definition changed since the
108    /// rotation read it.
109    RotatedKeys(Arc<super::command::connection::RotatedKeys>),
110    AlterRetainHistory {
111        id: CatalogItemId,
112        value: Option<Value>,
113        window: CompactionWindow,
114    },
115    AlterSourceTimestampInterval {
116        id: CatalogItemId,
117        value: Option<Value>,
118        interval: Duration,
119    },
120    AlterRole {
121        id: RoleId,
122        name: String,
123        attributes: RoleAttributesRaw,
124        nopassword: bool,
125        vars: RoleVars,
126    },
127    AlterNetworkPolicy {
128        id: NetworkPolicyId,
129        rules: Vec<NetworkPolicyRule>,
130        name: String,
131        owner_id: RoleId,
132    },
133    AlterQueryPolicy {
134        id: QueryPolicyId,
135        mode: QueryPolicyMode,
136        rules: Vec<QueryPolicyRule>,
137    },
138    AlterAddColumn {
139        id: CatalogItemId,
140        new_global_id: GlobalId,
141        name: ColumnName,
142        typ: SqlColumnType,
143        sql: RawDataType,
144    },
145    AlterMaterializedViewApplyReplacement {
146        id: CatalogItemId,
147        replacement_id: CatalogItemId,
148    },
149    CreateDatabase {
150        name: String,
151        owner_id: RoleId,
152    },
153    CreateSchema {
154        database_id: ResolvedDatabaseSpecifier,
155        schema_name: String,
156        owner_id: RoleId,
157    },
158    CreateRole {
159        name: String,
160        attributes: RoleAttributesRaw,
161    },
162    CreateCluster {
163        id: ClusterId,
164        name: String,
165        introspection_sources: Vec<&'static BuiltinLog>,
166        owner_id: RoleId,
167        config: ClusterConfig,
168    },
169    CreateClusterReplica {
170        cluster_id: ClusterId,
171        replica_id: ReplicaId,
172        name: String,
173        config: ReplicaConfig,
174        owner_id: RoleId,
175        reason: ReplicaCreateDropReason,
176    },
177    CreateItem {
178        id: CatalogItemId,
179        name: QualifiedItemName,
180        item: CatalogItem,
181        owner_id: RoleId,
182    },
183    CreateNetworkPolicy {
184        rules: Vec<NetworkPolicyRule>,
185        name: String,
186        owner_id: RoleId,
187    },
188    CreateQueryPolicy {
189        name: String,
190        mode: QueryPolicyMode,
191        rules: Vec<QueryPolicyRule>,
192        owner_id: RoleId,
193    },
194    Comment {
195        object_id: CommentObjectId,
196        sub_component: Option<usize>,
197        comment: Option<String>,
198    },
199    DropObjects {
200        objects: Vec<DropObjectInfo>,
201        cascade: bool,
202    },
203    GrantRole {
204        role_id: RoleId,
205        member_id: RoleId,
206        grantor_id: RoleId,
207    },
208    RenameCluster {
209        id: ClusterId,
210        name: String,
211        to_name: String,
212        check_reserved_names: bool,
213    },
214    RenameClusterReplica {
215        cluster_id: ClusterId,
216        replica_id: ReplicaId,
217        name: QualifiedReplica,
218        to_name: String,
219    },
220    RenameItem {
221        id: CatalogItemId,
222        current_full_name: FullItemName,
223        to_name: String,
224    },
225    RenameSchema {
226        database_spec: ResolvedDatabaseSpecifier,
227        schema_spec: SchemaSpecifier,
228        new_name: String,
229        check_reserved_names: bool,
230    },
231    UpdateOwner {
232        id: ObjectId,
233        new_owner: RoleId,
234    },
235    UpdatePrivilege {
236        target_id: SystemObjectId,
237        /// The ACL changes to apply to `target_id`, applied as a single durable write. A bulk
238        /// `GRANT`/`REVOKE` touching one object for many grantees lands here as one op rather
239        /// than one op per grantee.
240        privileges: Vec<MzAclItem>,
241        variant: UpdatePrivilegeVariant,
242    },
243    UpdateDefaultPrivilege {
244        privilege_object: DefaultPrivilegeObject,
245        privilege_acl_item: DefaultPrivilegeAclItem,
246        variant: UpdatePrivilegeVariant,
247    },
248    RevokeRole {
249        role_id: RoleId,
250        member_id: RoleId,
251        grantor_id: RoleId,
252    },
253    UpdateClusterConfig {
254        id: ClusterId,
255        name: String,
256        config: ClusterConfig,
257        /// Writer-declared reconfiguration lifecycle transition to audit for
258        /// this write, alongside the record carried in `config`.
259        reconfiguration_audit: Option<ReconfigurationAudit>,
260        /// Writer-declared hydration-burst lifecycle transition to audit for
261        /// this write, alongside the record carried in `config`.
262        burst_audit: Option<BurstAudit>,
263    },
264    UpdateItem {
265        id: CatalogItemId,
266        name: QualifiedItemName,
267        to_item: CatalogItem,
268    },
269    UpdateSourceReferences {
270        source_id: CatalogItemId,
271        references: SourceReferences,
272    },
273    UpdateSystemConfiguration {
274        name: String,
275        value: OwnedVarInput,
276    },
277    ResetSystemConfiguration {
278        name: String,
279    },
280    ResetAllSystemConfiguration,
281    /// Persists the durable cache of scoped (per-cluster and per-replica)
282    /// system parameters towards `scoped`. The handler diffs against the current
283    /// durable contents: it upserts changed/added entries and removes entries
284    /// the update no longer serves.
285    ///
286    /// `prune_scope` bounds removals to the objects the update was evaluated
287    /// for: a row is removed only when its owning object is in `prune_scope`, so
288    /// an object created after the update's evaluation snapshot, and the override
289    /// it folded into its own create transaction, survives a concurrent
290    /// full-state reconcile.
291    UpdateScopedSystemParameters {
292        scoped: ScopedParameters,
293        prune_scope: ScopedParametersScope,
294    },
295    /// Injects audit events into the catalog.
296    ///
297    /// This is a nonstandard path used for manually appending audit events at the current time.
298    /// Mainly useful for correcting the audit log in the face of bugs that made us forget to emit
299    /// audit events.
300    InjectAuditEvents {
301        events: Vec<InjectedAuditEvent>,
302    },
303    /// Precondition, not a mutation. Aborts the whole transaction unless
304    /// `cluster_id`'s current managed config still equals `expected`. Running
305    /// the check inside the transaction makes it inseparable from the commit it
306    /// guards, giving a compare-and-append over the cluster's config. A purely
307    /// internal op for conditional cluster-config writes, never emitted by SQL
308    /// DDL.
309    CheckClusterState {
310        cluster_id: ClusterId,
311        expected: ExpectedClusterState,
312    },
313}
314
315/// Almost the same as `ObjectId`, but the `ClusterReplica` case has an extra
316/// `ReplicaCreateDropReason` field. This is forwarded to `mz_audit_events.details` when applying
317/// the `Op::DropObjects`.
318#[derive(Debug, Clone)]
319pub enum DropObjectInfo {
320    Cluster(ClusterId),
321    ClusterReplica((ClusterId, ReplicaId, ReplicaCreateDropReason)),
322    Database(DatabaseId),
323    Schema((ResolvedDatabaseSpecifier, SchemaSpecifier)),
324    Role(RoleId),
325    Item(CatalogItemId),
326    NetworkPolicy(NetworkPolicyId),
327    QueryPolicy(QueryPolicyId),
328}
329
330impl DropObjectInfo {
331    /// Creates a `DropObjectInfo` from an `ObjectId`.
332    /// If it is a `ClusterReplica`, the reason will be set to `ReplicaCreateDropReason::Manual`.
333    pub(crate) fn manual_drop_from_object_id(id: ObjectId) -> Self {
334        match id {
335            ObjectId::Cluster(cluster_id) => DropObjectInfo::Cluster(cluster_id),
336            ObjectId::ClusterReplica((cluster_id, replica_id)) => DropObjectInfo::ClusterReplica((
337                cluster_id,
338                replica_id,
339                ReplicaCreateDropReason::Manual,
340            )),
341            ObjectId::Database(database_id) => DropObjectInfo::Database(database_id),
342            ObjectId::Schema(schema) => DropObjectInfo::Schema(schema),
343            ObjectId::Role(role_id) => DropObjectInfo::Role(role_id),
344            ObjectId::Item(item_id) => DropObjectInfo::Item(item_id),
345            ObjectId::NetworkPolicy(policy_id) => DropObjectInfo::NetworkPolicy(policy_id),
346            ObjectId::QueryPolicy(id) => DropObjectInfo::QueryPolicy(id),
347        }
348    }
349
350    /// Creates an `ObjectId` from a `DropObjectInfo`.
351    /// Loses the `ReplicaCreateDropReason` if there is one!
352    fn to_object_id(&self) -> ObjectId {
353        match &self {
354            DropObjectInfo::Cluster(cluster_id) => ObjectId::Cluster(cluster_id.clone()),
355            DropObjectInfo::ClusterReplica((cluster_id, replica_id, _reason)) => {
356                ObjectId::ClusterReplica((cluster_id.clone(), replica_id.clone()))
357            }
358            DropObjectInfo::Database(database_id) => ObjectId::Database(database_id.clone()),
359            DropObjectInfo::Schema(schema) => ObjectId::Schema(schema.clone()),
360            DropObjectInfo::Role(role_id) => ObjectId::Role(role_id.clone()),
361            DropObjectInfo::Item(item_id) => ObjectId::Item(item_id.clone()),
362            DropObjectInfo::NetworkPolicy(network_policy_id) => {
363                ObjectId::NetworkPolicy(network_policy_id.clone())
364            }
365            DropObjectInfo::QueryPolicy(id) => ObjectId::QueryPolicy(*id),
366        }
367    }
368}
369
370/// The reason for creating or dropping a replica.
371#[derive(Debug, Clone)]
372pub enum ReplicaCreateDropReason {
373    /// The user initiated the replica create or drop, e.g., by
374    /// - creating/dropping a cluster,
375    /// - ALTERing various options on a managed cluster,
376    /// - CREATE/DROP CLUSTER REPLICA on an unmanaged cluster.
377    Manual,
378    /// The cluster controller's graceful-reconfiguration strategy created the replica while
379    /// converging a cluster onto an in-flight `reconfiguration` target (a background
380    /// `ALTER CLUSTER`).
381    GracefulReconfiguration,
382    /// The cluster controller's hydration-burst strategy created the transient burst replica
383    /// it runs while a cluster's objects are not yet hydrated.
384    HydrationBurst,
385    /// The cluster controller's on-refresh strategy created the replica for a refresh window on
386    /// a `SCHEDULE = ON REFRESH` cluster. Audited as the `schedule` reason, carrying the tick's
387    /// window decision (which MVs needed a refresh or compaction time, and the hydration-time
388    /// estimate) as the `scheduling_policies` detail.
389    OnRefresh(RefreshWindowDecision),
390    /// The cluster controller dropped the replica because the cluster's configuration no longer
391    /// calls for it. The uniform reason on every controller-emitted drop (e.g. a
392    /// replication-factor decrease).
393    Retired,
394}
395
396impl ReplicaCreateDropReason {
397    pub fn into_audit_log(
398        self,
399    ) -> (
400        CreateOrDropClusterReplicaReasonV1,
401        Option<SchedulingDecisionsWithReasonsV2>,
402    ) {
403        match self {
404            ReplicaCreateDropReason::Manual => (CreateOrDropClusterReplicaReasonV1::Manual, None),
405            ReplicaCreateDropReason::GracefulReconfiguration => {
406                (CreateOrDropClusterReplicaReasonV1::Reconfiguration, None)
407            }
408            ReplicaCreateDropReason::HydrationBurst => {
409                (CreateOrDropClusterReplicaReasonV1::HydrationBurst, None)
410            }
411            ReplicaCreateDropReason::OnRefresh(decision) => (
412                CreateOrDropClusterReplicaReasonV1::Schedule,
413                Some(refresh_window_decision_to_audit_log(decision)),
414            ),
415            ReplicaCreateDropReason::Retired => (CreateOrDropClusterReplicaReasonV1::Retired, None),
416        }
417    }
418}
419
420/// Convert the controller's on-refresh window decision into the audit log's
421/// `scheduling_policies` detail: ids as strings and the hydration-time estimate
422/// as an interval string.
423fn refresh_window_decision_to_audit_log(
424    decision: RefreshWindowDecision,
425) -> SchedulingDecisionsWithReasonsV2 {
426    let mut hydration_time_estimate_str = String::new();
427    strconv::format_interval(
428        &mut hydration_time_estimate_str,
429        Interval::from_duration(&decision.hydration_time_estimate)
430            .expect("the estimate originated as a planned Interval"),
431    );
432    SchedulingDecisionsWithReasonsV2 {
433        on_refresh: RefreshDecisionWithReasonV2 {
434            // The controller produces a create (and so this detail) only for
435            // an open window; there is no "off" decision to record (a
436            // window-close is a `retired` drop with no detail).
437            decision: SchedulingDecisionV1::On,
438            objects_needing_refresh: decision
439                .objects_needing_refresh
440                .iter()
441                .map(|id| id.to_string())
442                .collect(),
443            objects_needing_compaction: decision
444                .objects_needing_compaction
445                .iter()
446                .map(|id| id.to_string())
447                .collect(),
448            hydration_time_estimate: hydration_time_estimate_str,
449        },
450    }
451}
452
453pub struct TransactionResult {
454    pub builtin_table_updates: Vec<BuiltinTableUpdate>,
455    /// Parsed catalog updates from which we will derive catalog implications.
456    pub catalog_updates: Vec<ParsedStateUpdate>,
457    pub audit_events: Vec<VersionedEvent>,
458}
459
460#[derive(Debug)]
461pub(crate) enum CommandWork {
462    Connection(super::command::connection::ConnectionPreparation),
463    ConnectionSecret(super::command::connection::ConnectionSecret),
464    Prepare(mz_sql::pure::SourcePreparationRequest),
465    Allocate(Vec<super::command::source::SourceObject>),
466}
467
468#[derive(Debug)]
469pub(crate) enum CommandResponse {
470    Source(mz_sql::pure::SourcePreparationResponse),
471    Connection(super::command::connection::ConnectionPreparationResponse),
472    ConnectionSecret(super::command::connection::ConnectionSecretResponse),
473}
474
475#[derive(Debug)]
476pub(crate) enum CommandExecutionError {
477    Error(AdapterError),
478    Pending { index: usize, work: CommandWork },
479}
480
481impl From<AdapterError> for CommandExecutionError {
482    fn from(error: AdapterError) -> Self {
483        Self::Error(error)
484    }
485}
486
487impl CommandExecutionError {
488    fn into_adapter_error(self) -> AdapterError {
489        match self {
490            Self::Error(error) => error,
491            Self::Pending { .. } => unreachable!("raw operations do not request preparation"),
492        }
493    }
494}
495
496enum TransactionOperations<'a> {
497    Raw(Vec<Op>),
498    Commands {
499        commands: &'a mut [super::command::CatalogCommand],
500        responses: &'a mut BTreeMap<usize, CommandResponse>,
501    },
502}
503
504enum OperationGroup<'a> {
505    Raw(Vec<Op>),
506    Command(usize, &'a mut super::command::CatalogCommand),
507}
508
509#[derive(Debug, Clone, Copy)]
510enum TransactInnerMode {
511    /// Prepare storage state and return a commit-ready transaction state.
512    ///
513    /// This mode is used by durable catalog transactions.
514    Commit,
515    /// Execute a dry run against a durable transaction that will not be
516    /// committed.
517    ///
518    /// This mode still validates and applies updates to an in-memory
519    /// `CatalogState`, but it must not call `prepare_state` because dry runs
520    /// must not trigger controller side effects.
521    DryRun,
522}
523
524impl Catalog {
525    fn should_audit_log_item(item: &CatalogItem) -> bool {
526        !item.is_temporary()
527    }
528
529    /// The cluster config's `reconfiguration` record, if any.
530    fn reconfiguration_record_of(
531        config: &ClusterConfig,
532    ) -> Option<&mz_catalog::memory::objects::ReconfigurationState> {
533        match &config.variant {
534            ClusterVariant::Managed(managed) => managed.reconfiguration.as_ref(),
535            ClusterVariant::Unmanaged => None,
536        }
537    }
538
539    /// The cluster config's `burst` record, if any.
540    fn burst_record_of(config: &ClusterConfig) -> Option<&mz_catalog::memory::objects::BurstState> {
541        match &config.variant {
542            ClusterVariant::Managed(managed) => managed.burst.as_ref(),
543            ClusterVariant::Unmanaged => None,
544        }
545    }
546
547    /// Whether a cluster config write moves the burst lifecycle: a record
548    /// appears or disappears. Unlike reconfiguration there is no status field,
549    /// so presence transitions are the whole lifecycle. Bookkeeping rewrites of
550    /// an existing record (the hydration stamp and its reset) move nothing.
551    ///
552    /// Every such movement is an audit-log transition, so a write performing
553    /// one must declare the matching intent.
554    fn burst_lifecycle_moved(old_config: &ClusterConfig, new_config: &ClusterConfig) -> bool {
555        matches!(
556            (
557                Self::burst_record_of(old_config),
558                Self::burst_record_of(new_config),
559            ),
560            (None, Some(_)) | (Some(_), None)
561        )
562    }
563
564    /// Whether a cluster config write moves the reconfiguration lifecycle: a
565    /// status change, a fresh record, or the drop of an in-progress record.
566    ///
567    /// Every such movement is an audit-log transition, so a write performing
568    /// one must declare the matching intent. Status-preserving copies (a write
569    /// carrying a record forward, re-targets that stay in progress with a
570    /// declared `Started`) and drops of already-settled records move nothing.
571    fn reconfiguration_lifecycle_moved(
572        old_config: &ClusterConfig,
573        new_config: &ClusterConfig,
574    ) -> bool {
575        match (
576            Self::reconfiguration_record_of(old_config),
577            Self::reconfiguration_record_of(new_config),
578        ) {
579            (None, Some(_)) => true,
580            (Some(old), Some(new)) => old.status != new.status,
581            (Some(old), None) => old.is_in_progress(),
582            (None, None) => false,
583        }
584    }
585
586    /// Builds a reconfiguration lifecycle audit event from the writer-declared
587    /// audit intent and the record in `config`.
588    ///
589    /// The intent must cohere with the record it rides along with: the durable
590    /// `status` and the audited transition are two views of one decision, so a
591    /// mismatch is a writer bug and fails the transaction rather than commit an
592    /// event that contradicts the state. The valid pairings are tabulated on
593    /// [`mz_catalog::memory::objects::ReconfigurationStatus`].
594    fn reconfiguration_audit_details(
595        config: &ClusterConfig,
596        cluster_id: ClusterId,
597        cluster_name: &str,
598        audit: ReconfigurationAudit,
599    ) -> Result<AlterClusterReconfigurationV1, AdapterError> {
600        let record = Self::reconfiguration_record_of(config);
601        let Some(record) = record else {
602            return Err(AdapterError::Internal(format!(
603                "reconfiguration audit transition {audit:?} for cluster {cluster_name} \
604                 without a reconfiguration record"
605            )));
606        };
607        // The one mirror match from the write-side vocabulary to the audit-log
608        // vocabulary. `forced` exists only on the intent: the durable status
609        // reads `Finalized` for both a hydrated and a forced cut-over.
610        let (transition, forced) = match audit {
611            ReconfigurationAudit::Started => (ReconfigurationLifecycleV1::Started, None),
612            ReconfigurationAudit::Cancelled => (ReconfigurationLifecycleV1::Cancelled, None),
613            ReconfigurationAudit::Finalized { forced } => {
614                (ReconfigurationLifecycleV1::Finalized, Some(forced))
615            }
616            ReconfigurationAudit::TimedOut => (ReconfigurationLifecycleV1::TimedOut, None),
617            ReconfigurationAudit::ResourceExhausted => {
618                (ReconfigurationLifecycleV1::ResourceExhausted, None)
619            }
620        };
621        let coherent = matches!(
622            (audit, record.status),
623            (
624                ReconfigurationAudit::Started,
625                ReconfigurationStatus::InProgress
626            ) | (
627                ReconfigurationAudit::Cancelled,
628                ReconfigurationStatus::Cancelled
629            ) | (
630                ReconfigurationAudit::Finalized { .. },
631                ReconfigurationStatus::Finalized
632            ) | (
633                ReconfigurationAudit::TimedOut,
634                ReconfigurationStatus::TimedOut
635            ) | (
636                ReconfigurationAudit::ResourceExhausted,
637                ReconfigurationStatus::ResourceExhausted
638            )
639        );
640        if !coherent {
641            return Err(AdapterError::Internal(format!(
642                "reconfiguration audit transition {audit:?} for cluster {cluster_name} \
643                 contradicts the written record status {:?}",
644                record.status
645            )));
646        }
647        let ReconfigurationState {
648            target,
649            deadline,
650            on_timeout: _,
651            status: _,
652        } = record;
653        let ReconfigurationTarget {
654            size,
655            replication_factor,
656            availability_zones,
657            logging,
658            // The append-only audit payload records the target shape's size,
659            // replication factor, availability zones, and logging. Arrangement
660            // compression is intentionally not part of it.
661            arrangement_compression: _,
662        } = target;
663        Ok(AlterClusterReconfigurationV1 {
664            cluster_id: cluster_id.to_string(),
665            cluster_name: cluster_name.to_string(),
666            transition,
667            forced,
668            target_size: size.clone(),
669            target_replication_factor: *replication_factor,
670            target_availability_zones: availability_zones.clone(),
671            target_logging: ClusterReplicaLoggingV1 {
672                log_logging: logging.log_logging,
673                interval: logging.interval,
674            },
675            deadline: Some((*deadline).into()),
676        })
677    }
678
679    /// Builds a hydration-burst lifecycle audit event from the writer-declared
680    /// audit intent and the `burst` record it rides along with.
681    ///
682    /// A `started` intent reads the record from the new config (the write that
683    /// armed the burst carries it). A `finished` intent reads it from the old
684    /// config, since the same write cleared it. A missing record on the
685    /// respective side means the intent contradicts the write, a writer bug
686    /// that fails the transaction.
687    fn burst_audit_details(
688        old_config: &ClusterConfig,
689        new_config: &ClusterConfig,
690        cluster_id: ClusterId,
691        cluster_name: &str,
692        audit: BurstAudit,
693    ) -> Result<ClusterHydrationBurstV1, AdapterError> {
694        let (transition, finish_cause, record) = match audit {
695            BurstAudit::Started => (
696                HydrationBurstLifecycleV1::Started,
697                None,
698                Self::burst_record_of(new_config),
699            ),
700            BurstAudit::Finished { cause } => {
701                let cause = match cause {
702                    BurstFinishCause::LingerElapsed => BurstFinishCauseV1::LingerElapsed,
703                    BurstFinishCause::NoLongerWarranted => BurstFinishCauseV1::NoLongerWarranted,
704                };
705                (
706                    HydrationBurstLifecycleV1::Finished,
707                    Some(cause),
708                    Self::burst_record_of(old_config),
709                )
710            }
711        };
712        let Some(record) = record else {
713            return Err(AdapterError::Internal(format!(
714                "burst audit transition {audit:?} for cluster {cluster_name} \
715                 without a burst record on the corresponding side of the write"
716            )));
717        };
718        Ok(ClusterHydrationBurstV1 {
719            cluster_id: cluster_id.to_string(),
720            cluster_name: cluster_name.to_string(),
721            transition,
722            finish_cause,
723            burst_size: record.burst_size.clone(),
724        })
725    }
726
727    /// Gets [`CatalogItemId`]s of temporary items to be created, checks for name collisions
728    /// within a connection id.
729    fn temporary_ids(
730        &self,
731        ops: &[Op],
732        temporary_drops: BTreeSet<(&ConnectionId, String)>,
733    ) -> Result<BTreeSet<CatalogItemId>, Error> {
734        let mut creating = BTreeSet::new();
735        let mut temporary_ids = BTreeSet::new();
736        for op in ops.iter() {
737            if let Op::CreateItem {
738                id,
739                name,
740                item,
741                owner_id: _,
742            } = op
743            {
744                if let Some(conn_id) = item.conn_id() {
745                    if self.item_exists_in_temp_schemas(conn_id, &name.item)
746                        && !temporary_drops.contains(&(conn_id, name.item.clone()))
747                        || creating.contains(&(conn_id, &name.item))
748                    {
749                        return Err(
750                            SqlCatalogError::ItemAlreadyExists(*id, name.item.clone()).into()
751                        );
752                    } else {
753                        creating.insert((conn_id, &name.item));
754                        temporary_ids.insert(id.clone());
755                    }
756                }
757            }
758        }
759        Ok(temporary_ids)
760    }
761
762    #[instrument(name = "catalog::transact")]
763    pub async fn transact(
764        &mut self,
765        // n.b. this is an option to prevent us from needing to build out a
766        // dummy impl of `StorageController` for tests.
767        storage_collections: Option<&mut Arc<dyn StorageCollections + Send + Sync>>,
768        oracle_write_ts: mz_repr::Timestamp,
769        session: Option<&ConnMeta>,
770        ops: Vec<Op>,
771    ) -> Result<TransactionResult, AdapterError> {
772        trace!("transact: {:?}", ops);
773        fail::fail_point!("catalog_transact", |arg| {
774            Err(AdapterError::Unstructured(anyhow::anyhow!(
775                "failpoint: {arg:?}"
776            )))
777        });
778
779        let drop_ids: BTreeSet<CatalogItemId> = ops
780            .iter()
781            .filter_map(|op| match op {
782                Op::DropObjects {
783                    objects: drop_object_infos,
784                    ..
785                } => {
786                    let ids = drop_object_infos.iter().map(|info| info.to_object_id());
787                    let item_ids = ids.filter_map(|id| match id {
788                        ObjectId::Item(id) => Some(id),
789                        _ => None,
790                    });
791                    Some(item_ids)
792                }
793                _ => None,
794            })
795            .flatten()
796            .collect();
797        let temporary_drops = drop_ids
798            .iter()
799            .filter_map(|id| {
800                let entry = self.get_entry(id);
801                match entry.item().conn_id() {
802                    Some(conn_id) => Some((conn_id, entry.name().item.clone())),
803                    None => None,
804                }
805            })
806            .collect();
807
808        let temporary_ids = self.temporary_ids(&ops, temporary_drops)?;
809        let mut builtin_table_updates = vec![];
810        let mut catalog_updates = vec![];
811        let mut audit_events = vec![];
812        let mut storage = self.storage().await;
813        let mut tx = storage
814            .transaction()
815            .await
816            .unwrap_or_terminate("starting catalog transaction");
817        // Empty progress may have overtaken the timestamp chosen before opening the transaction.
818        let commit_ts = std::cmp::max(oracle_write_ts, tx.upper());
819
820        let new_state = Self::transact_inner(
821            TransactInnerMode::Commit,
822            storage_collections,
823            commit_ts,
824            session,
825            TransactionOperations::Raw(ops),
826            temporary_ids,
827            &mut builtin_table_updates,
828            &mut catalog_updates,
829            &mut audit_events,
830            &mut tx,
831            &self.state,
832        )
833        .await
834        .map_err(CommandExecutionError::into_adapter_error)?;
835
836        // The user closure was successful, apply the updates. Terminate the
837        // process if this fails, because we have to restart envd due to
838        // indeterminate catalog state, which we only reconcile during catalog
839        // init.
840        tx.commit(commit_ts)
841            .await
842            .unwrap_or_terminate("catalog storage transaction commit must succeed");
843
844        // Dropping here keeps the mutable borrow on self, preventing us accidentally
845        // mutating anything until after f is executed.
846        drop(storage);
847        self.publish_transaction_state(new_state);
848
849        Ok(TransactionResult {
850            builtin_table_updates,
851            catalog_updates,
852            audit_events,
853        })
854    }
855
856    /// Executes commands in order against the current catalog and commits them atomically.
857    ///
858    /// `Pending { index, work }` returns without committing. The caller performs
859    /// `work`, stores a preparation response under `index` in `responses` or records
860    /// allocated IDs in that command, then retries with the same `commands`.
861    pub(crate) async fn transact_commands(
862        &mut self,
863        storage_collections: Option<&mut Arc<dyn StorageCollections + Send + Sync>>,
864        oracle_write_ts: mz_repr::Timestamp,
865        session: Option<&ConnMeta>,
866        commands: &mut [super::command::CatalogCommand],
867        responses: &mut BTreeMap<usize, CommandResponse>,
868    ) -> Result<TransactionResult, CommandExecutionError> {
869        fail::fail_point!("catalog_transact", |arg| {
870            Err(AdapterError::Unstructured(anyhow::anyhow!("failpoint: {arg:?}")).into())
871        });
872        let mut builtin_table_updates = Vec::new();
873        let mut catalog_updates = Vec::new();
874        let mut audit_events = Vec::new();
875        let mut storage = self.storage().await;
876        let mut tx = storage
877            .transaction()
878            .await
879            .unwrap_or_terminate("starting catalog command transaction");
880        let commit_ts = std::cmp::max(oracle_write_ts, tx.upper());
881        let new_state = Self::transact_inner(
882            TransactInnerMode::Commit,
883            storage_collections,
884            commit_ts,
885            session,
886            TransactionOperations::Commands {
887                commands,
888                responses,
889            },
890            BTreeSet::new(),
891            &mut builtin_table_updates,
892            &mut catalog_updates,
893            &mut audit_events,
894            &mut tx,
895            &self.state,
896        )
897        .await?;
898        tx.commit(commit_ts)
899            .await
900            .unwrap_or_terminate("catalog command transaction commit must succeed");
901        drop(storage);
902        self.publish_transaction_state(new_state);
903        Ok(TransactionResult {
904            builtin_table_updates,
905            catalog_updates,
906            audit_events,
907        })
908    }
909
910    fn publish_transaction_state(&mut self, new_state: Option<CatalogState>) {
911        if let Some(new_state) = new_state {
912            self.transient_revision += 1;
913            // Publish the new revision before returning. Everything that can
914            // reveal this transaction's effects (responses, notices, builtin
915            // table writes) happens after `transact` returns, so any session
916            // that has observed such evidence is guaranteed to see this bump
917            // and refresh its cached catalog snapshot.
918            self.shared_transient_revision
919                .store(self.transient_revision, atomic::Ordering::SeqCst);
920            self.state = new_state;
921        }
922    }
923
924    /// Applies a compiled source statement to a DDL transaction's speculative catalog.
925    ///
926    /// The compilation must be resolved against `base`.
927    pub(crate) async fn stage_source_statement(
928        &self,
929        statement: super::command::source_statement::SourceStatement,
930        mut compiled: super::command::source_statement::SourceCompilation,
931        base: (&CatalogState, &Snapshot),
932        session: Option<&ConnMeta>,
933        oracle_write_ts: mz_repr::Timestamp,
934    ) -> Result<super::command::source_statement::StagedSourceStatement, AdapterError> {
935        use super::command::source_statement::{SourceCommand, StagedSourceStatement};
936
937        let (state, snapshot) = base;
938        let ops = std::mem::take(&mut compiled.ops);
939        let result = self
940            .transact_incremental_dry_run(
941                state,
942                ops,
943                session,
944                Some(snapshot.clone()),
945                oracle_write_ts,
946            )
947            .await;
948        let (prepared_state, outcome) = compiled.classify_result(result)?;
949        let (state, snapshot) = prepared_state.unwrap_or_else(|| (state.clone(), snapshot.clone()));
950        Ok(StagedSourceStatement {
951            command: SourceCommand {
952                statement,
953                outcome,
954                observed: true,
955            },
956            state,
957            snapshot,
958        })
959    }
960
961    /// Returns in-memory catalog state and a durable snapshot of the same catalog revision.
962    pub(crate) async fn ddl_transaction_snapshot(&self) -> (CatalogState, Snapshot) {
963        let mut storage = self.storage().await;
964        let tx = storage
965            .transaction()
966            .await
967            .unwrap_or_terminate("starting DDL snapshot transaction");
968        (self.state.clone(), tx.current_snapshot())
969    }
970
971    /// Performs an incremental dry-run catalog transaction: processes only the
972    /// NEW ops against an accumulated `CatalogState` from previous dry runs.
973    /// This avoids the O(N^2) replay cost of replaying all accumulated ops.
974    ///
975    /// The durable transaction is intentionally never committed and no storage
976    /// controller prepare-state side effects are run.
977    ///
978    /// If `prev_snapshot` is `Some`, the transaction is initialized from that
979    /// snapshot (which represents the tx state after the previous dry run),
980    /// ensuring it starts in sync with `base_state`. If `None` (first
981    /// statement), a fresh transaction is loaded from durable storage.
982    ///
983    /// Returns the new accumulated state and a snapshot of the transaction's
984    /// state for use in subsequent incremental dry runs.
985    pub async fn transact_incremental_dry_run(
986        &self,
987        base_state: &CatalogState,
988        ops: Vec<Op>,
989        session: Option<&ConnMeta>,
990        prev_snapshot: Option<Snapshot>,
991        oracle_write_ts: mz_repr::Timestamp,
992    ) -> Result<(CatalogState, Snapshot), AdapterError> {
993        // For DDL transactions, items are not temporary (CREATE TABLE FROM SOURCE, etc.)
994        // but we still need to check for collisions.
995        let temporary_ids = self.temporary_ids(&ops, BTreeSet::new())?;
996
997        let mut builtin_table_updates = vec![];
998        let mut catalog_updates = vec![];
999        let mut audit_events = vec![];
1000        let mut storage = self.storage().await;
1001        let mut tx = if let Some(snapshot) = prev_snapshot {
1002            // Restore transaction from saved snapshot so it starts in sync
1003            // with the accumulated CatalogState from previous dry runs.
1004            storage
1005                .transaction_from_snapshot(snapshot)
1006                .unwrap_or_terminate("starting catalog transaction from snapshot")
1007        } else {
1008            // First statement: fresh transaction from durable storage, which
1009            // is in sync with the real catalog state.
1010            let tx = storage
1011                .transaction()
1012                .await
1013                .unwrap_or_terminate("starting catalog transaction");
1014            DryRunTransaction::new(tx)
1015        };
1016
1017        // Process only the new ops against the accumulated state in dry-run mode.
1018        let new_state = Self::transact_inner(
1019            TransactInnerMode::DryRun,
1020            None,
1021            oracle_write_ts,
1022            session,
1023            TransactionOperations::Raw(ops),
1024            temporary_ids,
1025            &mut builtin_table_updates,
1026            &mut catalog_updates,
1027            &mut audit_events,
1028            tx.transaction_mut(),
1029            base_state,
1030        )
1031        .await
1032        .map_err(CommandExecutionError::into_adapter_error)?;
1033
1034        // Save the transaction's current state as a snapshot for the next
1035        // incremental dry run.
1036        let new_snapshot = tx.current_snapshot();
1037
1038        // Transaction is NOT committed — drop it.
1039        drop(storage);
1040
1041        // transact_inner returns Some(state) when ops produced changes.
1042        let state = new_state.unwrap_or_else(|| base_state.clone());
1043        Ok((state, new_snapshot))
1044    }
1045
1046    /// Extracts optimized expressions from `Op::CreateItem` operations for views
1047    /// and materialized views. These can be used to populate a `LocalExpressionCache`
1048    /// to avoid re-optimization during `apply_updates`.
1049    fn extract_expressions_from_ops(
1050        ops: &[Op],
1051        optimizer_features: &OptimizerFeatures,
1052    ) -> BTreeMap<GlobalId, LocalExpressions> {
1053        let mut exprs = BTreeMap::new();
1054
1055        for op in ops {
1056            if let Op::CreateItem { item, .. } = op {
1057                match item {
1058                    CatalogItem::View(view) => {
1059                        exprs.insert(
1060                            view.global_id,
1061                            LocalExpressions {
1062                                local_mir: (*view.locally_optimized_expr).clone(),
1063                                optimizer_features: optimizer_features.clone(),
1064                                item_version: RelationVersion::root(),
1065                            },
1066                        );
1067                    }
1068                    CatalogItem::MaterializedView(mv) => {
1069                        exprs.insert(
1070                            mv.global_id_writes(),
1071                            LocalExpressions {
1072                                local_mir: (*mv.locally_optimized_expr).clone(),
1073                                optimizer_features: optimizer_features.clone(),
1074                                item_version: latest_item_version(&mv.collections),
1075                            },
1076                        );
1077                    }
1078                    CatalogItem::Table(_)
1079                    | CatalogItem::Source(_)
1080                    | CatalogItem::Log(_)
1081                    | CatalogItem::Sink(_)
1082                    | CatalogItem::Index(_)
1083                    | CatalogItem::Type(_)
1084                    | CatalogItem::Func(_)
1085                    | CatalogItem::Secret(_)
1086                    | CatalogItem::Connection(_)
1087                    | CatalogItem::MetricSink(_) => {}
1088                }
1089            }
1090        }
1091
1092        exprs
1093    }
1094
1095    /// Performs the transaction described by `ops` and returns the new state of the catalog, if
1096    /// it has changed. If `ops` don't result in a change in the state this method returns `None`.
1097    ///
1098    /// `mode` controls whether storage prepare-state side effects are allowed.
1099    /// In `DryRun` mode, this method may update the in-memory state returned to
1100    /// the caller, but it must not trigger controller side effects.
1101    ///
1102    #[instrument(name = "catalog::transact_inner")]
1103    async fn transact_inner(
1104        mode: TransactInnerMode,
1105        storage_collections: Option<&mut Arc<dyn StorageCollections + Send + Sync>>,
1106        oracle_write_ts: mz_repr::Timestamp,
1107        session: Option<&ConnMeta>,
1108        operations: TransactionOperations<'_>,
1109        temporary_ids: BTreeSet<CatalogItemId>,
1110        builtin_table_updates: &mut Vec<BuiltinTableUpdate>,
1111        parsed_catalog_updates: &mut Vec<ParsedStateUpdate>,
1112        audit_events: &mut Vec<VersionedEvent>,
1113        tx: &mut Transaction<'_>,
1114        state: &CatalogState,
1115    ) -> Result<Option<CatalogState>, CommandExecutionError> {
1116        // We come up with new catalog state, builtin state updates, and parsed
1117        // catalog updates (for deriving catalog implications) in two phases:
1118        //
1119        // 1. We (cow)-clone catalog state as `preliminary_state` and apply ops
1120        //    one-by-one. This will give us the full list of updates to apply to
1121        //    the catalog, which will allow us to apply it in one batch, which
1122        //    in turn will allow the apply machinery to consolidate the updates.
1123        // 2. We do one final apply call with all updates, which gives us the
1124        //    final builtin table updates and parsed catalog updates.
1125        //
1126        // The reason is that the loop that is working off ops first does a
1127        // transact_op to derive the state updates for that op, and then calls
1128        // apply_updates on the catalog state. And successive ops might expect
1129        // the catalog state to reflect the modified state _after_ applying
1130        // previous ops.
1131        //
1132        // We want to, however, have one final apply_state that takes all the
1133        // accumulated updates to derive the required controller updates and the
1134        // builtin table updates.
1135        //
1136        // We won't win any DDL throughput benchmarks, but so far that's not
1137        // what we're optimizing for and there would probably be other
1138        // bottlenecks before we hit this one as a bottleneck.
1139        //
1140        // We could work around this by refactoring how the interplay of
1141        // transact_op and apply_updates works, but that's a larger undertaking.
1142        let mut preliminary_state = Cow::Borrowed(state);
1143
1144        // The final state that we will return, if modified.
1145        let mut state = Cow::Borrowed(state);
1146
1147        let empty = match &operations {
1148            TransactionOperations::Raw(ops) => ops.is_empty(),
1149            TransactionOperations::Commands { commands, .. } => commands.is_empty(),
1150        };
1151        if empty {
1152            return Ok(None);
1153        }
1154
1155        let optimizer_features = OptimizerFeatures::from(state.system_config());
1156        let cached_exprs = match &operations {
1157            TransactionOperations::Raw(ops) => {
1158                Self::extract_expressions_from_ops(ops, &optimizer_features)
1159            }
1160            TransactionOperations::Commands { .. } => BTreeMap::new(),
1161        };
1162
1163        let mut storage_collections_to_create = BTreeSet::new();
1164        let mut storage_collections_to_drop = BTreeSet::new();
1165        let mut storage_collections_to_register = BTreeMap::new();
1166
1167        let mut updates = Vec::new();
1168
1169        let (groups, mut responses): (std::collections::VecDeque<_>, _) = match operations {
1170            TransactionOperations::Raw(ops) => {
1171                ([OperationGroup::Raw(ops)].into_iter().collect(), None)
1172            }
1173            TransactionOperations::Commands {
1174                commands,
1175                responses,
1176            } => (
1177                commands
1178                    .iter_mut()
1179                    .enumerate()
1180                    .map(|(index, command)| OperationGroup::Command(index, command))
1181                    .collect(),
1182                Some(responses),
1183            ),
1184        };
1185        for group in groups {
1186            use super::command::CommandExecution;
1187
1188            let mut execution = match group {
1189                OperationGroup::Raw(ops) => CommandExecution::raw(ops),
1190                OperationGroup::Command(index, command) => {
1191                    let response = responses
1192                        .as_mut()
1193                        .and_then(|responses| responses.remove(&index));
1194                    command.compile(&preliminary_state, index, response)?
1195                }
1196            };
1197            if let Some(ops) = execution.collision_probe_ops() {
1198                let result = {
1199                    let mut fork = tx.fork_dry_run().map_err(AdapterError::from)?;
1200                    Box::pin(Self::transact_inner(
1201                        TransactInnerMode::DryRun,
1202                        None,
1203                        oracle_write_ts,
1204                        session,
1205                        TransactionOperations::Raw(ops.to_vec()),
1206                        BTreeSet::new(),
1207                        &mut Vec::new(),
1208                        &mut Vec::new(),
1209                        &mut Vec::new(),
1210                        fork.transaction_mut(),
1211                        &preliminary_state,
1212                    ))
1213                    .await
1214                    .map(|_| ())
1215                    .map_err(CommandExecutionError::into_adapter_error)
1216                };
1217                let Some(remaining) = execution.finish_probe(result)? else {
1218                    continue;
1219                };
1220                execution = remaining;
1221            }
1222            let mut pending_ops: std::collections::VecDeque<_> = execution.take_ops().into();
1223            while let Some(op) = pending_ops.pop_front() {
1224                if let Op::RenameCommand(command) = op {
1225                    let compiled = command.execute(&preliminary_state)?;
1226                    for op in compiled.into_iter().rev() {
1227                        pending_ops.push_front(op);
1228                    }
1229                    continue;
1230                }
1231                if let Op::RotatedKeys(command) = op {
1232                    for op in command.execute(&preliminary_state)?.into_iter().rev() {
1233                        pending_ops.push_front(op);
1234                    }
1235                    continue;
1236                }
1237                let result = Self::transact_op(
1238                    oracle_write_ts,
1239                    session,
1240                    op,
1241                    &temporary_ids,
1242                    audit_events,
1243                    tx,
1244                    &*preliminary_state,
1245                    &mut storage_collections_to_create,
1246                    &mut storage_collections_to_drop,
1247                    &mut storage_collections_to_register,
1248                )
1249                .await;
1250                if let Err(error) = result {
1251                    return execution.finish(Err(error)).map_err(Into::into);
1252                }
1253
1254                let mut op_updates: Vec<_> = tx.get_and_commit_op_updates();
1255                if !op_updates.is_empty() {
1256                    // Clone the cache so each apply_updates call has access to cached expressions.
1257                    // The cache uses `remove` semantics, so we need a fresh clone for each call.
1258                    let mut local_expr_cache = LocalExpressionCache::new(cached_exprs.clone());
1259                    let (_op_builtin_table_updates, _op_catalog_updates) = preliminary_state
1260                        .to_mut()
1261                        .apply_updates(op_updates.clone(), &mut local_expr_cache)
1262                        .await;
1263                    let updated_item_ids =
1264                        op_updates.iter().filter_map(|update| match &update.kind {
1265                            mz_catalog::memory::objects::StateUpdateKind::Item(item)
1266                                if update.diff
1267                                    == mz_catalog::memory::objects::StateDiff::Addition =>
1268                            {
1269                                Some(item.id)
1270                            }
1271                            _ => None,
1272                        });
1273                    // Durably record metadata such as an item's columns.
1274                    preliminary_state
1275                        .record_item_metadata(tx, updated_item_ids)
1276                        .map_err(AdapterError::from)?;
1277                }
1278                updates.append(&mut op_updates);
1279            }
1280            execution.finish(Ok(()))?;
1281        }
1282
1283        if !updates.is_empty() {
1284            let mut local_expr_cache = LocalExpressionCache::new(cached_exprs.clone());
1285            let (op_builtin_table_updates, op_catalog_updates) = state
1286                .to_mut()
1287                .apply_updates(updates.clone(), &mut local_expr_cache)
1288                .await;
1289            let op_builtin_table_updates = state
1290                .to_mut()
1291                .resolve_builtin_table_updates(op_builtin_table_updates);
1292            builtin_table_updates.extend(op_builtin_table_updates);
1293            parsed_catalog_updates.extend(op_catalog_updates);
1294        }
1295
1296        match mode {
1297            TransactInnerMode::Commit => {
1298                // `storage_collections` can be `None` in tests.
1299                if let Some(c) = storage_collections {
1300                    c.prepare_state(
1301                        tx,
1302                        storage_collections_to_create,
1303                        storage_collections_to_drop,
1304                        storage_collections_to_register,
1305                    )
1306                    .await
1307                    .map_err(AdapterError::from)?;
1308                }
1309            }
1310            TransactInnerMode::DryRun => {
1311                mz_ore::soft_assert_no_log!(
1312                    storage_collections.is_none(),
1313                    "dry-run mode must not prepare storage state"
1314                );
1315            }
1316        }
1317
1318        let updates = tx.get_and_commit_op_updates();
1319        if !updates.is_empty() {
1320            let mut local_expr_cache = LocalExpressionCache::new(cached_exprs.clone());
1321            let (op_builtin_table_updates, op_catalog_updates) = state
1322                .to_mut()
1323                .apply_updates(updates.clone(), &mut local_expr_cache)
1324                .await;
1325            let op_builtin_table_updates = state
1326                .to_mut()
1327                .resolve_builtin_table_updates(op_builtin_table_updates);
1328            builtin_table_updates.extend(op_builtin_table_updates);
1329            parsed_catalog_updates.extend(op_catalog_updates);
1330        }
1331
1332        match state {
1333            Cow::Owned(state) => Ok(Some(state)),
1334            Cow::Borrowed(_) => Ok(None),
1335        }
1336    }
1337
1338    /// Performs the transaction operation described by `op`. This function prepares the changes in
1339    /// `tx`, but does not update `state`. `state` will be updated when applying the durable
1340    /// changes.
1341    #[instrument]
1342    async fn transact_op(
1343        oracle_write_ts: mz_repr::Timestamp,
1344        session: Option<&ConnMeta>,
1345        op: Op,
1346        temporary_ids: &BTreeSet<CatalogItemId>,
1347        audit_events: &mut Vec<VersionedEvent>,
1348        tx: &mut Transaction<'_>,
1349        state: &CatalogState,
1350        storage_collections_to_create: &mut BTreeSet<GlobalId>,
1351        storage_collections_to_drop: &mut BTreeSet<GlobalId>,
1352        storage_collections_to_register: &mut BTreeMap<GlobalId, ShardId>,
1353    ) -> Result<(), AdapterError> {
1354        match op {
1355            Op::RenameCommand(_) | Op::RotatedKeys(_) => {
1356                unreachable!("commands are expanded by transact_inner")
1357            }
1358            Op::CheckClusterState {
1359                cluster_id,
1360                expected,
1361            } => {
1362                // Precondition only. Returning `Err` here aborts `transact_inner`
1363                // before `tx.commit`, so the compare-and-append holds atomically
1364                // with the write it guards.
1365                if !crate::catalog::cluster_state::cluster_matches_expected(
1366                    state, cluster_id, &expected,
1367                ) {
1368                    return Err(AdapterError::ClusterStateChanged { cluster_id });
1369                }
1370            }
1371            Op::AlterRetainHistory { id, value, window } => {
1372                let entry = state.get_entry(&id);
1373                if id.is_system() {
1374                    let name = entry.name();
1375                    let full_name =
1376                        state.resolve_full_name(name, session.map(|session| session.conn_id()));
1377                    return Err(AdapterError::Catalog(Error::new(ErrorKind::ReadOnlyItem(
1378                        full_name.to_string(),
1379                    ))));
1380                }
1381
1382                let mut new_entry = entry.clone();
1383                let previous = new_entry
1384                    .item
1385                    .update_retain_history(value.clone(), window)
1386                    .map_err(|_| {
1387                        AdapterError::Catalog(Error::new(ErrorKind::Internal(
1388                            "planner should have rejected invalid alter retain history item type"
1389                                .to_string(),
1390                        )))
1391                    })?;
1392
1393                if Self::should_audit_log_item(new_entry.item()) {
1394                    let details =
1395                        EventDetails::AlterRetainHistoryV1(mz_audit_log::AlterRetainHistoryV1 {
1396                            id: id.to_string(),
1397                            old_history: previous.map(|previous| previous.to_string()),
1398                            new_history: value.map(|v| v.to_string()),
1399                        });
1400                    CatalogState::add_to_audit_log(
1401                        &state.system_configuration,
1402                        oracle_write_ts,
1403                        session,
1404                        tx,
1405                        audit_events,
1406                        EventType::Alter,
1407                        catalog_type_to_audit_object_type(new_entry.item().typ()),
1408                        details,
1409                    )?;
1410                }
1411
1412                tx.update_item(id, state.durable_item(new_entry)?)?;
1413
1414                Self::log_update(state, &id);
1415            }
1416            Op::AlterSourceTimestampInterval {
1417                id,
1418                value,
1419                interval,
1420            } => {
1421                let entry = state.get_entry(&id);
1422                if id.is_system() {
1423                    let name = entry.name();
1424                    let full_name =
1425                        state.resolve_full_name(name, session.map(|session| session.conn_id()));
1426                    return Err(AdapterError::Catalog(Error::new(ErrorKind::ReadOnlyItem(
1427                        full_name.to_string(),
1428                    ))));
1429                }
1430
1431                let mut new_entry = entry.clone();
1432                let previous = new_entry
1433                    .item
1434                    .update_timestamp_interval(value.clone(), interval)
1435                    .map_err(|_| {
1436                        AdapterError::Catalog(Error::new(ErrorKind::Internal(
1437                            "planner should have rejected invalid alter timestamp interval item type"
1438                                .to_string(),
1439                        )))
1440                    })?;
1441
1442                if Self::should_audit_log_item(new_entry.item()) {
1443                    let details = EventDetails::AlterSourceTimestampIntervalV1(
1444                        mz_audit_log::AlterSourceTimestampIntervalV1 {
1445                            id: id.to_string(),
1446                            old_interval: previous.map(|previous| previous.to_string()),
1447                            new_interval: value.map(|v| v.to_string()),
1448                        },
1449                    );
1450                    CatalogState::add_to_audit_log(
1451                        &state.system_configuration,
1452                        oracle_write_ts,
1453                        session,
1454                        tx,
1455                        audit_events,
1456                        EventType::Alter,
1457                        catalog_type_to_audit_object_type(new_entry.item().typ()),
1458                        details,
1459                    )?;
1460                }
1461
1462                tx.update_item(id, state.durable_item(new_entry)?)?;
1463
1464                Self::log_update(state, &id);
1465            }
1466            Op::AlterRole {
1467                id,
1468                name,
1469                attributes,
1470                nopassword,
1471                vars,
1472            } => {
1473                state.ensure_not_reserved_role(&id)?;
1474
1475                let mut existing_role = state.get_role(&id).clone();
1476                let password = attributes.password.clone();
1477                let scram_iterations = attributes
1478                    .scram_iterations
1479                    .unwrap_or_else(|| state.system_config().scram_iterations());
1480                existing_role.attributes = attributes.into();
1481                existing_role.vars = vars;
1482                let password_action = if nopassword {
1483                    PasswordAction::Clear
1484                } else if let Some(password) = password {
1485                    PasswordAction::Set(PasswordConfig {
1486                        password,
1487                        scram_iterations,
1488                    })
1489                } else {
1490                    PasswordAction::NoChange
1491                };
1492                tx.update_role(id, existing_role.into(), password_action)?;
1493
1494                CatalogState::add_to_audit_log(
1495                    &state.system_configuration,
1496                    oracle_write_ts,
1497                    session,
1498                    tx,
1499                    audit_events,
1500                    EventType::Alter,
1501                    ObjectType::Role,
1502                    EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
1503                        id: id.to_string(),
1504                        name: name.clone(),
1505                    }),
1506                )?;
1507
1508                info!("update role {name} ({id})");
1509            }
1510            Op::AlterQueryPolicy { id, mode, rules } => {
1511                let mut policy = state.get_query_policy(&id).clone();
1512                if id.is_system() {
1513                    return Err(AdapterError::Catalog(Error::new(
1514                        ErrorKind::ReadOnlyQueryPolicy(policy.name),
1515                    )));
1516                }
1517                policy.mode = mode;
1518                policy.rules = rules;
1519                let name = policy.name.clone();
1520                tx.update_query_policy(policy.into())?;
1521                CatalogState::add_to_audit_log(
1522                    &state.system_configuration,
1523                    oracle_write_ts,
1524                    session,
1525                    tx,
1526                    audit_events,
1527                    EventType::Alter,
1528                    ObjectType::QueryPolicy,
1529                    EventDetails::IdNameV1(IdNameV1 {
1530                        id: id.to_string(),
1531                        name,
1532                    }),
1533                )?;
1534            }
1535            Op::AlterNetworkPolicy {
1536                id,
1537                rules,
1538                name,
1539                owner_id: _owner_id,
1540            } => {
1541                let existing_policy = state.get_network_policy(&id).clone();
1542                let mut policy: NetworkPolicy = existing_policy.into();
1543                policy.rules = rules;
1544                if is_reserved_name(&name) {
1545                    return Err(AdapterError::Catalog(Error::new(
1546                        ErrorKind::ReservedNetworkPolicyName(name),
1547                    )));
1548                }
1549                tx.update_network_policy(id, policy.clone())?;
1550
1551                CatalogState::add_to_audit_log(
1552                    &state.system_configuration,
1553                    oracle_write_ts,
1554                    session,
1555                    tx,
1556                    audit_events,
1557                    EventType::Alter,
1558                    ObjectType::NetworkPolicy,
1559                    EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
1560                        id: id.to_string(),
1561                        name: name.clone(),
1562                    }),
1563                )?;
1564
1565                info!("update network policy {name} ({id})");
1566            }
1567            Op::AlterAddColumn {
1568                id,
1569                new_global_id,
1570                name,
1571                typ,
1572                sql,
1573            } => {
1574                let column_name = name.to_string();
1575                let column_type = typ.to_string();
1576                let nullable = typ.nullable;
1577                let mut new_entry = state.get_entry(&id).clone();
1578                let version = new_entry.item.add_column(name, typ, sql)?;
1579                // All versions of a table share the same shard, so it shouldn't matter what
1580                // GlobalId we use here.
1581                let shard_id = state
1582                    .storage_metadata()
1583                    .get_collection_shard(new_entry.latest_global_id())?;
1584
1585                // TODO(alter_table): Support adding columns to sources.
1586                let CatalogItem::Table(table) = &mut new_entry.item else {
1587                    return Err(AdapterError::Unsupported("adding columns to non-Table"));
1588                };
1589                table.collections.insert(version, new_global_id);
1590
1591                if Self::should_audit_log_item(new_entry.item()) {
1592                    let details = EventDetails::AlterAddColumnV1(mz_audit_log::AlterAddColumnV1 {
1593                        id: id.to_string(),
1594                        column: column_name,
1595                        column_type,
1596                        nullable,
1597                    });
1598                    CatalogState::add_to_audit_log(
1599                        &state.system_configuration,
1600                        oracle_write_ts,
1601                        session,
1602                        tx,
1603                        audit_events,
1604                        EventType::Alter,
1605                        catalog_type_to_audit_object_type(new_entry.item().typ()),
1606                        details,
1607                    )?;
1608                }
1609
1610                tx.update_item(id, state.durable_item(new_entry)?)?;
1611                storage_collections_to_register.insert(new_global_id, shard_id);
1612            }
1613            Op::AlterMaterializedViewApplyReplacement { id, replacement_id } => {
1614                let mut new_entry = state.get_entry(&id).clone();
1615                let replacement = state.get_entry(&replacement_id);
1616
1617                let new_audit_events =
1618                    apply_replacement_audit_events(state, &new_entry, replacement);
1619
1620                let CatalogItem::MaterializedView(mv) = &mut new_entry.item else {
1621                    return Err(AdapterError::internal(
1622                        "ALTER MATERIALIZED VIEW ... APPLY REPLACEMENT",
1623                        "id must refer to a materialized view",
1624                    ));
1625                };
1626                let CatalogItem::MaterializedView(replacement_mv) = &replacement.item else {
1627                    return Err(AdapterError::internal(
1628                        "ALTER MATERIALIZED VIEW ... APPLY REPLACEMENT",
1629                        "replacement_id must refer to a materialized view",
1630                    ));
1631                };
1632
1633                mv.apply_replacement(replacement_mv.clone());
1634
1635                tx.remove_item(replacement_id)?;
1636
1637                new_entry.id = replacement_id;
1638                tx_replace_item(tx, state, id, new_entry)?;
1639
1640                let comment_id = CommentObjectId::MaterializedView(replacement_id);
1641                tx.drop_comments(&[comment_id].into())?;
1642
1643                for (event_type, details) in new_audit_events {
1644                    CatalogState::add_to_audit_log(
1645                        &state.system_configuration,
1646                        oracle_write_ts,
1647                        session,
1648                        tx,
1649                        audit_events,
1650                        event_type,
1651                        ObjectType::MaterializedView,
1652                        details,
1653                    )?;
1654                }
1655            }
1656            Op::CreateDatabase { name, owner_id } => {
1657                let database_owner_privileges = vec![rbac::owner_privilege(
1658                    mz_sql::catalog::ObjectType::Database,
1659                    owner_id,
1660                )];
1661                let database_default_privileges = state
1662                    .default_privileges
1663                    .get_applicable_privileges(
1664                        owner_id,
1665                        None,
1666                        None,
1667                        mz_sql::catalog::ObjectType::Database,
1668                    )
1669                    .map(|item| item.mz_acl_item(owner_id));
1670                let database_privileges: Vec<_> = merge_mz_acl_items(
1671                    database_owner_privileges
1672                        .into_iter()
1673                        .chain(database_default_privileges),
1674                )
1675                .collect();
1676
1677                let schema_owner_privileges = vec![rbac::owner_privilege(
1678                    mz_sql::catalog::ObjectType::Schema,
1679                    owner_id,
1680                )];
1681                let schema_default_privileges = state
1682                    .default_privileges
1683                    .get_applicable_privileges(
1684                        owner_id,
1685                        None,
1686                        None,
1687                        mz_sql::catalog::ObjectType::Schema,
1688                    )
1689                    .map(|item| item.mz_acl_item(owner_id))
1690                    // Special default privilege on public schemas.
1691                    .chain(std::iter::once(MzAclItem {
1692                        grantee: RoleId::Public,
1693                        grantor: owner_id,
1694                        acl_mode: AclMode::USAGE,
1695                    }));
1696                let schema_privileges: Vec<_> = merge_mz_acl_items(
1697                    schema_owner_privileges
1698                        .into_iter()
1699                        .chain(schema_default_privileges),
1700                )
1701                .collect();
1702
1703                let temporary_oids: HashSet<_> = state.get_temporary_oids().collect();
1704                let (database_id, _) = tx.insert_user_database(
1705                    &name,
1706                    owner_id,
1707                    database_privileges.clone(),
1708                    &temporary_oids,
1709                )?;
1710                let (schema_id, _) = tx.insert_user_schema(
1711                    database_id,
1712                    DEFAULT_SCHEMA,
1713                    owner_id,
1714                    schema_privileges.clone(),
1715                    &temporary_oids,
1716                )?;
1717                CatalogState::add_to_audit_log(
1718                    &state.system_configuration,
1719                    oracle_write_ts,
1720                    session,
1721                    tx,
1722                    audit_events,
1723                    EventType::Create,
1724                    ObjectType::Database,
1725                    EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
1726                        id: database_id.to_string(),
1727                        name: name.clone(),
1728                    }),
1729                )?;
1730                info!("create database {}", name);
1731
1732                CatalogState::add_to_audit_log(
1733                    &state.system_configuration,
1734                    oracle_write_ts,
1735                    session,
1736                    tx,
1737                    audit_events,
1738                    EventType::Create,
1739                    ObjectType::Schema,
1740                    EventDetails::SchemaV2(mz_audit_log::SchemaV2 {
1741                        id: schema_id.to_string(),
1742                        name: DEFAULT_SCHEMA.to_string(),
1743                        database_name: Some(name),
1744                    }),
1745                )?;
1746            }
1747            Op::CreateSchema {
1748                database_id,
1749                schema_name,
1750                owner_id,
1751            } => {
1752                if is_reserved_name(&schema_name) {
1753                    return Err(AdapterError::Catalog(Error::new(
1754                        ErrorKind::ReservedSchemaName(schema_name),
1755                    )));
1756                }
1757                let database_id = match database_id {
1758                    ResolvedDatabaseSpecifier::Id(id) => id,
1759                    ResolvedDatabaseSpecifier::Ambient => {
1760                        return Err(AdapterError::Catalog(Error::new(
1761                            ErrorKind::ReadOnlySystemSchema(schema_name),
1762                        )));
1763                    }
1764                };
1765                let owner_privileges = vec![rbac::owner_privilege(
1766                    mz_sql::catalog::ObjectType::Schema,
1767                    owner_id,
1768                )];
1769                let default_privileges = state
1770                    .default_privileges
1771                    .get_applicable_privileges(
1772                        owner_id,
1773                        Some(database_id),
1774                        None,
1775                        mz_sql::catalog::ObjectType::Schema,
1776                    )
1777                    .map(|item| item.mz_acl_item(owner_id));
1778                let privileges: Vec<_> =
1779                    merge_mz_acl_items(owner_privileges.into_iter().chain(default_privileges))
1780                        .collect();
1781                let (schema_id, _) = tx.insert_user_schema(
1782                    database_id,
1783                    &schema_name,
1784                    owner_id,
1785                    privileges.clone(),
1786                    &state.get_temporary_oids().collect(),
1787                )?;
1788                CatalogState::add_to_audit_log(
1789                    &state.system_configuration,
1790                    oracle_write_ts,
1791                    session,
1792                    tx,
1793                    audit_events,
1794                    EventType::Create,
1795                    ObjectType::Schema,
1796                    EventDetails::SchemaV2(mz_audit_log::SchemaV2 {
1797                        id: schema_id.to_string(),
1798                        name: schema_name.clone(),
1799                        database_name: Some(state.database_by_id[&database_id].name.clone()),
1800                    }),
1801                )?;
1802            }
1803            Op::CreateRole { name, attributes } => {
1804                if is_reserved_role_name(&name) {
1805                    return Err(AdapterError::Catalog(Error::new(
1806                        ErrorKind::ReservedRoleName(name),
1807                    )));
1808                }
1809                let membership = RoleMembership::new();
1810                let vars = RoleVars::default();
1811                let (id, _) = tx.insert_user_role(
1812                    name.clone(),
1813                    attributes.clone(),
1814                    membership.clone(),
1815                    vars.clone(),
1816                    &state.get_temporary_oids().collect(),
1817                )?;
1818                CatalogState::add_to_audit_log(
1819                    &state.system_configuration,
1820                    oracle_write_ts,
1821                    session,
1822                    tx,
1823                    audit_events,
1824                    EventType::Create,
1825                    ObjectType::Role,
1826                    EventDetails::CreateRoleV1(mz_audit_log::CreateRoleV1 {
1827                        id: id.to_string(),
1828                        name: name.clone(),
1829                        auto_provision_source: attributes.auto_provision_source.map(|s| match s {
1830                            AutoProvisionSource::Oidc => "oidc".to_string(),
1831                            AutoProvisionSource::Frontegg => "frontegg".to_string(),
1832                            AutoProvisionSource::None => "none".to_string(),
1833                        }),
1834                    }),
1835                )?;
1836                info!("create role {}", name);
1837            }
1838            Op::CreateCluster {
1839                id,
1840                name,
1841                introspection_sources,
1842                owner_id,
1843                config,
1844            } => {
1845                if is_reserved_name(&name) {
1846                    return Err(AdapterError::Catalog(Error::new(
1847                        ErrorKind::ReservedClusterName(name),
1848                    )));
1849                }
1850                let owner_privileges = vec![rbac::owner_privilege(
1851                    mz_sql::catalog::ObjectType::Cluster,
1852                    owner_id,
1853                )];
1854                let default_privileges = state
1855                    .default_privileges
1856                    .get_applicable_privileges(
1857                        owner_id,
1858                        None,
1859                        None,
1860                        mz_sql::catalog::ObjectType::Cluster,
1861                    )
1862                    .map(|item| item.mz_acl_item(owner_id));
1863                let privileges: Vec<_> =
1864                    merge_mz_acl_items(owner_privileges.into_iter().chain(default_privileges))
1865                        .collect();
1866                let introspection_source_ids: Vec<_> = introspection_sources
1867                    .iter()
1868                    .map(|introspection_source| {
1869                        Transaction::allocate_introspection_source_index_id(
1870                            &id,
1871                            introspection_source.variant,
1872                        )
1873                    })
1874                    .collect();
1875
1876                let introspection_sources = introspection_sources
1877                    .into_iter()
1878                    .zip_eq(introspection_source_ids)
1879                    .map(|(log, (item_id, gid))| (log, item_id, gid))
1880                    .collect();
1881
1882                tx.insert_user_cluster(
1883                    id,
1884                    &name,
1885                    introspection_sources,
1886                    owner_id,
1887                    privileges.clone(),
1888                    config.clone().into(),
1889                    &state.get_temporary_oids().collect(),
1890                )?;
1891                CatalogState::add_to_audit_log(
1892                    &state.system_configuration,
1893                    oracle_write_ts,
1894                    session,
1895                    tx,
1896                    audit_events,
1897                    EventType::Create,
1898                    ObjectType::Cluster,
1899                    EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
1900                        id: id.to_string(),
1901                        name: name.clone(),
1902                    }),
1903                )?;
1904                info!("create cluster {}", name);
1905            }
1906            Op::CreateClusterReplica {
1907                cluster_id,
1908                replica_id,
1909                name,
1910                config,
1911                owner_id,
1912                reason,
1913            } => {
1914                if is_reserved_name(&name) {
1915                    return Err(AdapterError::Catalog(Error::new(
1916                        ErrorKind::ReservedReplicaName(name),
1917                    )));
1918                }
1919                let cluster = state.get_cluster(cluster_id);
1920                // The replica id is allocated out-of-band by the durable
1921                // allocator before the transaction, mirroring cluster and item
1922                // ids. Nothing allocates a replica id in-apply.
1923                tx.insert_cluster_replica_with_id(
1924                    cluster_id,
1925                    replica_id,
1926                    &name,
1927                    config.clone().into(),
1928                    owner_id,
1929                )?;
1930                if let ReplicaLocation::Managed(ManagedReplicaLocation {
1931                    size,
1932                    billed_as,
1933                    internal,
1934                    ..
1935                }) = &config.location
1936                {
1937                    let (reason, scheduling_policies) = reason.into_audit_log();
1938                    let details = EventDetails::CreateClusterReplicaV4(
1939                        mz_audit_log::CreateClusterReplicaV4 {
1940                            cluster_id: cluster_id.to_string(),
1941                            cluster_name: cluster.name.clone(),
1942                            replica_id: Some(replica_id.to_string()),
1943                            replica_name: name.clone(),
1944                            logical_size: size.clone(),
1945                            billed_as: billed_as.clone(),
1946                            internal: *internal,
1947                            reason,
1948                            scheduling_policies,
1949                        },
1950                    );
1951                    CatalogState::add_to_audit_log(
1952                        &state.system_configuration,
1953                        oracle_write_ts,
1954                        session,
1955                        tx,
1956                        audit_events,
1957                        EventType::Create,
1958                        ObjectType::ClusterReplica,
1959                        details,
1960                    )?;
1961                }
1962            }
1963            Op::CreateItem {
1964                id,
1965                name,
1966                item,
1967                owner_id,
1968            } => {
1969                state.check_unstable_dependencies(&item)?;
1970
1971                match &item {
1972                    CatalogItem::Table(table) => {
1973                        let gids: Vec<_> = table.global_ids().collect();
1974                        assert_eq!(gids.len(), 1);
1975                        storage_collections_to_create.extend(gids);
1976                    }
1977                    CatalogItem::Source(source) => {
1978                        storage_collections_to_create.insert(source.global_id());
1979                    }
1980                    CatalogItem::MaterializedView(mv) => {
1981                        let mv_gid = mv.global_id_writes();
1982                        if let Some(target_id) = mv.replacement_target {
1983                            let target_gid = state.get_entry(&target_id).latest_global_id();
1984                            let shard_id =
1985                                state.storage_metadata().get_collection_shard(target_gid)?;
1986                            storage_collections_to_register.insert(mv_gid, shard_id);
1987                        } else {
1988                            storage_collections_to_create.insert(mv_gid);
1989                        }
1990                    }
1991                    CatalogItem::Sink(sink) => {
1992                        storage_collections_to_create.insert(sink.global_id());
1993                    }
1994                    CatalogItem::Log(_)
1995                    | CatalogItem::View(_)
1996                    | CatalogItem::Index(_)
1997                    | CatalogItem::Type(_)
1998                    | CatalogItem::Func(_)
1999                    | CatalogItem::Secret(_)
2000                    | CatalogItem::Connection(_)
2001                    // Metric sinks write to the replica's metrics registry, never to persist,
2002                    // so there is no storage collection to create.
2003                    | CatalogItem::MetricSink(_) => (),
2004                }
2005
2006                let system_user = session.map_or(false, |s| s.user().is_system_user());
2007                if !system_user {
2008                    if let Some(id @ ClusterId::System(_)) = item.cluster_id() {
2009                        let cluster_name = state.clusters_by_id[&id].name.clone();
2010                        return Err(AdapterError::Catalog(Error::new(
2011                            ErrorKind::ReadOnlyCluster(cluster_name),
2012                        )));
2013                    }
2014                }
2015
2016                let owner_privileges = vec![rbac::owner_privilege(item.typ().into(), owner_id)];
2017                let default_privileges = state
2018                    .default_privileges
2019                    .get_applicable_privileges(
2020                        owner_id,
2021                        name.qualifiers.database_spec.id(),
2022                        Some(name.qualifiers.schema_spec.into()),
2023                        item.typ().into(),
2024                    )
2025                    .map(|item| item.mz_acl_item(owner_id));
2026                // mz_support can read all progress sources.
2027                let progress_source_privilege = if item.is_progress_source() {
2028                    Some(MzAclItem {
2029                        grantee: MZ_SUPPORT_ROLE_ID,
2030                        grantor: owner_id,
2031                        acl_mode: AclMode::SELECT,
2032                    })
2033                } else {
2034                    None
2035                };
2036                let privileges: Vec<_> = merge_mz_acl_items(
2037                    owner_privileges
2038                        .into_iter()
2039                        .chain(default_privileges)
2040                        .chain(progress_source_privilege),
2041                )
2042                .collect();
2043
2044                let temporary_oids = state.get_temporary_oids().collect();
2045
2046                if item.is_temporary() {
2047                    if name.qualifiers.database_spec != ResolvedDatabaseSpecifier::Ambient
2048                        || name.qualifiers.schema_spec != SchemaSpecifier::Temporary
2049                    {
2050                        return Err(AdapterError::Catalog(Error::new(
2051                            ErrorKind::InvalidTemporarySchema,
2052                        )));
2053                    }
2054                    let owner_session =
2055                        temporary_item_owner_session(state, session, &item, &name.item)?;
2056
2057                    let schema_id = name.qualifiers.schema_spec.clone().into();
2058                    let item_type = item.typ();
2059                    let (create_sql, global_id, versions) = item.to_serialized();
2060                    tx.insert_user_item(
2061                        id,
2062                        global_id,
2063                        schema_id,
2064                        &name.item,
2065                        create_sql,
2066                        owner_id,
2067                        privileges.clone(),
2068                        &temporary_oids,
2069                        versions,
2070                        Some(owner_session),
2071                    )?;
2072
2073                    info!(
2074                        "create temporary {} {} ({})",
2075                        item_type,
2076                        state.resolve_full_name(&name, None),
2077                        id
2078                    );
2079                } else {
2080                    if let Some(temp_id) =
2081                        item.uses()
2082                            .iter()
2083                            .find(|id| match state.try_get_entry(*id) {
2084                                Some(entry) => entry.item().is_temporary(),
2085                                None => temporary_ids.contains(id),
2086                            })
2087                    {
2088                        let temp_item = state.get_entry(temp_id);
2089                        return Err(AdapterError::Catalog(Error::new(
2090                            ErrorKind::InvalidTemporaryDependency(temp_item.name().item.clone()),
2091                        )));
2092                    }
2093                    if name.qualifiers.database_spec == ResolvedDatabaseSpecifier::Ambient
2094                        && !system_user
2095                    {
2096                        let schema_name = state
2097                            .resolve_full_name(&name, session.map(|session| session.conn_id()))
2098                            .schema;
2099                        return Err(AdapterError::Catalog(Error::new(
2100                            ErrorKind::ReadOnlySystemSchema(schema_name),
2101                        )));
2102                    }
2103                    if name.qualifiers.schema_spec.is_system() {
2104                        // Builtins live outside the durable items collection's uniqueness check.
2105                        let schema = state.get_schema(
2106                            &name.qualifiers.database_spec,
2107                            &name.qualifiers.schema_spec,
2108                            &SYSTEM_CONN_ID,
2109                        );
2110                        let namespace = match &item {
2111                            CatalogItem::Type(_) => &schema.types,
2112                            CatalogItem::Func(_) => &schema.functions,
2113                            _ => &schema.items,
2114                        };
2115                        if namespace.contains_key(&name.item) {
2116                            return Err(SqlCatalogError::ItemAlreadyExists(id, name.item).into());
2117                        }
2118                    }
2119                    let schema_id = name.qualifiers.schema_spec.clone().into();
2120                    let item_type = item.typ();
2121                    let (create_sql, global_id, versions) = item.to_serialized();
2122                    tx.insert_user_item(
2123                        id,
2124                        global_id,
2125                        schema_id,
2126                        &name.item,
2127                        create_sql,
2128                        owner_id,
2129                        privileges.clone(),
2130                        &temporary_oids,
2131                        versions,
2132                        None,
2133                    )?;
2134                    info!(
2135                        "create {} {} ({})",
2136                        item_type,
2137                        state.resolve_full_name(&name, None),
2138                        id
2139                    );
2140                }
2141
2142                if Self::should_audit_log_item(&item) {
2143                    let name = Self::full_name_detail(
2144                        &state.resolve_full_name(&name, session.map(|session| session.conn_id())),
2145                    );
2146                    let details = match &item {
2147                        CatalogItem::Source(s) => {
2148                            let cluster_id = match s.data_source {
2149                                // Ingestion exports don't have their own cluster, but
2150                                // run on their ingestion's cluster.
2151                                DataSourceDesc::IngestionExport { ingestion_id, .. } => {
2152                                    match state.get_entry(&ingestion_id).cluster_id() {
2153                                        Some(cluster_id) => Some(cluster_id.to_string()),
2154                                        None => None,
2155                                    }
2156                                }
2157                                _ => match item.cluster_id() {
2158                                    Some(cluster_id) => Some(cluster_id.to_string()),
2159                                    None => None,
2160                                },
2161                            };
2162
2163                            EventDetails::CreateSourceSinkV4(mz_audit_log::CreateSourceSinkV4 {
2164                                id: id.to_string(),
2165                                cluster_id,
2166                                name,
2167                                external_type: s.source_type().to_string(),
2168                            })
2169                        }
2170                        CatalogItem::Sink(s) => {
2171                            EventDetails::CreateSourceSinkV4(mz_audit_log::CreateSourceSinkV4 {
2172                                id: id.to_string(),
2173                                cluster_id: Some(s.cluster_id.to_string()),
2174                                name,
2175                                external_type: s.sink_type().to_string(),
2176                            })
2177                        }
2178                        CatalogItem::Index(i) => {
2179                            EventDetails::CreateIndexV1(mz_audit_log::CreateIndexV1 {
2180                                id: id.to_string(),
2181                                name,
2182                                cluster_id: i.cluster_id.to_string(),
2183                            })
2184                        }
2185                        CatalogItem::MaterializedView(mv) => {
2186                            EventDetails::CreateMaterializedViewV1(
2187                                mz_audit_log::CreateMaterializedViewV1 {
2188                                    id: id.to_string(),
2189                                    name,
2190                                    cluster_id: mv.cluster_id.to_string(),
2191                                    replacement_target_id: mv
2192                                        .replacement_target
2193                                        .map(|id| id.to_string()),
2194                                },
2195                            )
2196                        }
2197                        CatalogItem::Table(_)
2198                        | CatalogItem::Log(_)
2199                        | CatalogItem::View(_)
2200                        | CatalogItem::Type(_)
2201                        | CatalogItem::Func(_)
2202                        | CatalogItem::Secret(_)
2203                        | CatalogItem::Connection(_)
2204                        | CatalogItem::MetricSink(_) => EventDetails::IdFullNameV1(IdFullNameV1 {
2205                            id: id.to_string(),
2206                            name,
2207                        }),
2208                    };
2209                    CatalogState::add_to_audit_log(
2210                        &state.system_configuration,
2211                        oracle_write_ts,
2212                        session,
2213                        tx,
2214                        audit_events,
2215                        EventType::Create,
2216                        catalog_type_to_audit_object_type(item.typ()),
2217                        details,
2218                    )?;
2219                }
2220            }
2221            Op::CreateQueryPolicy {
2222                name,
2223                mode,
2224                rules,
2225                owner_id,
2226            } => {
2227                if state.query_policies_by_name.contains_key(&name) {
2228                    return Err(AdapterError::PlanError(PlanError::Catalog(
2229                        SqlCatalogError::QueryPolicyAlreadyExists(name),
2230                    )));
2231                }
2232                if is_reserved_name(&name) {
2233                    return Err(AdapterError::Catalog(Error::new(
2234                        ErrorKind::ReservedQueryPolicyName(name),
2235                    )));
2236                }
2237                let object_type = mz_sql::catalog::ObjectType::QueryPolicy;
2238                let owner_privileges =
2239                    std::iter::once(rbac::owner_privilege(object_type, owner_id));
2240                let default_privileges = state
2241                    .default_privileges
2242                    .get_applicable_privileges(owner_id, None, None, object_type)
2243                    .map(|item| item.mz_acl_item(owner_id));
2244                let privileges =
2245                    merge_mz_acl_items(owner_privileges.chain(default_privileges)).collect();
2246                let temporary_oids = state.get_temporary_oids().collect();
2247                let id = tx.insert_user_query_policy(
2248                    name.clone(),
2249                    mode,
2250                    rules,
2251                    privileges,
2252                    owner_id,
2253                    &temporary_oids,
2254                )?;
2255                CatalogState::add_to_audit_log(
2256                    &state.system_configuration,
2257                    oracle_write_ts,
2258                    session,
2259                    tx,
2260                    audit_events,
2261                    EventType::Create,
2262                    ObjectType::QueryPolicy,
2263                    EventDetails::IdNameV1(IdNameV1 {
2264                        id: id.to_string(),
2265                        name,
2266                    }),
2267                )?;
2268            }
2269            Op::CreateNetworkPolicy {
2270                rules,
2271                name,
2272                owner_id,
2273            } => {
2274                if state.network_policies_by_name.contains_key(&name) {
2275                    return Err(AdapterError::PlanError(PlanError::Catalog(
2276                        SqlCatalogError::NetworkPolicyAlreadyExists(name),
2277                    )));
2278                }
2279                if is_reserved_name(&name) {
2280                    return Err(AdapterError::Catalog(Error::new(
2281                        ErrorKind::ReservedNetworkPolicyName(name),
2282                    )));
2283                }
2284
2285                let owner_privileges = vec![rbac::owner_privilege(
2286                    mz_sql::catalog::ObjectType::NetworkPolicy,
2287                    owner_id,
2288                )];
2289                let default_privileges = state
2290                    .default_privileges
2291                    .get_applicable_privileges(
2292                        owner_id,
2293                        None,
2294                        None,
2295                        mz_sql::catalog::ObjectType::NetworkPolicy,
2296                    )
2297                    .map(|item| item.mz_acl_item(owner_id));
2298                let privileges: Vec<_> =
2299                    merge_mz_acl_items(owner_privileges.into_iter().chain(default_privileges))
2300                        .collect();
2301
2302                let temporary_oids: HashSet<_> = state.get_temporary_oids().collect();
2303                let id = tx.insert_user_network_policy(
2304                    name.clone(),
2305                    rules,
2306                    privileges,
2307                    owner_id,
2308                    &temporary_oids,
2309                )?;
2310
2311                CatalogState::add_to_audit_log(
2312                    &state.system_configuration,
2313                    oracle_write_ts,
2314                    session,
2315                    tx,
2316                    audit_events,
2317                    EventType::Create,
2318                    ObjectType::NetworkPolicy,
2319                    EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2320                        id: id.to_string(),
2321                        name: name.clone(),
2322                    }),
2323                )?;
2324
2325                info!("created network policy {name} ({id})");
2326            }
2327            Op::Comment {
2328                object_id,
2329                sub_component,
2330                comment,
2331            } => {
2332                tx.update_comment(object_id, sub_component, comment)?;
2333                let entry = state.get_comment_id_entry(&object_id);
2334                let should_log = entry
2335                    .map(|entry| Self::should_audit_log_item(entry.item()))
2336                    // Things that aren't catalog entries can't be temp, so should be logged.
2337                    .unwrap_or(true);
2338                // TODO: We need a conn_id to resolve schema names. This means that system-initiated
2339                // comments won't be logged for now.
2340                if let (Some(conn_id), true) =
2341                    (session.map(|session| session.conn_id()), should_log)
2342                {
2343                    CatalogState::add_to_audit_log(
2344                        &state.system_configuration,
2345                        oracle_write_ts,
2346                        session,
2347                        tx,
2348                        audit_events,
2349                        EventType::Comment,
2350                        comment_id_to_audit_object_type(object_id),
2351                        EventDetails::IdNameV1(IdNameV1 {
2352                            // CommentObjectIds don't have a great string representation, but debug will do for now.
2353                            id: format!("{object_id:?}"),
2354                            name: state.comment_id_to_audit_log_name(object_id, conn_id),
2355                        }),
2356                    )?;
2357                }
2358            }
2359            Op::UpdateSourceReferences {
2360                source_id,
2361                references,
2362            } => {
2363                tx.update_source_references(
2364                    source_id,
2365                    references
2366                        .references
2367                        .into_iter()
2368                        .map(|reference| reference.into())
2369                        .collect(),
2370                    references.updated_at,
2371                )?;
2372            }
2373            Op::DropObjects {
2374                objects: drop_object_infos,
2375                cascade,
2376            } => {
2377                // Generate all of the objects that need to get dropped.
2378                let delta = ObjectsToDrop::generate(drop_object_infos, state, session)?;
2379
2380                // Drop any associated comments.
2381                tx.drop_comments(&delta.comments)?;
2382
2383                // Drop any items.
2384                let items_to_drop: BTreeSet<_> = delta.items.iter().copied().collect();
2385                tx.remove_items(&items_to_drop)?;
2386
2387                for item_id in delta.items {
2388                    let entry = state.get_entry(&item_id);
2389
2390                    if entry.item().is_storage_collection() {
2391                        storage_collections_to_drop.extend(entry.global_ids());
2392                    }
2393
2394                    if state.source_references.contains_key(&item_id) {
2395                        tx.remove_source_references(item_id)?;
2396                    }
2397
2398                    if Self::should_audit_log_item(entry.item()) {
2399                        CatalogState::add_to_audit_log(
2400                            &state.system_configuration,
2401                            oracle_write_ts,
2402                            session,
2403                            tx,
2404                            audit_events,
2405                            EventType::Drop,
2406                            catalog_type_to_audit_object_type(entry.item().typ()),
2407                            EventDetails::IdFullNameV1(IdFullNameV1 {
2408                                id: item_id.to_string(),
2409                                name: Self::full_name_detail(&state.resolve_full_name(
2410                                    entry.name(),
2411                                    session.map(|session| session.conn_id()),
2412                                )),
2413                            }),
2414                        )?;
2415                    }
2416                    info!(
2417                        "drop {} {} ({})",
2418                        entry.item_type(),
2419                        state.resolve_full_name(entry.name(), entry.conn_id()),
2420                        item_id
2421                    );
2422                }
2423
2424                // Drop any schemas.
2425                let schemas = delta
2426                    .schemas
2427                    .iter()
2428                    .map(|(schema_spec, database_spec)| {
2429                        (SchemaId::from(schema_spec), *database_spec)
2430                    })
2431                    .collect();
2432                tx.remove_schemas(&schemas)?;
2433
2434                for (schema_spec, database_spec) in delta.schemas {
2435                    let schema = state.get_schema(
2436                        &database_spec,
2437                        &schema_spec,
2438                        session
2439                            .map(|session| session.conn_id())
2440                            .unwrap_or(&SYSTEM_CONN_ID),
2441                    );
2442
2443                    let schema_id = SchemaId::from(schema_spec);
2444                    let database_id = match database_spec {
2445                        ResolvedDatabaseSpecifier::Ambient => None,
2446                        ResolvedDatabaseSpecifier::Id(database_id) => Some(database_id),
2447                    };
2448
2449                    CatalogState::add_to_audit_log(
2450                        &state.system_configuration,
2451                        oracle_write_ts,
2452                        session,
2453                        tx,
2454                        audit_events,
2455                        EventType::Drop,
2456                        ObjectType::Schema,
2457                        EventDetails::SchemaV2(mz_audit_log::SchemaV2 {
2458                            id: schema_id.to_string(),
2459                            name: schema.name.schema.to_string(),
2460                            database_name: database_id
2461                                .map(|database_id| state.database_by_id[&database_id].name.clone()),
2462                        }),
2463                    )?;
2464                }
2465
2466                // Drop any databases.
2467                tx.remove_databases(&delta.databases)?;
2468
2469                for database_id in delta.databases {
2470                    let database = state.get_database(&database_id).clone();
2471
2472                    CatalogState::add_to_audit_log(
2473                        &state.system_configuration,
2474                        oracle_write_ts,
2475                        session,
2476                        tx,
2477                        audit_events,
2478                        EventType::Drop,
2479                        ObjectType::Database,
2480                        EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2481                            id: database_id.to_string(),
2482                            name: database.name.clone(),
2483                        }),
2484                    )?;
2485                }
2486
2487                // Drop any roles.
2488                tx.remove_user_roles(&delta.roles)?;
2489
2490                for role_id in delta.roles {
2491                    let role = state
2492                        .roles_by_id
2493                        .get(&role_id)
2494                        .expect("catalog out of sync");
2495
2496                    CatalogState::add_to_audit_log(
2497                        &state.system_configuration,
2498                        oracle_write_ts,
2499                        session,
2500                        tx,
2501                        audit_events,
2502                        EventType::Drop,
2503                        ObjectType::Role,
2504                        EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2505                            id: role.id.to_string(),
2506                            name: role.name.clone(),
2507                        }),
2508                    )?;
2509                    info!("drop role {}", role.name());
2510                }
2511
2512                // Drop any network policies.
2513                tx.remove_network_policies(&delta.network_policies)?;
2514
2515                for network_policy_id in delta.network_policies {
2516                    let policy = state
2517                        .network_policies_by_id
2518                        .get(&network_policy_id)
2519                        .expect("catalog out of sync");
2520
2521                    CatalogState::add_to_audit_log(
2522                        &state.system_configuration,
2523                        oracle_write_ts,
2524                        session,
2525                        tx,
2526                        audit_events,
2527                        EventType::Drop,
2528                        ObjectType::NetworkPolicy,
2529                        EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2530                            id: policy.id.to_string(),
2531                            name: policy.name.clone(),
2532                        }),
2533                    )?;
2534                    info!("drop network policy {}", policy.name.clone());
2535                }
2536
2537                // Drop any replicas.
2538                let replicas = delta.replicas.keys().copied().collect();
2539                tx.remove_cluster_replicas(&replicas)?;
2540
2541                for (replica_id, (cluster_id, reason)) in delta.replicas {
2542                    let cluster = state.get_cluster(cluster_id);
2543                    let replica = cluster.replica(replica_id).expect("Must exist");
2544
2545                    let (reason, scheduling_policies) = reason.into_audit_log();
2546                    let details =
2547                        EventDetails::DropClusterReplicaV3(mz_audit_log::DropClusterReplicaV3 {
2548                            cluster_id: cluster_id.to_string(),
2549                            cluster_name: cluster.name.clone(),
2550                            replica_id: Some(replica_id.to_string()),
2551                            replica_name: replica.name.clone(),
2552                            reason,
2553                            scheduling_policies,
2554                        });
2555                    CatalogState::add_to_audit_log(
2556                        &state.system_configuration,
2557                        oracle_write_ts,
2558                        session,
2559                        tx,
2560                        audit_events,
2561                        EventType::Drop,
2562                        ObjectType::ClusterReplica,
2563                        details,
2564                    )?;
2565                }
2566
2567                // Drop any clusters.
2568                tx.remove_clusters(&delta.clusters)?;
2569
2570                for cluster_id in delta.clusters {
2571                    let cluster = state.get_cluster(cluster_id);
2572
2573                    CatalogState::add_to_audit_log(
2574                        &state.system_configuration,
2575                        oracle_write_ts,
2576                        session,
2577                        tx,
2578                        audit_events,
2579                        EventType::Drop,
2580                        ObjectType::Cluster,
2581                        EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2582                            id: cluster.id.to_string(),
2583                            name: cluster.name.clone(),
2584                        }),
2585                    )?;
2586                }
2587
2588                // Remove attachment targets first so RESTRICT ignores targets
2589                // that are themselves part of this drop.
2590                let detached_clusters = tx.remove_query_policies(&delta.query_policies, cascade)?;
2591                for id in detached_clusters {
2592                    let cluster = state.get_cluster(id);
2593                    CatalogState::add_to_audit_log(
2594                        &state.system_configuration,
2595                        oracle_write_ts,
2596                        session,
2597                        tx,
2598                        audit_events,
2599                        EventType::Alter,
2600                        ObjectType::Cluster,
2601                        EventDetails::IdNameV1(IdNameV1 {
2602                            id: id.to_string(),
2603                            name: cluster.name.clone(),
2604                        }),
2605                    )?;
2606                }
2607                for id in delta.query_policies {
2608                    let policy = state.get_query_policy(&id);
2609                    CatalogState::add_to_audit_log(
2610                        &state.system_configuration,
2611                        oracle_write_ts,
2612                        session,
2613                        tx,
2614                        audit_events,
2615                        EventType::Drop,
2616                        ObjectType::QueryPolicy,
2617                        EventDetails::IdNameV1(IdNameV1 {
2618                            id: id.to_string(),
2619                            name: policy.name.clone(),
2620                        }),
2621                    )?;
2622                }
2623            }
2624            Op::GrantRole {
2625                role_id,
2626                member_id,
2627                grantor_id,
2628            } => {
2629                state.ensure_not_reserved_role(&member_id)?;
2630                state.ensure_grantable_role(&role_id)?;
2631                if state.collect_role_membership(&role_id).contains(&member_id) {
2632                    let group_role = state.get_role(&role_id);
2633                    let member_role = state.get_role(&member_id);
2634                    return Err(AdapterError::Catalog(Error::new(
2635                        ErrorKind::CircularRoleMembership {
2636                            role_name: group_role.name().to_string(),
2637                            member_name: member_role.name().to_string(),
2638                        },
2639                    )));
2640                }
2641                let mut member_role = state.get_role(&member_id).clone();
2642                member_role.membership.map.insert(role_id, grantor_id);
2643                tx.update_role(member_id, member_role.into(), PasswordAction::NoChange)?;
2644
2645                CatalogState::add_to_audit_log(
2646                    &state.system_configuration,
2647                    oracle_write_ts,
2648                    session,
2649                    tx,
2650                    audit_events,
2651                    EventType::Grant,
2652                    ObjectType::Role,
2653                    EventDetails::GrantRoleV2(mz_audit_log::GrantRoleV2 {
2654                        role_id: role_id.to_string(),
2655                        member_id: member_id.to_string(),
2656                        grantor_id: grantor_id.to_string(),
2657                        executed_by: session
2658                            .map(|session| session.authenticated_role_id())
2659                            .unwrap_or(&MZ_SYSTEM_ROLE_ID)
2660                            .to_string(),
2661                    }),
2662                )?;
2663            }
2664            Op::RevokeRole {
2665                role_id,
2666                member_id,
2667                grantor_id,
2668            } => {
2669                state.ensure_not_reserved_role(&member_id)?;
2670                state.ensure_grantable_role(&role_id)?;
2671                let mut member_role = state.get_role(&member_id).clone();
2672                member_role.membership.map.remove(&role_id);
2673                tx.update_role(member_id, member_role.into(), PasswordAction::NoChange)?;
2674
2675                CatalogState::add_to_audit_log(
2676                    &state.system_configuration,
2677                    oracle_write_ts,
2678                    session,
2679                    tx,
2680                    audit_events,
2681                    EventType::Revoke,
2682                    ObjectType::Role,
2683                    EventDetails::RevokeRoleV2(mz_audit_log::RevokeRoleV2 {
2684                        role_id: role_id.to_string(),
2685                        member_id: member_id.to_string(),
2686                        grantor_id: grantor_id.to_string(),
2687                        executed_by: session
2688                            .map(|session| session.authenticated_role_id())
2689                            .unwrap_or(&MZ_SYSTEM_ROLE_ID)
2690                            .to_string(),
2691                    }),
2692                )?;
2693            }
2694            Op::UpdatePrivilege {
2695                target_id,
2696                privileges,
2697                variant,
2698            } => {
2699                let update_privilege_fn = |target_privileges: &mut PrivilegeMap| {
2700                    for privilege in &privileges {
2701                        match variant {
2702                            UpdatePrivilegeVariant::Grant => {
2703                                target_privileges.grant(privilege.clone());
2704                            }
2705                            UpdatePrivilegeVariant::Revoke => {
2706                                target_privileges.revoke(privilege);
2707                            }
2708                        }
2709                    }
2710                };
2711                match &target_id {
2712                    SystemObjectId::Object(object_id) => match object_id {
2713                        ObjectId::Cluster(id) => {
2714                            let mut cluster = state.get_cluster(*id).clone();
2715                            update_privilege_fn(&mut cluster.privileges);
2716                            tx.update_cluster(*id, cluster.into())?;
2717                        }
2718                        ObjectId::Database(id) => {
2719                            let mut database = state.get_database(id).clone();
2720                            update_privilege_fn(&mut database.privileges);
2721                            tx.update_database(*id, database.into())?;
2722                        }
2723                        ObjectId::NetworkPolicy(id) => {
2724                            let mut policy = state.get_network_policy(id).clone();
2725                            update_privilege_fn(&mut policy.privileges);
2726                            tx.update_network_policy(*id, policy.into())?;
2727                        }
2728                        ObjectId::QueryPolicy(id) => {
2729                            let mut policy = state.get_query_policy(id).clone();
2730                            update_privilege_fn(&mut policy.privileges);
2731                            tx.update_query_policy(policy.into())?;
2732                        }
2733                        ObjectId::Schema((database_spec, schema_spec)) => {
2734                            let schema_id = schema_spec.clone().into();
2735                            let mut schema = state
2736                                .get_schema(
2737                                    database_spec,
2738                                    schema_spec,
2739                                    session
2740                                        .map(|session| session.conn_id())
2741                                        .unwrap_or(&SYSTEM_CONN_ID),
2742                                )
2743                                .clone();
2744                            update_privilege_fn(&mut schema.privileges);
2745                            tx.update_schema(schema_id, schema.into())?;
2746                        }
2747                        ObjectId::Item(id) => {
2748                            let entry = state.get_entry(id);
2749                            let mut new_entry = entry.clone();
2750                            update_privilege_fn(&mut new_entry.privileges);
2751                            tx.update_item(*id, state.durable_item(new_entry)?)?;
2752                        }
2753                        ObjectId::Role(_) | ObjectId::ClusterReplica(_) => {}
2754                    },
2755                    SystemObjectId::System => {
2756                        let mut system_privileges = PrivilegeMap::clone(&state.system_privileges);
2757                        update_privilege_fn(&mut system_privileges);
2758                        for privilege in &privileges {
2759                            let new_privilege = system_privileges
2760                                .get_acl_item(&privilege.grantee, &privilege.grantor);
2761                            tx.set_system_privilege(
2762                                privilege.grantee,
2763                                privilege.grantor,
2764                                new_privilege.map(|new_privilege| new_privilege.acl_mode),
2765                            )?;
2766                        }
2767                    }
2768                }
2769                let object_type = state.get_system_object_type(&target_id);
2770                let object_id_str = match &target_id {
2771                    SystemObjectId::System => "SYSTEM".to_string(),
2772                    SystemObjectId::Object(id) => id.to_string(),
2773                };
2774                // One audit event per grantee, even though the batch is a single durable write.
2775                for privilege in &privileges {
2776                    CatalogState::add_to_audit_log(
2777                        &state.system_configuration,
2778                        oracle_write_ts,
2779                        session,
2780                        tx,
2781                        audit_events,
2782                        variant.into(),
2783                        system_object_type_to_audit_object_type(&object_type),
2784                        EventDetails::UpdatePrivilegeV1(mz_audit_log::UpdatePrivilegeV1 {
2785                            object_id: object_id_str.clone(),
2786                            grantee_id: privilege.grantee.to_string(),
2787                            grantor_id: privilege.grantor.to_string(),
2788                            privileges: privilege.acl_mode.to_string(),
2789                        }),
2790                    )?;
2791                }
2792            }
2793            Op::UpdateDefaultPrivilege {
2794                privilege_object,
2795                privilege_acl_item,
2796                variant,
2797            } => {
2798                let mut default_privileges = DefaultPrivileges::clone(&state.default_privileges);
2799                match variant {
2800                    UpdatePrivilegeVariant::Grant => default_privileges
2801                        .grant(privilege_object.clone(), privilege_acl_item.clone()),
2802                    UpdatePrivilegeVariant::Revoke => {
2803                        default_privileges.revoke(&privilege_object, &privilege_acl_item)
2804                    }
2805                }
2806                let new_acl_mode = default_privileges
2807                    .get_privileges_for_grantee(&privilege_object, &privilege_acl_item.grantee);
2808                tx.set_default_privilege(
2809                    privilege_object.role_id,
2810                    privilege_object.database_id,
2811                    privilege_object.schema_id,
2812                    privilege_object.object_type,
2813                    privilege_acl_item.grantee,
2814                    new_acl_mode.cloned(),
2815                )?;
2816                CatalogState::add_to_audit_log(
2817                    &state.system_configuration,
2818                    oracle_write_ts,
2819                    session,
2820                    tx,
2821                    audit_events,
2822                    variant.into(),
2823                    object_type_to_audit_object_type(privilege_object.object_type),
2824                    EventDetails::AlterDefaultPrivilegeV1(mz_audit_log::AlterDefaultPrivilegeV1 {
2825                        role_id: privilege_object.role_id.to_string(),
2826                        database_id: privilege_object.database_id.map(|id| id.to_string()),
2827                        schema_id: privilege_object.schema_id.map(|id| id.to_string()),
2828                        grantee_id: privilege_acl_item.grantee.to_string(),
2829                        privileges: privilege_acl_item.acl_mode.to_string(),
2830                    }),
2831                )?;
2832            }
2833            Op::RenameCluster {
2834                id,
2835                name,
2836                to_name,
2837                check_reserved_names,
2838            } => {
2839                if id.is_system() {
2840                    return Err(AdapterError::Catalog(Error::new(
2841                        ErrorKind::ReadOnlyCluster(name.clone()),
2842                    )));
2843                }
2844                if check_reserved_names && is_reserved_name(&to_name) {
2845                    return Err(AdapterError::Catalog(Error::new(
2846                        ErrorKind::ReservedClusterName(to_name),
2847                    )));
2848                }
2849                tx.rename_cluster(id, &name, &to_name)?;
2850                CatalogState::add_to_audit_log(
2851                    &state.system_configuration,
2852                    oracle_write_ts,
2853                    session,
2854                    tx,
2855                    audit_events,
2856                    EventType::Alter,
2857                    ObjectType::Cluster,
2858                    EventDetails::RenameClusterV1(mz_audit_log::RenameClusterV1 {
2859                        id: id.to_string(),
2860                        old_name: name.clone(),
2861                        new_name: to_name.clone(),
2862                    }),
2863                )?;
2864                info!("rename cluster {name} to {to_name}");
2865            }
2866            Op::RenameClusterReplica {
2867                cluster_id,
2868                replica_id,
2869                name,
2870                to_name,
2871            } => {
2872                if is_reserved_name(&to_name) {
2873                    return Err(AdapterError::Catalog(Error::new(
2874                        ErrorKind::ReservedReplicaName(to_name),
2875                    )));
2876                }
2877                tx.rename_cluster_replica(replica_id, &name, &to_name)?;
2878                CatalogState::add_to_audit_log(
2879                    &state.system_configuration,
2880                    oracle_write_ts,
2881                    session,
2882                    tx,
2883                    audit_events,
2884                    EventType::Alter,
2885                    ObjectType::ClusterReplica,
2886                    EventDetails::RenameClusterReplicaV1(mz_audit_log::RenameClusterReplicaV1 {
2887                        cluster_id: cluster_id.to_string(),
2888                        replica_id: replica_id.to_string(),
2889                        old_name: name.replica.as_str().to_string(),
2890                        new_name: to_name.clone(),
2891                    }),
2892                )?;
2893                info!("rename cluster replica {name} to {to_name}");
2894            }
2895            Op::RenameItem {
2896                id,
2897                to_name,
2898                current_full_name,
2899            } => {
2900                let mut updates = Vec::new();
2901
2902                let entry = state.get_entry(&id);
2903                if let CatalogItem::Type(_) = entry.item() {
2904                    return Err(AdapterError::Catalog(Error::new(ErrorKind::TypeRename(
2905                        current_full_name.to_string(),
2906                    ))));
2907                }
2908
2909                if entry.id().is_system() {
2910                    let name = state
2911                        .resolve_full_name(entry.name(), session.map(|session| session.conn_id()));
2912                    return Err(AdapterError::Catalog(Error::new(ErrorKind::ReadOnlyItem(
2913                        name.to_string(),
2914                    ))));
2915                }
2916
2917                let mut to_full_name = current_full_name.clone();
2918                to_full_name.item.clone_from(&to_name);
2919
2920                let mut to_qualified_name = entry.name().clone();
2921                to_qualified_name.item.clone_from(&to_name);
2922
2923                let details = EventDetails::RenameItemV1(mz_audit_log::RenameItemV1 {
2924                    id: id.to_string(),
2925                    old_name: Self::full_name_detail(&current_full_name),
2926                    new_name: Self::full_name_detail(&to_full_name),
2927                });
2928                if Self::should_audit_log_item(entry.item()) {
2929                    CatalogState::add_to_audit_log(
2930                        &state.system_configuration,
2931                        oracle_write_ts,
2932                        session,
2933                        tx,
2934                        audit_events,
2935                        EventType::Alter,
2936                        catalog_type_to_audit_object_type(entry.item().typ()),
2937                        details,
2938                    )?;
2939                }
2940
2941                // Rename item itself.
2942                let mut new_entry = entry.clone();
2943                new_entry.name.item.clone_from(&to_name);
2944                new_entry.item = entry.item().rename(to_name);
2945
2946                for id in entry.referenced_by() {
2947                    let dependent_item = state.get_entry(id);
2948                    let mut to_entry = dependent_item.clone();
2949                    to_entry.item = dependent_item
2950                        .item()
2951                        .rename_item_refs(current_full_name.clone(), to_full_name.item.clone())
2952                        .map_err(|e| {
2953                            Error::new(ErrorKind::from(AmbiguousRename {
2954                                depender: state
2955                                    .resolve_full_name(
2956                                        dependent_item.name(),
2957                                        dependent_item.conn_id(),
2958                                    )
2959                                    .to_string(),
2960                                dependee: state
2961                                    .resolve_full_name(entry.name(), entry.conn_id())
2962                                    .to_string(),
2963                                message: e,
2964                            }))
2965                        })?;
2966
2967                    tx.update_item(*id, state.durable_item(to_entry)?)?;
2968                    updates.push(*id);
2969                }
2970                tx.update_item(id, state.durable_item(new_entry)?)?;
2971
2972                updates.push(id);
2973                for id in updates {
2974                    Self::log_update(state, &id);
2975                }
2976            }
2977            Op::RenameSchema {
2978                database_spec,
2979                schema_spec,
2980                new_name,
2981                check_reserved_names,
2982            } => {
2983                if check_reserved_names && is_reserved_name(&new_name) {
2984                    return Err(AdapterError::Catalog(Error::new(
2985                        ErrorKind::ReservedSchemaName(new_name),
2986                    )));
2987                }
2988
2989                let conn_id = session
2990                    .map(|session| session.conn_id())
2991                    .unwrap_or(&SYSTEM_CONN_ID);
2992
2993                let schema = state.get_schema(&database_spec, &schema_spec, conn_id);
2994                let cur_name = schema.name().schema.clone();
2995
2996                let ResolvedDatabaseSpecifier::Id(database_id) = database_spec else {
2997                    return Err(AdapterError::Catalog(Error::new(
2998                        ErrorKind::AmbientSchemaRename(cur_name),
2999                    )));
3000                };
3001                let database = state.get_database(&database_id);
3002                let database_name = &database.name;
3003
3004                let mut updates: Vec<CatalogItemId> = Vec::new();
3005                let mut items_to_update = BTreeMap::new();
3006                // An item can be reached more than once: once as a member of
3007                // the schema and again for each object in the schema it
3008                // depends on. Skip items that were already rewritten.
3009                let mut seen: BTreeSet<CatalogItemId> = BTreeSet::new();
3010
3011                let mut update_item = |id: &CatalogItemId| {
3012                    if !seen.insert(*id) {
3013                        return Ok(());
3014                    }
3015
3016                    let entry = state.get_entry(id);
3017
3018                    // Update our item.
3019                    let mut new_entry = entry.clone();
3020                    new_entry.item = entry
3021                        .item
3022                        .rename_schema_refs(database_name, &cur_name, &new_name)
3023                        .map_err(|(s, _i)| {
3024                            Error::new(ErrorKind::from(AmbiguousRename {
3025                                depender: state
3026                                    .resolve_full_name(entry.name(), entry.conn_id())
3027                                    .to_string(),
3028                                dependee: format!("{database_name}.{cur_name}"),
3029                                message: format!("ambiguous reference to schema named {s}"),
3030                            }))
3031                        })?;
3032
3033                    // Queue updates for Catalog storage and Builtin Tables.
3034                    items_to_update.insert(*id, state.durable_item(new_entry)?);
3035                    updates.push(*id);
3036
3037                    Ok::<_, AdapterError>(())
3038                };
3039
3040                // Update all of the items in the schema. A schema holds items,
3041                // types, and functions in separate maps, and any of them may be
3042                // referenced by another object's create_sql via a schema-qualified
3043                // name, so all three must be rewritten.
3044                for (_name, item_id) in schema
3045                    .items
3046                    .iter()
3047                    .chain(schema.types.iter())
3048                    .chain(schema.functions.iter())
3049                {
3050                    // Update the item itself.
3051                    update_item(item_id)?;
3052
3053                    // Update everything that depends on this item.
3054                    for id in state.get_entry(item_id).referenced_by() {
3055                        update_item(id)?;
3056                    }
3057                }
3058                // Note: When updating the transaction it's very important that we update the
3059                // items as a whole group, otherwise we exhibit quadratic behavior.
3060                tx.update_items(items_to_update)?;
3061
3062                // Renaming temporary schemas is not supported.
3063                let SchemaSpecifier::Id(schema_id) = *schema.id() else {
3064                    let schema_name = schema.name().schema.clone();
3065                    return Err(AdapterError::Catalog(crate::catalog::Error::new(
3066                        crate::catalog::ErrorKind::ReadOnlySystemSchema(schema_name),
3067                    )));
3068                };
3069
3070                // Add an entry to the audit log.
3071                let database_name = database_spec
3072                    .id()
3073                    .map(|id| state.get_database(&id).name.clone());
3074                let details = EventDetails::RenameSchemaV1(mz_audit_log::RenameSchemaV1 {
3075                    id: schema_id.to_string(),
3076                    old_name: schema.name().schema.clone(),
3077                    new_name: new_name.clone(),
3078                    database_name,
3079                });
3080                CatalogState::add_to_audit_log(
3081                    &state.system_configuration,
3082                    oracle_write_ts,
3083                    session,
3084                    tx,
3085                    audit_events,
3086                    EventType::Alter,
3087                    mz_audit_log::ObjectType::Schema,
3088                    details,
3089                )?;
3090
3091                // Update the schema itself.
3092                let mut new_schema = schema.clone();
3093                new_schema.name.schema.clone_from(&new_name);
3094                tx.update_schema(schema_id, new_schema.into())?;
3095
3096                for id in updates {
3097                    Self::log_update(state, &id);
3098                }
3099            }
3100            Op::UpdateOwner { id, new_owner } => {
3101                let conn_id = session
3102                    .map(|session| session.conn_id())
3103                    .unwrap_or(&SYSTEM_CONN_ID);
3104                let old_owner = state
3105                    .get_owner_id(&id, conn_id)
3106                    .expect("cannot update the owner of an object without an owner");
3107                match &id {
3108                    ObjectId::Cluster(id) => {
3109                        let mut cluster = state.get_cluster(*id).clone();
3110                        if id.is_system() {
3111                            return Err(AdapterError::Catalog(Error::new(
3112                                ErrorKind::ReadOnlyCluster(cluster.name),
3113                            )));
3114                        }
3115                        Self::update_privilege_owners(
3116                            &mut cluster.privileges,
3117                            cluster.owner_id,
3118                            new_owner,
3119                        );
3120                        cluster.owner_id = new_owner;
3121                        tx.update_cluster(*id, cluster.into())?;
3122                    }
3123                    ObjectId::ClusterReplica((cluster_id, replica_id)) => {
3124                        let cluster = state.get_cluster(*cluster_id);
3125                        let mut replica = cluster
3126                            .replica(*replica_id)
3127                            .expect("catalog out of sync")
3128                            .clone();
3129                        if replica_id.is_system() {
3130                            return Err(AdapterError::Catalog(Error::new(
3131                                ErrorKind::ReadOnlyClusterReplica(replica.name),
3132                            )));
3133                        }
3134                        replica.owner_id = new_owner;
3135                        tx.update_cluster_replica(*replica_id, replica.into())?;
3136                    }
3137                    ObjectId::Database(id) => {
3138                        let mut database = state.get_database(id).clone();
3139                        if id.is_system() {
3140                            return Err(AdapterError::Catalog(Error::new(
3141                                ErrorKind::ReadOnlyDatabase(database.name),
3142                            )));
3143                        }
3144                        Self::update_privilege_owners(
3145                            &mut database.privileges,
3146                            database.owner_id,
3147                            new_owner,
3148                        );
3149                        database.owner_id = new_owner;
3150                        tx.update_database(*id, database.clone().into())?;
3151                    }
3152                    ObjectId::Schema((database_spec, schema_spec)) => {
3153                        let schema_id: SchemaId = schema_spec.clone().into();
3154                        let mut schema = state
3155                            .get_schema(database_spec, schema_spec, conn_id)
3156                            .clone();
3157                        if schema_id.is_system() {
3158                            let name = schema.name();
3159                            let full_name = state.resolve_full_schema_name(name);
3160                            return Err(AdapterError::Catalog(Error::new(
3161                                ErrorKind::ReadOnlySystemSchema(full_name.to_string()),
3162                            )));
3163                        }
3164                        Self::update_privilege_owners(
3165                            &mut schema.privileges,
3166                            schema.owner_id,
3167                            new_owner,
3168                        );
3169                        schema.owner_id = new_owner;
3170                        tx.update_schema(schema_id, schema.into())?;
3171                    }
3172                    ObjectId::Item(id) => {
3173                        let entry = state.get_entry(id);
3174                        let mut new_entry = entry.clone();
3175                        if id.is_system() {
3176                            let full_name = state.resolve_full_name(
3177                                new_entry.name(),
3178                                session.map(|session| session.conn_id()),
3179                            );
3180                            return Err(AdapterError::Catalog(Error::new(
3181                                ErrorKind::ReadOnlyItem(full_name.to_string()),
3182                            )));
3183                        }
3184                        Self::update_privilege_owners(
3185                            &mut new_entry.privileges,
3186                            new_entry.owner_id,
3187                            new_owner,
3188                        );
3189                        new_entry.owner_id = new_owner;
3190                        tx.update_item(*id, state.durable_item(new_entry)?)?;
3191                    }
3192                    ObjectId::NetworkPolicy(id) => {
3193                        let mut policy = state.get_network_policy(id).clone();
3194                        if id.is_system() {
3195                            return Err(AdapterError::Catalog(Error::new(
3196                                ErrorKind::ReadOnlyNetworkPolicy(policy.name),
3197                            )));
3198                        }
3199                        Self::update_privilege_owners(
3200                            &mut policy.privileges,
3201                            policy.owner_id,
3202                            new_owner,
3203                        );
3204                        policy.owner_id = new_owner;
3205                        tx.update_network_policy(*id, policy.into())?;
3206                    }
3207                    ObjectId::QueryPolicy(id) => {
3208                        let mut policy = state.get_query_policy(id).clone();
3209                        if id.is_system() {
3210                            return Err(AdapterError::Catalog(Error::new(
3211                                ErrorKind::ReadOnlyQueryPolicy(policy.name),
3212                            )));
3213                        }
3214                        Self::update_privilege_owners(
3215                            &mut policy.privileges,
3216                            policy.owner_id,
3217                            new_owner,
3218                        );
3219                        policy.owner_id = new_owner;
3220                        tx.update_query_policy(policy.into())?;
3221                    }
3222                    ObjectId::Role(_) => unreachable!("roles have no owner"),
3223                }
3224                let object_type = state.get_object_type(&id);
3225                CatalogState::add_to_audit_log(
3226                    &state.system_configuration,
3227                    oracle_write_ts,
3228                    session,
3229                    tx,
3230                    audit_events,
3231                    EventType::Alter,
3232                    object_type_to_audit_object_type(object_type),
3233                    EventDetails::UpdateOwnerV1(mz_audit_log::UpdateOwnerV1 {
3234                        object_id: id.to_string(),
3235                        old_owner_id: old_owner.to_string(),
3236                        new_owner_id: new_owner.to_string(),
3237                    }),
3238                )?;
3239            }
3240            Op::UpdateClusterConfig {
3241                id,
3242                name,
3243                mut config,
3244                reconfiguration_audit,
3245                mut burst_audit,
3246            } => {
3247                let mut cluster = state.get_cluster(id).clone();
3248                // A write that invalidates the in-flight burst (policy removed
3249                // or re-sized, cluster turned off) retires the record here, in
3250                // the same transaction. Retiring at this chokepoint rather
3251                // than in each sequencer path means no writer can forget, so a
3252                // committed config never carries a record it does not warrant.
3253                // Writes that declare a burst intent manage the record
3254                // themselves.
3255                if burst_audit.is_none() {
3256                    if let ClusterVariant::Managed(managed) = &mut config.variant {
3257                        if managed.has_unwarranted_burst_record() {
3258                            managed.burst = None;
3259                            burst_audit = Some(BurstAudit::Finished {
3260                                cause: BurstFinishCause::NoLongerWarranted,
3261                            });
3262                        }
3263                    }
3264                }
3265                // Writes that declare no reconfiguration intent must not move
3266                // the reconfiguration lifecycle, or the audit log would
3267                // silently lose the transition. Writer bug, fails the
3268                // transaction.
3269                if reconfiguration_audit.is_none()
3270                    && Self::reconfiguration_lifecycle_moved(&cluster.config, &config)
3271                {
3272                    return Err(AdapterError::Internal(format!(
3273                        "cluster {name} reconfiguration record moved without a declared \
3274                         audit intent"
3275                    )));
3276                }
3277                // The same contract for the burst lifecycle: a record appearing
3278                // or disappearing without a declared intent would silently lose
3279                // the started/finished audit transition.
3280                if burst_audit.is_none() && Self::burst_lifecycle_moved(&cluster.config, &config) {
3281                    return Err(AdapterError::Internal(format!(
3282                        "cluster {name} burst record moved without a declared audit intent"
3283                    )));
3284                }
3285                let reconfiguration_event = reconfiguration_audit
3286                    .map(|audit| Self::reconfiguration_audit_details(&config, id, &name, audit))
3287                    .transpose()?;
3288                let burst_event = burst_audit
3289                    .map(|audit| {
3290                        Self::burst_audit_details(&cluster.config, &config, id, &name, audit)
3291                    })
3292                    .transpose()?;
3293                cluster.config = config;
3294                tx.update_cluster(id, cluster.into())?;
3295                info!("update cluster {}", name);
3296
3297                CatalogState::add_to_audit_log(
3298                    &state.system_configuration,
3299                    oracle_write_ts,
3300                    session,
3301                    tx,
3302                    audit_events,
3303                    EventType::Alter,
3304                    ObjectType::Cluster,
3305                    EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
3306                        id: id.to_string(),
3307                        name,
3308                    }),
3309                )?;
3310
3311                if let Some(details) = reconfiguration_event {
3312                    CatalogState::add_to_audit_log(
3313                        &state.system_configuration,
3314                        oracle_write_ts,
3315                        session,
3316                        tx,
3317                        audit_events,
3318                        EventType::Alter,
3319                        ObjectType::Cluster,
3320                        EventDetails::AlterClusterReconfigurationV1(details),
3321                    )?;
3322                }
3323
3324                if let Some(details) = burst_event {
3325                    CatalogState::add_to_audit_log(
3326                        &state.system_configuration,
3327                        oracle_write_ts,
3328                        session,
3329                        tx,
3330                        audit_events,
3331                        EventType::Alter,
3332                        ObjectType::Cluster,
3333                        EventDetails::ClusterHydrationBurstV1(details),
3334                    )?;
3335                }
3336            }
3337            Op::UpdateItem { id, name, to_item } => {
3338                // A non-temporary item must not depend on a temporary one.
3339                // Temporary objects are session-scoped and disappear with
3340                // their session, so a longer-lived item referencing one would
3341                // be left with a dangling reference. `Op::CreateItem` enforces
3342                // it; mirror it here so ALTER paths (e.g. ALTER SINK ... SET
3343                // FROM) cannot repoint a persistent item at a temporary one.
3344                if !to_item.is_temporary() {
3345                    if let Some(temp_id) =
3346                        to_item
3347                            .uses()
3348                            .iter()
3349                            .find(|id| match state.try_get_entry(*id) {
3350                                Some(entry) => entry.item().is_temporary(),
3351                                None => temporary_ids.contains(id),
3352                            })
3353                    {
3354                        let temp_item = state.get_entry(temp_id);
3355                        return Err(AdapterError::Catalog(Error::new(
3356                            ErrorKind::InvalidTemporaryDependency(temp_item.name().item.clone()),
3357                        )));
3358                    }
3359                }
3360
3361                let mut entry = state.get_entry(&id).clone();
3362                entry.name = name.clone();
3363                entry.item = to_item.clone();
3364                tx.update_item(id, state.durable_item(entry)?)?;
3365
3366                if Self::should_audit_log_item(&to_item) {
3367                    let mut full_name = Self::full_name_detail(
3368                        &state.resolve_full_name(&name, session.map(|session| session.conn_id())),
3369                    );
3370                    full_name.item = name.item;
3371
3372                    CatalogState::add_to_audit_log(
3373                        &state.system_configuration,
3374                        oracle_write_ts,
3375                        session,
3376                        tx,
3377                        audit_events,
3378                        EventType::Alter,
3379                        catalog_type_to_audit_object_type(to_item.typ()),
3380                        EventDetails::UpdateItemV1(mz_audit_log::UpdateItemV1 {
3381                            id: id.to_string(),
3382                            name: full_name,
3383                        }),
3384                    )?;
3385                }
3386
3387                Self::log_update(state, &id);
3388            }
3389            Op::UpdateSystemConfiguration { name, value } => {
3390                let parsed_value = state.parse_system_configuration(&name, value.borrow())?;
3391                tx.upsert_system_config(&name, parsed_value.clone())?;
3392                // This mirrors some "system vars" into the catalog storage
3393                // "config" collection so that we can toggle the flag with
3394                // Launch Darkly, but use it in boot before Launch Darkly is
3395                // available.
3396                if name == WITH_0DT_DEPLOYMENT_MAX_WAIT.name() {
3397                    let with_0dt_deployment_max_wait =
3398                        Duration::parse(VarInput::Flat(&parsed_value))
3399                            .expect("parsing succeeded above");
3400                    tx.set_0dt_deployment_max_wait(with_0dt_deployment_max_wait)?;
3401                } else if name == WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name() {
3402                    let with_0dt_deployment_ddl_check_interval =
3403                        Duration::parse(VarInput::Flat(&parsed_value))
3404                            .expect("parsing succeeded above");
3405                    tx.set_0dt_deployment_ddl_check_interval(
3406                        with_0dt_deployment_ddl_check_interval,
3407                    )?;
3408                } else if name == ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.name() {
3409                    let panic_after_timeout =
3410                        strconv::parse_bool(&parsed_value).expect("parsing succeeded above");
3411                    tx.set_enable_0dt_deployment_panic_after_timeout(panic_after_timeout)?;
3412                }
3413
3414                CatalogState::add_to_audit_log(
3415                    &state.system_configuration,
3416                    oracle_write_ts,
3417                    session,
3418                    tx,
3419                    audit_events,
3420                    EventType::Alter,
3421                    ObjectType::System,
3422                    EventDetails::SetV1(mz_audit_log::SetV1 {
3423                        name,
3424                        value: Some(value.borrow().to_vec().join(", ")),
3425                    }),
3426                )?;
3427            }
3428            Op::ResetSystemConfiguration { name } => {
3429                tx.remove_system_config(&name);
3430                // This mirrors some "system vars" into the catalog storage
3431                // "config" collection so that we can toggle the flag with
3432                // Launch Darkly, but use it in boot before Launch Darkly is
3433                // available.
3434                if name == WITH_0DT_DEPLOYMENT_MAX_WAIT.name() {
3435                    tx.reset_0dt_deployment_max_wait()?;
3436                } else if name == WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name() {
3437                    tx.reset_0dt_deployment_ddl_check_interval()?;
3438                } else if name == ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.name() {
3439                    tx.reset_enable_0dt_deployment_panic_after_timeout()?;
3440                }
3441
3442                CatalogState::add_to_audit_log(
3443                    &state.system_configuration,
3444                    oracle_write_ts,
3445                    session,
3446                    tx,
3447                    audit_events,
3448                    EventType::Alter,
3449                    ObjectType::System,
3450                    EventDetails::SetV1(mz_audit_log::SetV1 { name, value: None }),
3451                )?;
3452            }
3453            Op::ResetAllSystemConfiguration => {
3454                tx.clear_system_configs();
3455                tx.reset_0dt_deployment_max_wait()?;
3456                tx.reset_0dt_deployment_ddl_check_interval()?;
3457                tx.reset_enable_0dt_deployment_panic_after_timeout()?;
3458
3459                CatalogState::add_to_audit_log(
3460                    &state.system_configuration,
3461                    oracle_write_ts,
3462                    session,
3463                    tx,
3464                    audit_events,
3465                    EventType::Alter,
3466                    ObjectType::System,
3467                    EventDetails::ResetAllV1,
3468                )?;
3469            }
3470            Op::UpdateScopedSystemParameters {
3471                scoped,
3472                prune_scope,
3473            } => {
3474                // Diff `scoped` against the durable cache and persist only the
3475                // delta: upsert changed/added entries, then remove entries the
3476                // update no longer serves. A removal for a still-live object is
3477                // bounded by `prune_scope` so this update does not delete a row
3478                // for an object it was not evaluated for (e.g. one created after
3479                // the update's snapshot, whose override rode its own create
3480                // transaction). Rows whose owning object is no longer live are
3481                // always pruned regardless of `prune_scope`, because nothing else
3482                // garbage collects them and ids are never reused, so this lazily
3483                // reclaims orphans left by dropped objects.
3484                let live_clusters: BTreeSet<ClusterId> =
3485                    tx.get_clusters().map(|cluster| cluster.id).collect();
3486                let live_replicas: BTreeSet<ReplicaId> = tx
3487                    .get_cluster_replicas()
3488                    .map(|replica| replica.replica_id)
3489                    .collect();
3490
3491                // Cluster-coherent scope.
3492                let existing_cluster: BTreeMap<(ClusterId, String), String> = tx
3493                    .get_cluster_system_configurations()
3494                    .map(|c| ((c.cluster_id, c.name), c.value))
3495                    .collect();
3496                let mut desired_cluster: BTreeSet<(ClusterId, String)> = BTreeSet::new();
3497                for (cluster_id, values) in &scoped.cluster {
3498                    if !live_clusters.contains(cluster_id) {
3499                        continue;
3500                    }
3501                    for (name, value) in values {
3502                        desired_cluster.insert((*cluster_id, name.clone()));
3503                        if existing_cluster.get(&(*cluster_id, name.clone())) != Some(value) {
3504                            tx.upsert_cluster_system_config(*cluster_id, name, value.clone())?;
3505                        }
3506                    }
3507                }
3508                for (cluster_id, name) in existing_cluster.into_keys() {
3509                    if (!live_clusters.contains(&cluster_id)
3510                        || prune_scope.clusters.contains(&cluster_id))
3511                        && !desired_cluster.contains(&(cluster_id, name.clone()))
3512                    {
3513                        tx.remove_cluster_system_config(cluster_id, &name);
3514                    }
3515                }
3516
3517                // Replica-local scope.
3518                let existing_replica: BTreeMap<(ReplicaId, String), String> = tx
3519                    .get_replica_system_configurations()
3520                    .map(|r| ((r.replica_id, r.name), r.value))
3521                    .collect();
3522                let mut desired_replica: BTreeSet<(ReplicaId, String)> = BTreeSet::new();
3523                for (replica_id, values) in &scoped.replica {
3524                    if !live_replicas.contains(replica_id) {
3525                        continue;
3526                    }
3527                    for (name, value) in values {
3528                        desired_replica.insert((*replica_id, name.clone()));
3529                        if existing_replica.get(&(*replica_id, name.clone())) != Some(value) {
3530                            tx.upsert_replica_system_config(*replica_id, name, value.clone())?;
3531                        }
3532                    }
3533                }
3534                for (replica_id, name) in existing_replica.into_keys() {
3535                    if (!live_replicas.contains(&replica_id)
3536                        || prune_scope.replicas.contains(&replica_id))
3537                        && !desired_replica.contains(&(replica_id, name.clone()))
3538                    {
3539                        tx.remove_replica_system_config(replica_id, &name);
3540                    }
3541                }
3542            }
3543            Op::InjectAuditEvents { events } => {
3544                for event in events {
3545                    let id = tx.allocate_audit_log_id()?;
3546                    let ev = VersionedEvent::new(
3547                        id,
3548                        event.event_type,
3549                        event.object_type,
3550                        event.details,
3551                        event.user,
3552                        oracle_write_ts.into(),
3553                    );
3554                    audit_events.push(ev.clone());
3555                    tx.insert_audit_log_event(ev);
3556                }
3557            }
3558        };
3559        Ok(())
3560    }
3561
3562    fn log_update(state: &CatalogState, id: &CatalogItemId) {
3563        let entry = state.get_entry(id);
3564        info!(
3565            "update {} {} ({})",
3566            entry.item_type(),
3567            state.resolve_full_name(entry.name(), entry.conn_id()),
3568            id
3569        );
3570    }
3571
3572    /// Update privileges to reflect the new owner. Based off of PostgreSQL's
3573    /// implementation:
3574    /// <https://github.com/postgres/postgres/blob/43a33ef54e503b61f269d088f2623ba3b9484ad7/src/backend/utils/adt/acl.c#L1078-L1177>
3575    fn update_privilege_owners(
3576        privileges: &mut PrivilegeMap,
3577        old_owner: RoleId,
3578        new_owner: RoleId,
3579    ) {
3580        // TODO(jkosh44) Would be nice not to clone every privilege.
3581        let mut flat_privileges: Vec<_> = privileges.all_values_owned().collect();
3582
3583        let mut new_present = false;
3584        for privilege in flat_privileges.iter_mut() {
3585            // Old owner's granted privilege are updated to be granted by the new
3586            // owner.
3587            if privilege.grantor == old_owner {
3588                privilege.grantor = new_owner;
3589            } else if privilege.grantor == new_owner {
3590                new_present = true;
3591            }
3592            // Old owner's privileges is given to the new owner.
3593            if privilege.grantee == old_owner {
3594                privilege.grantee = new_owner;
3595            } else if privilege.grantee == new_owner {
3596                new_present = true;
3597            }
3598        }
3599
3600        // If the old privilege list contained references to the new owner, we may
3601        // have created duplicate entries. Here we try and consolidate them. This
3602        // is inspired by PostgreSQL's algorithm but not identical.
3603        if new_present {
3604            // Group privileges by (grantee, grantor).
3605            let privilege_map: BTreeMap<_, Vec<_>> =
3606                flat_privileges
3607                    .into_iter()
3608                    .fold(BTreeMap::new(), |mut accum, privilege| {
3609                        accum
3610                            .entry((privilege.grantee, privilege.grantor))
3611                            .or_default()
3612                            .push(privilege);
3613                        accum
3614                    });
3615
3616            // Consolidate and update all privileges.
3617            flat_privileges = privilege_map
3618                .into_iter()
3619                .map(|((grantee, grantor), values)|
3620                    // Combine the acl_mode of all mz_aclitems with the same grantee and grantor.
3621                    values.into_iter().fold(
3622                        MzAclItem::empty(grantee, grantor),
3623                        |mut accum, mz_aclitem| {
3624                            accum.acl_mode =
3625                                accum.acl_mode.union(mz_aclitem.acl_mode);
3626                            accum
3627                        },
3628                    ))
3629                .collect();
3630        }
3631
3632        *privileges = PrivilegeMap::from_mz_acl_items(flat_privileges);
3633    }
3634}
3635
3636/// Resolves the session UUID that durably owns a temporary item being
3637/// created. The durable owner is the session that created the item.
3638///
3639/// The connection -> session mapping is registered lazily in
3640/// `catalog_transact_inner`, so we defensively verify that the registered
3641/// mapping matches the creating session.
3642fn temporary_item_owner_session(
3643    state: &CatalogState,
3644    session: Option<&ConnMeta>,
3645    item: &CatalogItem,
3646    item_name: &str,
3647) -> Result<Uuid, AdapterError> {
3648    let session = session.ok_or_else(|| {
3649        AdapterError::Internal("temporary items must have an owner session".to_string())
3650    })?;
3651    let owner_session = session.uuid();
3652    soft_assert_or_log!(
3653        Some(session.conn_id()) == item.conn_id(),
3654        "temporary item connection must match the creating session"
3655    );
3656    if state.temporary_namespaces.uuid_for_conn(session.conn_id()) != Some(owner_session) {
3657        return Err(AdapterError::Internal(format!(
3658            "connection {} has no temporary namespace while creating temporary item {}",
3659            session.conn_id(),
3660            item_name,
3661        )));
3662    }
3663    Ok(owner_session)
3664}
3665
3666/// Prepare the given transaction for replacing a catalog item with a new version.
3667///
3668/// The new version gets a new `CatalogItemId`, which requires rewriting the `create_sql` of all
3669/// dependent objects to refer to that new ID (at a previous version).
3670///
3671/// Note that here is where we break the assumption that the `CatalogItemId` is a stable identifier
3672/// for catalog items. We currently think that there are no use cases that require this assumption,
3673/// but no way to know for sure.
3674fn tx_replace_item(
3675    tx: &mut Transaction<'_>,
3676    state: &CatalogState,
3677    id: CatalogItemId,
3678    new_entry: CatalogEntry,
3679) -> Result<(), AdapterError> {
3680    let new_id = new_entry.id;
3681
3682    // Rewrite dependent objects to point to the new ID.
3683    for use_id in new_entry.referenced_by() {
3684        let dependent = state.get_entry(use_id);
3685
3686        // The dependent might be dropped in the same tx, so check.
3687        if tx.get_item(use_id).is_none() {
3688            continue;
3689        }
3690
3691        let mut dependent = dependent.clone();
3692        dependent.item = dependent.item.replace_item_refs(id, new_id);
3693        tx.update_item(*use_id, state.durable_item(dependent)?)?;
3694    }
3695
3696    // Move comments to the new ID.
3697    let old_comment_id = state.get_comment_id(ObjectId::Item(id));
3698    let new_comment_id = new_entry.comment_object_id();
3699    if let Some(comments) = state.comments.get_object_comments(old_comment_id) {
3700        tx.drop_comments(&[old_comment_id].into())?;
3701        for (sub, comment) in comments {
3702            tx.update_comment(new_comment_id, *sub, Some(comment.clone()))?;
3703        }
3704    }
3705
3706    let mz_catalog::durable::Item {
3707        id: _,
3708        oid,
3709        global_id,
3710        schema_id,
3711        name,
3712        create_sql,
3713        owner_id,
3714        privileges,
3715        extra_versions,
3716        ephemeral_owner_session,
3717    } = state.durable_item(new_entry)?;
3718
3719    tx.remove_item(id)?;
3720    tx.insert_item(
3721        new_id,
3722        oid,
3723        global_id,
3724        schema_id,
3725        &name,
3726        create_sql,
3727        owner_id,
3728        privileges,
3729        extra_versions,
3730        ephemeral_owner_session,
3731    )?;
3732
3733    Ok(())
3734}
3735
3736/// Generate audit events for a replacement apply operation.
3737fn apply_replacement_audit_events(
3738    state: &CatalogState,
3739    target: &CatalogEntry,
3740    replacement: &CatalogEntry,
3741) -> Vec<(EventType, EventDetails)> {
3742    let mut events = Vec::new();
3743
3744    let target_name = state.resolve_full_name(target.name(), target.conn_id());
3745    let target_id_name = IdFullNameV1 {
3746        id: target.id().to_string(),
3747        name: Catalog::full_name_detail(&target_name),
3748    };
3749    let replacement_name = state.resolve_full_name(replacement.name(), replacement.conn_id());
3750    let replacement_id_name = IdFullNameV1 {
3751        id: replacement.id().to_string(),
3752        name: Catalog::full_name_detail(&replacement_name),
3753    };
3754
3755    if Catalog::should_audit_log_item(&replacement.item) {
3756        events.push((
3757            EventType::Drop,
3758            EventDetails::IdFullNameV1(replacement_id_name.clone()),
3759        ));
3760    }
3761
3762    if Catalog::should_audit_log_item(&target.item) {
3763        events.push((
3764            EventType::Alter,
3765            EventDetails::AlterApplyReplacementV1(mz_audit_log::AlterApplyReplacementV1 {
3766                target: target_id_name.clone(),
3767                replacement: replacement_id_name,
3768            }),
3769        ));
3770
3771        if let Some(old_cluster_id) = target.cluster_id()
3772            && let Some(new_cluster_id) = replacement.cluster_id()
3773            && old_cluster_id != new_cluster_id
3774        {
3775            // When the replacement is applied, the target takes on the ID of the replacement, so
3776            // we should use that ID for subsequent events.
3777            events.push((
3778                EventType::Alter,
3779                EventDetails::AlterSetClusterV1(mz_audit_log::AlterSetClusterV1 {
3780                    id: replacement.id().to_string(),
3781                    name: target_id_name.name,
3782                    old_cluster_id: old_cluster_id.to_string(),
3783                    new_cluster_id: new_cluster_id.to_string(),
3784                }),
3785            ));
3786        }
3787    }
3788
3789    events
3790}
3791
3792/// All of the objects that need to be removed in response to an [`Op::DropObjects`].
3793///
3794/// Note: Previously we used to omit a single `Op::DropObject` for every object
3795/// we needed to drop. But removing a batch of objects from a durable Catalog
3796/// Transaction is O(n) where `n` is the number of objects that exist in the
3797/// Catalog. This resulted in an unacceptable `O(m * n)` performance for a
3798/// `DROP ... CASCADE` statement.
3799#[derive(Debug, Default)]
3800pub(crate) struct ObjectsToDrop {
3801    pub comments: BTreeSet<CommentObjectId>,
3802    pub databases: BTreeSet<DatabaseId>,
3803    pub schemas: BTreeMap<SchemaSpecifier, ResolvedDatabaseSpecifier>,
3804    pub clusters: BTreeSet<ClusterId>,
3805    pub replicas: BTreeMap<ReplicaId, (ClusterId, ReplicaCreateDropReason)>,
3806    pub roles: BTreeSet<RoleId>,
3807    pub items: Vec<CatalogItemId>,
3808    pub network_policies: BTreeSet<NetworkPolicyId>,
3809    pub query_policies: BTreeSet<QueryPolicyId>,
3810}
3811
3812impl ObjectsToDrop {
3813    pub fn generate(
3814        drop_object_infos: impl IntoIterator<Item = DropObjectInfo>,
3815        state: &CatalogState,
3816        session: Option<&ConnMeta>,
3817    ) -> Result<Self, AdapterError> {
3818        let mut delta = ObjectsToDrop::default();
3819
3820        for drop_object_info in drop_object_infos {
3821            delta.add_item(drop_object_info, state, session)?;
3822        }
3823
3824        Ok(delta)
3825    }
3826
3827    fn add_item(
3828        &mut self,
3829        drop_object_info: DropObjectInfo,
3830        state: &CatalogState,
3831        session: Option<&ConnMeta>,
3832    ) -> Result<(), AdapterError> {
3833        self.comments
3834            .insert(state.get_comment_id(drop_object_info.to_object_id()));
3835
3836        match drop_object_info {
3837            DropObjectInfo::Database(database_id) => {
3838                let database = &state.database_by_id[&database_id];
3839                if database_id.is_system() {
3840                    return Err(AdapterError::Catalog(Error::new(
3841                        ErrorKind::ReadOnlyDatabase(database.name().to_string()),
3842                    )));
3843                }
3844
3845                self.databases.insert(database_id);
3846            }
3847            DropObjectInfo::Schema((database_spec, schema_spec)) => {
3848                let schema = state.get_schema(
3849                    &database_spec,
3850                    &schema_spec,
3851                    session
3852                        .map(|session| session.conn_id())
3853                        .unwrap_or(&SYSTEM_CONN_ID),
3854                );
3855                let schema_id: SchemaId = schema_spec.into();
3856                if schema_id.is_system() {
3857                    let name = schema.name();
3858                    let full_name = state.resolve_full_schema_name(name);
3859                    return Err(AdapterError::Catalog(Error::new(
3860                        ErrorKind::ReadOnlySystemSchema(full_name.to_string()),
3861                    )));
3862                }
3863
3864                self.schemas.insert(schema_spec, database_spec);
3865            }
3866            DropObjectInfo::Role(role_id) => {
3867                let name = state.get_role(&role_id).name().to_string();
3868                if role_id.is_system() || role_id.is_predefined() {
3869                    return Err(AdapterError::Catalog(Error::new(
3870                        ErrorKind::ReservedRoleName(name.clone()),
3871                    )));
3872                }
3873                state.ensure_not_reserved_role(&role_id)?;
3874
3875                self.roles.insert(role_id);
3876            }
3877            DropObjectInfo::Cluster(cluster_id) => {
3878                let cluster = state.get_cluster(cluster_id);
3879                let name = &cluster.name;
3880                if cluster_id.is_system() {
3881                    return Err(AdapterError::Catalog(Error::new(
3882                        ErrorKind::ReadOnlyCluster(name.clone()),
3883                    )));
3884                }
3885
3886                self.clusters.insert(cluster_id);
3887            }
3888            DropObjectInfo::ClusterReplica((cluster_id, replica_id, reason)) => {
3889                let cluster = state.get_cluster(cluster_id);
3890                let replica = cluster.replica(replica_id).expect("Must exist");
3891
3892                self.replicas
3893                    .insert(replica.replica_id, (cluster.id, reason));
3894
3895                // Implicitly drop materialized views that target this replica.
3896                // When the target replica is gone, no replica advances the
3897                // persist shard's upper frontier, causing reads to hang. Cascade
3898                // to anything depending on the implicitly-dropped MV so we don't
3899                // leave dangling references in the catalog.
3900                //
3901                // Plan-driven drops already include these dependents as their
3902                // own `DropObjectInfo::Item` entries (the plan stage expands
3903                // them via `cluster_replica_dependents`), so each one's comment
3904                // is recorded by the top-of-function `self.comments` insert.
3905                // This branch handles internal callers that build
3906                // `Op::DropObjects` directly with only the replica, so we expand
3907                // the dependents and record their comments ourselves.
3908                //
3909                // `seen` is seeded from the items already collected so that the
3910                // plan-driven path (where the dependents are processed before
3911                // the replica, in reverse-dependency order) does not re-add them
3912                // here.
3913                let mut seen: BTreeSet<ObjectId> =
3914                    self.items.iter().copied().map(ObjectId::Item).collect();
3915                for dep in state.cluster_replica_dependents(cluster_id, replica_id, &mut seen) {
3916                    if let ObjectId::Item(dep_id) = dep {
3917                        info!(
3918                            "implicitly dropping {} because target replica was dropped",
3919                            state.get_entry(&dep_id).name().item,
3920                        );
3921                        self.comments
3922                            .insert(state.get_comment_id(ObjectId::Item(dep_id)));
3923                        self.items.push(dep_id);
3924                    }
3925                }
3926            }
3927            DropObjectInfo::Item(item_id) => {
3928                let entry = state.get_entry(&item_id);
3929                if item_id.is_system() {
3930                    let name = entry.name();
3931                    let full_name =
3932                        state.resolve_full_name(name, session.map(|session| session.conn_id()));
3933                    return Err(AdapterError::Catalog(Error::new(ErrorKind::ReadOnlyItem(
3934                        full_name.to_string(),
3935                    ))));
3936                }
3937
3938                self.items.push(item_id);
3939            }
3940            DropObjectInfo::NetworkPolicy(network_policy_id) => {
3941                let policy = state.get_network_policy(&network_policy_id);
3942                let name = &policy.name;
3943                if network_policy_id.is_system() {
3944                    return Err(AdapterError::Catalog(Error::new(
3945                        ErrorKind::ReadOnlyNetworkPolicy(name.clone()),
3946                    )));
3947                }
3948
3949                self.network_policies.insert(network_policy_id);
3950            }
3951            DropObjectInfo::QueryPolicy(id) => {
3952                let policy = state.get_query_policy(&id);
3953                if id.is_system() {
3954                    return Err(AdapterError::Catalog(Error::new(
3955                        ErrorKind::ReadOnlyQueryPolicy(policy.name.clone()),
3956                    )));
3957                }
3958                self.query_policies.insert(id);
3959            }
3960        }
3961
3962        Ok(())
3963    }
3964}
3965
3966#[cfg(test)]
3967mod tests {
3968    use std::sync::{Arc, Mutex};
3969
3970    use mz_catalog::SYSTEM_CONN_ID;
3971    use mz_catalog::memory::objects::{CatalogItem, Table, TableDataSource};
3972    use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem, PrivilegeMap};
3973    use mz_repr::role_id::RoleId;
3974    use mz_repr::{RelationDesc, RelationVersion, VersionedRelationDesc};
3975    use mz_sql::DEFAULT_SCHEMA;
3976    use mz_sql::catalog::CatalogDatabase;
3977    use mz_sql::names::{
3978        ItemQualifiers, QualifiedItemName, ResolvedDatabaseSpecifier, ResolvedIds,
3979    };
3980    use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
3981    use mz_sql::session::vars::{MAX_CONNECTIONS, OwnedVarInput, SystemVars};
3982
3983    use crate::catalog::{Catalog, Op};
3984    use crate::session::DEFAULT_DATABASE_NAME;
3985
3986    #[mz_ore::test]
3987    fn test_reconfiguration_audit_details() {
3988        use std::time::Duration;
3989
3990        use mz_adapter_types::cluster_state::ReconfigurationAudit;
3991        use mz_audit_log::ReconfigurationLifecycleV1;
3992        use mz_catalog::memory::objects::{
3993            ClusterConfig, ClusterVariant, ClusterVariantManaged, ReconfigurationState,
3994            ReconfigurationStatus, ReconfigurationTarget,
3995        };
3996        use mz_controller::clusters::ReplicaLogging;
3997        use mz_controller_types::ClusterId;
3998        use mz_repr::Timestamp;
3999        use mz_repr::optimize::OptimizerFeatureOverrides;
4000
4001        let cluster_id = ClusterId::user(1).expect("valid id");
4002        let logging = ReplicaLogging {
4003            log_logging: false,
4004            interval: None,
4005        };
4006        let managed = |reconfiguration: Option<ReconfigurationState>| ClusterConfig {
4007            variant: ClusterVariant::Managed(ClusterVariantManaged {
4008                size: "small".into(),
4009                availability_zones: Vec::new(),
4010                logging: logging.clone(),
4011                arrangement_compression: false,
4012                replication_factor: 1,
4013                optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4014                schedule: Default::default(),
4015                auto_scaling_strategy: None,
4016                reconfiguration,
4017                burst: None,
4018            }),
4019            workload_class: None,
4020            query_policy: None,
4021        };
4022        let record = |status| ReconfigurationState {
4023            target: ReconfigurationTarget {
4024                size: "large".into(),
4025                replication_factor: 2,
4026                availability_zones: vec!["az1".into(), "az2".into()],
4027                logging: ReplicaLogging {
4028                    log_logging: true,
4029                    interval: Some(Duration::from_secs(5)),
4030                },
4031                arrangement_compression: false,
4032            },
4033            deadline: Timestamp::from(400u64),
4034            on_timeout: mz_sql::plan::OnTimeoutAction::Rollback,
4035            status,
4036        };
4037
4038        let details = Catalog::reconfiguration_audit_details(
4039            &managed(Some(record(ReconfigurationStatus::InProgress))),
4040            cluster_id,
4041            "c",
4042            ReconfigurationAudit::Started,
4043        )
4044        .expect("record supplies audit details");
4045        assert_eq!(details.cluster_id, cluster_id.to_string());
4046        assert_eq!(details.cluster_name, "c");
4047        assert_eq!(details.transition, ReconfigurationLifecycleV1::Started);
4048        assert_eq!(details.forced, None);
4049        assert_eq!(details.target_size, "large");
4050        assert_eq!(details.target_replication_factor, 2);
4051        assert_eq!(
4052            details.target_availability_zones,
4053            vec!["az1".to_string(), "az2".to_string()]
4054        );
4055        assert_eq!(details.target_logging.log_logging, true);
4056        assert_eq!(
4057            details.target_logging.interval,
4058            Some(Duration::from_secs(5))
4059        );
4060        assert_eq!(details.deadline, Some(400));
4061
4062        // The `forced` bit exists only on the intent. The durable status reads
4063        // `Finalized` for both a hydrated and a forced cut-over, and the event
4064        // preserves the distinction.
4065        let forced = Catalog::reconfiguration_audit_details(
4066            &managed(Some(record(ReconfigurationStatus::Finalized))),
4067            cluster_id,
4068            "c",
4069            ReconfigurationAudit::Finalized { forced: true },
4070        )
4071        .expect("a coherent finalize supplies audit details");
4072        assert_eq!(forced.transition, ReconfigurationLifecycleV1::Finalized);
4073        assert_eq!(forced.forced, Some(true));
4074
4075        // A declared transition that contradicts the written record's status is
4076        // a writer bug and must fail the transaction.
4077        let incoherent = Catalog::reconfiguration_audit_details(
4078            &managed(Some(record(ReconfigurationStatus::TimedOut))),
4079            cluster_id,
4080            "c",
4081            ReconfigurationAudit::ResourceExhausted,
4082        );
4083        assert!(incoherent.is_err());
4084
4085        let missing = Catalog::reconfiguration_audit_details(
4086            &managed(None),
4087            cluster_id,
4088            "c",
4089            ReconfigurationAudit::Started,
4090        );
4091        assert!(missing.is_err());
4092    }
4093
4094    #[mz_ore::test]
4095    fn test_reconfiguration_lifecycle_moved() {
4096        use std::time::Duration;
4097
4098        use mz_catalog::memory::objects::{
4099            ClusterConfig, ClusterVariant, ClusterVariantManaged, ReconfigurationState,
4100            ReconfigurationStatus, ReconfigurationTarget,
4101        };
4102        use mz_controller::clusters::ReplicaLogging;
4103        use mz_repr::Timestamp;
4104        use mz_repr::optimize::OptimizerFeatureOverrides;
4105
4106        let managed = |reconfiguration: Option<ReconfigurationState>| ClusterConfig {
4107            variant: ClusterVariant::Managed(ClusterVariantManaged {
4108                size: "small".into(),
4109                availability_zones: Vec::new(),
4110                logging: ReplicaLogging {
4111                    log_logging: false,
4112                    interval: None,
4113                },
4114                arrangement_compression: false,
4115                replication_factor: 1,
4116                optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4117                schedule: Default::default(),
4118                auto_scaling_strategy: None,
4119                reconfiguration,
4120                burst: None,
4121            }),
4122            workload_class: None,
4123            query_policy: None,
4124        };
4125        let unmanaged = ClusterConfig {
4126            variant: ClusterVariant::Unmanaged,
4127            workload_class: None,
4128            query_policy: None,
4129        };
4130        let record = |status| ReconfigurationState {
4131            target: ReconfigurationTarget {
4132                size: "large".into(),
4133                replication_factor: 2,
4134                availability_zones: Vec::new(),
4135                logging: ReplicaLogging {
4136                    log_logging: false,
4137                    interval: Some(Duration::from_secs(1)),
4138                },
4139                arrangement_compression: false,
4140            },
4141            deadline: Timestamp::from(400u64),
4142            on_timeout: mz_sql::plan::OnTimeoutAction::Rollback,
4143            status,
4144        };
4145
4146        // Lifecycle movements: these writes must declare an audit intent.
4147        // A fresh record appears.
4148        assert!(Catalog::reconfiguration_lifecycle_moved(
4149            &managed(None),
4150            &managed(Some(record(ReconfigurationStatus::InProgress))),
4151        ));
4152        // The status changes.
4153        assert!(Catalog::reconfiguration_lifecycle_moved(
4154            &managed(Some(record(ReconfigurationStatus::InProgress))),
4155            &managed(Some(record(ReconfigurationStatus::Finalized))),
4156        ));
4157        // An in-progress record is dropped, e.g. by converting the cluster to
4158        // unmanaged (which the sequencer refuses, and this guard backstops).
4159        assert!(Catalog::reconfiguration_lifecycle_moved(
4160            &managed(Some(record(ReconfigurationStatus::InProgress))),
4161            &unmanaged,
4162        ));
4163
4164        // Not movements: no record at all, a status-preserving copy (a write
4165        // that carries the record forward), and dropping a settled record.
4166        assert!(!Catalog::reconfiguration_lifecycle_moved(
4167            &managed(None),
4168            &managed(None),
4169        ));
4170        assert!(!Catalog::reconfiguration_lifecycle_moved(
4171            &managed(Some(record(ReconfigurationStatus::InProgress))),
4172            &managed(Some(record(ReconfigurationStatus::InProgress))),
4173        ));
4174        assert!(!Catalog::reconfiguration_lifecycle_moved(
4175            &managed(Some(record(ReconfigurationStatus::Cancelled))),
4176            &unmanaged,
4177        ));
4178    }
4179
4180    #[mz_ore::test]
4181    fn test_burst_lifecycle_moved() {
4182        use std::time::Duration;
4183
4184        use mz_catalog::memory::objects::{
4185            BurstState, ClusterConfig, ClusterVariant, ClusterVariantManaged,
4186        };
4187        use mz_controller::clusters::ReplicaLogging;
4188        use mz_repr::Timestamp;
4189        use mz_repr::optimize::OptimizerFeatureOverrides;
4190
4191        let managed = |burst: Option<BurstState>| ClusterConfig {
4192            variant: ClusterVariant::Managed(ClusterVariantManaged {
4193                size: "small".into(),
4194                availability_zones: Vec::new(),
4195                logging: ReplicaLogging {
4196                    log_logging: false,
4197                    interval: None,
4198                },
4199                arrangement_compression: false,
4200                replication_factor: 1,
4201                optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4202                schedule: Default::default(),
4203                auto_scaling_strategy: None,
4204                reconfiguration: None,
4205                burst,
4206            }),
4207            workload_class: None,
4208            query_policy: None,
4209        };
4210        let unmanaged = ClusterConfig {
4211            variant: ClusterVariant::Unmanaged,
4212            workload_class: None,
4213            query_policy: None,
4214        };
4215        let record = |steady_ready_at| BurstState {
4216            burst_size: "large".into(),
4217            linger_duration: Duration::from_secs(60),
4218            steady_ready_at,
4219        };
4220
4221        // Lifecycle movements: these writes must declare an audit intent.
4222        // A fresh record appears.
4223        assert!(Catalog::burst_lifecycle_moved(
4224            &managed(None),
4225            &managed(Some(record(None))),
4226        ));
4227        // The record is cleared.
4228        assert!(Catalog::burst_lifecycle_moved(
4229            &managed(Some(record(None))),
4230            &managed(None),
4231        ));
4232        // The record is dropped by converting the cluster to unmanaged (which
4233        // the sequencer refuses, and this guard backstops).
4234        assert!(Catalog::burst_lifecycle_moved(
4235            &managed(Some(record(None))),
4236            &unmanaged,
4237        ));
4238
4239        // Not movements: no record at all, and the bookkeeping rewrites (the
4240        // hydration stamp and its reset) that keep the record present.
4241        assert!(!Catalog::burst_lifecycle_moved(
4242            &managed(None),
4243            &managed(None)
4244        ));
4245        assert!(!Catalog::burst_lifecycle_moved(
4246            &managed(Some(record(None))),
4247            &managed(Some(record(Some(Timestamp::from(100u64))))),
4248        ));
4249        assert!(!Catalog::burst_lifecycle_moved(
4250            &managed(Some(record(Some(Timestamp::from(100u64))))),
4251            &managed(Some(record(None))),
4252        ));
4253    }
4254
4255    #[mz_ore::test]
4256    fn test_has_unwarranted_burst_record() {
4257        use std::time::Duration;
4258
4259        use mz_catalog::memory::objects::{BurstState, ClusterVariantManaged};
4260        use mz_controller::clusters::ReplicaLogging;
4261        use mz_repr::optimize::OptimizerFeatureOverrides;
4262        use mz_sql::plan::{AutoScalingStrategy, OnHydration};
4263
4264        let managed = |replication_factor: u32,
4265                       strategy: Option<AutoScalingStrategy>,
4266                       burst: Option<BurstState>| ClusterVariantManaged {
4267            size: "small".into(),
4268            availability_zones: Vec::new(),
4269            logging: ReplicaLogging {
4270                log_logging: false,
4271                interval: None,
4272            },
4273            arrangement_compression: false,
4274            replication_factor,
4275            optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4276            schedule: Default::default(),
4277            auto_scaling_strategy: strategy,
4278            reconfiguration: None,
4279            burst,
4280        };
4281        let policy = |hydration_size: &str| AutoScalingStrategy {
4282            on_hydration: Some(OnHydration {
4283                hydration_size: hydration_size.into(),
4284                linger_duration: None,
4285            }),
4286        };
4287        let record = || BurstState {
4288            burst_size: "large".into(),
4289            linger_duration: Duration::from_secs(60),
4290            steady_ready_at: None,
4291        };
4292
4293        // No record: nothing to retire, with or without a policy.
4294        assert!(!managed(1, None, None).has_unwarranted_burst_record());
4295        assert!(!managed(1, Some(policy("large")), None).has_unwarranted_burst_record());
4296
4297        // A record backed by a matching, active policy is warranted.
4298        assert!(!managed(1, Some(policy("large")), Some(record())).has_unwarranted_burst_record());
4299
4300        // Unwarranted: policy removed, policy re-sized, or cluster turned off.
4301        assert!(managed(1, None, Some(record())).has_unwarranted_burst_record());
4302        assert!(
4303            managed(
4304                1,
4305                Some(AutoScalingStrategy { on_hydration: None }),
4306                Some(record())
4307            )
4308            .has_unwarranted_burst_record()
4309        );
4310        assert!(managed(1, Some(policy("xlarge")), Some(record())).has_unwarranted_burst_record());
4311        assert!(managed(0, Some(policy("large")), Some(record())).has_unwarranted_burst_record());
4312    }
4313
4314    #[mz_ore::test]
4315    fn test_replica_create_drop_reason_into_audit_log() {
4316        use std::time::Duration;
4317
4318        use mz_audit_log::{CreateOrDropClusterReplicaReasonV1, SchedulingDecisionV1};
4319        use mz_cluster_controller::ctx::RefreshWindowDecision;
4320        use mz_repr::GlobalId;
4321
4322        use crate::catalog::ReplicaCreateDropReason;
4323
4324        // `OnRefresh` audits the `schedule` word and converts the controller's
4325        // window decision into the `scheduling_policies` detail blob: ids as
4326        // strings, the hydration-time estimate as an interval string, and the
4327        // decision hardcoded `on` (the controller produces a create, and so
4328        // this detail, only for an open window).
4329        let (reason, scheduling_policies) =
4330            ReplicaCreateDropReason::OnRefresh(RefreshWindowDecision {
4331                objects_needing_refresh: vec![GlobalId::User(1)],
4332                objects_needing_compaction: vec![GlobalId::User(2), GlobalId::User(3)],
4333                hydration_time_estimate: Duration::from_secs(995),
4334            })
4335            .into_audit_log();
4336        assert_eq!(reason, CreateOrDropClusterReplicaReasonV1::Schedule);
4337        let blob = scheduling_policies.expect("on-refresh create carries the detail");
4338        assert_eq!(blob.on_refresh.decision, SchedulingDecisionV1::On);
4339        assert_eq!(blob.on_refresh.objects_needing_refresh, vec!["u1"]);
4340        assert_eq!(blob.on_refresh.objects_needing_compaction, vec!["u2", "u3"]);
4341        assert_eq!(blob.on_refresh.hydration_time_estimate, "00:16:35");
4342
4343        // `Retired` is the uniform word for every controller drop, with no
4344        // blob.
4345        let (reason, scheduling_policies) = ReplicaCreateDropReason::Retired.into_audit_log();
4346        assert_eq!(reason, CreateOrDropClusterReplicaReasonV1::Retired);
4347        assert!(scheduling_policies.is_none());
4348    }
4349
4350    #[mz_ore::test]
4351    fn test_burst_audit_details() {
4352        use std::time::Duration;
4353
4354        use mz_adapter_types::cluster_state::{BurstAudit, BurstFinishCause};
4355        use mz_audit_log::{BurstFinishCauseV1, HydrationBurstLifecycleV1};
4356        use mz_catalog::memory::objects::{
4357            BurstState, ClusterConfig, ClusterVariant, ClusterVariantManaged,
4358        };
4359        use mz_controller::clusters::ReplicaLogging;
4360        use mz_controller_types::ClusterId;
4361        use mz_repr::optimize::OptimizerFeatureOverrides;
4362
4363        let cluster_id = ClusterId::user(1).expect("valid id");
4364        let managed = |burst: Option<BurstState>| ClusterConfig {
4365            variant: ClusterVariant::Managed(ClusterVariantManaged {
4366                size: "small".into(),
4367                availability_zones: Vec::new(),
4368                logging: ReplicaLogging {
4369                    log_logging: false,
4370                    interval: None,
4371                },
4372                arrangement_compression: false,
4373                replication_factor: 1,
4374                optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4375                schedule: Default::default(),
4376                auto_scaling_strategy: None,
4377                reconfiguration: None,
4378                burst,
4379            }),
4380            workload_class: None,
4381            query_policy: None,
4382        };
4383        let record = || BurstState {
4384            burst_size: "large".into(),
4385            linger_duration: Duration::from_secs(60),
4386            steady_ready_at: None,
4387        };
4388
4389        // A started intent reads the armed record from the new config.
4390        let started = Catalog::burst_audit_details(
4391            &managed(None),
4392            &managed(Some(record())),
4393            cluster_id,
4394            "c",
4395            BurstAudit::Started,
4396        )
4397        .expect("armed record supplies audit details");
4398        assert_eq!(started.transition, HydrationBurstLifecycleV1::Started);
4399        assert_eq!(started.finish_cause, None);
4400        assert_eq!(started.burst_size, "large");
4401
4402        // A finished intent reads the cleared record from the old config and
4403        // carries the writer-declared cause.
4404        let finished = Catalog::burst_audit_details(
4405            &managed(Some(record())),
4406            &managed(None),
4407            cluster_id,
4408            "c",
4409            BurstAudit::Finished {
4410                cause: BurstFinishCause::LingerElapsed,
4411            },
4412        )
4413        .expect("cleared record supplies audit details");
4414        assert_eq!(finished.transition, HydrationBurstLifecycleV1::Finished);
4415        assert_eq!(
4416            finished.finish_cause,
4417            Some(BurstFinishCauseV1::LingerElapsed)
4418        );
4419        assert_eq!(finished.burst_size, "large");
4420
4421        // An intent without a record on the corresponding side contradicts the
4422        // write and must fail the transaction.
4423        let incoherent = Catalog::burst_audit_details(
4424            &managed(None),
4425            &managed(None),
4426            cluster_id,
4427            "c",
4428            BurstAudit::Started,
4429        );
4430        assert!(incoherent.is_err());
4431    }
4432
4433    #[mz_ore::test]
4434    fn test_update_privilege_owners() {
4435        let old_owner = RoleId::User(1);
4436        let new_owner = RoleId::User(2);
4437        let other_role = RoleId::User(3);
4438
4439        // older owner exists as grantor.
4440        let mut privileges = PrivilegeMap::from_mz_acl_items(vec![
4441            MzAclItem {
4442                grantee: other_role,
4443                grantor: old_owner,
4444                acl_mode: AclMode::UPDATE,
4445            },
4446            MzAclItem {
4447                grantee: other_role,
4448                grantor: new_owner,
4449                acl_mode: AclMode::SELECT,
4450            },
4451        ]);
4452        Catalog::update_privilege_owners(&mut privileges, old_owner, new_owner);
4453        assert_eq!(1, privileges.all_values().count());
4454        assert_eq!(
4455            vec![MzAclItem {
4456                grantee: other_role,
4457                grantor: new_owner,
4458                acl_mode: AclMode::SELECT.union(AclMode::UPDATE)
4459            }],
4460            privileges.all_values_owned().collect::<Vec<_>>()
4461        );
4462
4463        // older owner exists as grantee.
4464        let mut privileges = PrivilegeMap::from_mz_acl_items(vec![
4465            MzAclItem {
4466                grantee: old_owner,
4467                grantor: other_role,
4468                acl_mode: AclMode::UPDATE,
4469            },
4470            MzAclItem {
4471                grantee: new_owner,
4472                grantor: other_role,
4473                acl_mode: AclMode::SELECT,
4474            },
4475        ]);
4476        Catalog::update_privilege_owners(&mut privileges, old_owner, new_owner);
4477        assert_eq!(1, privileges.all_values().count());
4478        assert_eq!(
4479            vec![MzAclItem {
4480                grantee: new_owner,
4481                grantor: other_role,
4482                acl_mode: AclMode::SELECT.union(AclMode::UPDATE)
4483            }],
4484            privileges.all_values_owned().collect::<Vec<_>>()
4485        );
4486
4487        // older owner exists as grantee and grantor.
4488        let mut privileges = PrivilegeMap::from_mz_acl_items(vec![
4489            MzAclItem {
4490                grantee: old_owner,
4491                grantor: old_owner,
4492                acl_mode: AclMode::UPDATE,
4493            },
4494            MzAclItem {
4495                grantee: new_owner,
4496                grantor: new_owner,
4497                acl_mode: AclMode::SELECT,
4498            },
4499        ]);
4500        Catalog::update_privilege_owners(&mut privileges, old_owner, new_owner);
4501        assert_eq!(1, privileges.all_values().count());
4502        assert_eq!(
4503            vec![MzAclItem {
4504                grantee: new_owner,
4505                grantor: new_owner,
4506                acl_mode: AclMode::SELECT.union(AclMode::UPDATE)
4507            }],
4508            privileges.all_values_owned().collect::<Vec<_>>()
4509        );
4510    }
4511
4512    #[mz_ore::test(tokio::test)]
4513    #[cfg_attr(miri, ignore)]
4514    async fn test_ddl_snapshot_survives_intervening_commit() {
4515        Catalog::with_debug(|mut catalog| async move {
4516            let name = "ddl_snapshot_database";
4517            let create = || Op::CreateDatabase {
4518                name: name.to_string(),
4519                owner_id: MZ_SYSTEM_ROLE_ID,
4520            };
4521            let (base, snapshot) = catalog.ddl_transaction_snapshot().await;
4522            let ts = catalog.current_upper().await;
4523            catalog
4524                .transact(None, ts, None, vec![create()])
4525                .await
4526                .expect("commit concurrent database");
4527            let (candidate, _) = catalog
4528                .transact_incremental_dry_run(&base, vec![create()], None, Some(snapshot), ts)
4529                .await
4530                .expect("speculative creation uses the captured durable baseline");
4531            assert!(!base.database_by_name.contains_key(name));
4532            assert!(candidate.database_by_name.contains_key(name));
4533            assert!(catalog.state().database_by_name.contains_key(name));
4534            catalog.expire().await;
4535        })
4536        .await
4537    }
4538
4539    /// Verifies that `transact_incremental_dry_run` processes only new ops
4540    /// against the accumulated state, not all ops from scratch. Two paths are
4541    /// compared:
4542    ///   - Incremental: two separate calls, each with one op
4543    ///   - All-at-once: one call with both ops
4544    /// Both must produce equivalent catalog state.
4545    #[mz_ore::test(tokio::test)]
4546    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
4547    async fn test_transact_incremental_dry_run_processes_only_new_ops() {
4548        Catalog::with_debug(|catalog| async move {
4549            // Resolve default database and schema.
4550            let database = catalog
4551                .resolve_database(DEFAULT_DATABASE_NAME)
4552                .expect("default database");
4553            let database_name = database.name.clone();
4554            let database_spec = ResolvedDatabaseSpecifier::Id(database.id());
4555            let schema = catalog
4556                .resolve_schema_in_database(&database_spec, DEFAULT_SCHEMA, &SYSTEM_CONN_ID)
4557                .expect("default schema");
4558            let schema_name = schema.name.schema.clone();
4559            let schema_spec = schema.id.clone();
4560
4561            // Allocate IDs for two tables.
4562            let (id_t1, global_id_t1) = catalog
4563                .allocate_user_id_for_test()
4564                .await
4565                .expect("allocate id for t1");
4566            let (id_t2, global_id_t2) = catalog
4567                .allocate_user_id_for_test()
4568                .await
4569                .expect("allocate id for t2");
4570
4571            let oracle_write_ts = catalog.current_upper().await;
4572
4573            // Build two CreateItem ops.
4574            let make_table_op = |id, global_id, name: &str| Op::CreateItem {
4575                id,
4576                name: QualifiedItemName {
4577                    qualifiers: ItemQualifiers {
4578                        database_spec: database_spec.clone(),
4579                        schema_spec: schema_spec.clone(),
4580                    },
4581                    item: name.to_string(),
4582                },
4583                item: CatalogItem::Table(Table {
4584                    create_sql: Some(format!(
4585                        "CREATE TABLE {database_name}.{schema_name}.{name} ()"
4586                    )),
4587                    desc: VersionedRelationDesc::new(RelationDesc::empty()),
4588                    collections: [(RelationVersion::root(), global_id)].into_iter().collect(),
4589                    conn_id: None,
4590                    resolved_ids: ResolvedIds::empty(),
4591                    custom_logical_compaction_window: None,
4592                    is_retained_metrics_object: false,
4593                    data_source: TableDataSource::TableWrites { defaults: vec![] },
4594                }),
4595                owner_id: MZ_SYSTEM_ROLE_ID,
4596            };
4597
4598            let op_t1 = make_table_op(id_t1, global_id_t1, "t1");
4599            let op_t2 = make_table_op(id_t2, global_id_t2, "t2");
4600
4601            let base_state = catalog.state().clone();
4602
4603            // --- Path A: Incremental (two separate dry-run calls) ---
4604
4605            // First call: only op_t1, no previous snapshot.
4606            let (state_after_t1, snapshot_after_t1) = catalog
4607                .transact_incremental_dry_run(
4608                    &base_state,
4609                    vec![op_t1.clone()],
4610                    None,
4611                    None,
4612                    oracle_write_ts,
4613                )
4614                .await
4615                .expect("first dry run");
4616
4617            // After first dry run: t1 exists, t2 does not.
4618            assert!(
4619                state_after_t1.try_get_entry(&id_t1).is_some(),
4620                "t1 should exist after first dry run"
4621            );
4622            assert_eq!(
4623                state_after_t1
4624                    .try_get_entry(&id_t1)
4625                    .expect("t1 entry")
4626                    .name()
4627                    .item,
4628                "t1"
4629            );
4630            assert!(
4631                state_after_t1.try_get_entry(&id_t2).is_none(),
4632                "t2 should NOT exist after first dry run"
4633            );
4634
4635            // Second call: only op_t2, using state/snapshot from first call.
4636            let (state_incremental, _) = catalog
4637                .transact_incremental_dry_run(
4638                    &state_after_t1,
4639                    vec![op_t2.clone()],
4640                    None,
4641                    Some(snapshot_after_t1),
4642                    oracle_write_ts,
4643                )
4644                .await
4645                .expect("second dry run");
4646
4647            // After second dry run: both t1 and t2 exist.
4648            assert!(
4649                state_incremental.try_get_entry(&id_t1).is_some(),
4650                "t1 should exist in incremental result"
4651            );
4652            assert!(
4653                state_incremental.try_get_entry(&id_t2).is_some(),
4654                "t2 should exist in incremental result"
4655            );
4656
4657            // --- Path B: All-at-once (single dry-run call with both ops) ---
4658
4659            let (state_all_at_once, _) = catalog
4660                .transact_incremental_dry_run(
4661                    &base_state,
4662                    vec![op_t1.clone(), op_t2.clone()],
4663                    None,
4664                    None,
4665                    oracle_write_ts,
4666                )
4667                .await
4668                .expect("all-at-once dry run");
4669
4670            assert!(
4671                state_all_at_once.try_get_entry(&id_t1).is_some(),
4672                "t1 should exist in all-at-once result"
4673            );
4674            assert!(
4675                state_all_at_once.try_get_entry(&id_t2).is_some(),
4676                "t2 should exist in all-at-once result"
4677            );
4678
4679            // --- Compare: both paths produce equivalent items ---
4680
4681            let inc_t1 = state_incremental.try_get_entry(&id_t1).expect("inc t1");
4682            let all_t1 = state_all_at_once.try_get_entry(&id_t1).expect("all t1");
4683            assert_eq!(inc_t1.name(), all_t1.name());
4684            assert_eq!(inc_t1.owner_id, all_t1.owner_id);
4685
4686            let inc_t2 = state_incremental.try_get_entry(&id_t2).expect("inc t2");
4687            let all_t2 = state_all_at_once.try_get_entry(&id_t2).expect("all t2");
4688            assert_eq!(inc_t2.name(), all_t2.name());
4689            assert_eq!(inc_t2.owner_id, all_t2.owner_id);
4690
4691            catalog.expire().await;
4692        })
4693        .await
4694    }
4695
4696    /// Exercises the diff-and-prune semantics of the
4697    /// `Op::UpdateScopedSystemParameters` apply handler over the cluster scope.
4698    /// Covers four behaviors: upsert of a desired row, the bounded-prune
4699    /// protection that spares a live cluster outside `prune_scope`, removal of a
4700    /// stale in-scope row, and the orphan-prune that reclaims a row whose owning
4701    /// cluster was dropped even though that id is absent from `prune_scope`.
4702    #[mz_ore::test(tokio::test)]
4703    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
4704    async fn test_transact_update_scoped_system_parameters_prune() {
4705        use std::collections::{BTreeMap, BTreeSet};
4706
4707        use mz_catalog::memory::objects::{ClusterConfig, ClusterVariant};
4708        use mz_controller_types::ClusterId;
4709
4710        use crate::catalog::DropObjectInfo;
4711        use crate::config::{ScopedParameters, ScopedParametersScope};
4712
4713        Catalog::with_debug(|mut catalog| async move {
4714            let param = "max_query_result_size".to_string();
4715            let value = "1MB".to_string();
4716
4717            // Allocate and create two live clusters, A and B, the same way
4718            // production code does.
4719            let commit_ts = catalog.current_upper().await;
4720            let cluster_a = catalog
4721                .allocate_user_cluster_id(commit_ts)
4722                .await
4723                .expect("allocate cluster A");
4724            let commit_ts = catalog.current_upper().await;
4725            let cluster_b = catalog
4726                .allocate_user_cluster_id(commit_ts)
4727                .await
4728                .expect("allocate cluster B");
4729
4730            let make_cluster_op = |id: ClusterId, name: &str| Op::CreateCluster {
4731                id,
4732                name: name.to_string(),
4733                introspection_sources: Vec::new(),
4734                owner_id: MZ_SYSTEM_ROLE_ID,
4735                config: ClusterConfig {
4736                    variant: ClusterVariant::Unmanaged,
4737                    workload_class: None,
4738                    query_policy: None,
4739                },
4740            };
4741
4742            let oracle_write_ts = catalog.current_upper().await;
4743            catalog
4744                .transact(
4745                    None,
4746                    oracle_write_ts,
4747                    None,
4748                    vec![
4749                        make_cluster_op(cluster_a, "test_cluster_a"),
4750                        make_cluster_op(cluster_b, "test_cluster_b"),
4751                    ],
4752                )
4753                .await
4754                .expect("create clusters");
4755
4756            // Reads the durable cluster system configuration rows.
4757            async fn rows(catalog: &Catalog) -> BTreeSet<(ClusterId, String, String)> {
4758                let mut storage = catalog.storage().await;
4759                let tx = storage.transaction().await.expect("open transaction");
4760                tx.get_cluster_system_configurations()
4761                    .map(|c| (c.cluster_id, c.name, c.value))
4762                    .collect()
4763            }
4764
4765            let scope_with = |ids: &[ClusterId]| ScopedParametersScope {
4766                clusters: ids.iter().copied().collect(),
4767                replicas: BTreeSet::new(),
4768            };
4769            let cluster_scoped = |id: ClusterId| {
4770                let mut cluster = BTreeMap::new();
4771                let mut overrides = BTreeMap::new();
4772                overrides.insert(param.clone(), value.clone());
4773                cluster.insert(id, overrides);
4774                ScopedParameters {
4775                    cluster,
4776                    replica: BTreeMap::new(),
4777                }
4778            };
4779            let empty_scoped = || ScopedParameters {
4780                cluster: BTreeMap::new(),
4781                replica: BTreeMap::new(),
4782            };
4783
4784            // Behavior 1: upsert. A is live and in scope, so the row is created.
4785            let oracle_write_ts = catalog.current_upper().await;
4786            catalog
4787                .transact(
4788                    None,
4789                    oracle_write_ts,
4790                    None,
4791                    vec![Op::UpdateScopedSystemParameters {
4792                        scoped: cluster_scoped(cluster_a),
4793                        prune_scope: scope_with(&[cluster_a]),
4794                    }],
4795                )
4796                .await
4797                .expect("upsert A");
4798            assert!(
4799                rows(&catalog)
4800                    .await
4801                    .contains(&(cluster_a, param.clone(), value.clone())),
4802                "upsert must create the row for A"
4803            );
4804
4805            // Set up an additional row for B so the prune cases have something to
4806            // act on.
4807            let oracle_write_ts = catalog.current_upper().await;
4808            catalog
4809                .transact(
4810                    None,
4811                    oracle_write_ts,
4812                    None,
4813                    vec![Op::UpdateScopedSystemParameters {
4814                        scoped: cluster_scoped(cluster_b),
4815                        prune_scope: scope_with(&[cluster_b]),
4816                    }],
4817                )
4818                .await
4819                .expect("upsert B");
4820            assert!(
4821                rows(&catalog)
4822                    .await
4823                    .contains(&(cluster_b, param.clone(), value.clone())),
4824                "setup must create the row for B"
4825            );
4826
4827            // Behavior 2: bounded prune. Running with empty `scoped` and a scope
4828            // that excludes the live cluster B must leave B's row intact, because
4829            // the update was not authoritative for B.
4830            let oracle_write_ts = catalog.current_upper().await;
4831            catalog
4832                .transact(
4833                    None,
4834                    oracle_write_ts,
4835                    None,
4836                    vec![Op::UpdateScopedSystemParameters {
4837                        scoped: empty_scoped(),
4838                        prune_scope: scope_with(&[cluster_a]),
4839                    }],
4840                )
4841                .await
4842                .expect("bounded prune");
4843            assert!(
4844                rows(&catalog)
4845                    .await
4846                    .contains(&(cluster_b, param.clone(), value.clone())),
4847                "a live cluster outside prune_scope must keep its row"
4848            );
4849
4850            // Behavior 3: stale in-scope prune. A is live and in scope but not
4851            // desired, so its row is removed.
4852            let oracle_write_ts = catalog.current_upper().await;
4853            catalog
4854                .transact(
4855                    None,
4856                    oracle_write_ts,
4857                    None,
4858                    vec![Op::UpdateScopedSystemParameters {
4859                        scoped: empty_scoped(),
4860                        prune_scope: scope_with(&[cluster_a]),
4861                    }],
4862                )
4863                .await
4864                .expect("stale in-scope prune");
4865            assert!(
4866                !rows(&catalog)
4867                    .await
4868                    .iter()
4869                    .any(|(id, _, _)| *id == cluster_a),
4870                "a live in-scope undesired row must be removed"
4871            );
4872
4873            // Behavior 4: orphan prune. Re-create A's row, drop cluster A, then run
4874            // the update with a scope that does NOT contain A. The sync loop only
4875            // ever places live ids in prune_scope, so the orphan must still be
4876            // reclaimed because its owning cluster is no longer live.
4877            let oracle_write_ts = catalog.current_upper().await;
4878            catalog
4879                .transact(
4880                    None,
4881                    oracle_write_ts,
4882                    None,
4883                    vec![Op::UpdateScopedSystemParameters {
4884                        scoped: cluster_scoped(cluster_a),
4885                        prune_scope: scope_with(&[cluster_a]),
4886                    }],
4887                )
4888                .await
4889                .expect("re-create A row");
4890            assert!(
4891                rows(&catalog)
4892                    .await
4893                    .contains(&(cluster_a, param.clone(), value.clone())),
4894                "re-created row for A must exist"
4895            );
4896
4897            let oracle_write_ts = catalog.current_upper().await;
4898            catalog
4899                .transact(
4900                    None,
4901                    oracle_write_ts,
4902                    None,
4903                    vec![Op::DropObjects {
4904                        objects: vec![DropObjectInfo::Cluster(cluster_a)],
4905                        cascade: false,
4906                    }],
4907                )
4908                .await
4909                .expect("drop cluster A");
4910
4911            // B is the only live cluster the sync loop would have evaluated, so
4912            // only B appears in prune_scope. A's id is deliberately absent.
4913            let oracle_write_ts = catalog.current_upper().await;
4914            catalog
4915                .transact(
4916                    None,
4917                    oracle_write_ts,
4918                    None,
4919                    vec![Op::UpdateScopedSystemParameters {
4920                        scoped: cluster_scoped(cluster_b),
4921                        prune_scope: scope_with(&[cluster_b]),
4922                    }],
4923                )
4924                .await
4925                .expect("orphan prune");
4926            assert!(
4927                !rows(&catalog)
4928                    .await
4929                    .iter()
4930                    .any(|(id, _, _)| *id == cluster_a),
4931                "orphan row for a dropped cluster must be removed even when absent from prune_scope"
4932            );
4933
4934            catalog.expire().await;
4935        })
4936        .await
4937    }
4938
4939    /// Registers a `MAX_CONNECTIONS` callback that records every value it sees.
4940    /// The initial fire from `register_callback` is cleared out, so callers
4941    /// only observe notifications that happen afterwards.
4942    fn record_max_connections(catalog: &mut Catalog) -> Arc<Mutex<Vec<u32>>> {
4943        let observed = Arc::new(Mutex::new(Vec::new()));
4944        let recorder = Arc::clone(&observed);
4945        catalog.system_config_mut().register_callback(
4946            &MAX_CONNECTIONS,
4947            Arc::new(move |vars: &SystemVars| {
4948                recorder
4949                    .lock()
4950                    .expect("recorder lock")
4951                    .push(vars.max_connections())
4952            }),
4953        );
4954        observed.lock().expect("recorder lock").clear();
4955        observed
4956    }
4957
4958    fn set_max_connections_op(value: u32) -> Op {
4959        Op::UpdateSystemConfiguration {
4960            name: MAX_CONNECTIONS.name.to_string(),
4961            value: OwnedVarInput::Flat(value.to_string()),
4962        }
4963    }
4964
4965    // The commit-boundary firing now lives in
4966    // `Coordinator::apply_catalog_implications`, so it is not observable from a
4967    // bare `Catalog`. The tests below stay here to guard the speculative path:
4968    // `Catalog::transact` itself must never notify.
4969
4970    /// A dry-run transaction is never committed, so it must not notify.
4971    #[mz_ore::test(tokio::test)]
4972    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
4973    async fn test_system_config_callback_not_fired_on_dry_run() {
4974        Catalog::with_debug(|mut catalog| async move {
4975            let observed = record_max_connections(&mut catalog);
4976            let before = catalog.system_config().max_connections();
4977
4978            // The clone carries the registered callbacks, so the dry run
4979            // genuinely *could* fire them. That's what makes this test worth
4980            // anything.
4981            let base_state = catalog.state().clone();
4982            let oracle_write_ts = catalog.current_upper().await;
4983            let (dry_run_state, _snapshot) = catalog
4984                .transact_incremental_dry_run(
4985                    &base_state,
4986                    vec![set_max_connections_op(before + 1)],
4987                    None,
4988                    None,
4989                    oracle_write_ts,
4990                )
4991                .await
4992                .expect("dry run");
4993
4994            assert_eq!(dry_run_state.system_config().max_connections(), before + 1);
4995            assert_eq!(catalog.system_config().max_connections(), before);
4996            assert!(
4997                observed.lock().expect("recorder lock").is_empty(),
4998                "a dry run must not notify callbacks"
4999            );
5000
5001            catalog.expire().await;
5002        })
5003        .await
5004    }
5005
5006    /// A transaction that fails after applying a system-config op to the
5007    /// candidate state must not notify, since nothing ever gets committed.
5008    #[mz_ore::test(tokio::test)]
5009    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
5010    async fn test_system_config_callback_not_fired_on_rollback() {
5011        Catalog::with_debug(|mut catalog| async move {
5012            let observed = record_max_connections(&mut catalog);
5013            let before = catalog.system_config().max_connections();
5014
5015            let oracle_write_ts = catalog.current_upper().await;
5016            let result = catalog
5017                .transact(
5018                    None,
5019                    oracle_write_ts,
5020                    None,
5021                    vec![
5022                        set_max_connections_op(before + 1),
5023                        // `transact_op` rejects this while parsing, after the
5024                        // first op already applied to the candidate state.
5025                        Op::UpdateSystemConfiguration {
5026                            name: MAX_CONNECTIONS.name.to_string(),
5027                            value: OwnedVarInput::Flat("not a number".to_string()),
5028                        },
5029                    ],
5030                )
5031                .await;
5032
5033            assert!(result.is_err(), "the second op must abort the transaction");
5034            assert_eq!(catalog.system_config().max_connections(), before);
5035            assert!(
5036                observed.lock().expect("recorder lock").is_empty(),
5037                "an aborted transaction must not notify callbacks"
5038            );
5039
5040            catalog.expire().await;
5041        })
5042        .await
5043    }
5044}