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                    let schema_id = name.qualifiers.schema_spec.clone().into();
2104                    let item_type = item.typ();
2105                    let (create_sql, global_id, versions) = item.to_serialized();
2106                    tx.insert_user_item(
2107                        id,
2108                        global_id,
2109                        schema_id,
2110                        &name.item,
2111                        create_sql,
2112                        owner_id,
2113                        privileges.clone(),
2114                        &temporary_oids,
2115                        versions,
2116                        None,
2117                    )?;
2118                    info!(
2119                        "create {} {} ({})",
2120                        item_type,
2121                        state.resolve_full_name(&name, None),
2122                        id
2123                    );
2124                }
2125
2126                if Self::should_audit_log_item(&item) {
2127                    let name = Self::full_name_detail(
2128                        &state.resolve_full_name(&name, session.map(|session| session.conn_id())),
2129                    );
2130                    let details = match &item {
2131                        CatalogItem::Source(s) => {
2132                            let cluster_id = match s.data_source {
2133                                // Ingestion exports don't have their own cluster, but
2134                                // run on their ingestion's cluster.
2135                                DataSourceDesc::IngestionExport { ingestion_id, .. } => {
2136                                    match state.get_entry(&ingestion_id).cluster_id() {
2137                                        Some(cluster_id) => Some(cluster_id.to_string()),
2138                                        None => None,
2139                                    }
2140                                }
2141                                _ => match item.cluster_id() {
2142                                    Some(cluster_id) => Some(cluster_id.to_string()),
2143                                    None => None,
2144                                },
2145                            };
2146
2147                            EventDetails::CreateSourceSinkV4(mz_audit_log::CreateSourceSinkV4 {
2148                                id: id.to_string(),
2149                                cluster_id,
2150                                name,
2151                                external_type: s.source_type().to_string(),
2152                            })
2153                        }
2154                        CatalogItem::Sink(s) => {
2155                            EventDetails::CreateSourceSinkV4(mz_audit_log::CreateSourceSinkV4 {
2156                                id: id.to_string(),
2157                                cluster_id: Some(s.cluster_id.to_string()),
2158                                name,
2159                                external_type: s.sink_type().to_string(),
2160                            })
2161                        }
2162                        CatalogItem::Index(i) => {
2163                            EventDetails::CreateIndexV1(mz_audit_log::CreateIndexV1 {
2164                                id: id.to_string(),
2165                                name,
2166                                cluster_id: i.cluster_id.to_string(),
2167                            })
2168                        }
2169                        CatalogItem::MaterializedView(mv) => {
2170                            EventDetails::CreateMaterializedViewV1(
2171                                mz_audit_log::CreateMaterializedViewV1 {
2172                                    id: id.to_string(),
2173                                    name,
2174                                    cluster_id: mv.cluster_id.to_string(),
2175                                    replacement_target_id: mv
2176                                        .replacement_target
2177                                        .map(|id| id.to_string()),
2178                                },
2179                            )
2180                        }
2181                        CatalogItem::Table(_)
2182                        | CatalogItem::Log(_)
2183                        | CatalogItem::View(_)
2184                        | CatalogItem::Type(_)
2185                        | CatalogItem::Func(_)
2186                        | CatalogItem::Secret(_)
2187                        | CatalogItem::Connection(_)
2188                        | CatalogItem::MetricSink(_) => EventDetails::IdFullNameV1(IdFullNameV1 {
2189                            id: id.to_string(),
2190                            name,
2191                        }),
2192                    };
2193                    CatalogState::add_to_audit_log(
2194                        &state.system_configuration,
2195                        oracle_write_ts,
2196                        session,
2197                        tx,
2198                        audit_events,
2199                        EventType::Create,
2200                        catalog_type_to_audit_object_type(item.typ()),
2201                        details,
2202                    )?;
2203                }
2204            }
2205            Op::CreateQueryPolicy {
2206                name,
2207                mode,
2208                rules,
2209                owner_id,
2210            } => {
2211                if state.query_policies_by_name.contains_key(&name) {
2212                    return Err(AdapterError::PlanError(PlanError::Catalog(
2213                        SqlCatalogError::QueryPolicyAlreadyExists(name),
2214                    )));
2215                }
2216                if is_reserved_name(&name) {
2217                    return Err(AdapterError::Catalog(Error::new(
2218                        ErrorKind::ReservedQueryPolicyName(name),
2219                    )));
2220                }
2221                let object_type = mz_sql::catalog::ObjectType::QueryPolicy;
2222                let owner_privileges =
2223                    std::iter::once(rbac::owner_privilege(object_type, owner_id));
2224                let default_privileges = state
2225                    .default_privileges
2226                    .get_applicable_privileges(owner_id, None, None, object_type)
2227                    .map(|item| item.mz_acl_item(owner_id));
2228                let privileges =
2229                    merge_mz_acl_items(owner_privileges.chain(default_privileges)).collect();
2230                let temporary_oids = state.get_temporary_oids().collect();
2231                let id = tx.insert_user_query_policy(
2232                    name.clone(),
2233                    mode,
2234                    rules,
2235                    privileges,
2236                    owner_id,
2237                    &temporary_oids,
2238                )?;
2239                CatalogState::add_to_audit_log(
2240                    &state.system_configuration,
2241                    oracle_write_ts,
2242                    session,
2243                    tx,
2244                    audit_events,
2245                    EventType::Create,
2246                    ObjectType::QueryPolicy,
2247                    EventDetails::IdNameV1(IdNameV1 {
2248                        id: id.to_string(),
2249                        name,
2250                    }),
2251                )?;
2252            }
2253            Op::CreateNetworkPolicy {
2254                rules,
2255                name,
2256                owner_id,
2257            } => {
2258                if state.network_policies_by_name.contains_key(&name) {
2259                    return Err(AdapterError::PlanError(PlanError::Catalog(
2260                        SqlCatalogError::NetworkPolicyAlreadyExists(name),
2261                    )));
2262                }
2263                if is_reserved_name(&name) {
2264                    return Err(AdapterError::Catalog(Error::new(
2265                        ErrorKind::ReservedNetworkPolicyName(name),
2266                    )));
2267                }
2268
2269                let owner_privileges = vec![rbac::owner_privilege(
2270                    mz_sql::catalog::ObjectType::NetworkPolicy,
2271                    owner_id,
2272                )];
2273                let default_privileges = state
2274                    .default_privileges
2275                    .get_applicable_privileges(
2276                        owner_id,
2277                        None,
2278                        None,
2279                        mz_sql::catalog::ObjectType::NetworkPolicy,
2280                    )
2281                    .map(|item| item.mz_acl_item(owner_id));
2282                let privileges: Vec<_> =
2283                    merge_mz_acl_items(owner_privileges.into_iter().chain(default_privileges))
2284                        .collect();
2285
2286                let temporary_oids: HashSet<_> = state.get_temporary_oids().collect();
2287                let id = tx.insert_user_network_policy(
2288                    name.clone(),
2289                    rules,
2290                    privileges,
2291                    owner_id,
2292                    &temporary_oids,
2293                )?;
2294
2295                CatalogState::add_to_audit_log(
2296                    &state.system_configuration,
2297                    oracle_write_ts,
2298                    session,
2299                    tx,
2300                    audit_events,
2301                    EventType::Create,
2302                    ObjectType::NetworkPolicy,
2303                    EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2304                        id: id.to_string(),
2305                        name: name.clone(),
2306                    }),
2307                )?;
2308
2309                info!("created network policy {name} ({id})");
2310            }
2311            Op::Comment {
2312                object_id,
2313                sub_component,
2314                comment,
2315            } => {
2316                tx.update_comment(object_id, sub_component, comment)?;
2317                let entry = state.get_comment_id_entry(&object_id);
2318                let should_log = entry
2319                    .map(|entry| Self::should_audit_log_item(entry.item()))
2320                    // Things that aren't catalog entries can't be temp, so should be logged.
2321                    .unwrap_or(true);
2322                // TODO: We need a conn_id to resolve schema names. This means that system-initiated
2323                // comments won't be logged for now.
2324                if let (Some(conn_id), true) =
2325                    (session.map(|session| session.conn_id()), should_log)
2326                {
2327                    CatalogState::add_to_audit_log(
2328                        &state.system_configuration,
2329                        oracle_write_ts,
2330                        session,
2331                        tx,
2332                        audit_events,
2333                        EventType::Comment,
2334                        comment_id_to_audit_object_type(object_id),
2335                        EventDetails::IdNameV1(IdNameV1 {
2336                            // CommentObjectIds don't have a great string representation, but debug will do for now.
2337                            id: format!("{object_id:?}"),
2338                            name: state.comment_id_to_audit_log_name(object_id, conn_id),
2339                        }),
2340                    )?;
2341                }
2342            }
2343            Op::UpdateSourceReferences {
2344                source_id,
2345                references,
2346            } => {
2347                tx.update_source_references(
2348                    source_id,
2349                    references
2350                        .references
2351                        .into_iter()
2352                        .map(|reference| reference.into())
2353                        .collect(),
2354                    references.updated_at,
2355                )?;
2356            }
2357            Op::DropObjects {
2358                objects: drop_object_infos,
2359                cascade,
2360            } => {
2361                // Generate all of the objects that need to get dropped.
2362                let delta = ObjectsToDrop::generate(drop_object_infos, state, session)?;
2363
2364                // Drop any associated comments.
2365                tx.drop_comments(&delta.comments)?;
2366
2367                // Drop any items.
2368                let items_to_drop: BTreeSet<_> = delta.items.iter().copied().collect();
2369                tx.remove_items(&items_to_drop)?;
2370
2371                for item_id in delta.items {
2372                    let entry = state.get_entry(&item_id);
2373
2374                    if entry.item().is_storage_collection() {
2375                        storage_collections_to_drop.extend(entry.global_ids());
2376                    }
2377
2378                    if state.source_references.contains_key(&item_id) {
2379                        tx.remove_source_references(item_id)?;
2380                    }
2381
2382                    if Self::should_audit_log_item(entry.item()) {
2383                        CatalogState::add_to_audit_log(
2384                            &state.system_configuration,
2385                            oracle_write_ts,
2386                            session,
2387                            tx,
2388                            audit_events,
2389                            EventType::Drop,
2390                            catalog_type_to_audit_object_type(entry.item().typ()),
2391                            EventDetails::IdFullNameV1(IdFullNameV1 {
2392                                id: item_id.to_string(),
2393                                name: Self::full_name_detail(&state.resolve_full_name(
2394                                    entry.name(),
2395                                    session.map(|session| session.conn_id()),
2396                                )),
2397                            }),
2398                        )?;
2399                    }
2400                    info!(
2401                        "drop {} {} ({})",
2402                        entry.item_type(),
2403                        state.resolve_full_name(entry.name(), entry.conn_id()),
2404                        item_id
2405                    );
2406                }
2407
2408                // Drop any schemas.
2409                let schemas = delta
2410                    .schemas
2411                    .iter()
2412                    .map(|(schema_spec, database_spec)| {
2413                        (SchemaId::from(schema_spec), *database_spec)
2414                    })
2415                    .collect();
2416                tx.remove_schemas(&schemas)?;
2417
2418                for (schema_spec, database_spec) in delta.schemas {
2419                    let schema = state.get_schema(
2420                        &database_spec,
2421                        &schema_spec,
2422                        session
2423                            .map(|session| session.conn_id())
2424                            .unwrap_or(&SYSTEM_CONN_ID),
2425                    );
2426
2427                    let schema_id = SchemaId::from(schema_spec);
2428                    let database_id = match database_spec {
2429                        ResolvedDatabaseSpecifier::Ambient => None,
2430                        ResolvedDatabaseSpecifier::Id(database_id) => Some(database_id),
2431                    };
2432
2433                    CatalogState::add_to_audit_log(
2434                        &state.system_configuration,
2435                        oracle_write_ts,
2436                        session,
2437                        tx,
2438                        audit_events,
2439                        EventType::Drop,
2440                        ObjectType::Schema,
2441                        EventDetails::SchemaV2(mz_audit_log::SchemaV2 {
2442                            id: schema_id.to_string(),
2443                            name: schema.name.schema.to_string(),
2444                            database_name: database_id
2445                                .map(|database_id| state.database_by_id[&database_id].name.clone()),
2446                        }),
2447                    )?;
2448                }
2449
2450                // Drop any databases.
2451                tx.remove_databases(&delta.databases)?;
2452
2453                for database_id in delta.databases {
2454                    let database = state.get_database(&database_id).clone();
2455
2456                    CatalogState::add_to_audit_log(
2457                        &state.system_configuration,
2458                        oracle_write_ts,
2459                        session,
2460                        tx,
2461                        audit_events,
2462                        EventType::Drop,
2463                        ObjectType::Database,
2464                        EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2465                            id: database_id.to_string(),
2466                            name: database.name.clone(),
2467                        }),
2468                    )?;
2469                }
2470
2471                // Drop any roles.
2472                tx.remove_user_roles(&delta.roles)?;
2473
2474                for role_id in delta.roles {
2475                    let role = state
2476                        .roles_by_id
2477                        .get(&role_id)
2478                        .expect("catalog out of sync");
2479
2480                    CatalogState::add_to_audit_log(
2481                        &state.system_configuration,
2482                        oracle_write_ts,
2483                        session,
2484                        tx,
2485                        audit_events,
2486                        EventType::Drop,
2487                        ObjectType::Role,
2488                        EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2489                            id: role.id.to_string(),
2490                            name: role.name.clone(),
2491                        }),
2492                    )?;
2493                    info!("drop role {}", role.name());
2494                }
2495
2496                // Drop any network policies.
2497                tx.remove_network_policies(&delta.network_policies)?;
2498
2499                for network_policy_id in delta.network_policies {
2500                    let policy = state
2501                        .network_policies_by_id
2502                        .get(&network_policy_id)
2503                        .expect("catalog out of sync");
2504
2505                    CatalogState::add_to_audit_log(
2506                        &state.system_configuration,
2507                        oracle_write_ts,
2508                        session,
2509                        tx,
2510                        audit_events,
2511                        EventType::Drop,
2512                        ObjectType::NetworkPolicy,
2513                        EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2514                            id: policy.id.to_string(),
2515                            name: policy.name.clone(),
2516                        }),
2517                    )?;
2518                    info!("drop network policy {}", policy.name.clone());
2519                }
2520
2521                // Drop any replicas.
2522                let replicas = delta.replicas.keys().copied().collect();
2523                tx.remove_cluster_replicas(&replicas)?;
2524
2525                for (replica_id, (cluster_id, reason)) in delta.replicas {
2526                    let cluster = state.get_cluster(cluster_id);
2527                    let replica = cluster.replica(replica_id).expect("Must exist");
2528
2529                    let (reason, scheduling_policies) = reason.into_audit_log();
2530                    let details =
2531                        EventDetails::DropClusterReplicaV3(mz_audit_log::DropClusterReplicaV3 {
2532                            cluster_id: cluster_id.to_string(),
2533                            cluster_name: cluster.name.clone(),
2534                            replica_id: Some(replica_id.to_string()),
2535                            replica_name: replica.name.clone(),
2536                            reason,
2537                            scheduling_policies,
2538                        });
2539                    CatalogState::add_to_audit_log(
2540                        &state.system_configuration,
2541                        oracle_write_ts,
2542                        session,
2543                        tx,
2544                        audit_events,
2545                        EventType::Drop,
2546                        ObjectType::ClusterReplica,
2547                        details,
2548                    )?;
2549                }
2550
2551                // Drop any clusters.
2552                tx.remove_clusters(&delta.clusters)?;
2553
2554                for cluster_id in delta.clusters {
2555                    let cluster = state.get_cluster(cluster_id);
2556
2557                    CatalogState::add_to_audit_log(
2558                        &state.system_configuration,
2559                        oracle_write_ts,
2560                        session,
2561                        tx,
2562                        audit_events,
2563                        EventType::Drop,
2564                        ObjectType::Cluster,
2565                        EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
2566                            id: cluster.id.to_string(),
2567                            name: cluster.name.clone(),
2568                        }),
2569                    )?;
2570                }
2571
2572                // Remove attachment targets first so RESTRICT ignores targets
2573                // that are themselves part of this drop.
2574                let detached_clusters = tx.remove_query_policies(&delta.query_policies, cascade)?;
2575                for id in detached_clusters {
2576                    let cluster = state.get_cluster(id);
2577                    CatalogState::add_to_audit_log(
2578                        &state.system_configuration,
2579                        oracle_write_ts,
2580                        session,
2581                        tx,
2582                        audit_events,
2583                        EventType::Alter,
2584                        ObjectType::Cluster,
2585                        EventDetails::IdNameV1(IdNameV1 {
2586                            id: id.to_string(),
2587                            name: cluster.name.clone(),
2588                        }),
2589                    )?;
2590                }
2591                for id in delta.query_policies {
2592                    let policy = state.get_query_policy(&id);
2593                    CatalogState::add_to_audit_log(
2594                        &state.system_configuration,
2595                        oracle_write_ts,
2596                        session,
2597                        tx,
2598                        audit_events,
2599                        EventType::Drop,
2600                        ObjectType::QueryPolicy,
2601                        EventDetails::IdNameV1(IdNameV1 {
2602                            id: id.to_string(),
2603                            name: policy.name.clone(),
2604                        }),
2605                    )?;
2606                }
2607            }
2608            Op::GrantRole {
2609                role_id,
2610                member_id,
2611                grantor_id,
2612            } => {
2613                state.ensure_not_reserved_role(&member_id)?;
2614                state.ensure_grantable_role(&role_id)?;
2615                if state.collect_role_membership(&role_id).contains(&member_id) {
2616                    let group_role = state.get_role(&role_id);
2617                    let member_role = state.get_role(&member_id);
2618                    return Err(AdapterError::Catalog(Error::new(
2619                        ErrorKind::CircularRoleMembership {
2620                            role_name: group_role.name().to_string(),
2621                            member_name: member_role.name().to_string(),
2622                        },
2623                    )));
2624                }
2625                let mut member_role = state.get_role(&member_id).clone();
2626                member_role.membership.map.insert(role_id, grantor_id);
2627                tx.update_role(member_id, member_role.into(), PasswordAction::NoChange)?;
2628
2629                CatalogState::add_to_audit_log(
2630                    &state.system_configuration,
2631                    oracle_write_ts,
2632                    session,
2633                    tx,
2634                    audit_events,
2635                    EventType::Grant,
2636                    ObjectType::Role,
2637                    EventDetails::GrantRoleV2(mz_audit_log::GrantRoleV2 {
2638                        role_id: role_id.to_string(),
2639                        member_id: member_id.to_string(),
2640                        grantor_id: grantor_id.to_string(),
2641                        executed_by: session
2642                            .map(|session| session.authenticated_role_id())
2643                            .unwrap_or(&MZ_SYSTEM_ROLE_ID)
2644                            .to_string(),
2645                    }),
2646                )?;
2647            }
2648            Op::RevokeRole {
2649                role_id,
2650                member_id,
2651                grantor_id,
2652            } => {
2653                state.ensure_not_reserved_role(&member_id)?;
2654                state.ensure_grantable_role(&role_id)?;
2655                let mut member_role = state.get_role(&member_id).clone();
2656                member_role.membership.map.remove(&role_id);
2657                tx.update_role(member_id, member_role.into(), PasswordAction::NoChange)?;
2658
2659                CatalogState::add_to_audit_log(
2660                    &state.system_configuration,
2661                    oracle_write_ts,
2662                    session,
2663                    tx,
2664                    audit_events,
2665                    EventType::Revoke,
2666                    ObjectType::Role,
2667                    EventDetails::RevokeRoleV2(mz_audit_log::RevokeRoleV2 {
2668                        role_id: role_id.to_string(),
2669                        member_id: member_id.to_string(),
2670                        grantor_id: grantor_id.to_string(),
2671                        executed_by: session
2672                            .map(|session| session.authenticated_role_id())
2673                            .unwrap_or(&MZ_SYSTEM_ROLE_ID)
2674                            .to_string(),
2675                    }),
2676                )?;
2677            }
2678            Op::UpdatePrivilege {
2679                target_id,
2680                privileges,
2681                variant,
2682            } => {
2683                let update_privilege_fn = |target_privileges: &mut PrivilegeMap| {
2684                    for privilege in &privileges {
2685                        match variant {
2686                            UpdatePrivilegeVariant::Grant => {
2687                                target_privileges.grant(privilege.clone());
2688                            }
2689                            UpdatePrivilegeVariant::Revoke => {
2690                                target_privileges.revoke(privilege);
2691                            }
2692                        }
2693                    }
2694                };
2695                match &target_id {
2696                    SystemObjectId::Object(object_id) => match object_id {
2697                        ObjectId::Cluster(id) => {
2698                            let mut cluster = state.get_cluster(*id).clone();
2699                            update_privilege_fn(&mut cluster.privileges);
2700                            tx.update_cluster(*id, cluster.into())?;
2701                        }
2702                        ObjectId::Database(id) => {
2703                            let mut database = state.get_database(id).clone();
2704                            update_privilege_fn(&mut database.privileges);
2705                            tx.update_database(*id, database.into())?;
2706                        }
2707                        ObjectId::NetworkPolicy(id) => {
2708                            let mut policy = state.get_network_policy(id).clone();
2709                            update_privilege_fn(&mut policy.privileges);
2710                            tx.update_network_policy(*id, policy.into())?;
2711                        }
2712                        ObjectId::QueryPolicy(id) => {
2713                            let mut policy = state.get_query_policy(id).clone();
2714                            update_privilege_fn(&mut policy.privileges);
2715                            tx.update_query_policy(policy.into())?;
2716                        }
2717                        ObjectId::Schema((database_spec, schema_spec)) => {
2718                            let schema_id = schema_spec.clone().into();
2719                            let mut schema = state
2720                                .get_schema(
2721                                    database_spec,
2722                                    schema_spec,
2723                                    session
2724                                        .map(|session| session.conn_id())
2725                                        .unwrap_or(&SYSTEM_CONN_ID),
2726                                )
2727                                .clone();
2728                            update_privilege_fn(&mut schema.privileges);
2729                            tx.update_schema(schema_id, schema.into())?;
2730                        }
2731                        ObjectId::Item(id) => {
2732                            let entry = state.get_entry(id);
2733                            let mut new_entry = entry.clone();
2734                            update_privilege_fn(&mut new_entry.privileges);
2735                            tx.update_item(*id, state.durable_item(new_entry)?)?;
2736                        }
2737                        ObjectId::Role(_) | ObjectId::ClusterReplica(_) => {}
2738                    },
2739                    SystemObjectId::System => {
2740                        let mut system_privileges = PrivilegeMap::clone(&state.system_privileges);
2741                        update_privilege_fn(&mut system_privileges);
2742                        for privilege in &privileges {
2743                            let new_privilege = system_privileges
2744                                .get_acl_item(&privilege.grantee, &privilege.grantor);
2745                            tx.set_system_privilege(
2746                                privilege.grantee,
2747                                privilege.grantor,
2748                                new_privilege.map(|new_privilege| new_privilege.acl_mode),
2749                            )?;
2750                        }
2751                    }
2752                }
2753                let object_type = state.get_system_object_type(&target_id);
2754                let object_id_str = match &target_id {
2755                    SystemObjectId::System => "SYSTEM".to_string(),
2756                    SystemObjectId::Object(id) => id.to_string(),
2757                };
2758                // One audit event per grantee, even though the batch is a single durable write.
2759                for privilege in &privileges {
2760                    CatalogState::add_to_audit_log(
2761                        &state.system_configuration,
2762                        oracle_write_ts,
2763                        session,
2764                        tx,
2765                        audit_events,
2766                        variant.into(),
2767                        system_object_type_to_audit_object_type(&object_type),
2768                        EventDetails::UpdatePrivilegeV1(mz_audit_log::UpdatePrivilegeV1 {
2769                            object_id: object_id_str.clone(),
2770                            grantee_id: privilege.grantee.to_string(),
2771                            grantor_id: privilege.grantor.to_string(),
2772                            privileges: privilege.acl_mode.to_string(),
2773                        }),
2774                    )?;
2775                }
2776            }
2777            Op::UpdateDefaultPrivilege {
2778                privilege_object,
2779                privilege_acl_item,
2780                variant,
2781            } => {
2782                let mut default_privileges = DefaultPrivileges::clone(&state.default_privileges);
2783                match variant {
2784                    UpdatePrivilegeVariant::Grant => default_privileges
2785                        .grant(privilege_object.clone(), privilege_acl_item.clone()),
2786                    UpdatePrivilegeVariant::Revoke => {
2787                        default_privileges.revoke(&privilege_object, &privilege_acl_item)
2788                    }
2789                }
2790                let new_acl_mode = default_privileges
2791                    .get_privileges_for_grantee(&privilege_object, &privilege_acl_item.grantee);
2792                tx.set_default_privilege(
2793                    privilege_object.role_id,
2794                    privilege_object.database_id,
2795                    privilege_object.schema_id,
2796                    privilege_object.object_type,
2797                    privilege_acl_item.grantee,
2798                    new_acl_mode.cloned(),
2799                )?;
2800                CatalogState::add_to_audit_log(
2801                    &state.system_configuration,
2802                    oracle_write_ts,
2803                    session,
2804                    tx,
2805                    audit_events,
2806                    variant.into(),
2807                    object_type_to_audit_object_type(privilege_object.object_type),
2808                    EventDetails::AlterDefaultPrivilegeV1(mz_audit_log::AlterDefaultPrivilegeV1 {
2809                        role_id: privilege_object.role_id.to_string(),
2810                        database_id: privilege_object.database_id.map(|id| id.to_string()),
2811                        schema_id: privilege_object.schema_id.map(|id| id.to_string()),
2812                        grantee_id: privilege_acl_item.grantee.to_string(),
2813                        privileges: privilege_acl_item.acl_mode.to_string(),
2814                    }),
2815                )?;
2816            }
2817            Op::RenameCluster {
2818                id,
2819                name,
2820                to_name,
2821                check_reserved_names,
2822            } => {
2823                if id.is_system() {
2824                    return Err(AdapterError::Catalog(Error::new(
2825                        ErrorKind::ReadOnlyCluster(name.clone()),
2826                    )));
2827                }
2828                if check_reserved_names && is_reserved_name(&to_name) {
2829                    return Err(AdapterError::Catalog(Error::new(
2830                        ErrorKind::ReservedClusterName(to_name),
2831                    )));
2832                }
2833                tx.rename_cluster(id, &name, &to_name)?;
2834                CatalogState::add_to_audit_log(
2835                    &state.system_configuration,
2836                    oracle_write_ts,
2837                    session,
2838                    tx,
2839                    audit_events,
2840                    EventType::Alter,
2841                    ObjectType::Cluster,
2842                    EventDetails::RenameClusterV1(mz_audit_log::RenameClusterV1 {
2843                        id: id.to_string(),
2844                        old_name: name.clone(),
2845                        new_name: to_name.clone(),
2846                    }),
2847                )?;
2848                info!("rename cluster {name} to {to_name}");
2849            }
2850            Op::RenameClusterReplica {
2851                cluster_id,
2852                replica_id,
2853                name,
2854                to_name,
2855            } => {
2856                if is_reserved_name(&to_name) {
2857                    return Err(AdapterError::Catalog(Error::new(
2858                        ErrorKind::ReservedReplicaName(to_name),
2859                    )));
2860                }
2861                tx.rename_cluster_replica(replica_id, &name, &to_name)?;
2862                CatalogState::add_to_audit_log(
2863                    &state.system_configuration,
2864                    oracle_write_ts,
2865                    session,
2866                    tx,
2867                    audit_events,
2868                    EventType::Alter,
2869                    ObjectType::ClusterReplica,
2870                    EventDetails::RenameClusterReplicaV1(mz_audit_log::RenameClusterReplicaV1 {
2871                        cluster_id: cluster_id.to_string(),
2872                        replica_id: replica_id.to_string(),
2873                        old_name: name.replica.as_str().to_string(),
2874                        new_name: to_name.clone(),
2875                    }),
2876                )?;
2877                info!("rename cluster replica {name} to {to_name}");
2878            }
2879            Op::RenameItem {
2880                id,
2881                to_name,
2882                current_full_name,
2883            } => {
2884                let mut updates = Vec::new();
2885
2886                let entry = state.get_entry(&id);
2887                if let CatalogItem::Type(_) = entry.item() {
2888                    return Err(AdapterError::Catalog(Error::new(ErrorKind::TypeRename(
2889                        current_full_name.to_string(),
2890                    ))));
2891                }
2892
2893                if entry.id().is_system() {
2894                    let name = state
2895                        .resolve_full_name(entry.name(), session.map(|session| session.conn_id()));
2896                    return Err(AdapterError::Catalog(Error::new(ErrorKind::ReadOnlyItem(
2897                        name.to_string(),
2898                    ))));
2899                }
2900
2901                let mut to_full_name = current_full_name.clone();
2902                to_full_name.item.clone_from(&to_name);
2903
2904                let mut to_qualified_name = entry.name().clone();
2905                to_qualified_name.item.clone_from(&to_name);
2906
2907                let details = EventDetails::RenameItemV1(mz_audit_log::RenameItemV1 {
2908                    id: id.to_string(),
2909                    old_name: Self::full_name_detail(&current_full_name),
2910                    new_name: Self::full_name_detail(&to_full_name),
2911                });
2912                if Self::should_audit_log_item(entry.item()) {
2913                    CatalogState::add_to_audit_log(
2914                        &state.system_configuration,
2915                        oracle_write_ts,
2916                        session,
2917                        tx,
2918                        audit_events,
2919                        EventType::Alter,
2920                        catalog_type_to_audit_object_type(entry.item().typ()),
2921                        details,
2922                    )?;
2923                }
2924
2925                // Rename item itself.
2926                let mut new_entry = entry.clone();
2927                new_entry.name.item.clone_from(&to_name);
2928                new_entry.item = entry.item().rename(to_name);
2929
2930                for id in entry.referenced_by() {
2931                    let dependent_item = state.get_entry(id);
2932                    let mut to_entry = dependent_item.clone();
2933                    to_entry.item = dependent_item
2934                        .item()
2935                        .rename_item_refs(current_full_name.clone(), to_full_name.item.clone())
2936                        .map_err(|e| {
2937                            Error::new(ErrorKind::from(AmbiguousRename {
2938                                depender: state
2939                                    .resolve_full_name(
2940                                        dependent_item.name(),
2941                                        dependent_item.conn_id(),
2942                                    )
2943                                    .to_string(),
2944                                dependee: state
2945                                    .resolve_full_name(entry.name(), entry.conn_id())
2946                                    .to_string(),
2947                                message: e,
2948                            }))
2949                        })?;
2950
2951                    tx.update_item(*id, state.durable_item(to_entry)?)?;
2952                    updates.push(*id);
2953                }
2954                tx.update_item(id, state.durable_item(new_entry)?)?;
2955
2956                updates.push(id);
2957                for id in updates {
2958                    Self::log_update(state, &id);
2959                }
2960            }
2961            Op::RenameSchema {
2962                database_spec,
2963                schema_spec,
2964                new_name,
2965                check_reserved_names,
2966            } => {
2967                if check_reserved_names && is_reserved_name(&new_name) {
2968                    return Err(AdapterError::Catalog(Error::new(
2969                        ErrorKind::ReservedSchemaName(new_name),
2970                    )));
2971                }
2972
2973                let conn_id = session
2974                    .map(|session| session.conn_id())
2975                    .unwrap_or(&SYSTEM_CONN_ID);
2976
2977                let schema = state.get_schema(&database_spec, &schema_spec, conn_id);
2978                let cur_name = schema.name().schema.clone();
2979
2980                let ResolvedDatabaseSpecifier::Id(database_id) = database_spec else {
2981                    return Err(AdapterError::Catalog(Error::new(
2982                        ErrorKind::AmbientSchemaRename(cur_name),
2983                    )));
2984                };
2985                let database = state.get_database(&database_id);
2986                let database_name = &database.name;
2987
2988                let mut updates: Vec<CatalogItemId> = Vec::new();
2989                let mut items_to_update = BTreeMap::new();
2990                // An item can be reached more than once: once as a member of
2991                // the schema and again for each object in the schema it
2992                // depends on. Skip items that were already rewritten.
2993                let mut seen: BTreeSet<CatalogItemId> = BTreeSet::new();
2994
2995                let mut update_item = |id: &CatalogItemId| {
2996                    if !seen.insert(*id) {
2997                        return Ok(());
2998                    }
2999
3000                    let entry = state.get_entry(id);
3001
3002                    // Update our item.
3003                    let mut new_entry = entry.clone();
3004                    new_entry.item = entry
3005                        .item
3006                        .rename_schema_refs(database_name, &cur_name, &new_name)
3007                        .map_err(|(s, _i)| {
3008                            Error::new(ErrorKind::from(AmbiguousRename {
3009                                depender: state
3010                                    .resolve_full_name(entry.name(), entry.conn_id())
3011                                    .to_string(),
3012                                dependee: format!("{database_name}.{cur_name}"),
3013                                message: format!("ambiguous reference to schema named {s}"),
3014                            }))
3015                        })?;
3016
3017                    // Queue updates for Catalog storage and Builtin Tables.
3018                    items_to_update.insert(*id, state.durable_item(new_entry)?);
3019                    updates.push(*id);
3020
3021                    Ok::<_, AdapterError>(())
3022                };
3023
3024                // Update all of the items in the schema. A schema holds items,
3025                // types, and functions in separate maps, and any of them may be
3026                // referenced by another object's create_sql via a schema-qualified
3027                // name, so all three must be rewritten.
3028                for (_name, item_id) in schema
3029                    .items
3030                    .iter()
3031                    .chain(schema.types.iter())
3032                    .chain(schema.functions.iter())
3033                {
3034                    // Update the item itself.
3035                    update_item(item_id)?;
3036
3037                    // Update everything that depends on this item.
3038                    for id in state.get_entry(item_id).referenced_by() {
3039                        update_item(id)?;
3040                    }
3041                }
3042                // Note: When updating the transaction it's very important that we update the
3043                // items as a whole group, otherwise we exhibit quadratic behavior.
3044                tx.update_items(items_to_update)?;
3045
3046                // Renaming temporary schemas is not supported.
3047                let SchemaSpecifier::Id(schema_id) = *schema.id() else {
3048                    let schema_name = schema.name().schema.clone();
3049                    return Err(AdapterError::Catalog(crate::catalog::Error::new(
3050                        crate::catalog::ErrorKind::ReadOnlySystemSchema(schema_name),
3051                    )));
3052                };
3053
3054                // Add an entry to the audit log.
3055                let database_name = database_spec
3056                    .id()
3057                    .map(|id| state.get_database(&id).name.clone());
3058                let details = EventDetails::RenameSchemaV1(mz_audit_log::RenameSchemaV1 {
3059                    id: schema_id.to_string(),
3060                    old_name: schema.name().schema.clone(),
3061                    new_name: new_name.clone(),
3062                    database_name,
3063                });
3064                CatalogState::add_to_audit_log(
3065                    &state.system_configuration,
3066                    oracle_write_ts,
3067                    session,
3068                    tx,
3069                    audit_events,
3070                    EventType::Alter,
3071                    mz_audit_log::ObjectType::Schema,
3072                    details,
3073                )?;
3074
3075                // Update the schema itself.
3076                let mut new_schema = schema.clone();
3077                new_schema.name.schema.clone_from(&new_name);
3078                tx.update_schema(schema_id, new_schema.into())?;
3079
3080                for id in updates {
3081                    Self::log_update(state, &id);
3082                }
3083            }
3084            Op::UpdateOwner { id, new_owner } => {
3085                let conn_id = session
3086                    .map(|session| session.conn_id())
3087                    .unwrap_or(&SYSTEM_CONN_ID);
3088                let old_owner = state
3089                    .get_owner_id(&id, conn_id)
3090                    .expect("cannot update the owner of an object without an owner");
3091                match &id {
3092                    ObjectId::Cluster(id) => {
3093                        let mut cluster = state.get_cluster(*id).clone();
3094                        if id.is_system() {
3095                            return Err(AdapterError::Catalog(Error::new(
3096                                ErrorKind::ReadOnlyCluster(cluster.name),
3097                            )));
3098                        }
3099                        Self::update_privilege_owners(
3100                            &mut cluster.privileges,
3101                            cluster.owner_id,
3102                            new_owner,
3103                        );
3104                        cluster.owner_id = new_owner;
3105                        tx.update_cluster(*id, cluster.into())?;
3106                    }
3107                    ObjectId::ClusterReplica((cluster_id, replica_id)) => {
3108                        let cluster = state.get_cluster(*cluster_id);
3109                        let mut replica = cluster
3110                            .replica(*replica_id)
3111                            .expect("catalog out of sync")
3112                            .clone();
3113                        if replica_id.is_system() {
3114                            return Err(AdapterError::Catalog(Error::new(
3115                                ErrorKind::ReadOnlyClusterReplica(replica.name),
3116                            )));
3117                        }
3118                        replica.owner_id = new_owner;
3119                        tx.update_cluster_replica(*replica_id, replica.into())?;
3120                    }
3121                    ObjectId::Database(id) => {
3122                        let mut database = state.get_database(id).clone();
3123                        if id.is_system() {
3124                            return Err(AdapterError::Catalog(Error::new(
3125                                ErrorKind::ReadOnlyDatabase(database.name),
3126                            )));
3127                        }
3128                        Self::update_privilege_owners(
3129                            &mut database.privileges,
3130                            database.owner_id,
3131                            new_owner,
3132                        );
3133                        database.owner_id = new_owner;
3134                        tx.update_database(*id, database.clone().into())?;
3135                    }
3136                    ObjectId::Schema((database_spec, schema_spec)) => {
3137                        let schema_id: SchemaId = schema_spec.clone().into();
3138                        let mut schema = state
3139                            .get_schema(database_spec, schema_spec, conn_id)
3140                            .clone();
3141                        if schema_id.is_system() {
3142                            let name = schema.name();
3143                            let full_name = state.resolve_full_schema_name(name);
3144                            return Err(AdapterError::Catalog(Error::new(
3145                                ErrorKind::ReadOnlySystemSchema(full_name.to_string()),
3146                            )));
3147                        }
3148                        Self::update_privilege_owners(
3149                            &mut schema.privileges,
3150                            schema.owner_id,
3151                            new_owner,
3152                        );
3153                        schema.owner_id = new_owner;
3154                        tx.update_schema(schema_id, schema.into())?;
3155                    }
3156                    ObjectId::Item(id) => {
3157                        let entry = state.get_entry(id);
3158                        let mut new_entry = entry.clone();
3159                        if id.is_system() {
3160                            let full_name = state.resolve_full_name(
3161                                new_entry.name(),
3162                                session.map(|session| session.conn_id()),
3163                            );
3164                            return Err(AdapterError::Catalog(Error::new(
3165                                ErrorKind::ReadOnlyItem(full_name.to_string()),
3166                            )));
3167                        }
3168                        Self::update_privilege_owners(
3169                            &mut new_entry.privileges,
3170                            new_entry.owner_id,
3171                            new_owner,
3172                        );
3173                        new_entry.owner_id = new_owner;
3174                        tx.update_item(*id, state.durable_item(new_entry)?)?;
3175                    }
3176                    ObjectId::NetworkPolicy(id) => {
3177                        let mut policy = state.get_network_policy(id).clone();
3178                        if id.is_system() {
3179                            return Err(AdapterError::Catalog(Error::new(
3180                                ErrorKind::ReadOnlyNetworkPolicy(policy.name),
3181                            )));
3182                        }
3183                        Self::update_privilege_owners(
3184                            &mut policy.privileges,
3185                            policy.owner_id,
3186                            new_owner,
3187                        );
3188                        policy.owner_id = new_owner;
3189                        tx.update_network_policy(*id, policy.into())?;
3190                    }
3191                    ObjectId::QueryPolicy(id) => {
3192                        let mut policy = state.get_query_policy(id).clone();
3193                        if id.is_system() {
3194                            return Err(AdapterError::Catalog(Error::new(
3195                                ErrorKind::ReadOnlyQueryPolicy(policy.name),
3196                            )));
3197                        }
3198                        Self::update_privilege_owners(
3199                            &mut policy.privileges,
3200                            policy.owner_id,
3201                            new_owner,
3202                        );
3203                        policy.owner_id = new_owner;
3204                        tx.update_query_policy(policy.into())?;
3205                    }
3206                    ObjectId::Role(_) => unreachable!("roles have no owner"),
3207                }
3208                let object_type = state.get_object_type(&id);
3209                CatalogState::add_to_audit_log(
3210                    &state.system_configuration,
3211                    oracle_write_ts,
3212                    session,
3213                    tx,
3214                    audit_events,
3215                    EventType::Alter,
3216                    object_type_to_audit_object_type(object_type),
3217                    EventDetails::UpdateOwnerV1(mz_audit_log::UpdateOwnerV1 {
3218                        object_id: id.to_string(),
3219                        old_owner_id: old_owner.to_string(),
3220                        new_owner_id: new_owner.to_string(),
3221                    }),
3222                )?;
3223            }
3224            Op::UpdateClusterConfig {
3225                id,
3226                name,
3227                mut config,
3228                reconfiguration_audit,
3229                mut burst_audit,
3230            } => {
3231                let mut cluster = state.get_cluster(id).clone();
3232                // A write that invalidates the in-flight burst (policy removed
3233                // or re-sized, cluster turned off) retires the record here, in
3234                // the same transaction. Retiring at this chokepoint rather
3235                // than in each sequencer path means no writer can forget, so a
3236                // committed config never carries a record it does not warrant.
3237                // Writes that declare a burst intent manage the record
3238                // themselves.
3239                if burst_audit.is_none() {
3240                    if let ClusterVariant::Managed(managed) = &mut config.variant {
3241                        if managed.has_unwarranted_burst_record() {
3242                            managed.burst = None;
3243                            burst_audit = Some(BurstAudit::Finished {
3244                                cause: BurstFinishCause::NoLongerWarranted,
3245                            });
3246                        }
3247                    }
3248                }
3249                // Writes that declare no reconfiguration intent must not move
3250                // the reconfiguration lifecycle, or the audit log would
3251                // silently lose the transition. Writer bug, fails the
3252                // transaction.
3253                if reconfiguration_audit.is_none()
3254                    && Self::reconfiguration_lifecycle_moved(&cluster.config, &config)
3255                {
3256                    return Err(AdapterError::Internal(format!(
3257                        "cluster {name} reconfiguration record moved without a declared \
3258                         audit intent"
3259                    )));
3260                }
3261                // The same contract for the burst lifecycle: a record appearing
3262                // or disappearing without a declared intent would silently lose
3263                // the started/finished audit transition.
3264                if burst_audit.is_none() && Self::burst_lifecycle_moved(&cluster.config, &config) {
3265                    return Err(AdapterError::Internal(format!(
3266                        "cluster {name} burst record moved without a declared audit intent"
3267                    )));
3268                }
3269                let reconfiguration_event = reconfiguration_audit
3270                    .map(|audit| Self::reconfiguration_audit_details(&config, id, &name, audit))
3271                    .transpose()?;
3272                let burst_event = burst_audit
3273                    .map(|audit| {
3274                        Self::burst_audit_details(&cluster.config, &config, id, &name, audit)
3275                    })
3276                    .transpose()?;
3277                cluster.config = config;
3278                tx.update_cluster(id, cluster.into())?;
3279                info!("update cluster {}", name);
3280
3281                CatalogState::add_to_audit_log(
3282                    &state.system_configuration,
3283                    oracle_write_ts,
3284                    session,
3285                    tx,
3286                    audit_events,
3287                    EventType::Alter,
3288                    ObjectType::Cluster,
3289                    EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
3290                        id: id.to_string(),
3291                        name,
3292                    }),
3293                )?;
3294
3295                if let Some(details) = reconfiguration_event {
3296                    CatalogState::add_to_audit_log(
3297                        &state.system_configuration,
3298                        oracle_write_ts,
3299                        session,
3300                        tx,
3301                        audit_events,
3302                        EventType::Alter,
3303                        ObjectType::Cluster,
3304                        EventDetails::AlterClusterReconfigurationV1(details),
3305                    )?;
3306                }
3307
3308                if let Some(details) = burst_event {
3309                    CatalogState::add_to_audit_log(
3310                        &state.system_configuration,
3311                        oracle_write_ts,
3312                        session,
3313                        tx,
3314                        audit_events,
3315                        EventType::Alter,
3316                        ObjectType::Cluster,
3317                        EventDetails::ClusterHydrationBurstV1(details),
3318                    )?;
3319                }
3320            }
3321            Op::UpdateItem { id, name, to_item } => {
3322                // A non-temporary item must not depend on a temporary one.
3323                // Temporary objects are session-scoped and disappear with
3324                // their session, so a longer-lived item referencing one would
3325                // be left with a dangling reference. `Op::CreateItem` enforces
3326                // it; mirror it here so ALTER paths (e.g. ALTER SINK ... SET
3327                // FROM) cannot repoint a persistent item at a temporary one.
3328                if !to_item.is_temporary() {
3329                    if let Some(temp_id) =
3330                        to_item
3331                            .uses()
3332                            .iter()
3333                            .find(|id| match state.try_get_entry(*id) {
3334                                Some(entry) => entry.item().is_temporary(),
3335                                None => temporary_ids.contains(id),
3336                            })
3337                    {
3338                        let temp_item = state.get_entry(temp_id);
3339                        return Err(AdapterError::Catalog(Error::new(
3340                            ErrorKind::InvalidTemporaryDependency(temp_item.name().item.clone()),
3341                        )));
3342                    }
3343                }
3344
3345                let mut entry = state.get_entry(&id).clone();
3346                entry.name = name.clone();
3347                entry.item = to_item.clone();
3348                tx.update_item(id, state.durable_item(entry)?)?;
3349
3350                if Self::should_audit_log_item(&to_item) {
3351                    let mut full_name = Self::full_name_detail(
3352                        &state.resolve_full_name(&name, session.map(|session| session.conn_id())),
3353                    );
3354                    full_name.item = name.item;
3355
3356                    CatalogState::add_to_audit_log(
3357                        &state.system_configuration,
3358                        oracle_write_ts,
3359                        session,
3360                        tx,
3361                        audit_events,
3362                        EventType::Alter,
3363                        catalog_type_to_audit_object_type(to_item.typ()),
3364                        EventDetails::UpdateItemV1(mz_audit_log::UpdateItemV1 {
3365                            id: id.to_string(),
3366                            name: full_name,
3367                        }),
3368                    )?;
3369                }
3370
3371                Self::log_update(state, &id);
3372            }
3373            Op::UpdateSystemConfiguration { name, value } => {
3374                let parsed_value = state.parse_system_configuration(&name, value.borrow())?;
3375                tx.upsert_system_config(&name, parsed_value.clone())?;
3376                // This mirrors some "system vars" into the catalog storage
3377                // "config" collection so that we can toggle the flag with
3378                // Launch Darkly, but use it in boot before Launch Darkly is
3379                // available.
3380                if name == WITH_0DT_DEPLOYMENT_MAX_WAIT.name() {
3381                    let with_0dt_deployment_max_wait =
3382                        Duration::parse(VarInput::Flat(&parsed_value))
3383                            .expect("parsing succeeded above");
3384                    tx.set_0dt_deployment_max_wait(with_0dt_deployment_max_wait)?;
3385                } else if name == WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name() {
3386                    let with_0dt_deployment_ddl_check_interval =
3387                        Duration::parse(VarInput::Flat(&parsed_value))
3388                            .expect("parsing succeeded above");
3389                    tx.set_0dt_deployment_ddl_check_interval(
3390                        with_0dt_deployment_ddl_check_interval,
3391                    )?;
3392                } else if name == ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.name() {
3393                    let panic_after_timeout =
3394                        strconv::parse_bool(&parsed_value).expect("parsing succeeded above");
3395                    tx.set_enable_0dt_deployment_panic_after_timeout(panic_after_timeout)?;
3396                }
3397
3398                CatalogState::add_to_audit_log(
3399                    &state.system_configuration,
3400                    oracle_write_ts,
3401                    session,
3402                    tx,
3403                    audit_events,
3404                    EventType::Alter,
3405                    ObjectType::System,
3406                    EventDetails::SetV1(mz_audit_log::SetV1 {
3407                        name,
3408                        value: Some(value.borrow().to_vec().join(", ")),
3409                    }),
3410                )?;
3411            }
3412            Op::ResetSystemConfiguration { name } => {
3413                tx.remove_system_config(&name);
3414                // This mirrors some "system vars" into the catalog storage
3415                // "config" collection so that we can toggle the flag with
3416                // Launch Darkly, but use it in boot before Launch Darkly is
3417                // available.
3418                if name == WITH_0DT_DEPLOYMENT_MAX_WAIT.name() {
3419                    tx.reset_0dt_deployment_max_wait()?;
3420                } else if name == WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name() {
3421                    tx.reset_0dt_deployment_ddl_check_interval()?;
3422                } else if name == ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.name() {
3423                    tx.reset_enable_0dt_deployment_panic_after_timeout()?;
3424                }
3425
3426                CatalogState::add_to_audit_log(
3427                    &state.system_configuration,
3428                    oracle_write_ts,
3429                    session,
3430                    tx,
3431                    audit_events,
3432                    EventType::Alter,
3433                    ObjectType::System,
3434                    EventDetails::SetV1(mz_audit_log::SetV1 { name, value: None }),
3435                )?;
3436            }
3437            Op::ResetAllSystemConfiguration => {
3438                tx.clear_system_configs();
3439                tx.reset_0dt_deployment_max_wait()?;
3440                tx.reset_0dt_deployment_ddl_check_interval()?;
3441                tx.reset_enable_0dt_deployment_panic_after_timeout()?;
3442
3443                CatalogState::add_to_audit_log(
3444                    &state.system_configuration,
3445                    oracle_write_ts,
3446                    session,
3447                    tx,
3448                    audit_events,
3449                    EventType::Alter,
3450                    ObjectType::System,
3451                    EventDetails::ResetAllV1,
3452                )?;
3453            }
3454            Op::UpdateScopedSystemParameters {
3455                scoped,
3456                prune_scope,
3457            } => {
3458                // Diff `scoped` against the durable cache and persist only the
3459                // delta: upsert changed/added entries, then remove entries the
3460                // update no longer serves. A removal for a still-live object is
3461                // bounded by `prune_scope` so this update does not delete a row
3462                // for an object it was not evaluated for (e.g. one created after
3463                // the update's snapshot, whose override rode its own create
3464                // transaction). Rows whose owning object is no longer live are
3465                // always pruned regardless of `prune_scope`, because nothing else
3466                // garbage collects them and ids are never reused, so this lazily
3467                // reclaims orphans left by dropped objects.
3468                let live_clusters: BTreeSet<ClusterId> =
3469                    tx.get_clusters().map(|cluster| cluster.id).collect();
3470                let live_replicas: BTreeSet<ReplicaId> = tx
3471                    .get_cluster_replicas()
3472                    .map(|replica| replica.replica_id)
3473                    .collect();
3474
3475                // Cluster-coherent scope.
3476                let existing_cluster: BTreeMap<(ClusterId, String), String> = tx
3477                    .get_cluster_system_configurations()
3478                    .map(|c| ((c.cluster_id, c.name), c.value))
3479                    .collect();
3480                let mut desired_cluster: BTreeSet<(ClusterId, String)> = BTreeSet::new();
3481                for (cluster_id, values) in &scoped.cluster {
3482                    if !live_clusters.contains(cluster_id) {
3483                        continue;
3484                    }
3485                    for (name, value) in values {
3486                        desired_cluster.insert((*cluster_id, name.clone()));
3487                        if existing_cluster.get(&(*cluster_id, name.clone())) != Some(value) {
3488                            tx.upsert_cluster_system_config(*cluster_id, name, value.clone())?;
3489                        }
3490                    }
3491                }
3492                for (cluster_id, name) in existing_cluster.into_keys() {
3493                    if (!live_clusters.contains(&cluster_id)
3494                        || prune_scope.clusters.contains(&cluster_id))
3495                        && !desired_cluster.contains(&(cluster_id, name.clone()))
3496                    {
3497                        tx.remove_cluster_system_config(cluster_id, &name);
3498                    }
3499                }
3500
3501                // Replica-local scope.
3502                let existing_replica: BTreeMap<(ReplicaId, String), String> = tx
3503                    .get_replica_system_configurations()
3504                    .map(|r| ((r.replica_id, r.name), r.value))
3505                    .collect();
3506                let mut desired_replica: BTreeSet<(ReplicaId, String)> = BTreeSet::new();
3507                for (replica_id, values) in &scoped.replica {
3508                    if !live_replicas.contains(replica_id) {
3509                        continue;
3510                    }
3511                    for (name, value) in values {
3512                        desired_replica.insert((*replica_id, name.clone()));
3513                        if existing_replica.get(&(*replica_id, name.clone())) != Some(value) {
3514                            tx.upsert_replica_system_config(*replica_id, name, value.clone())?;
3515                        }
3516                    }
3517                }
3518                for (replica_id, name) in existing_replica.into_keys() {
3519                    if (!live_replicas.contains(&replica_id)
3520                        || prune_scope.replicas.contains(&replica_id))
3521                        && !desired_replica.contains(&(replica_id, name.clone()))
3522                    {
3523                        tx.remove_replica_system_config(replica_id, &name);
3524                    }
3525                }
3526            }
3527            Op::InjectAuditEvents { events } => {
3528                for event in events {
3529                    let id = tx.allocate_audit_log_id()?;
3530                    let ev = VersionedEvent::new(
3531                        id,
3532                        event.event_type,
3533                        event.object_type,
3534                        event.details,
3535                        event.user,
3536                        oracle_write_ts.into(),
3537                    );
3538                    audit_events.push(ev.clone());
3539                    tx.insert_audit_log_event(ev);
3540                }
3541            }
3542        };
3543        Ok(())
3544    }
3545
3546    fn log_update(state: &CatalogState, id: &CatalogItemId) {
3547        let entry = state.get_entry(id);
3548        info!(
3549            "update {} {} ({})",
3550            entry.item_type(),
3551            state.resolve_full_name(entry.name(), entry.conn_id()),
3552            id
3553        );
3554    }
3555
3556    /// Update privileges to reflect the new owner. Based off of PostgreSQL's
3557    /// implementation:
3558    /// <https://github.com/postgres/postgres/blob/43a33ef54e503b61f269d088f2623ba3b9484ad7/src/backend/utils/adt/acl.c#L1078-L1177>
3559    fn update_privilege_owners(
3560        privileges: &mut PrivilegeMap,
3561        old_owner: RoleId,
3562        new_owner: RoleId,
3563    ) {
3564        // TODO(jkosh44) Would be nice not to clone every privilege.
3565        let mut flat_privileges: Vec<_> = privileges.all_values_owned().collect();
3566
3567        let mut new_present = false;
3568        for privilege in flat_privileges.iter_mut() {
3569            // Old owner's granted privilege are updated to be granted by the new
3570            // owner.
3571            if privilege.grantor == old_owner {
3572                privilege.grantor = new_owner;
3573            } else if privilege.grantor == new_owner {
3574                new_present = true;
3575            }
3576            // Old owner's privileges is given to the new owner.
3577            if privilege.grantee == old_owner {
3578                privilege.grantee = new_owner;
3579            } else if privilege.grantee == new_owner {
3580                new_present = true;
3581            }
3582        }
3583
3584        // If the old privilege list contained references to the new owner, we may
3585        // have created duplicate entries. Here we try and consolidate them. This
3586        // is inspired by PostgreSQL's algorithm but not identical.
3587        if new_present {
3588            // Group privileges by (grantee, grantor).
3589            let privilege_map: BTreeMap<_, Vec<_>> =
3590                flat_privileges
3591                    .into_iter()
3592                    .fold(BTreeMap::new(), |mut accum, privilege| {
3593                        accum
3594                            .entry((privilege.grantee, privilege.grantor))
3595                            .or_default()
3596                            .push(privilege);
3597                        accum
3598                    });
3599
3600            // Consolidate and update all privileges.
3601            flat_privileges = privilege_map
3602                .into_iter()
3603                .map(|((grantee, grantor), values)|
3604                    // Combine the acl_mode of all mz_aclitems with the same grantee and grantor.
3605                    values.into_iter().fold(
3606                        MzAclItem::empty(grantee, grantor),
3607                        |mut accum, mz_aclitem| {
3608                            accum.acl_mode =
3609                                accum.acl_mode.union(mz_aclitem.acl_mode);
3610                            accum
3611                        },
3612                    ))
3613                .collect();
3614        }
3615
3616        *privileges = PrivilegeMap::from_mz_acl_items(flat_privileges);
3617    }
3618}
3619
3620/// Resolves the session UUID that durably owns a temporary item being
3621/// created. The durable owner is the session that created the item.
3622///
3623/// The connection -> session mapping is registered lazily in
3624/// `catalog_transact_inner`, so we defensively verify that the registered
3625/// mapping matches the creating session.
3626fn temporary_item_owner_session(
3627    state: &CatalogState,
3628    session: Option<&ConnMeta>,
3629    item: &CatalogItem,
3630    item_name: &str,
3631) -> Result<Uuid, AdapterError> {
3632    let session = session.ok_or_else(|| {
3633        AdapterError::Internal("temporary items must have an owner session".to_string())
3634    })?;
3635    let owner_session = session.uuid();
3636    soft_assert_or_log!(
3637        Some(session.conn_id()) == item.conn_id(),
3638        "temporary item connection must match the creating session"
3639    );
3640    if state.temporary_namespaces.uuid_for_conn(session.conn_id()) != Some(owner_session) {
3641        return Err(AdapterError::Internal(format!(
3642            "connection {} has no temporary namespace while creating temporary item {}",
3643            session.conn_id(),
3644            item_name,
3645        )));
3646    }
3647    Ok(owner_session)
3648}
3649
3650/// Prepare the given transaction for replacing a catalog item with a new version.
3651///
3652/// The new version gets a new `CatalogItemId`, which requires rewriting the `create_sql` of all
3653/// dependent objects to refer to that new ID (at a previous version).
3654///
3655/// Note that here is where we break the assumption that the `CatalogItemId` is a stable identifier
3656/// for catalog items. We currently think that there are no use cases that require this assumption,
3657/// but no way to know for sure.
3658fn tx_replace_item(
3659    tx: &mut Transaction<'_>,
3660    state: &CatalogState,
3661    id: CatalogItemId,
3662    new_entry: CatalogEntry,
3663) -> Result<(), AdapterError> {
3664    let new_id = new_entry.id;
3665
3666    // Rewrite dependent objects to point to the new ID.
3667    for use_id in new_entry.referenced_by() {
3668        let dependent = state.get_entry(use_id);
3669
3670        // The dependent might be dropped in the same tx, so check.
3671        if tx.get_item(use_id).is_none() {
3672            continue;
3673        }
3674
3675        let mut dependent = dependent.clone();
3676        dependent.item = dependent.item.replace_item_refs(id, new_id);
3677        tx.update_item(*use_id, state.durable_item(dependent)?)?;
3678    }
3679
3680    // Move comments to the new ID.
3681    let old_comment_id = state.get_comment_id(ObjectId::Item(id));
3682    let new_comment_id = new_entry.comment_object_id();
3683    if let Some(comments) = state.comments.get_object_comments(old_comment_id) {
3684        tx.drop_comments(&[old_comment_id].into())?;
3685        for (sub, comment) in comments {
3686            tx.update_comment(new_comment_id, *sub, Some(comment.clone()))?;
3687        }
3688    }
3689
3690    let mz_catalog::durable::Item {
3691        id: _,
3692        oid,
3693        global_id,
3694        schema_id,
3695        name,
3696        create_sql,
3697        owner_id,
3698        privileges,
3699        extra_versions,
3700        ephemeral_owner_session,
3701    } = state.durable_item(new_entry)?;
3702
3703    tx.remove_item(id)?;
3704    tx.insert_item(
3705        new_id,
3706        oid,
3707        global_id,
3708        schema_id,
3709        &name,
3710        create_sql,
3711        owner_id,
3712        privileges,
3713        extra_versions,
3714        ephemeral_owner_session,
3715    )?;
3716
3717    Ok(())
3718}
3719
3720/// Generate audit events for a replacement apply operation.
3721fn apply_replacement_audit_events(
3722    state: &CatalogState,
3723    target: &CatalogEntry,
3724    replacement: &CatalogEntry,
3725) -> Vec<(EventType, EventDetails)> {
3726    let mut events = Vec::new();
3727
3728    let target_name = state.resolve_full_name(target.name(), target.conn_id());
3729    let target_id_name = IdFullNameV1 {
3730        id: target.id().to_string(),
3731        name: Catalog::full_name_detail(&target_name),
3732    };
3733    let replacement_name = state.resolve_full_name(replacement.name(), replacement.conn_id());
3734    let replacement_id_name = IdFullNameV1 {
3735        id: replacement.id().to_string(),
3736        name: Catalog::full_name_detail(&replacement_name),
3737    };
3738
3739    if Catalog::should_audit_log_item(&replacement.item) {
3740        events.push((
3741            EventType::Drop,
3742            EventDetails::IdFullNameV1(replacement_id_name.clone()),
3743        ));
3744    }
3745
3746    if Catalog::should_audit_log_item(&target.item) {
3747        events.push((
3748            EventType::Alter,
3749            EventDetails::AlterApplyReplacementV1(mz_audit_log::AlterApplyReplacementV1 {
3750                target: target_id_name.clone(),
3751                replacement: replacement_id_name,
3752            }),
3753        ));
3754
3755        if let Some(old_cluster_id) = target.cluster_id()
3756            && let Some(new_cluster_id) = replacement.cluster_id()
3757            && old_cluster_id != new_cluster_id
3758        {
3759            // When the replacement is applied, the target takes on the ID of the replacement, so
3760            // we should use that ID for subsequent events.
3761            events.push((
3762                EventType::Alter,
3763                EventDetails::AlterSetClusterV1(mz_audit_log::AlterSetClusterV1 {
3764                    id: replacement.id().to_string(),
3765                    name: target_id_name.name,
3766                    old_cluster_id: old_cluster_id.to_string(),
3767                    new_cluster_id: new_cluster_id.to_string(),
3768                }),
3769            ));
3770        }
3771    }
3772
3773    events
3774}
3775
3776/// All of the objects that need to be removed in response to an [`Op::DropObjects`].
3777///
3778/// Note: Previously we used to omit a single `Op::DropObject` for every object
3779/// we needed to drop. But removing a batch of objects from a durable Catalog
3780/// Transaction is O(n) where `n` is the number of objects that exist in the
3781/// Catalog. This resulted in an unacceptable `O(m * n)` performance for a
3782/// `DROP ... CASCADE` statement.
3783#[derive(Debug, Default)]
3784pub(crate) struct ObjectsToDrop {
3785    pub comments: BTreeSet<CommentObjectId>,
3786    pub databases: BTreeSet<DatabaseId>,
3787    pub schemas: BTreeMap<SchemaSpecifier, ResolvedDatabaseSpecifier>,
3788    pub clusters: BTreeSet<ClusterId>,
3789    pub replicas: BTreeMap<ReplicaId, (ClusterId, ReplicaCreateDropReason)>,
3790    pub roles: BTreeSet<RoleId>,
3791    pub items: Vec<CatalogItemId>,
3792    pub network_policies: BTreeSet<NetworkPolicyId>,
3793    pub query_policies: BTreeSet<QueryPolicyId>,
3794}
3795
3796impl ObjectsToDrop {
3797    pub fn generate(
3798        drop_object_infos: impl IntoIterator<Item = DropObjectInfo>,
3799        state: &CatalogState,
3800        session: Option<&ConnMeta>,
3801    ) -> Result<Self, AdapterError> {
3802        let mut delta = ObjectsToDrop::default();
3803
3804        for drop_object_info in drop_object_infos {
3805            delta.add_item(drop_object_info, state, session)?;
3806        }
3807
3808        Ok(delta)
3809    }
3810
3811    fn add_item(
3812        &mut self,
3813        drop_object_info: DropObjectInfo,
3814        state: &CatalogState,
3815        session: Option<&ConnMeta>,
3816    ) -> Result<(), AdapterError> {
3817        self.comments
3818            .insert(state.get_comment_id(drop_object_info.to_object_id()));
3819
3820        match drop_object_info {
3821            DropObjectInfo::Database(database_id) => {
3822                let database = &state.database_by_id[&database_id];
3823                if database_id.is_system() {
3824                    return Err(AdapterError::Catalog(Error::new(
3825                        ErrorKind::ReadOnlyDatabase(database.name().to_string()),
3826                    )));
3827                }
3828
3829                self.databases.insert(database_id);
3830            }
3831            DropObjectInfo::Schema((database_spec, schema_spec)) => {
3832                let schema = state.get_schema(
3833                    &database_spec,
3834                    &schema_spec,
3835                    session
3836                        .map(|session| session.conn_id())
3837                        .unwrap_or(&SYSTEM_CONN_ID),
3838                );
3839                let schema_id: SchemaId = schema_spec.into();
3840                if schema_id.is_system() {
3841                    let name = schema.name();
3842                    let full_name = state.resolve_full_schema_name(name);
3843                    return Err(AdapterError::Catalog(Error::new(
3844                        ErrorKind::ReadOnlySystemSchema(full_name.to_string()),
3845                    )));
3846                }
3847
3848                self.schemas.insert(schema_spec, database_spec);
3849            }
3850            DropObjectInfo::Role(role_id) => {
3851                let name = state.get_role(&role_id).name().to_string();
3852                if role_id.is_system() || role_id.is_predefined() {
3853                    return Err(AdapterError::Catalog(Error::new(
3854                        ErrorKind::ReservedRoleName(name.clone()),
3855                    )));
3856                }
3857                state.ensure_not_reserved_role(&role_id)?;
3858
3859                self.roles.insert(role_id);
3860            }
3861            DropObjectInfo::Cluster(cluster_id) => {
3862                let cluster = state.get_cluster(cluster_id);
3863                let name = &cluster.name;
3864                if cluster_id.is_system() {
3865                    return Err(AdapterError::Catalog(Error::new(
3866                        ErrorKind::ReadOnlyCluster(name.clone()),
3867                    )));
3868                }
3869
3870                self.clusters.insert(cluster_id);
3871            }
3872            DropObjectInfo::ClusterReplica((cluster_id, replica_id, reason)) => {
3873                let cluster = state.get_cluster(cluster_id);
3874                let replica = cluster.replica(replica_id).expect("Must exist");
3875
3876                self.replicas
3877                    .insert(replica.replica_id, (cluster.id, reason));
3878
3879                // Implicitly drop materialized views that target this replica.
3880                // When the target replica is gone, no replica advances the
3881                // persist shard's upper frontier, causing reads to hang. Cascade
3882                // to anything depending on the implicitly-dropped MV so we don't
3883                // leave dangling references in the catalog.
3884                //
3885                // Plan-driven drops already include these dependents as their
3886                // own `DropObjectInfo::Item` entries (the plan stage expands
3887                // them via `cluster_replica_dependents`), so each one's comment
3888                // is recorded by the top-of-function `self.comments` insert.
3889                // This branch handles internal callers that build
3890                // `Op::DropObjects` directly with only the replica, so we expand
3891                // the dependents and record their comments ourselves.
3892                //
3893                // `seen` is seeded from the items already collected so that the
3894                // plan-driven path (where the dependents are processed before
3895                // the replica, in reverse-dependency order) does not re-add them
3896                // here.
3897                let mut seen: BTreeSet<ObjectId> =
3898                    self.items.iter().copied().map(ObjectId::Item).collect();
3899                for dep in state.cluster_replica_dependents(cluster_id, replica_id, &mut seen) {
3900                    if let ObjectId::Item(dep_id) = dep {
3901                        info!(
3902                            "implicitly dropping {} because target replica was dropped",
3903                            state.get_entry(&dep_id).name().item,
3904                        );
3905                        self.comments
3906                            .insert(state.get_comment_id(ObjectId::Item(dep_id)));
3907                        self.items.push(dep_id);
3908                    }
3909                }
3910            }
3911            DropObjectInfo::Item(item_id) => {
3912                let entry = state.get_entry(&item_id);
3913                if item_id.is_system() {
3914                    let name = entry.name();
3915                    let full_name =
3916                        state.resolve_full_name(name, session.map(|session| session.conn_id()));
3917                    return Err(AdapterError::Catalog(Error::new(ErrorKind::ReadOnlyItem(
3918                        full_name.to_string(),
3919                    ))));
3920                }
3921
3922                self.items.push(item_id);
3923            }
3924            DropObjectInfo::NetworkPolicy(network_policy_id) => {
3925                let policy = state.get_network_policy(&network_policy_id);
3926                let name = &policy.name;
3927                if network_policy_id.is_system() {
3928                    return Err(AdapterError::Catalog(Error::new(
3929                        ErrorKind::ReadOnlyNetworkPolicy(name.clone()),
3930                    )));
3931                }
3932
3933                self.network_policies.insert(network_policy_id);
3934            }
3935            DropObjectInfo::QueryPolicy(id) => {
3936                let policy = state.get_query_policy(&id);
3937                if id.is_system() {
3938                    return Err(AdapterError::Catalog(Error::new(
3939                        ErrorKind::ReadOnlyQueryPolicy(policy.name.clone()),
3940                    )));
3941                }
3942                self.query_policies.insert(id);
3943            }
3944        }
3945
3946        Ok(())
3947    }
3948}
3949
3950#[cfg(test)]
3951mod tests {
3952    use std::sync::{Arc, Mutex};
3953
3954    use mz_catalog::SYSTEM_CONN_ID;
3955    use mz_catalog::memory::objects::{CatalogItem, Table, TableDataSource};
3956    use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem, PrivilegeMap};
3957    use mz_repr::role_id::RoleId;
3958    use mz_repr::{RelationDesc, RelationVersion, VersionedRelationDesc};
3959    use mz_sql::DEFAULT_SCHEMA;
3960    use mz_sql::catalog::CatalogDatabase;
3961    use mz_sql::names::{
3962        ItemQualifiers, QualifiedItemName, ResolvedDatabaseSpecifier, ResolvedIds,
3963    };
3964    use mz_sql::session::user::MZ_SYSTEM_ROLE_ID;
3965    use mz_sql::session::vars::{MAX_CONNECTIONS, OwnedVarInput, SystemVars};
3966
3967    use crate::catalog::{Catalog, Op};
3968    use crate::session::DEFAULT_DATABASE_NAME;
3969
3970    #[mz_ore::test]
3971    fn test_reconfiguration_audit_details() {
3972        use std::time::Duration;
3973
3974        use mz_adapter_types::cluster_state::ReconfigurationAudit;
3975        use mz_audit_log::ReconfigurationLifecycleV1;
3976        use mz_catalog::memory::objects::{
3977            ClusterConfig, ClusterVariant, ClusterVariantManaged, ReconfigurationState,
3978            ReconfigurationStatus, ReconfigurationTarget,
3979        };
3980        use mz_controller::clusters::ReplicaLogging;
3981        use mz_controller_types::ClusterId;
3982        use mz_repr::Timestamp;
3983        use mz_repr::optimize::OptimizerFeatureOverrides;
3984
3985        let cluster_id = ClusterId::user(1).expect("valid id");
3986        let logging = ReplicaLogging {
3987            log_logging: false,
3988            interval: None,
3989        };
3990        let managed = |reconfiguration: Option<ReconfigurationState>| ClusterConfig {
3991            variant: ClusterVariant::Managed(ClusterVariantManaged {
3992                size: "small".into(),
3993                availability_zones: Vec::new(),
3994                logging: logging.clone(),
3995                arrangement_compression: false,
3996                replication_factor: 1,
3997                optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
3998                schedule: Default::default(),
3999                auto_scaling_strategy: None,
4000                reconfiguration,
4001                burst: None,
4002            }),
4003            workload_class: None,
4004            query_policy: None,
4005        };
4006        let record = |status| ReconfigurationState {
4007            target: ReconfigurationTarget {
4008                size: "large".into(),
4009                replication_factor: 2,
4010                availability_zones: vec!["az1".into(), "az2".into()],
4011                logging: ReplicaLogging {
4012                    log_logging: true,
4013                    interval: Some(Duration::from_secs(5)),
4014                },
4015                arrangement_compression: false,
4016            },
4017            deadline: Timestamp::from(400u64),
4018            on_timeout: mz_sql::plan::OnTimeoutAction::Rollback,
4019            status,
4020        };
4021
4022        let details = Catalog::reconfiguration_audit_details(
4023            &managed(Some(record(ReconfigurationStatus::InProgress))),
4024            cluster_id,
4025            "c",
4026            ReconfigurationAudit::Started,
4027        )
4028        .expect("record supplies audit details");
4029        assert_eq!(details.cluster_id, cluster_id.to_string());
4030        assert_eq!(details.cluster_name, "c");
4031        assert_eq!(details.transition, ReconfigurationLifecycleV1::Started);
4032        assert_eq!(details.forced, None);
4033        assert_eq!(details.target_size, "large");
4034        assert_eq!(details.target_replication_factor, 2);
4035        assert_eq!(
4036            details.target_availability_zones,
4037            vec!["az1".to_string(), "az2".to_string()]
4038        );
4039        assert_eq!(details.target_logging.log_logging, true);
4040        assert_eq!(
4041            details.target_logging.interval,
4042            Some(Duration::from_secs(5))
4043        );
4044        assert_eq!(details.deadline, Some(400));
4045
4046        // The `forced` bit exists only on the intent. The durable status reads
4047        // `Finalized` for both a hydrated and a forced cut-over, and the event
4048        // preserves the distinction.
4049        let forced = Catalog::reconfiguration_audit_details(
4050            &managed(Some(record(ReconfigurationStatus::Finalized))),
4051            cluster_id,
4052            "c",
4053            ReconfigurationAudit::Finalized { forced: true },
4054        )
4055        .expect("a coherent finalize supplies audit details");
4056        assert_eq!(forced.transition, ReconfigurationLifecycleV1::Finalized);
4057        assert_eq!(forced.forced, Some(true));
4058
4059        // A declared transition that contradicts the written record's status is
4060        // a writer bug and must fail the transaction.
4061        let incoherent = Catalog::reconfiguration_audit_details(
4062            &managed(Some(record(ReconfigurationStatus::TimedOut))),
4063            cluster_id,
4064            "c",
4065            ReconfigurationAudit::ResourceExhausted,
4066        );
4067        assert!(incoherent.is_err());
4068
4069        let missing = Catalog::reconfiguration_audit_details(
4070            &managed(None),
4071            cluster_id,
4072            "c",
4073            ReconfigurationAudit::Started,
4074        );
4075        assert!(missing.is_err());
4076    }
4077
4078    #[mz_ore::test]
4079    fn test_reconfiguration_lifecycle_moved() {
4080        use std::time::Duration;
4081
4082        use mz_catalog::memory::objects::{
4083            ClusterConfig, ClusterVariant, ClusterVariantManaged, ReconfigurationState,
4084            ReconfigurationStatus, ReconfigurationTarget,
4085        };
4086        use mz_controller::clusters::ReplicaLogging;
4087        use mz_repr::Timestamp;
4088        use mz_repr::optimize::OptimizerFeatureOverrides;
4089
4090        let managed = |reconfiguration: Option<ReconfigurationState>| ClusterConfig {
4091            variant: ClusterVariant::Managed(ClusterVariantManaged {
4092                size: "small".into(),
4093                availability_zones: Vec::new(),
4094                logging: ReplicaLogging {
4095                    log_logging: false,
4096                    interval: None,
4097                },
4098                arrangement_compression: false,
4099                replication_factor: 1,
4100                optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4101                schedule: Default::default(),
4102                auto_scaling_strategy: None,
4103                reconfiguration,
4104                burst: None,
4105            }),
4106            workload_class: None,
4107            query_policy: None,
4108        };
4109        let unmanaged = ClusterConfig {
4110            variant: ClusterVariant::Unmanaged,
4111            workload_class: None,
4112            query_policy: None,
4113        };
4114        let record = |status| ReconfigurationState {
4115            target: ReconfigurationTarget {
4116                size: "large".into(),
4117                replication_factor: 2,
4118                availability_zones: Vec::new(),
4119                logging: ReplicaLogging {
4120                    log_logging: false,
4121                    interval: Some(Duration::from_secs(1)),
4122                },
4123                arrangement_compression: false,
4124            },
4125            deadline: Timestamp::from(400u64),
4126            on_timeout: mz_sql::plan::OnTimeoutAction::Rollback,
4127            status,
4128        };
4129
4130        // Lifecycle movements: these writes must declare an audit intent.
4131        // A fresh record appears.
4132        assert!(Catalog::reconfiguration_lifecycle_moved(
4133            &managed(None),
4134            &managed(Some(record(ReconfigurationStatus::InProgress))),
4135        ));
4136        // The status changes.
4137        assert!(Catalog::reconfiguration_lifecycle_moved(
4138            &managed(Some(record(ReconfigurationStatus::InProgress))),
4139            &managed(Some(record(ReconfigurationStatus::Finalized))),
4140        ));
4141        // An in-progress record is dropped, e.g. by converting the cluster to
4142        // unmanaged (which the sequencer refuses, and this guard backstops).
4143        assert!(Catalog::reconfiguration_lifecycle_moved(
4144            &managed(Some(record(ReconfigurationStatus::InProgress))),
4145            &unmanaged,
4146        ));
4147
4148        // Not movements: no record at all, a status-preserving copy (a write
4149        // that carries the record forward), and dropping a settled record.
4150        assert!(!Catalog::reconfiguration_lifecycle_moved(
4151            &managed(None),
4152            &managed(None),
4153        ));
4154        assert!(!Catalog::reconfiguration_lifecycle_moved(
4155            &managed(Some(record(ReconfigurationStatus::InProgress))),
4156            &managed(Some(record(ReconfigurationStatus::InProgress))),
4157        ));
4158        assert!(!Catalog::reconfiguration_lifecycle_moved(
4159            &managed(Some(record(ReconfigurationStatus::Cancelled))),
4160            &unmanaged,
4161        ));
4162    }
4163
4164    #[mz_ore::test]
4165    fn test_burst_lifecycle_moved() {
4166        use std::time::Duration;
4167
4168        use mz_catalog::memory::objects::{
4169            BurstState, ClusterConfig, ClusterVariant, ClusterVariantManaged,
4170        };
4171        use mz_controller::clusters::ReplicaLogging;
4172        use mz_repr::Timestamp;
4173        use mz_repr::optimize::OptimizerFeatureOverrides;
4174
4175        let managed = |burst: Option<BurstState>| ClusterConfig {
4176            variant: ClusterVariant::Managed(ClusterVariantManaged {
4177                size: "small".into(),
4178                availability_zones: Vec::new(),
4179                logging: ReplicaLogging {
4180                    log_logging: false,
4181                    interval: None,
4182                },
4183                arrangement_compression: false,
4184                replication_factor: 1,
4185                optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4186                schedule: Default::default(),
4187                auto_scaling_strategy: None,
4188                reconfiguration: None,
4189                burst,
4190            }),
4191            workload_class: None,
4192            query_policy: None,
4193        };
4194        let unmanaged = ClusterConfig {
4195            variant: ClusterVariant::Unmanaged,
4196            workload_class: None,
4197            query_policy: None,
4198        };
4199        let record = |steady_ready_at| BurstState {
4200            burst_size: "large".into(),
4201            linger_duration: Duration::from_secs(60),
4202            steady_ready_at,
4203        };
4204
4205        // Lifecycle movements: these writes must declare an audit intent.
4206        // A fresh record appears.
4207        assert!(Catalog::burst_lifecycle_moved(
4208            &managed(None),
4209            &managed(Some(record(None))),
4210        ));
4211        // The record is cleared.
4212        assert!(Catalog::burst_lifecycle_moved(
4213            &managed(Some(record(None))),
4214            &managed(None),
4215        ));
4216        // The record is dropped by converting the cluster to unmanaged (which
4217        // the sequencer refuses, and this guard backstops).
4218        assert!(Catalog::burst_lifecycle_moved(
4219            &managed(Some(record(None))),
4220            &unmanaged,
4221        ));
4222
4223        // Not movements: no record at all, and the bookkeeping rewrites (the
4224        // hydration stamp and its reset) that keep the record present.
4225        assert!(!Catalog::burst_lifecycle_moved(
4226            &managed(None),
4227            &managed(None)
4228        ));
4229        assert!(!Catalog::burst_lifecycle_moved(
4230            &managed(Some(record(None))),
4231            &managed(Some(record(Some(Timestamp::from(100u64))))),
4232        ));
4233        assert!(!Catalog::burst_lifecycle_moved(
4234            &managed(Some(record(Some(Timestamp::from(100u64))))),
4235            &managed(Some(record(None))),
4236        ));
4237    }
4238
4239    #[mz_ore::test]
4240    fn test_has_unwarranted_burst_record() {
4241        use std::time::Duration;
4242
4243        use mz_catalog::memory::objects::{BurstState, ClusterVariantManaged};
4244        use mz_controller::clusters::ReplicaLogging;
4245        use mz_repr::optimize::OptimizerFeatureOverrides;
4246        use mz_sql::plan::{AutoScalingStrategy, OnHydration};
4247
4248        let managed = |replication_factor: u32,
4249                       strategy: Option<AutoScalingStrategy>,
4250                       burst: Option<BurstState>| ClusterVariantManaged {
4251            size: "small".into(),
4252            availability_zones: Vec::new(),
4253            logging: ReplicaLogging {
4254                log_logging: false,
4255                interval: None,
4256            },
4257            arrangement_compression: false,
4258            replication_factor,
4259            optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4260            schedule: Default::default(),
4261            auto_scaling_strategy: strategy,
4262            reconfiguration: None,
4263            burst,
4264        };
4265        let policy = |hydration_size: &str| AutoScalingStrategy {
4266            on_hydration: Some(OnHydration {
4267                hydration_size: hydration_size.into(),
4268                linger_duration: None,
4269            }),
4270        };
4271        let record = || BurstState {
4272            burst_size: "large".into(),
4273            linger_duration: Duration::from_secs(60),
4274            steady_ready_at: None,
4275        };
4276
4277        // No record: nothing to retire, with or without a policy.
4278        assert!(!managed(1, None, None).has_unwarranted_burst_record());
4279        assert!(!managed(1, Some(policy("large")), None).has_unwarranted_burst_record());
4280
4281        // A record backed by a matching, active policy is warranted.
4282        assert!(!managed(1, Some(policy("large")), Some(record())).has_unwarranted_burst_record());
4283
4284        // Unwarranted: policy removed, policy re-sized, or cluster turned off.
4285        assert!(managed(1, None, Some(record())).has_unwarranted_burst_record());
4286        assert!(
4287            managed(
4288                1,
4289                Some(AutoScalingStrategy { on_hydration: None }),
4290                Some(record())
4291            )
4292            .has_unwarranted_burst_record()
4293        );
4294        assert!(managed(1, Some(policy("xlarge")), Some(record())).has_unwarranted_burst_record());
4295        assert!(managed(0, Some(policy("large")), Some(record())).has_unwarranted_burst_record());
4296    }
4297
4298    #[mz_ore::test]
4299    fn test_replica_create_drop_reason_into_audit_log() {
4300        use std::time::Duration;
4301
4302        use mz_audit_log::{CreateOrDropClusterReplicaReasonV1, SchedulingDecisionV1};
4303        use mz_cluster_controller::ctx::RefreshWindowDecision;
4304        use mz_repr::GlobalId;
4305
4306        use crate::catalog::ReplicaCreateDropReason;
4307
4308        // `OnRefresh` audits the `schedule` word and converts the controller's
4309        // window decision into the `scheduling_policies` detail blob: ids as
4310        // strings, the hydration-time estimate as an interval string, and the
4311        // decision hardcoded `on` (the controller produces a create, and so
4312        // this detail, only for an open window).
4313        let (reason, scheduling_policies) =
4314            ReplicaCreateDropReason::OnRefresh(RefreshWindowDecision {
4315                objects_needing_refresh: vec![GlobalId::User(1)],
4316                objects_needing_compaction: vec![GlobalId::User(2), GlobalId::User(3)],
4317                hydration_time_estimate: Duration::from_secs(995),
4318            })
4319            .into_audit_log();
4320        assert_eq!(reason, CreateOrDropClusterReplicaReasonV1::Schedule);
4321        let blob = scheduling_policies.expect("on-refresh create carries the detail");
4322        assert_eq!(blob.on_refresh.decision, SchedulingDecisionV1::On);
4323        assert_eq!(blob.on_refresh.objects_needing_refresh, vec!["u1"]);
4324        assert_eq!(blob.on_refresh.objects_needing_compaction, vec!["u2", "u3"]);
4325        assert_eq!(blob.on_refresh.hydration_time_estimate, "00:16:35");
4326
4327        // `Retired` is the uniform word for every controller drop, with no
4328        // blob.
4329        let (reason, scheduling_policies) = ReplicaCreateDropReason::Retired.into_audit_log();
4330        assert_eq!(reason, CreateOrDropClusterReplicaReasonV1::Retired);
4331        assert!(scheduling_policies.is_none());
4332    }
4333
4334    #[mz_ore::test]
4335    fn test_burst_audit_details() {
4336        use std::time::Duration;
4337
4338        use mz_adapter_types::cluster_state::{BurstAudit, BurstFinishCause};
4339        use mz_audit_log::{BurstFinishCauseV1, HydrationBurstLifecycleV1};
4340        use mz_catalog::memory::objects::{
4341            BurstState, ClusterConfig, ClusterVariant, ClusterVariantManaged,
4342        };
4343        use mz_controller::clusters::ReplicaLogging;
4344        use mz_controller_types::ClusterId;
4345        use mz_repr::optimize::OptimizerFeatureOverrides;
4346
4347        let cluster_id = ClusterId::user(1).expect("valid id");
4348        let managed = |burst: Option<BurstState>| ClusterConfig {
4349            variant: ClusterVariant::Managed(ClusterVariantManaged {
4350                size: "small".into(),
4351                availability_zones: Vec::new(),
4352                logging: ReplicaLogging {
4353                    log_logging: false,
4354                    interval: None,
4355                },
4356                arrangement_compression: false,
4357                replication_factor: 1,
4358                optimizer_feature_overrides: OptimizerFeatureOverrides::default(),
4359                schedule: Default::default(),
4360                auto_scaling_strategy: None,
4361                reconfiguration: None,
4362                burst,
4363            }),
4364            workload_class: None,
4365            query_policy: None,
4366        };
4367        let record = || BurstState {
4368            burst_size: "large".into(),
4369            linger_duration: Duration::from_secs(60),
4370            steady_ready_at: None,
4371        };
4372
4373        // A started intent reads the armed record from the new config.
4374        let started = Catalog::burst_audit_details(
4375            &managed(None),
4376            &managed(Some(record())),
4377            cluster_id,
4378            "c",
4379            BurstAudit::Started,
4380        )
4381        .expect("armed record supplies audit details");
4382        assert_eq!(started.transition, HydrationBurstLifecycleV1::Started);
4383        assert_eq!(started.finish_cause, None);
4384        assert_eq!(started.burst_size, "large");
4385
4386        // A finished intent reads the cleared record from the old config and
4387        // carries the writer-declared cause.
4388        let finished = Catalog::burst_audit_details(
4389            &managed(Some(record())),
4390            &managed(None),
4391            cluster_id,
4392            "c",
4393            BurstAudit::Finished {
4394                cause: BurstFinishCause::LingerElapsed,
4395            },
4396        )
4397        .expect("cleared record supplies audit details");
4398        assert_eq!(finished.transition, HydrationBurstLifecycleV1::Finished);
4399        assert_eq!(
4400            finished.finish_cause,
4401            Some(BurstFinishCauseV1::LingerElapsed)
4402        );
4403        assert_eq!(finished.burst_size, "large");
4404
4405        // An intent without a record on the corresponding side contradicts the
4406        // write and must fail the transaction.
4407        let incoherent = Catalog::burst_audit_details(
4408            &managed(None),
4409            &managed(None),
4410            cluster_id,
4411            "c",
4412            BurstAudit::Started,
4413        );
4414        assert!(incoherent.is_err());
4415    }
4416
4417    #[mz_ore::test]
4418    fn test_update_privilege_owners() {
4419        let old_owner = RoleId::User(1);
4420        let new_owner = RoleId::User(2);
4421        let other_role = RoleId::User(3);
4422
4423        // older owner exists as grantor.
4424        let mut privileges = PrivilegeMap::from_mz_acl_items(vec![
4425            MzAclItem {
4426                grantee: other_role,
4427                grantor: old_owner,
4428                acl_mode: AclMode::UPDATE,
4429            },
4430            MzAclItem {
4431                grantee: other_role,
4432                grantor: new_owner,
4433                acl_mode: AclMode::SELECT,
4434            },
4435        ]);
4436        Catalog::update_privilege_owners(&mut privileges, old_owner, new_owner);
4437        assert_eq!(1, privileges.all_values().count());
4438        assert_eq!(
4439            vec![MzAclItem {
4440                grantee: other_role,
4441                grantor: new_owner,
4442                acl_mode: AclMode::SELECT.union(AclMode::UPDATE)
4443            }],
4444            privileges.all_values_owned().collect::<Vec<_>>()
4445        );
4446
4447        // older owner exists as grantee.
4448        let mut privileges = PrivilegeMap::from_mz_acl_items(vec![
4449            MzAclItem {
4450                grantee: old_owner,
4451                grantor: other_role,
4452                acl_mode: AclMode::UPDATE,
4453            },
4454            MzAclItem {
4455                grantee: new_owner,
4456                grantor: other_role,
4457                acl_mode: AclMode::SELECT,
4458            },
4459        ]);
4460        Catalog::update_privilege_owners(&mut privileges, old_owner, new_owner);
4461        assert_eq!(1, privileges.all_values().count());
4462        assert_eq!(
4463            vec![MzAclItem {
4464                grantee: new_owner,
4465                grantor: other_role,
4466                acl_mode: AclMode::SELECT.union(AclMode::UPDATE)
4467            }],
4468            privileges.all_values_owned().collect::<Vec<_>>()
4469        );
4470
4471        // older owner exists as grantee and grantor.
4472        let mut privileges = PrivilegeMap::from_mz_acl_items(vec![
4473            MzAclItem {
4474                grantee: old_owner,
4475                grantor: old_owner,
4476                acl_mode: AclMode::UPDATE,
4477            },
4478            MzAclItem {
4479                grantee: new_owner,
4480                grantor: new_owner,
4481                acl_mode: AclMode::SELECT,
4482            },
4483        ]);
4484        Catalog::update_privilege_owners(&mut privileges, old_owner, new_owner);
4485        assert_eq!(1, privileges.all_values().count());
4486        assert_eq!(
4487            vec![MzAclItem {
4488                grantee: new_owner,
4489                grantor: new_owner,
4490                acl_mode: AclMode::SELECT.union(AclMode::UPDATE)
4491            }],
4492            privileges.all_values_owned().collect::<Vec<_>>()
4493        );
4494    }
4495
4496    #[mz_ore::test(tokio::test)]
4497    #[cfg_attr(miri, ignore)]
4498    async fn test_ddl_snapshot_survives_intervening_commit() {
4499        Catalog::with_debug(|mut catalog| async move {
4500            let name = "ddl_snapshot_database";
4501            let create = || Op::CreateDatabase {
4502                name: name.to_string(),
4503                owner_id: MZ_SYSTEM_ROLE_ID,
4504            };
4505            let (base, snapshot) = catalog.ddl_transaction_snapshot().await;
4506            let ts = catalog.current_upper().await;
4507            catalog
4508                .transact(None, ts, None, vec![create()])
4509                .await
4510                .expect("commit concurrent database");
4511            let (candidate, _) = catalog
4512                .transact_incremental_dry_run(&base, vec![create()], None, Some(snapshot), ts)
4513                .await
4514                .expect("speculative creation uses the captured durable baseline");
4515            assert!(!base.database_by_name.contains_key(name));
4516            assert!(candidate.database_by_name.contains_key(name));
4517            assert!(catalog.state().database_by_name.contains_key(name));
4518            catalog.expire().await;
4519        })
4520        .await
4521    }
4522
4523    /// Verifies that `transact_incremental_dry_run` processes only new ops
4524    /// against the accumulated state, not all ops from scratch. Two paths are
4525    /// compared:
4526    ///   - Incremental: two separate calls, each with one op
4527    ///   - All-at-once: one call with both ops
4528    /// Both must produce equivalent catalog state.
4529    #[mz_ore::test(tokio::test)]
4530    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
4531    async fn test_transact_incremental_dry_run_processes_only_new_ops() {
4532        Catalog::with_debug(|catalog| async move {
4533            // Resolve default database and schema.
4534            let database = catalog
4535                .resolve_database(DEFAULT_DATABASE_NAME)
4536                .expect("default database");
4537            let database_name = database.name.clone();
4538            let database_spec = ResolvedDatabaseSpecifier::Id(database.id());
4539            let schema = catalog
4540                .resolve_schema_in_database(&database_spec, DEFAULT_SCHEMA, &SYSTEM_CONN_ID)
4541                .expect("default schema");
4542            let schema_name = schema.name.schema.clone();
4543            let schema_spec = schema.id.clone();
4544
4545            // Allocate IDs for two tables.
4546            let (id_t1, global_id_t1) = catalog
4547                .allocate_user_id_for_test()
4548                .await
4549                .expect("allocate id for t1");
4550            let (id_t2, global_id_t2) = catalog
4551                .allocate_user_id_for_test()
4552                .await
4553                .expect("allocate id for t2");
4554
4555            let oracle_write_ts = catalog.current_upper().await;
4556
4557            // Build two CreateItem ops.
4558            let make_table_op = |id, global_id, name: &str| Op::CreateItem {
4559                id,
4560                name: QualifiedItemName {
4561                    qualifiers: ItemQualifiers {
4562                        database_spec: database_spec.clone(),
4563                        schema_spec: schema_spec.clone(),
4564                    },
4565                    item: name.to_string(),
4566                },
4567                item: CatalogItem::Table(Table {
4568                    create_sql: Some(format!(
4569                        "CREATE TABLE {database_name}.{schema_name}.{name} ()"
4570                    )),
4571                    desc: VersionedRelationDesc::new(RelationDesc::empty()),
4572                    collections: [(RelationVersion::root(), global_id)].into_iter().collect(),
4573                    conn_id: None,
4574                    resolved_ids: ResolvedIds::empty(),
4575                    custom_logical_compaction_window: None,
4576                    is_retained_metrics_object: false,
4577                    data_source: TableDataSource::TableWrites { defaults: vec![] },
4578                }),
4579                owner_id: MZ_SYSTEM_ROLE_ID,
4580            };
4581
4582            let op_t1 = make_table_op(id_t1, global_id_t1, "t1");
4583            let op_t2 = make_table_op(id_t2, global_id_t2, "t2");
4584
4585            let base_state = catalog.state().clone();
4586
4587            // --- Path A: Incremental (two separate dry-run calls) ---
4588
4589            // First call: only op_t1, no previous snapshot.
4590            let (state_after_t1, snapshot_after_t1) = catalog
4591                .transact_incremental_dry_run(
4592                    &base_state,
4593                    vec![op_t1.clone()],
4594                    None,
4595                    None,
4596                    oracle_write_ts,
4597                )
4598                .await
4599                .expect("first dry run");
4600
4601            // After first dry run: t1 exists, t2 does not.
4602            assert!(
4603                state_after_t1.try_get_entry(&id_t1).is_some(),
4604                "t1 should exist after first dry run"
4605            );
4606            assert_eq!(
4607                state_after_t1
4608                    .try_get_entry(&id_t1)
4609                    .expect("t1 entry")
4610                    .name()
4611                    .item,
4612                "t1"
4613            );
4614            assert!(
4615                state_after_t1.try_get_entry(&id_t2).is_none(),
4616                "t2 should NOT exist after first dry run"
4617            );
4618
4619            // Second call: only op_t2, using state/snapshot from first call.
4620            let (state_incremental, _) = catalog
4621                .transact_incremental_dry_run(
4622                    &state_after_t1,
4623                    vec![op_t2.clone()],
4624                    None,
4625                    Some(snapshot_after_t1),
4626                    oracle_write_ts,
4627                )
4628                .await
4629                .expect("second dry run");
4630
4631            // After second dry run: both t1 and t2 exist.
4632            assert!(
4633                state_incremental.try_get_entry(&id_t1).is_some(),
4634                "t1 should exist in incremental result"
4635            );
4636            assert!(
4637                state_incremental.try_get_entry(&id_t2).is_some(),
4638                "t2 should exist in incremental result"
4639            );
4640
4641            // --- Path B: All-at-once (single dry-run call with both ops) ---
4642
4643            let (state_all_at_once, _) = catalog
4644                .transact_incremental_dry_run(
4645                    &base_state,
4646                    vec![op_t1.clone(), op_t2.clone()],
4647                    None,
4648                    None,
4649                    oracle_write_ts,
4650                )
4651                .await
4652                .expect("all-at-once dry run");
4653
4654            assert!(
4655                state_all_at_once.try_get_entry(&id_t1).is_some(),
4656                "t1 should exist in all-at-once result"
4657            );
4658            assert!(
4659                state_all_at_once.try_get_entry(&id_t2).is_some(),
4660                "t2 should exist in all-at-once result"
4661            );
4662
4663            // --- Compare: both paths produce equivalent items ---
4664
4665            let inc_t1 = state_incremental.try_get_entry(&id_t1).expect("inc t1");
4666            let all_t1 = state_all_at_once.try_get_entry(&id_t1).expect("all t1");
4667            assert_eq!(inc_t1.name(), all_t1.name());
4668            assert_eq!(inc_t1.owner_id, all_t1.owner_id);
4669
4670            let inc_t2 = state_incremental.try_get_entry(&id_t2).expect("inc t2");
4671            let all_t2 = state_all_at_once.try_get_entry(&id_t2).expect("all t2");
4672            assert_eq!(inc_t2.name(), all_t2.name());
4673            assert_eq!(inc_t2.owner_id, all_t2.owner_id);
4674
4675            catalog.expire().await;
4676        })
4677        .await
4678    }
4679
4680    /// Exercises the diff-and-prune semantics of the
4681    /// `Op::UpdateScopedSystemParameters` apply handler over the cluster scope.
4682    /// Covers four behaviors: upsert of a desired row, the bounded-prune
4683    /// protection that spares a live cluster outside `prune_scope`, removal of a
4684    /// stale in-scope row, and the orphan-prune that reclaims a row whose owning
4685    /// cluster was dropped even though that id is absent from `prune_scope`.
4686    #[mz_ore::test(tokio::test)]
4687    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
4688    async fn test_transact_update_scoped_system_parameters_prune() {
4689        use std::collections::{BTreeMap, BTreeSet};
4690
4691        use mz_catalog::memory::objects::{ClusterConfig, ClusterVariant};
4692        use mz_controller_types::ClusterId;
4693
4694        use crate::catalog::DropObjectInfo;
4695        use crate::config::{ScopedParameters, ScopedParametersScope};
4696
4697        Catalog::with_debug(|mut catalog| async move {
4698            let param = "max_query_result_size".to_string();
4699            let value = "1MB".to_string();
4700
4701            // Allocate and create two live clusters, A and B, the same way
4702            // production code does.
4703            let commit_ts = catalog.current_upper().await;
4704            let cluster_a = catalog
4705                .allocate_user_cluster_id(commit_ts)
4706                .await
4707                .expect("allocate cluster A");
4708            let commit_ts = catalog.current_upper().await;
4709            let cluster_b = catalog
4710                .allocate_user_cluster_id(commit_ts)
4711                .await
4712                .expect("allocate cluster B");
4713
4714            let make_cluster_op = |id: ClusterId, name: &str| Op::CreateCluster {
4715                id,
4716                name: name.to_string(),
4717                introspection_sources: Vec::new(),
4718                owner_id: MZ_SYSTEM_ROLE_ID,
4719                config: ClusterConfig {
4720                    variant: ClusterVariant::Unmanaged,
4721                    workload_class: None,
4722                    query_policy: None,
4723                },
4724            };
4725
4726            let oracle_write_ts = catalog.current_upper().await;
4727            catalog
4728                .transact(
4729                    None,
4730                    oracle_write_ts,
4731                    None,
4732                    vec![
4733                        make_cluster_op(cluster_a, "test_cluster_a"),
4734                        make_cluster_op(cluster_b, "test_cluster_b"),
4735                    ],
4736                )
4737                .await
4738                .expect("create clusters");
4739
4740            // Reads the durable cluster system configuration rows.
4741            async fn rows(catalog: &Catalog) -> BTreeSet<(ClusterId, String, String)> {
4742                let mut storage = catalog.storage().await;
4743                let tx = storage.transaction().await.expect("open transaction");
4744                tx.get_cluster_system_configurations()
4745                    .map(|c| (c.cluster_id, c.name, c.value))
4746                    .collect()
4747            }
4748
4749            let scope_with = |ids: &[ClusterId]| ScopedParametersScope {
4750                clusters: ids.iter().copied().collect(),
4751                replicas: BTreeSet::new(),
4752            };
4753            let cluster_scoped = |id: ClusterId| {
4754                let mut cluster = BTreeMap::new();
4755                let mut overrides = BTreeMap::new();
4756                overrides.insert(param.clone(), value.clone());
4757                cluster.insert(id, overrides);
4758                ScopedParameters {
4759                    cluster,
4760                    replica: BTreeMap::new(),
4761                }
4762            };
4763            let empty_scoped = || ScopedParameters {
4764                cluster: BTreeMap::new(),
4765                replica: BTreeMap::new(),
4766            };
4767
4768            // Behavior 1: upsert. A is live and in scope, so the row is created.
4769            let oracle_write_ts = catalog.current_upper().await;
4770            catalog
4771                .transact(
4772                    None,
4773                    oracle_write_ts,
4774                    None,
4775                    vec![Op::UpdateScopedSystemParameters {
4776                        scoped: cluster_scoped(cluster_a),
4777                        prune_scope: scope_with(&[cluster_a]),
4778                    }],
4779                )
4780                .await
4781                .expect("upsert A");
4782            assert!(
4783                rows(&catalog)
4784                    .await
4785                    .contains(&(cluster_a, param.clone(), value.clone())),
4786                "upsert must create the row for A"
4787            );
4788
4789            // Set up an additional row for B so the prune cases have something to
4790            // act on.
4791            let oracle_write_ts = catalog.current_upper().await;
4792            catalog
4793                .transact(
4794                    None,
4795                    oracle_write_ts,
4796                    None,
4797                    vec![Op::UpdateScopedSystemParameters {
4798                        scoped: cluster_scoped(cluster_b),
4799                        prune_scope: scope_with(&[cluster_b]),
4800                    }],
4801                )
4802                .await
4803                .expect("upsert B");
4804            assert!(
4805                rows(&catalog)
4806                    .await
4807                    .contains(&(cluster_b, param.clone(), value.clone())),
4808                "setup must create the row for B"
4809            );
4810
4811            // Behavior 2: bounded prune. Running with empty `scoped` and a scope
4812            // that excludes the live cluster B must leave B's row intact, because
4813            // the update was not authoritative for B.
4814            let oracle_write_ts = catalog.current_upper().await;
4815            catalog
4816                .transact(
4817                    None,
4818                    oracle_write_ts,
4819                    None,
4820                    vec![Op::UpdateScopedSystemParameters {
4821                        scoped: empty_scoped(),
4822                        prune_scope: scope_with(&[cluster_a]),
4823                    }],
4824                )
4825                .await
4826                .expect("bounded prune");
4827            assert!(
4828                rows(&catalog)
4829                    .await
4830                    .contains(&(cluster_b, param.clone(), value.clone())),
4831                "a live cluster outside prune_scope must keep its row"
4832            );
4833
4834            // Behavior 3: stale in-scope prune. A is live and in scope but not
4835            // desired, so its row is removed.
4836            let oracle_write_ts = catalog.current_upper().await;
4837            catalog
4838                .transact(
4839                    None,
4840                    oracle_write_ts,
4841                    None,
4842                    vec![Op::UpdateScopedSystemParameters {
4843                        scoped: empty_scoped(),
4844                        prune_scope: scope_with(&[cluster_a]),
4845                    }],
4846                )
4847                .await
4848                .expect("stale in-scope prune");
4849            assert!(
4850                !rows(&catalog)
4851                    .await
4852                    .iter()
4853                    .any(|(id, _, _)| *id == cluster_a),
4854                "a live in-scope undesired row must be removed"
4855            );
4856
4857            // Behavior 4: orphan prune. Re-create A's row, drop cluster A, then run
4858            // the update with a scope that does NOT contain A. The sync loop only
4859            // ever places live ids in prune_scope, so the orphan must still be
4860            // reclaimed because its owning cluster is no longer live.
4861            let oracle_write_ts = catalog.current_upper().await;
4862            catalog
4863                .transact(
4864                    None,
4865                    oracle_write_ts,
4866                    None,
4867                    vec![Op::UpdateScopedSystemParameters {
4868                        scoped: cluster_scoped(cluster_a),
4869                        prune_scope: scope_with(&[cluster_a]),
4870                    }],
4871                )
4872                .await
4873                .expect("re-create A row");
4874            assert!(
4875                rows(&catalog)
4876                    .await
4877                    .contains(&(cluster_a, param.clone(), value.clone())),
4878                "re-created row for A must exist"
4879            );
4880
4881            let oracle_write_ts = catalog.current_upper().await;
4882            catalog
4883                .transact(
4884                    None,
4885                    oracle_write_ts,
4886                    None,
4887                    vec![Op::DropObjects {
4888                        objects: vec![DropObjectInfo::Cluster(cluster_a)],
4889                        cascade: false,
4890                    }],
4891                )
4892                .await
4893                .expect("drop cluster A");
4894
4895            // B is the only live cluster the sync loop would have evaluated, so
4896            // only B appears in prune_scope. A's id is deliberately absent.
4897            let oracle_write_ts = catalog.current_upper().await;
4898            catalog
4899                .transact(
4900                    None,
4901                    oracle_write_ts,
4902                    None,
4903                    vec![Op::UpdateScopedSystemParameters {
4904                        scoped: cluster_scoped(cluster_b),
4905                        prune_scope: scope_with(&[cluster_b]),
4906                    }],
4907                )
4908                .await
4909                .expect("orphan prune");
4910            assert!(
4911                !rows(&catalog)
4912                    .await
4913                    .iter()
4914                    .any(|(id, _, _)| *id == cluster_a),
4915                "orphan row for a dropped cluster must be removed even when absent from prune_scope"
4916            );
4917
4918            catalog.expire().await;
4919        })
4920        .await
4921    }
4922
4923    /// Registers a `MAX_CONNECTIONS` callback that records every value it sees.
4924    /// The initial fire from `register_callback` is cleared out, so callers
4925    /// only observe notifications that happen afterwards.
4926    fn record_max_connections(catalog: &mut Catalog) -> Arc<Mutex<Vec<u32>>> {
4927        let observed = Arc::new(Mutex::new(Vec::new()));
4928        let recorder = Arc::clone(&observed);
4929        catalog.system_config_mut().register_callback(
4930            &MAX_CONNECTIONS,
4931            Arc::new(move |vars: &SystemVars| {
4932                recorder
4933                    .lock()
4934                    .expect("recorder lock")
4935                    .push(vars.max_connections())
4936            }),
4937        );
4938        observed.lock().expect("recorder lock").clear();
4939        observed
4940    }
4941
4942    fn set_max_connections_op(value: u32) -> Op {
4943        Op::UpdateSystemConfiguration {
4944            name: MAX_CONNECTIONS.name.to_string(),
4945            value: OwnedVarInput::Flat(value.to_string()),
4946        }
4947    }
4948
4949    // The commit-boundary firing now lives in
4950    // `Coordinator::apply_catalog_implications`, so it is not observable from a
4951    // bare `Catalog`. The tests below stay here to guard the speculative path:
4952    // `Catalog::transact` itself must never notify.
4953
4954    /// A dry-run transaction is never committed, so it must not notify.
4955    #[mz_ore::test(tokio::test)]
4956    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
4957    async fn test_system_config_callback_not_fired_on_dry_run() {
4958        Catalog::with_debug(|mut catalog| async move {
4959            let observed = record_max_connections(&mut catalog);
4960            let before = catalog.system_config().max_connections();
4961
4962            // The clone carries the registered callbacks, so the dry run
4963            // genuinely *could* fire them. That's what makes this test worth
4964            // anything.
4965            let base_state = catalog.state().clone();
4966            let oracle_write_ts = catalog.current_upper().await;
4967            let (dry_run_state, _snapshot) = catalog
4968                .transact_incremental_dry_run(
4969                    &base_state,
4970                    vec![set_max_connections_op(before + 1)],
4971                    None,
4972                    None,
4973                    oracle_write_ts,
4974                )
4975                .await
4976                .expect("dry run");
4977
4978            assert_eq!(dry_run_state.system_config().max_connections(), before + 1);
4979            assert_eq!(catalog.system_config().max_connections(), before);
4980            assert!(
4981                observed.lock().expect("recorder lock").is_empty(),
4982                "a dry run must not notify callbacks"
4983            );
4984
4985            catalog.expire().await;
4986        })
4987        .await
4988    }
4989
4990    /// A transaction that fails after applying a system-config op to the
4991    /// candidate state must not notify, since nothing ever gets committed.
4992    #[mz_ore::test(tokio::test)]
4993    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `TLS_client_method`
4994    async fn test_system_config_callback_not_fired_on_rollback() {
4995        Catalog::with_debug(|mut catalog| async move {
4996            let observed = record_max_connections(&mut catalog);
4997            let before = catalog.system_config().max_connections();
4998
4999            let oracle_write_ts = catalog.current_upper().await;
5000            let result = catalog
5001                .transact(
5002                    None,
5003                    oracle_write_ts,
5004                    None,
5005                    vec![
5006                        set_max_connections_op(before + 1),
5007                        // `transact_op` rejects this while parsing, after the
5008                        // first op already applied to the candidate state.
5009                        Op::UpdateSystemConfiguration {
5010                            name: MAX_CONNECTIONS.name.to_string(),
5011                            value: OwnedVarInput::Flat("not a number".to_string()),
5012                        },
5013                    ],
5014                )
5015                .await;
5016
5017            assert!(result.is_err(), "the second op must abort the transaction");
5018            assert_eq!(catalog.system_config().max_connections(), before);
5019            assert!(
5020                observed.lock().expect("recorder lock").is_empty(),
5021                "an aborted transaction must not notify callbacks"
5022            );
5023
5024            catalog.expire().await;
5025        })
5026        .await
5027    }
5028}